Skip to content

feat(kernel_workflow): run mode=mega on the kernel_lane lifecycle - #649

Open
IzacharyI wants to merge 16 commits into
AMD-AGI:mainfrom
IzacharyI:GEAK/feat/mega_lane_pr
Open

IzacharyI wants to merge 16 commits into
AMD-AGI:mainfrom
IzacharyI:GEAK/feat/mega_lane_pr

Conversation

@IzacharyI

@IzacharyI IzacharyI commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

feat(kernel_workflow): run mode=mega on the kernel_lane lifecycle

Summary

mode=mega optimizes a multi-rank operator as one fused kernel: e.g. an EP MoE block whose dispatch,
GEMMs and combine across all GPUs become one persistent kernel. mode=optimize makes one kernel faster;
mega replaces a whole multi-kernel, multi-GPU region, which needs more than one candidate in flight,
backtracking, and stricter acceptance (a fused multi-rank kernel can deadlock, read stale data, or win only
inside the noise).

#539 added mega as a self-contained workflow under
perf_knowledge/expert_skills/expert_workflows/mega_fusion/ (its own workflow script, roles and loop).
This PR moves it onto kernel_lane.js, so mega and optimize/author share one lifecycle, one set of agent
calls and one set of roles. The #539 package is left unchanged here; removing it is a follow-up PR.

  • One lifecycle. kernel_lane.js sets MEGA = MODE === 'mega'. Setup, Analyze, Benchmark, Profile,
    the Optimize loop, Report and Validate are the lane's own phases; each calls a mega hook only under MEGA.
  • One agent call per phase and round step. Mega does not fork the call; it passes its inputs, schema
    and timeouts to the same call and runs its steps before/after it.
  • One set of roles. Mega reads roles/<role>.md plus roles/_fragments/<role>_mega.md; a fragment
    section replaces the same-named section. Main's role files are unchanged.
  • optimize/author unchanged: their prompts and results are byte-identical to main (golden test).
  • Region UT input (region_ut): mega can take a UT task dir of any layout (see below).

What changed, where

kernel_lane.js (+5,956 / −1,170)

Part Lines What
Shared call sites +171 / −106 (47 places) MEGA flag; roleAgent reads the mega fragment; agentT per-call timeout options; at each shared call the MEGA ? inputs/schema/options and the call to the mega hook
// mode=mega backend section +5,581 / −282 (one block, lines ~2173–7448) everything mega-specific, see the next table
Main's comments shortened −782 / +204 (159 places, ≈60 KB) only to keep the script under the workflow tool's 512 KiB limit; no code or prompt text changed

The calls mega shares and what it adds around each:

Lane call mode=mega adds
director setup megaAfterSetup (mega checks, resume from state_dir)
tech_lead analyze megaAnalyzeInputs; megaAfterAnalyze (contract check + one full re-run, task graph, ladder)
benchmark_engineer setup megaBenchInputs; megaAfterBenchmark (recover a baseline left on disk); megaCalibrate (positive/null control)
profile_engineer baseline per-stage form; megaAfterProfile (MoE analysis skill)
tech_lead plan_round megaPlanPrompt; megaPlanStep (direction checks, candidate-lane binding)
engineer megaEngineerTurn (one candidate lane in its own tree); after: recover, record
verify_engineer verify verifyStep (structure check, inputs); after: score, recover, record
select / integrate megaSelectCandidate (best eligible candidate from the registry; candidates are never merged)
tech_lead update_memory megaStateWrite / megaCheckStateWrite (registry to STATE.json, read back)
stop megaStopRule (modeled clock, deliverable)
tech_lead report / director validate megaReportInputs / megaValidateInputs; megaFinish (finalist re-test, identity check, delivery)

Why mega needs its own code, and what is shared

Mega needs Why optimize's version is not enough Lines (approx.)
Several candidates at once, with backtracking: a registry of independent candidate lanes, parking/resuming a lane, final selection, delivery a fusion often pays off only after several steps that are slower or broken on the way; optimize keeps one cumulative best and builds on it ~670
Stricter acceptance: positive control (a known slowdown must be detected), null arm (noise floor), paired readings with a sign test, launch-count check, graph-replay liveness, identity check of the finalist a fused multi-rank kernel can deadlock, read stale data or "win" inside the noise; optimize checks speedup and correctness only ~410
Analysis/plan constraints: task graph, pipe-occupancy table, step ladder, direction contract keeps the planner from proposing fusions the hardware or the dependence chain cannot pay for ~450
Phase hooks and per-candidate engineer/verify steps (the table above) the shared calls need mega's inputs and its after-steps ~1,970
Reply schemas the gates above need fields the lane's schemas do not have; each mega schema spreads the lane schema and adds/redefines only those fields ~830
Args, STATE persist/resume, misc ~940

Shared with optimize: every phase and round call, the role files (mega adds fragments), the lane's schemas
(mega extends them), the GPU lease, the stop/budget machinery.

Outside kernel_lane.js

Where Lines What
kernel_workflow.js +6 / −5 mode=mega goes to kernel_lane.js
roles/_fragments/*_mega.md (7) +3,309 mega sections of director, tech_lead, engineer, deep_engineer, benchmark_engineer, profile_engineer, verify_engineer (from #539's forked roles; no mega-only roles)
knowledge/mega/ (14) +3,299 mega knowledge (distributed fusion, measurement, regimes, task graph, pipe occupancy, region UT, ...)
knowledge/collectors/, knowledge/analysis_skills/ +2,683 profile collectors and the MoE bottleneck analysis skill
knowledge/amd_instinct.md, hip_optimization.md +72 gfx950 synchronization notes that point to knowledge/mega/
scripts/mega/ (10) +6,495 mega helpers: graph A/B runner, regime check, graph contract, skill contract/runtime, A/B retry, commandment rebase, STATE chunk reader, region UT starting contract, run replay
scripts/multi_rank_analysis/ +7,540 per-rank trace/counter aggregation
tests/ (54) +12,675 mode=mega tests, retargeted at kernel_lane.js
scripts/tests/test_lane_golden.py + fixtures +573 optimize/author prompts and results pinned to main
CI +10 kernel_workflow/tests in its own pytest/node steps (file names repeat the #539 package's)
README +65 / −3 layout and mode=mega

Most of the non-lane lines are copied from the #539 package and go away with it in the follow-up PR.

kernel_workflow/
├── kernel_workflow.js              # dispatcher: optimize | author | mega -> kernel_lane.js
├── kernel_lane.js                  # one lifecycle: shared calls + the mode=mega backend section
├── roles/
│   ├── <role>.md                   # shared by all modes (unchanged)
│   └── _fragments/<role>_mega.md   # NEW (7): what mode=mega changes in each role
├── knowledge/
│   ├── <main's files>              # + two gfx950 notes pointing to mega/
│   ├── mega/                       # NEW (14): mode=mega knowledge
│   ├── collectors/                 # NEW: profile collectors
│   └── analysis_skills/            # NEW: MoE bottleneck analysis skill
├── scripts/
│   ├── mega/                       # NEW (10): mode=mega helpers
│   ├── multi_rank_analysis/        # NEW: per-rank analysis library
│   └── tests/test_lane_golden.py   # NEW: optimize/author byte-identical to main
└── tests/                          # NEW (54): mode=mega tests
perf_knowledge/expert_skills/
└── expert_workflows/mega_fusion/   # #539 package, unchanged here; removed in a follow-up PR

Region UT input

  • region_ut: a caller passes a UT task dir (any layout) and the GPU set. Before Setup, a region UT
    adapter agent reads the UT and writes one unified contract beside it (<region_ut>.mega_ut.json): the
    mega args (benchmark, target and regression guards with noise-aware floors, accuracy bound in the UT's
    own units, replay count, bound module, positive control) and how to run and read the UT (command and GPU
    count, editable files, correctness verdict, per-case times, replay evidence, null arm).
  • Fixed target form, adaptive reading: knowledge/mega/mega_region_ut.md fixes the contract's fields
    and the adapter's limits (adapt, never weaken the UT's own check or tolerance; a wrapper beside the UT
    when something is missing, never inside it). scripts/mega/region_ut_args.py gives the adapter a
    starting contract for the UT layouts GEAK already produces.
  • Checked, not trusted: the lane refuses a contract without a benchmark or a target guard; the
    benchmark engineer proves the contract on the first baseline run (verdict PASS, every case timed on both
    legs, headline and replay evidence where the contract says) or stops Setup; when the benchmark is a
    wrapper, the director also runs the UT's own command on the final patch and that verdict counts.
  • Every role then runs and reads the UT through the contract; only the editable files change; the result is
    their patch plus support.json / notes.md.

Fixes found on-card

  • the prior-reuse leak check no longer fires on a candidate built on this run's own candidate;
  • candidate heads are compared by commit (short vs full SHA) in the final verdict, finalist rows, verify
    and delivery;
  • finalists measure every target and regression guard to its required pair count;
  • check_mega_identity passes rows the lane only excluded locally (.git/info/exclude) when they are
    byte-identical; the engineer fragment excludes file patterns, not source directories;
  • the mega planner gets a mode=mega opening and specialties section instead of the lane's;
  • mega_graph_ab deletes its per-rank output tensors when a run ends.

Results (EP8 MegaMoE, 8× MI355X, no Expert Skill)

Performance matches the version before the refactor:

Scenario Before After
MTPR 64 1.13× 1.11×
MTPR 8192 1.16× 1.15×

Tests

  • optimize/author unchanged: scripts/tests/test_lane_golden.py replays 5 lane scenarios; prompts and
    results are byte-identical to main.
  • mode=mega: 8 recorded mega runs (64/8192, skill on/off, resume, certify) replay with the same agent calls
    and results, except one (gen64) from its round 3 on, where a candidate is now correctly scored (the
    commit-comparison fix above).
  • kernel_workflow/tests/ (JS + Python, incl. test_mega_paths.js: every workflow path mega hands an agent
    exists), test_mode_dispatch.js, test_fast_mode_off_identical.js, test_lane_refs.py,
    test_workflow_script_size.js, the L0 unit pytest: pass, except tests that fail on main too.
  • The region UT adapter was run on UTs of several layouts; its contracts were checked against real runs
    on card (verdict, per-case times, headline, replay evidence), and a broken candidate reads FAIL.

Notes

  • kernel_lane.js is 519,185 B, under the workflow tool's limit with the 4 KiB margin of
    test_workflow_script_size.js (≈1 KB left). To fit, 159 of main's comments in kernel_lane.js are
    shortened (≈60 KB); no code or prompt text is changed by that. The advisory growth check will warn.
  • expert_workflows/mega_fusion/ stays as is in this PR, so mega knowledge/tools/tests exist twice until
    the follow-up PR removes the package.
  • Not included: the learned-knowledge cards for mega and the residual correction of how much the planner
    relies on them; they follow separately.

Adds mode=mega to kernel_lane.js. Mega runs the lane's own phases and its
Optimize round (plan -> engineer -> verify -> select -> memory). Each phase
and round step keeps one agent call for every mode: under MODE === 'mega' it
gets the mega inputs, schema and timeouts, and mega steps run before/after
it (e.g. megaAfterAnalyze, megaEngineerTurn/after, verifyStep/after,
megaStateWrite/megaCheckStateWrite). Roles are the lane's role files
plus roles/_fragments/<role>_mega.md, whose sections replace the same-named
sections. optimize/author prompts and results are byte-identical to main
(scripts/tests/test_lane_golden.py).

The AMD-AGI#539 package (perf_knowledge/expert_skills/expert_workflows/mega_fusion/)
is left unchanged; its knowledge, tools, scripts and tests are copied under
kernel_workflow/ and the package is removed in a follow-up PR. CI runs
kernel_workflow/tests in their own steps (file names repeat the package's).

Also:
- several candidate lanes per round (mega_directions_per_round);
- mega_graph_ab deletes per-rank output tensors when a run ends;
- the prior-reuse leak check skips a candidate built on this run's own
  candidate;
- finalist identity compares commits, not SHA strings (short vs full);
- check_mega_identity passes rows the lane only excluded locally when they
  are byte-identical; the engineer excludes file patterns, not source dirs;
- the mega planner gets a mode=mega opening and specialties section;
- the lane version leaves out the fast-test cache, the chain-debt tracker,
  route-only mode and the strict-autonomy proof runs.
…very rank

A pipeline (e.g. KernelFusion for an L3 MegaKernel region, or the e2e kernel
track) can now hand mode=mega a multi-rank operator as a region UT task dir:
the caller passes only region_ut (= kernel_path), gpu_ids and gpus_per_job.

mode=mega (kernel_lane.js):
- tools/region_ut_args.py turns the UT's meta.json into the mega args the
  caller left unset (its unittest.py as benchmark, case sigs as guards and
  accuracy cases, the case tolerances, the bound modules, a positive control
  inside kernel_src/); an arg the caller passed wins. Read once, before any
  mega arg is parsed.
- every mode=mega role also reads knowledge/mega_region_ut.md: only
  kernel_src/ may change, the UT's unittest.py is the benchmark and the
  accuracy verdict, the engineer writes kernel_src/_handback/support.json and
  notes.md. Without region_ut no prompt changes (8 mega replays identical).

e2e UT harness (e2e_workflow/scripts):
- meta.world_size > 1: every leg runs under torchrun on the leased GPU set;
  time is the slowest rank (per_rank_ms kept), run_correctness_ranks checks
  every rank's outputs against the baseline leg's, eager and under one
  captured graph per case; cases.setup_dist / teardown_dist hooks.
- meta.correct_metric "rel_l2" and a per-case tol, for operators whose stock
  output is not elementwise reproducible.
- candidate_bind may be a list (one entry per module of a region); the
  integrator replays it entry by entry.
Single-rank tasks run exactly as before.
…ked re-run dir keeps the task dir off sys.path

Found on card (MegaMoE region UT, EP4 on 4 GPUs): a multi-rank task builds its
inputs per rank, so listing its cases needs the process group (list now runs
under torchrun too); and a hand-back re-run dir that symlinks the task's files
put the task dir (with its unittest.py) on sys.path, shadowing stdlib unittest.
…mode=mega's finalist gate

Found by an on-card mode=mega flow run on a MegaMoE region UT (EP4): the
candidate was correct (bit-exact on 4 ranks) and 1.13x on the heaviest case,
but no finalist could pass, because every case was a target guard (a case the
implementation declares a refusal for, at stock speed, failed the target
readout) and the UT gave no replay count for the liveness gate.

- region_ut_args.py: the heaviest case is the target; the others are
  regression guards with a 2% floor; required_replays comes from the UT's
  meta.graph_replays.
- leg_runner check: meta.graph_replays more replays of each case's captured
  graph, cycling through the draws, every one checked on every rank
  (graph_replays in the result); mega_region_ut.md: the UT's GRAPH_REPLAYS line
  is the liveness evidence.
…heck (never n/a)

Found by the second on-card flow run: the verifier reported graph_safe n/a for a
config-only candidate, which the finalist gate reads as not graph-safe, though
the UT had captured and replayed the seam 256 times on every rank.
…inalists measure every guard to its pair count

Found by the third on-card flow run on a MegaMoE region UT (EP4): the finalist
(3 launches, 1.087x, correct on 4 ranks) was rejected because the registry head
was short (41ff2d2) and the director reported the full SHA (the identity check
was fixed for this in 70ec987dc, the final verdict was not), and because the
director measured the regression guard with 3 pairs where REQUIRED_PAIRS is 5.
…ere (delivery, finalist rows, verify)

Found by the certify-only on-card run on a MegaMoE region UT (EP4): finalist
re-test, identity check (all 56 tree rows equal), report and director validate
all passed (1.09x on the target case, validation accepted), yet nothing was
delivered: the delivery check compared the director's full source SHA with the
registry's short one as strings. The finalist-row and verify head checks had
the same flaw. sameCommit also accepts two equal non-hex strings.

Replays: 7 of 8 identical; gen64 now keeps a candidate whose verify reported
the full SHA of its short registry head as scored (it was wrongly left
runnable), so that replay diverges from round 3 on.
Resolve conflicts with AMD-AGI#636 (batched UT timing, multi-GPU per-rank receipts):
- leg_runner/harness_lib: multi-rank legs on the timing_specs/make_timing_case API; list is
  metadata only and single-process; time mode follows --sigs on every rank.
- kernel_lane: per-call timeouts default to AGENT_WAIT_MS; mode=mega keeps its own schemas and
  does not take the UT_MR path.
- test_lane_golden: size cap uses the 4 KiB margin of test_workflow_script_size.js.
…tract format; drop the e2e multi-rank harness

region_ut_args.py now reads the fields KernelFusion writes: acceptance.tol (the UT's own error units)
as the accuracy bound, per-case regression floors widened by run/self_noise.json, and the UT's graph-case
--iters as the replay count. mega_region_ut.md follows that UT's runner and output (mp_harness ranks,
ORACLE/RANDOM/SERVED gates, case lines, ut_result.json).

A KernelFusion UT runs its ranks through its own mp_harness.py, so the torchrun legs, per-rank check
mode and list candidate_bind in leg_runner/harness_lib (and their test) are reverted to main.
… as well as a KernelFusion one

region_ut_args.py reads either format GEAK produces: cases from meta.cases or meta.workload.cases (weight,
else effective_calls), the bound from acceptance.tol or meta.tol, graph cases from regime or
phase_regimes. The replay evidence is the UT's own: --iters when its runner has it, else its one
refreshed-input replay per graph case; the search-time liveness check uses at most required_replays.
mega_region_ut.md describes both UTs' runs and outputs.
…ut into one unified contract

mode=mega no longer requires a fixed UT format. Before any mega arg is read, the region UT adapter reads
the UT and writes <region_ut>.mega_ut.json: the mega args plus how to run and read the UT (command, GPU
count, editable files, verdict, per-case times, replay evidence, null arm). mega_region_ut.md fixes the
contract's fields and the adapter's limits; region_ut_args.py is its starting point for the layouts GEAK
produces. The lane refuses a contract without a benchmark or a target guard, and every mode=mega role
reads the contract.
…baseline run; a wrapper never decides validation

The benchmark engineer checks the adapter's contract against the unchanged code on its first run
(verdict PASS, every case timed on both legs, headline and replay evidence where the contract says) and
stops Setup otherwise. When the benchmark is a wrapper, the director also runs the UT's own command on
the final patch, and that verdict counts.
MEGA_BENCH/VERIFY/PLAN_BASE/ANALYZE_BASE/MEMORY_SCHEMA spread the lane schema and keep only the fields
mega adds or redefines. Every schema an agent receives is the same object (replays: same fields, key
order only).
…a/ folders

tools/*.py and scripts/replay_runs.js move to scripts/mega/, the mode=mega knowledge files to
knowledge/mega/; every reference (lane prompts, role fragments, knowledge, tests, README) follows.
tests/test_mega_paths.js checks that every workflow path mode=mega hands an agent exists. Replays:
same calls and results; prompts differ only in these paths.
@zihaoanllm

Copy link
Copy Markdown
Collaborator

Thanks for the work on integrating mega mode into the unified kernel workflow. I agree with the overall direction, but have a few concerns regarding the implementation:

  1. Modularization of kernel_lane.js. This PR adds nearly 6,000 lines to kernel_lane.js, bringing it very close to the workflow script size limit. Shortening existing comments to accommodate the new implementation is not a sustainable solution. Could we minimize changes to kernel_lane.js, maximize the reuse of existing workflow components, and move mega-specific logic into separate modules or helper scripts?

  2. Duplicate implementations. Could we complete the migration and remove the duplicated implementation under expert_workflows/mega_fusion/ in this PR? If backward compatibility is needed, the existing entry point could delegate to the unified implementation instead of maintaining two copies.

  3. Role reuse and task-specific skills. This PR introduces a separate set of role fragments specifically for MegaMoE, which effectively duplicates a significant portion of the existing role definitions. Could we reuse the original roles and encapsulate MegaMoE-specific knowledge, optimization strategies, and task requirements into task-specific skills instead? This would avoid maintaining separate role definitions for each optimization scenario and make it easier to extend the workflow to other tasks.

Overall, I would prefer to keep the core workflow and roles as generic as possible, maximize the reuse of existing components, and introduce task-specific capabilities through modular skills rather than modifying the main workflow extensively.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants