Skip to content

[ASM] [HIP] [CK] Add gfx950 Q256 fused MXFP4 prefill pipeline - #5988

Merged
JohnNikolay84 merged 29 commits into
mainfrom
feature/fmoe-q256-prefill
Nov 4, 2026
Merged

JohnNikolay84 merged 29 commits into
mainfrom
feature/fmoe-q256-prefill

Conversation

@vstakhov-amd

@vstakhov-amd vstakhov-amd commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Add a fused assembly path for gfx950 MXFP4 MoE prefill, selected through the existing Qwen model configs. Compared with the tuned FlyDSL baseline, full fused_moe latency improves by 8.9–15.1% at 8K–64K tokens and 3.2–7.2% on captured Qwen routing patterns.

The public API is unchanged. The path uses the existing assembly launcher and FlyDSL reduction, with no additional scheduling launch.

Performance

MI355X/gfx950; model dimension 8192, intermediate dimension 256, 512 routed experts plus one shared expert, top-10 routed selection plus the shared route, SiLU, MXFP4 activations/weights and BF16 output.

The tables compare the selected ASM implementation with the existing tuned FlyDSL baseline. Latency includes activation quantization, sorting, scale preparation, both projections and reduction.

Tokens FlyDSL baseline, µs ASM prefill, µs Latency reduction
8K 1287.7 1173.0 8.91%
16K 2422.5 2175.4 10.20%
32K 4570.1 3882.5 15.05%
64K 9017.0 7914.8 12.22%

Captured Qwen routing snapshots at 8K tokens:

Routing snapshot FlyDSL baseline, µs ASM prefill, µs Latency reduction
029 1219.2 1131.0 7.23%
046 1288.3 1239.0 3.83%
049 1272.3 1232.2 3.15%

Each value is the median of nine samples of 50 graph replays, measured serially on the same GPU with identical inputs and caller-provided output buffers. The sequence-length sweep uses uniform-random routing; the snapshot comparison uses captured Qwen route IDs and weights. Activations and expert weights are synthetic, so these are operator-level results rather than full-model speedups. Environment: Torch 2.10, ROCm 7.2, FlyDSL 0.4.0.

Architecture and motivation

The existing two-stage path materializes intermediate activations between the gate/up and down projections. This specialized prefill path keeps activation and intermediate quantization inside one producer, reducing intermediate global-memory traffic and separate kernel launches.

The pipeline is:

  1. Reuse the existing route sorting and activation-scale preparation.
  2. Run one persistent assembly producer that fuses gate/up GEMM, SiLU, MXFP4 requantization, down GEMM and route weighting.
  3. Write one BF16 contribution per (token, topk) slot into a [tokens, topk, model_dim] buffer.
  4. Use the existing FlyDSL reducer to sum those contributions in FP32 and write the final BF16 output.

Keeping the reduction separate gives each producer a disjoint output slot and avoids atomic accumulation into the final output. The assembly kernels use the standard fmoe_g1u1 launcher and kernarg layout.

Skewed routing gives persistent workgroups different amounts of work. For the 8K shared-expert case, the producer estimates tile costs from the sorted routes and computes a balanced schedule directly in assembly. It also uses larger shared-expert jobs where that reduces the completion tail. Smaller layouts use the compact policy. No host job-map tensor or Triton scheduling kernel is needed.

Why the FlyDSL reducer changed

The contribution buffer is written once and consumed once. The reducer now supports opt-in streaming/non-temporal loads, used by this ASM path to avoid filling caches with contributions that will not be reused and competing with reusable expert-weight data.

The change reuses the existing reducer rather than adding a second reduction implementation. Its FP32 accumulation and output conversion are unchanged; streaming loads default to disabled for other callers.

Integration and validation

The existing Qwen configs select the new kernels for the supported prefill shapes. The Qwen3.8 CSV changes only its three prefill rows. Eligibility checks preserve automatic fallback to the two-stage path for unsupported call contracts.

Validation covers independent numerical references, captured and random routing, scheduler boundaries, graph replay with changed routes, prequantized inputs, caller-provided output buffers and 64K tail handling. Full outputs matched the FlyDSL baseline bitwise in the measured comparisons. Config-collision, Ruff and Black checks passed.

@github-actions

Copy link
Copy Markdown
Contributor

🏷️ CI Guide

Runs automatically on every PR:

  • ✅ Pre-checks (submodule verification, code formatting)
  • ✅ Aiter op tests (gfx942 + gfx950)
  • ✅ Triton tests on MI35X (only when aiter/ops/triton/** or related paths are changed)

Extended tests (opt-in via labels):

Label Tests
ci:gfx1250-ffm-triton Run the five-shard gfx1250 FFM Triton test suite
ci:triton-300x Run an additional Triton test job on MI300X in PRs (added automatically when gfx942 configs change); main branch always runs both MI35X and MI300X
ci:triton-355 Run the full Triton test suite on MI35X, not only the tests the change affects
multigpu Aiter multi-GPU tests on the 8-GPU runner
ci:sglang SGLang integration tests: DeepSeek-R1-MXFP4 accuracy, Qwen 3.5 accuracy
ci:atom ATOM benchmark: DeepSeek-R1-0528, GPT-OSS-120B
ci:atom_full ATOM accuracy suite for PR and main models from ATOM models_accuracy.json
ci:vllm vLLM benchmark: GPT-OSS-120B, DeepSeek-R1-0528, Kimi-K2.5
ci:all All standard extended tests (excludes ci:atom_full)

Only add ci:atom_full for FlyDSL or Triton upgrades.
Add labels via the sidebar or gh pr edit 5988 --add-label <label>

One backend per PR:
A PR changes one kernel backend: [Triton/Gluon] (Triton and Gluon count as one), [HIP], [ASM], [CK], [OPUS] or [FlyDSL]. If the title ends up with two backend tags, split the PR -- as stacked pull requests when one part cannot merge without the other.

PR title tags & labels:
Component tags ([Triton/Gluon], [HIP], [CK], [ASM], ...) are added to the PR title and as PR labels automatically from the changed files and re-synced on every push — change-type tags like [fix]/[Perf], op tags like [MLA], and human labels (ci:*) are left untouched. Add the no-auto-title label to stop the title rewrites; labels stay in sync either way.

Comment thread csrc/py_itfs_cu/asm_fmoe_q256.cu Resolved
@vstakhov-amd
vstakhov-amd force-pushed the feature/fmoe-q256-prefill branch 3 times, most recently from b32149d to e89ada0 Compare October 2, 2026 10:48
@vstakhov-amd
vstakhov-amd force-pushed the feature/fmoe-q256-prefill branch from 4acd967 to 4d41912 Compare October 14, 2026 09:14
@vstakhov-amd vstakhov-amd self-assigned this Oct 14, 2026
Comment thread aiter/fused_moe.py Resolved
Comment thread aiter/fused_moe.py Resolved
Comment thread csrc/py_itfs_cu/asm_fmoe_q256.cu Resolved
@vstakhov-amd
vstakhov-amd force-pushed the feature/fmoe-q256-prefill branch from f60e127 to bc2b299 Compare October 23, 2026 16:51
@vstakhov-amd
vstakhov-amd marked this pull request as ready for review October 26, 2026 09:13
@vstakhov-amd
vstakhov-amd requested a review from a team October 26, 2026 09:13
@github-actions github-actions Bot changed the title Add gfx950 Q256 fused MXFP4 prefill pipeline [Triton/Gluon] [ASM] [HIP] Add gfx950 Q256 fused MXFP4 prefill pipeline Oct 26, 2026
@Boss2002n
Boss2002n requested a balanced review from Copilot October 26, 2026 09:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Q256 dispatch accepts incompatible weight layouts, and the default model tables enable a path described as opt-in.

5 open issues
What changed in this PR

Adds a gfx950 Q256 MXFP4 MoE prefill path to AITER’s existing dispatch system, combining an assembly producer with a Triton scheduler and FlyDSL FP32 reduction.

Changes:

  • Adds producer bindings, argument validation, scheduling, and dispatch integration.
  • Updates model tables and adds optional streaming loads to the shared reducer.
  • Adds scheduler benchmarks and checks for numerical accuracy, output reuse, changing routes, and fallback dispatch.
File Description
op_tests/​triton_tests/​moe/​test_q256_schedule.py Adds a CPU scheduling oracle and GPU checks.
op_tests/​test_moe_2stage.py Adds Q256 integration and dispatch regression checks.
op_tests/​op_benchmarks/​triton/​bench_q256_schedule.py Adds scheduler latency benchmarks.
csrc/​py_itfs_cu/​asm_fmoe_q256.cu Validates inputs and launches assembly producers.
csrc/​include/​q256_producer_args.hpp Defines and checks the producer argument layout.
aiter/​ops/​triton/​moe/​q256_schedule.py Adds the validated scheduler wrapper.
aiter/​ops/​triton/​_triton_kernels/​moe/​q256_schedule.py Implements ranked job scheduling and identity fallback.
aiter/​ops/​moe_op.py Connects scheduling, production, and reduction.
aiter/​ops/​flydsl/​moe_kernels.py Passes the streaming-load option to reduction compilation.
aiter/​ops/​flydsl/​kernels/​moe_reduce.py Adds optional nontemporal contribution loads.
aiter/​jit/​optCompilerConfig.json Registers the Q256 native module.
aiter/​fused_moe.py Integrates Q256 selection, sorting, and fallback handling.
aiter/​configs/​model_configs/​qwen3_8_2400b_fp4_tuned_fmoe.csv Selects Q256 for large 8192-wide prefill shapes.
aiter/​configs/​model_configs/​qwen3_5_397b_fp4_tuned_fmoe.csv Adds Q256 selections for 4096-wide prefill shapes.

Review effort: Balanced

Comment thread aiter/fused_moe.py Resolved
Comment thread aiter/fused_moe.py Resolved
Comment thread aiter/ops/moe_op.py Resolved
Comment thread op_tests/test_moe_2stage.py Resolved
@JohnNikolay84

Copy link
Copy Markdown
Contributor

Let's just talk an Agent to an Agent, shall we ? :)

PR #5988 — [Triton/Gluon] [ASM] [HIP] Add gfx950 Q256 fused MXFP4 prefill pipeline

Overall: Solid work with significant performance gains, but there are a few issues worth addressing before merge.

What it does

Adds a fused single-stage MXFP4 MoE prefill path for gfx950 (MI355X). Instead of the traditional two-GEMM pipeline (stage1 projection → quantize → stage2 down projection), it fuses both projections, SiLU activation, hidden quantization, and routing-weight multiplication into one ASM producer kernel, then reduces the per-topk contributions with the existing FlyDSL reduction.

Reported: 5–35% latency improvement across six shapes on MI355X.

Strengths

  • Comprehensive testing: CPU oracle for the Triton job-map scheduler with exact bit-for-bit GPU comparison; boundary conditions (8191/8192/8193 tokens); random routing with CUDA graph replay; fallback dispatch verification.
  • Good fallback design: When Q256 conditions aren't met (expert-parallel, bias, interleave, unshuffled weights, wrong dtypes), it falls back to the two-stage path with a clear warning.
  • Well-documented ABI: The ProducerArgs struct has static_assert on every field offset.
  • No public API change: The integration is transparent through the existing fused_moe dispatch.

Issues

  1. Docstring is factually wrong (moe_op.py:817)

"""Run both projections, SiLU, hidden MXFP4 quantization and route weighting.

The ASM producer writes BF16 contributions in token/top-k order. FlyDSL
sums those contributions in FP32 and writes the final caller output.

The docstring is actually fine, but the Copilot review flagged a different description elsewhere that says "Triton FP32 route reduction" — the actual reduction uses FlyDSL _run_moe_reduction, not a Triton kernel. Worth verifying which description is current and correcting.

  1. _atomic = True for Q256 is semantically misleading

if metadata.run_1stage:
_atomic = True # Allocate the final output for producer + reduction.

Throughout the codebase, _atomic means "the stage2 GEMM2 uses atomic scatter." For Q256, there is no stage2 — the flag is being repurposed to mean "zero-init the output during sorting." The comment helps but a named constant or separate variable would be clearer:

if metadata.run_1stage:
_zero_init_output = True # Q256: sorting zero-inits output; producer writes partials.
_atomic = True

  1. _Q256_KERNEL duplicated in test_moe_2stage.py

_Q256_KERNEL = "fused_moe_mxfp4_prefill_1tg_4w_256mx1_128nx1_ps_fp32gate"

This is defined identically in aiter/ops/moe_op.py. The test should import from moe_op instead of redefining it — if the kernel name changes in production, the test would silently test the old name.

  1. Hard-coded geometry limits

Several tightly-coupled magic numbers:

  • streaming_loads=(tokens, model, topk) == (8192, 8192, 11) — only triggers for the exact Qwen 8K config
  • tokens == 8192 for weighted scheduling
  • intermediate_width = 256 hard-coded in the C++ args

These are all documented in comments and tests, but they mean the Q256 path is only correct for one specific model geometry. This is intentional (it's a tuned path for the Qwen 397B/2400B models) but should be more prominently documented in the module docstring.

  1. CSV rows are auto-selected without opt-in

The tuned CSV rows are merged into the model config table automatically. When a user loads qwen3_5_397b_fp4_tuned_fmoe.csv, the Q256 kernel is selected by default. The fallback logic is correct (falls back to two-stage for unsupported conditions), but there's no way to
explicitly disable Q256 if a user wants to force the two-stage path. An env variable like AITER_DISABLE_Q256=1 would give users an escape hatch.

  1. reverse_sorted is validated but unused by the producer

The C++ entrypoint validates reverse_sorted dtype and numel, but it's never passed to the producer kernel args. It's dead code that could confuse readers. A comment explaining why it's part of the interface (e.g., "kept for interface consistency with the sorting output
contract") would help.

  1. BufferCopy128b(0) vs BufferCopy128b() cache behavior
  •    load_atom = fx.make_copy_atom(fx.rocdl.BufferCopy128b(), in_elem)
    
  •    load_atom = fx.make_copy_atom(fx.rocdl.BufferCopy128b(load_cache), in_elem)
    

When streaming_loads=False, load_cache=0. This should be equivalent to the old no-arg constructor if 0 means "default cache policy" in FlyDSL, but this should be verified — if 0 is a distinct cache modifier (e.g., "no override" vs "bypass"), existing MoE reductions would
silently change behavior.

  1. Minor: has_a2_scale is added to get_2stage_cfgs but only checked for Q256

The new has_a2_scale parameter is checked in the Q256 q256_supported condition but not used anywhere else. If there are other kernel families that also can't handle a2_scale, they'd silently accept it. This is fine if Q256 is the only affected path, but worth noting.

Copilot review items I checked

  • gate_up_interleave=True rejection: The code does reject it — gate_up_interleave is None or gate_up_interleave is False evaluates to False for True. Copilot's comment may have been on an earlier revision.
  • is_shuffled vs opus_weights_shuffled: The code correctly uses opus_weights_shuffled, not is_shuffled. This was likely addressed in a later commit.

Recommendation

Address items 2, 3, and 4 (naming, duplication, documentation of geometry limits) as easy fixes. Item 5 (opt-out mechanism) is a design decision that should be discussed with the maintainers. Items 6–7 are worth investigating but not blocking.

@zufayu
zufayu requested review from a team and vgokhale October 27, 2026 01:15
azaidy
azaidy previously requested changes Oct 27, 2026

@azaidy azaidy left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please create separate PRs for separate kernel providers. Stack the PRs if there is a dependency chain.

@github-actions github-actions Bot changed the title [Triton/Gluon] [ASM] [HIP] Add gfx950 Q256 fused MXFP4 prefill pipeline [ASM] [FlyDSL] Add gfx950 Q256 fused MXFP4 prefill pipeline Oct 27, 2026
@github-actions github-actions Bot changed the title [ASM] [FlyDSL] Add gfx950 Q256 fused MXFP4 prefill pipeline [ASM] [HIP] [CK] Add gfx950 Q256 fused MXFP4 prefill pipeline Oct 28, 2026
Restore the existing Qwen CSV schema and unrelated rows so its PR diff contains only the three prefill selections. Compare the canonical kernel name directly in fused_moe and remove the separate moe_op helper.

Config collision guard passes all 30 tests; Ruff, Black and syntax checks pass.
Rebuild the weighted producer with wave-local key exchanges, one cross-wave LDS exchange and four register-cached jobs shared by dispatch and prefetch. The standard FMoE launcher passes no job map, and the kernel never reads the smoothing-scale pointer.

Select weighted M128 scheduling for qualifying routed boundaries 576 through 960; retain the compact M32/M64 path for smaller layouts, invalid suffixes and over-capacity schedules. Keep direct dispatch checks and the three-row CSV diff.

Validated 113 policy cases and 115712 slots with zero mismatches, production Q256 integration and forced larger-token fallback. Captured routes 029/046/049 improve 6.6-9.5% against compact and 3.1-7.2% against FlyDSL. The matched-allocation timing follow-up remains blocked by GPU availability.
Adapt the PR style patch to both compact and assembly-weighted producers. Select the partial-output branch before the generic G1U1 branch, enforce its tile size locally, and simplify equivalent FlyDSL copy constructors.

Populate the six existing prefill rows from validated timing receipts without changing CSV schemas or unrelated rows. Retain tested eligibility, FP8 fallback, reference and import-safe test contracts.

Validated 30 config collision tests, 22 old/new host-call cases, eight installed FlyDSL copy-type comparisons, Ruff and Black. Assembly code objects are unchanged.
Use the flat column to distinguish sorted, no_sort, emsort and sorted post-reduction producers. Replace kernel-name classification with mode checks, preserve host sorting and standard launch geometry for mode 3, and update model and assembly manifests.

Keep post-reduction entries out of the direct-output tuner and account for sorting according to mode. Cover all four sorting/output modes with CPU tests.

Validated 30 config tests, both CPU mode tests, 12 Q256 integration/profile checks, four emsort rows and ten no-sort rows on gfx950. Assembly code objects are unchanged.
Define AsmMoeMode with the existing CSV values and a requires_host_sort property. Normalize numeric modes at dispatch boundaries, derive tuner mode groups from the enum, and use matching named constants in the C++ launcher.

Preserve numeric CSV serialization and legacy boolean inputs. Three CPU mode tests, 30 config tests, codegen contracts, Ruff, Black and fresh standard ASM compilation pass. GPU revalidation was blocked by device activity; assembly code objects are unchanged.
Return the op test to its normal CSV sweep with only post-reduction row selection and settings. Remove producer mocks, profiler assertions, model-specific suites and pytest-only mode tests.

Use the standard 256-row Opus sort without auxiliary indices, remove the one-stage atomic detour and has_a2_scale plumbing, and retain only weight-layout eligibility. Zero partials when filtering can leave route slots unwritten.

Validated all six configured shapes through the real script, exact captured-route outputs, local-token graph replay and masked local-expert mapping. Captured routes improve 8.61%, 5.88% and 5.40% versus FlyDSL; config, Ruff and Black checks pass.
Give the sort an empty buffer and let the reducer overwrite the final output, including masked rows. Revert the unrelated FP8 fallback changes.
Include POST_REDUCE candidates with shuffled MXFP4 inputs and report their combined cost as us1 without an extra intermediate quantization charge. Reset merged candidate indices so winner selection emits one valid CSV row.
Use measured producer-plus-reducer costs for each configured kernel and explicitly record zero stage-two cost. Keep the weighted 8K row matched to its own measurement.
@vstakhov-amd
vstakhov-amd force-pushed the feature/fmoe-q256-prefill branch from 2b808bc to 9f85193 Compare November 3, 2026 09:13
@JohnNikolay84

JohnNikolay84 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Please create separate PRs for separate kernel providers. Stack the PRs if there is a dependency chain.

This version of the change has only 1 producer now @azaidy

@JohnNikolay84
JohnNikolay84 requested a review from azaidy November 3, 2026 14:56
@JohnNikolay84
JohnNikolay84 dismissed azaidy’s stale review November 4, 2026 09:44

the reviewer is not responding

@JohnNikolay84
JohnNikolay84 merged commit 0e072ca into main Nov 4, 2026
@JohnNikolay84
JohnNikolay84 deleted the feature/fmoe-q256-prefill branch November 4, 2026 09:45
yuychang added a commit to yuychang/aiter that referenced this pull request Nov 5, 2026
- Resolve fused_moe.py conflict: keep the presort-ignored check and main's AsmMoeMode (ROCm#5988) line
- No presort interaction with ROCm#7294: use_valid_token_count needs num_local_tokens, which disables the presort
ZhiweiYan-96 added a commit that referenced this pull request Nov 9, 2026
Keep both sides of qwen3_5_397b_fp4_tuned_fmoe.csv: this branch's TP4
(513, 4096, 256, 11) decode rows for M=1..64 and main's (#5988) rows for
M=8192..32768. No key is duplicated.
shantipriya-amd pushed a commit to shantipriya-amd/aiter that referenced this pull request Nov 18, 2026
)

* Add gfx950 Q256 fused MXFP4 prefill pipeline

Integrate the universal assembly producer and supplied Triton route reducer through AITER with guarded dispatch and an opt-in configuration. Preserve the public fused_moe API and reuse the Opus inverse route map.

Validated on gfx950 at 8k, 16k, and 32k tokens with 512 routed experts plus a shared expert, including graph replay, independent producer launch checks, and comparison with the FlyDSL pipeline.

* Use compact hybrid Q256 contributions with shared FlyDSL reduction

* Fix Ruff and Black checks for compact Q256 integration

* Fix Q256 scheduling at shifted shared-expert boundaries

* Use weighted M128 scheduling for Qwen Q256 prefill

Install the matching weighted M128 producer and GPU routing planner from the 2026-10-16 PyISA package. Pass its 1024-entry map at ABI offset 128 and select it directly for compact Qwen 8K geometry, retaining the shared FlyDSL reducer.

Validated on SMCI355 gfx950 PCI 0000:05:00.0: exact compact/sorted contributions; reference NRMS 0.00273150; graph/eager, prequantized and caller-output parity; weighted/map profile confirmed. Full-API graph median 1156.51 us (7 x 50 replays). CPU contracts and ABI assertions passed.

* Select weighted Q256 producer explicitly from config

Name the weighted producer in the validated Qwen 8K/D8192 CSV row and carry kernelName through Q256 dispatch. Retain compact producer selection for the other rows and reject unsupported weighted geometry. Record the selected kernel in the existing integration test.

SMCI355 gfx950 PCI 0000:15:00.0: exact compact/sorted contributions, reference NRMS 0.00273150, graph/eager/prequantized/output parity, and all 20 config collision checks passed. Full-API median 1125.49 us. Kernel trace evidence incomplete: PyTorch trace had no kernel events; rocprof capture blocked by competing KFD process.

* Constrain Q256 scheduler to production ABI and add coverage

Preserve the M128 production map while removing unused scheduling options. Add a category wrapper, trace representation, independent CPU/GPU tests and a preallocated-output benchmark.

Validated on gfx950: 7 tests and 55 subtests pass; all 12 benchmark cases match the independent oracle.

* Fix Q256 dispatch boundaries and recover shared-route prefill performance

Move scratch allocation and producer/reducer orchestration below shared MoE dispatch. Keep semantic guards in Python, validate tensor contracts in the CU launcher, and remove the unused sorted-output path.

Consolidate model configurations and replace the broken standalone harness with shared-expert, random-control, boundary, graph replay and independent-reference coverage. Retain explicit weighted selection and limit streaming reduction to the exact 8K Qwen shape.

Validated on gfx950 with FlyDSL 0.4.0: six shared shapes, random control, five token boundaries and 26 config checks pass. Captured routes with synthetic activations and weights improve full-API latency by 7.84%, 6.35% and 5.40% versus main across seven rounds of 50 graph replays.

* Remove internal Q256 notes and unused sorted-output code object

Retain only the compact and weighted producers selected by the current launcher.

* Simplify Q256 tests and restore the generic MoE harness

Restore the existing single-candidate timing and sweep behavior. Consolidate Q256 case setup, expected-error checks and scheduler GPU fixtures while retaining shared/random routing, token boundaries, graph replay, producer selection and independent numerical checks.

Validated on gfx950: all 12 Q256 cases, 7 scheduler tests and 55 subtests, and the normal CLI startup pass. Full configured Ruff 0.16.0 and Black checks pass without new suppressions.

* Enforce Q256 sorting layout and preserve automatic dispatch fallback

Validate the effective block_size_M before sorting. Discard incompatible automatic Q256 configurations before backend selection, while retaining rejection for incompatible dedicated configurations and preserving prequantized A1 support.

Honor FP8 intermediates in the two-stage fallback. Add unmocked public-dispatch regressions for incompatible block overrides, FP8 intermediates and supplied A2 scales, including profiler and independent-reference checks.

Validated on gfx950: all 12 existing Q256 cases, both override-before-sort checks, both two-stage fallback checks and four CLI startup regressions pass. Full Ruff 0.16.0 and Black checks pass.

* Potential fix for pull request finding 'Reject interleaved weights before selecting Q256'

Co-authored-by: Copilot Autofix powered by AI <[email protected]>

* Require shuffled Q256 projections and restore MoE test device state

Use the normalized both-projection shuffle flag for Q256 eligibility while preserving the interleaving guard and legacy metadata fallback. Cover either missing projection tag through real two-stage dispatch.

Scope GPU test entry points so they restore the caller default device on success and exceptions without changing benchmark argument logging.

Validated on gfx950 with fresh native caches: all 12 Q256 cases, four fallback cases and device-state regressions pass. Full Ruff 0.16.0 and Black checks pass.

* Preserve default FlyDSL MoE reduction load constructors

Keep the original no-argument BufferCopy64b and BufferCopy128b constructors when streaming is disabled. Apply the explicit non-temporal policy only to the streaming variant.

Validated on gfx950 with the existing FP8 masked-reduction test and the configured MoE shape sweep.

* Move Q256 scheduler fixtures into test utilities

Share the independent CPU inputs and oracle through test utilities instead of importing a test module from the benchmark. Remove the unittest script entry point and keep pytest coverage unchanged.

Validated on gfx950: all 7 tests and 55 subtests pass, and the benchmark matches the oracle for both selected cases.

* Simplify Q256 launcher plumbing and complete script-driven coverage

Remove unused reverse-sort forwarding and native validation while retaining the shared sorting contract and producer argument layout. Clarify output allocation and separate compact constraints from weighted geometry.

Reuse the kernel-name constant and run random-route and device-state checks from the script entry point. Keep the existing model-table selection, configuration override and scale handling.

Validated the actual gfx950 script entry with six shared shapes, random routing, five boundaries and four real fallbacks. The producer argument block remains 448 bytes and the code objects are unchanged. Ruff and Black pass; the exact MI300X linear-attention comparison remains pending access to its failure log.

* Rename Q256 fused experts and align assembly kernel names

Replace the producer entry point with fmoe_q256_fused_experts and use a new JIT module namespace. Align compact and weighted ELF exports, metadata, code-object filenames and model selectors with the fmoe naming family.

Keep the existing selector spellings as compatibility aliases for AITER_CONFIG_FMOE overrides. Update tests and diagnostics to use the fused-expert names.

Both code objects preserve their exact machine-code bytes, 448-byte kernel arguments and resource settings. Verified canonical HIP lookups, fresh native exports, all 12 Q256 cases, four fallback cases and both legacy selectors on gfx950. Ruff and Black pass; unrelated SwiGLU startup comparison warnings reproduce on the pre-rename head.

* Use standard FMoE launcher and drop weighted Q256 scheduling

Launch the self-contained compact producer through the existing assembly manifest and reduce token/top-k partials with FlyDSL. Remove the Triton job-map planner, custom Q256 launcher, weighted code object and pre-merge selector aliases.

The in-kernel scheduler matched all 81,920 diagnostic slots but was 6.16% slower than compact on the exact 8K shared-expert shape. Final gfx950 correctness passed six configured shapes, random routes and token boundaries; maximum NRMS was 0.00017653. Config collision, Ruff and Black checks passed.

* Limit Q256 config changes and inline kernel selection

Restore the existing Qwen CSV schema and unrelated rows so its PR diff contains only the three prefill selections. Compare the canonical kernel name directly in fused_moe and remove the separate moe_op helper.

Config collision guard passes all 30 tests; Ruff, Black and syntax checks pass.

* Compute Q256 weighted schedules inside assembly

Rebuild the weighted producer with wave-local key exchanges, one cross-wave LDS exchange and four register-cached jobs shared by dispatch and prefetch. The standard FMoE launcher passes no job map, and the kernel never reads the smoothing-scale pointer.

Select weighted M128 scheduling for qualifying routed boundaries 576 through 960; retain the compact M32/M64 path for smaller layouts, invalid suffixes and over-capacity schedules. Keep direct dispatch checks and the three-row CSV diff.

Validated 113 policy cases and 115712 slots with zero mismatches, production Q256 integration and forced larger-token fallback. Captured routes 029/046/049 improve 6.6-9.5% against compact and 3.1-7.2% against FlyDSL. The matched-allocation timing follow-up remains blocked by GPU availability.

* Store weighted Q256 code object without executable permissions

* Clarify ASM route-partial dispatch and populate tuned timings

Adapt the PR style patch to both compact and assembly-weighted producers. Select the partial-output branch before the generic G1U1 branch, enforce its tile size locally, and simplify equivalent FlyDSL copy constructors.

Populate the six existing prefill rows from validated timing receipts without changing CSV schemas or unrelated rows. Retain tested eligibility, FP8 fallback, reference and import-safe test contracts.

Validated 30 config collision tests, 22 old/new host-call cases, eight installed FlyDSL copy-type comparisons, Ruff and Black. Assembly code objects are unchanged.

* Select ASM post-reduction through manifest mode 3

Use the flat column to distinguish sorted, no_sort, emsort and sorted post-reduction producers. Replace kernel-name classification with mode checks, preserve host sorting and standard launch geometry for mode 3, and update model and assembly manifests.

Keep post-reduction entries out of the direct-output tuner and account for sorting according to mode. Cover all four sorting/output modes with CPU tests.

Validated 30 config tests, both CPU mode tests, 12 Q256 integration/profile checks, four emsort rows and ten no-sort rows on gfx950. Assembly code objects are unchanged.

* Use named ASM MoE modes and canonical sorting semantics

Define AsmMoeMode with the existing CSV values and a requires_host_sort property. Normalize numeric modes at dispatch boundaries, derive tuner mode groups from the enum, and use matching named constants in the C++ launcher.

Preserve numeric CSV serialization and legacy boolean inputs. Three CPU mode tests, 30 config tests, codegen contracts, Ruff, Black and fresh standard ASM compilation pass. GPU revalidation was blocked by device activity; assembly code objects are unchanged.

* Remove Q256 test scaffolding and use ordinary route sorting

Return the op test to its normal CSV sweep with only post-reduction row selection and settings. Remove producer mocks, profiler assertions, model-specific suites and pytest-only mode tests.

Use the standard 256-row Opus sort without auxiliary indices, remove the one-stage atomic detour and has_a2_scale plumbing, and retain only weight-layout eligibility. Zero partials when filtering can leave route slots unwritten.

Validated all six configured shapes through the real script, exact captured-route outputs, local-token graph replay and masked local-expert mapping. Captured routes improve 8.61%, 5.88% and 5.40% versus FlyDSL; config, Ruff and Black checks pass.

* Skip output zero-fill for ASM post-reduction

Give the sort an empty buffer and let the reducer overwrite the final output, including masked rows. Revert the unrelated FP8 fallback changes.

* Tune ASM post-reduction producer and reducer together

Include POST_REDUCE candidates with shuffled MXFP4 inputs and report their combined cost as us1 without an extra intermediate quantization charge. Reset merged candidate indices so winner selection emits one valid CSV row.

* Format POST_REDUCE tuner conditionals

* Refresh ASM post-reduction tuning timings

Use measured producer-plus-reducer costs for each configured kernel and explicitly record zero stage-two cost. Keep the weighted 8K row matched to its own measurement.

---------

Co-authored-by: Copilot Autofix powered by AI <[email protected]>
zufayu pushed a commit to qli88/aiter that referenced this pull request Nov 19, 2026
Add the problem/plan/segment framework to aiter/moev2 and move the first
fused_moe path onto it. Per-tensor fp8 2-stage fused_moe calls run through
aiter.moev2 only when enabled with AITER_MOEV2=a8w8_pt (or on). This covers
the CK default heuristic, tuned CK and ASM rows, and FlyDSL gfx942
whole-graph rows. The path is not graduated: by default every call still
runs the legacy code.

Behavior claim:
- Legacy dispatch is unchanged. Every existing record of the CPU dispatch
  snapshot of legacy fused_moe is identical on gfx942, gfx942_cu80, gfx950
  and gfx1201. The snapshot gains feature-variant keys (see Tests), and
  the regenerated files are byte-identical to ones generated with the
  upstream base's aiter package.
- When a8w8_pt runs a call in v2, it launches the same kernels with the
  same parameters and inputs as legacy. It also prints the same log lines,
  raises the same exceptions (including legacy's RuntimeError for
  unshuffled fp8 CK weights on gfx950), and gives the same outputs, within
  legacy's own run-to-run noise (see Tests).
- With AITER_MOEV2 unset or off, every call runs the legacy code.
  AITER_MOEV2=a8w8_pt (or on) enables the path.
- The path declines calls it does not reproduce, and they run on the legacy
  code. These are herd_topk, deterministic=True, a presort registered with
  register_presorted_moe, swiglu_limit, beta or linear_beta, bias, padding,
  scatter, caller-chosen activation dtypes, and AITER_ONLINE_TUNE.
- The path also declines a call whose second lookup it cannot reproduce.
  After sorting, fused_moe_2stages looks the key up again, on the
  hidden_states rows and without the activation-scales, num_local_tokens
  and scatter flags. _fused_moe_impl's _metadata_transform then puts the
  first lookup's result back, so the second lookup only logs, but it can
  raise. v2 resolves it before emitting anything, and declines when it
  raises (legacy raises after the sort) or when v2 declines it (v2 could
  not emit its lines). Example: gfx950, unshuffled fp8, 2 topk_ids rows
  and 3 hidden_states rows, where the 2-token row is ASM stage 1 + CK
  stage 2 with no kernelName2 and the 4-token row is a tuned CK row: the
  second lookup raises the gfx950 shuffle error.

What changed:
- aiter/moev2 adds:
  - problem.py: MoeProblem, which round-trips the legacy get_2stage_cfgs key;
  - dispatch/{ops,buf,plan,kernel_names,tuned,resolver,overrides,ranking,
    profile};
  - segments/{base,sort,quant,ck,asm,whole_graph,defaults};
  - execute/{executor,metadata,output};
  - migration/a8w8_pt.py: claims, declines and path registration.
- aiter/moev2/README.md: describes the new files (purpose, permanent or
  removed after the migration) and how a call flows through a path.
- Moved from fused_moe.py and imported back under the same names. Each
  definition is AST-identical to the current one it replaces:
  - execute/output.py: _validate_output_buffer_metadata,
    _validate_output_buffer_no_overlap, _return_output;
  - execute/metadata.py: MOEMetadata, and AsmMoeMode (the type of its flat
    field);
  - shapes.py: nextPow2, _PADDED_M_TIERS, get_padded_M, _is_row_major_2d;
  - policy.py: _normalize_mxfp4_activation_params;
  - segments/asm.py: asm_stage1;
  - segments/ck.py: ck_moe_stage1, _require_shuffled_gfx950_fp8;
  - segments/defaults.py: BLOCK_SIZE_M, get_block_size_M, get_ksplit,
    use_nt;
  - dispatch/tuned.py: _ACT_TYPE_DISABLED_KEY, plus the tuned-table
    reader. fused_moe.py's get_cfg_2stages(tune_file, tag=None) calls it
    with the swiglu_limit tag filter unchanged.
- v2 mirrors the legacy changes made upstream after this work branched.
  They change code that v2 copies rather than calls, so they raised no
  merge conflicts:
  - ROCm#6736 (gfx950 fp8 CK needs shuffled weights): the resolver raises
    legacy's RuntimeError at the same two points as get_2stage_cfgs. A
    tuned CK 2-stage row raises before any log line. The default CK
    2-stage plan raises after the "run_1stage = ..." and "using 2stage
    default" lines, which v2 also logs first.
  - ROCm#7500 (row-strided activations): the executor copies hidden_states
    that is neither contiguous nor row-major before it checks the output
    buffer for overlap, and copies any other non-contiguous hidden_states
    before sorting, as legacy does.
  - ROCm#6926 (zero a2 before dynamic per-tensor quant): with per-tensor
    quant and no a2_scale, the stage 1 output is zeroed, so the a2 scale
    ignores slots stage 1 never writes (padding rows, non-local experts).
  - ROCm#5988 (gfx950 fused MXFP4 prefill): the resolver declines tuned rows
    with flat=POST_REDUCE. Only MXFP4 rows use it today, so no a8w8_pt
    key is affected.
- The legacy key now carries _exclude_mxmoe and
  _has_input_activation_scales.
  - _exclude_mxmoe becomes the problem extra exclude_mxmoe. No segment
    accepts that extra, so v2 declines such calls.
  - _has_input_activation_scales becomes the feature a1_scale, which the
    sort, quant and CK segments accept.
- aiter.moev2.fused_moe (v2's own entry point) clears a registered presort
  when the call returns or raises, as legacy fused_moe does with
  drop_presort_after.
- kernel_names parses the bare ASM symbols that tuned tables now carry
  (fmoe_..._ps_fp32gate_route), alongside the _ZN5aiter...E names.
- api.op_call passes splitk, herd_topk, herd_routed_scaling_factor and
  deterministic to fused_moe_, matching the legacy fused_moe.
- dispatch/ranking.py holds the default ranking table as entries and
  regions:
  - an entry matches by set membership on problem fields;
  - a region is an integer threshold on named scalars, and lists its
    structures best first.
  The checks that fail CI are:
  - overlapping entries or regions, or contradictory regions;
  - unknown or non-adjacent segments;
  - a last structure whose feasibility depends on the shape;
  - over the snapshot key grid (ranking_checks.py): a rankable key that
    does not land in exactly one entry and region with a feasible last
    structure, or a region that no key reaches.
- Paths:
  - graduated may be a set of archs;
  - the entry is "api" (top of fused_moe) or "op" (inside the fused_moe_
    custom op);
  - DECLINED hands the call back to legacy;
  - the api hook is skipped while torch.compile traces.
- Tuned tables: v2 reads the default table through legacy's cfg_2stages
  global. get_2stage_cfgs.cache_clear(), used by the CK tuner and tests,
  also clears v2's caches.
- Tests:
  - new: tests/test_moev2_dispatch.py, test_moev2_ranking.py,
    key_checks.py (problem/legacy key round trip; the tuned lookup returns
    legacy's row), ranking_checks.py, gpu_differential.py;
  - test_moev2_dispatch.py covers each mirrored change: the gfx950 raise
    (same message and log lines as legacy, for a default and a tuned CK
    row), both hidden_states copies, the a2 zero-fill, and the
    POST_REDUCE decline. It also covers the second lookup: one that raises
    or that v2 declines makes the call decline with no log line and no
    sort, and one that selects another plan still runs the first plan;
  - test_moev2_switch.py: v2's fused_moe drops a registered presort when
    it raises;
  - keys.py adds feature variants for the quant types in
    FEATURE_QUANT_TYPES (per_Tensor for now; each later path adds its
    own). Each base tuned and grid key gets 20 variants, the same call with
    one more get_2stage_cfgs feature: num_local_tokens, activation scales
    (with and without input scales), fp8 input with and without scales,
    scatter, unshuffled and half-shuffled weights, stage 1 or stage 2
    bias, gate interleave, gate_up_interleave, swiglu_limit 0.0 and 7.0,
    _exclude_mxmoe, q_dtype_a2, doweight_stage1, Gelu, no g1u1, and
    padding. A changed decision for one of these calls now shows up as
    its own key in the snapshot, differential, key and ranking checks.
    The golden files are regenerated with them (about 13,000-17,000 new
    keys per arch). A unit test binds every variant to the
    get_2stage_cfgs signature, so a typo cannot become an error record;
  - gpu_suites.py adds op_tests/test_moe_per_tensor_a2_init.py (from
    ROCm#6926) to the a8w8_pt suites;
  - the switch and differential tests are extended;
  - tests that read the aiter logger through caplog turn on its
    propagation, since pytest's caplog listens on the root logger;
  - the perf golden gains a dsv3_tp8_pt case.

Known differences and limits:
- swiglu_limit=0.0, which vLLM sends for "no limit", is declined like any
  other swiglu_limit value, so those calls stay on the legacy code.
- v2's per-shape caches are LRU and evict only beyond 2048 distinct
  shapes.
- The a8w8_pt ASM and whole-graph branches are verified only by the CPU
  differential. Their tuned rows are gfx942-only, and no gfx942 was
  available.
- Legacy nondeterminism found while building the GPU gate:
  - CK stage2 accumulates with atomics, so the gate compares outputs within
    a tolerance based on legacy-vs-legacy noise.
  - Some ASM stage1 kernels are not repeatable. This is a legacy bug, and
    the gate does not excuse it: a case that hits it fails.
- test_moe_2stage -q 1 reports 28 failed checks (the swiglu limit cases),
  test_moe_ep 2 and test_moe_dp_share_expert 13. They fail the same way
  with AITER_MOEV2 off and on, and in the upstream tree without this
  work.

Tests:
- CPU: tests/test_moev2_*.py and test_moe_dispatch_snapshot.py, 89 passed.
- CPU gates, on all 4 archs, 0 problems:
  - differential.py: 22,087 claimed keys (3,885 without the feature
    variants);
  - key_checks.py: 107,572 keys, 17,149 tuned rows;
  - ranking_checks.py: 29,424 ranked keys.
- With the second-lookup check disabled, both of its decline tests fail.
- With v2's gfx950 shuffle raise disabled, the differential reports 1,088
  problems on gfx950, all in the new grid unshuffled and half-shuffled
  keys. The keys without feature variants catch none of them, since
  gfx950 has no per-tensor tuned rows.
- GPU differential, gfx950, all with 0 problems (rerun after the
  second-lookup check, which declines none of these cases):
  - 15 default cases;
  - 63 cases against a synthetic CK tuned table;
  - the default cases with AITER_USE_NT=1 and again with
    AITER_BYPASS_TUNE_CONFIG=1.
- GPU suites, AITER_MOEV2=off vs a8w8_pt, with tabulate installed:
  test_moe_2stage -q 1, test_moe_per_tensor_a2_init, test_moe_sorting,
  test_moe_ep, test_moe_local_expert_ids, test_moe_dp_share_expert. Same
  exit codes and the same outcome for every check in both modes.
  AITER_MOE_EXPLAIN=1 shows v2 resolving the per-tensor calls of
  test_moe_2stage and test_moe_per_tensor_a2_init; the other four make no
  per-tensor fp8 fused_moe call. With v2's a2 zero-fill disabled, all 4
  cases of test_moe_per_tensor_a2_init fail in a8w8_pt mode. After the
  second-lookup check, test_moe_per_tensor_a2_init passes again in
  a8w8_pt mode, with v2 selecting a plan for all 4 cases.
- GPU legacy check: op_tests/test_moe_2stage.py small cases (-t 1 16 256,
  each of the 10 quant types), every fused_moe output captured, upstream
  base (db3b870) vs this commit, same JIT build, seeded inputs
  (identical in both):
  - 8410 calls; the 170 deterministic calls are bit-identical;
  - the other 8240 vary run to run in the upstream base too;
  - for quant types 1 and 4, three runs of each tree put the mean
    distance between trees at 0.997 and 1.003 of that between runs;
  - one quant type 4 call stood apart in three runs (1.55); six fresh
    runs of each tree put it at 1.10, with no call apart and a mean of
    1.003.
- perf_gfx950.json: dsv3_tp8_pt was recorded on one idle MI355 (gfx950
  cu256). --check of all cases passes right after. The same case with
  AITER_MOEV2=a8w8_pt is within 2.2% of legacy at every token count, with
  mixed signs (mean of two runs per mode).
- black and ruff (0.16.0) clean.

Co-authored-by: Cursor <[email protected]>
zufayu added a commit that referenced this pull request Nov 25, 2026
…the per-tensor fp8 path (not graduated) (#8255)

* [MoE] moev2 phase 0/1: scaffolding, legacy-parity harness, move leaf helpers (no behavior change)

Introduce aiter/moev2, which will coexist with aiter/fused_moe.py while
fused_moe paths move over one at a time. No path is registered yet, so
every call still runs exactly the legacy code.

Behavior claim:
- No behavior change. Every fused_moe call runs the legacy code, with or
  without AITER_MOEV2.

What changed:
- aiter/fused_moe.py: the helpers below move to aiter/moev2 and are imported
  back, so every name that code and tests import from aiter.fused_moe still
  resolves (36 names checked). fused_moe() gains a switch hook that does
  nothing while no moev2 path is registered; _fused_moe_impl passes
  gfx=get_gfx_runtime() to resolve_activation_dtype, the default it already
  used.
- Moved from fused_moe.py, each definition AST-identical to the one it
  replaces:
  - policy.py: resolve_activation_dtype, quant_remap, _bound_split,
    _SWIGLU_MXFP4_BF16_BOUND;
  - shapes.py: get_inter_dim;
  - routing/topk.py: fused_topk;
  - reference/torch_moe.py: the torch reference (torch_moe, torch_moe_act,
    torch_moe_stage1, torch_moe_stage2, swiglu, situv2,
    _clamp_swiglu_gate_up) and the per-1x32 dequant helpers. It imports the
    SiLU-limit helpers from aiter.ops.moe_limits.
- aiter/moev2/README.md: what each moev2 package file and test file is for,
  and whether it is permanent or removed after the migration.
- aiter/moev2 scaffolding: AITER_MOEV2 switch (envs.py), path registry
  (paths.py, empty), v2 entry point with the legacy signature (api.py, up to
  herd_topk, herd_routed_scaling_factor and deterministic), test hooks
  (hooks.py), dispatch cache helper (dispatch/tuned.py).
- tests/moe_dispatch (lock in legacy behavior): public-name inventory, CPU
  arch simulation, a legacy dispatch snapshot, a GPU suite list per planned
  path, and a perf baseline script. Goldens:
  - dispatch snapshot for gfx942 (13135 keys), gfx942_cu80 (16108), gfx950
    (19307) and gfx1201 (12628), read from a frozen copy of the merged
    tuned_fmoe.csv and tuned_fhmoe.csv (golden/inputs);
  - perf_gfx950.json: 9 model cases x 7 token counts, one idle MI355.
    Case shapes are the sizes vLLM passes to aiter: GPT-OSS dims are padded
    2880 -> 3072 on ROCm MXFP4, and Qwen3-235B FP8 block scale runs at TP4
    (its TP8 inter_dim 192 is not a multiple of 128). The default --check
    tolerance is 10%: unchanged code drifted up to 8% at small M on gfx950.
- Tests: moev2 must not import legacy MoE modules; switch parsing and
  routing; signature parity; hooks; a differential harness that requires v2
  to make the same choice as legacy for every key it claims; the dispatch
  snapshot. The warning test turns on propagation for the aiter logger,
  which does not propagate, since pytest's caplog listens on the root logger.

Known differences and limits:
- None in behavior. The perf golden is a measurement: --check compares
  against it with a tolerance, on an idle GPU.

Tests:
- CPU: test_moev2_imports, test_moev2_hooks, test_moev2_switch,
  test_moev2_differential, test_moe_dispatch_snapshot: 24 passed, 1 skipped.
- Dispatch snapshot recorded from the parent commit and from this commit,
  same recorder and frozen inputs: byte-identical on all 4 archs.
- GPU, gfx950: op_tests/test_moe_2stage.py small cases (-t 1 16 256, each
  of the 10 quant types, with its fixed tests), every fused_moe output
  captured, parent commit vs this commit, same JIT build, seeded inputs
  (identical in both): 8410 calls. The 170 calls that are deterministic are
  bit-identical. The other 8240 vary run to run in the parent commit too
  (1-2 bf16 ULP, accumulation order); for quant types 1 and 4, three runs
  of each commit put the mean distance between the two commits at 0.98 and
  1.00 of that between runs of the parent commit (at most 1.25 on any call).
- perf_gfx950.json recorded on one idle MI355 (gfx950 cu256); a --check
  right after passes (10% tolerance).
- black and ruff (0.16.0) clean.

Co-authored-by: Cursor <[email protected]>

* [MoE] moev2 phase 2: per-tensor fp8 (a8w8_pt) path (not graduated)

Add the problem/plan/segment framework to aiter/moev2 and move the first
fused_moe path onto it. Per-tensor fp8 2-stage fused_moe calls run through
aiter.moev2 only when enabled with AITER_MOEV2=a8w8_pt (or on). This covers
the CK default heuristic, tuned CK and ASM rows, and FlyDSL gfx942
whole-graph rows. The path is not graduated: by default every call still
runs the legacy code.

Behavior claim:
- Legacy dispatch is unchanged. Every existing record of the CPU dispatch
  snapshot of legacy fused_moe is identical on gfx942, gfx942_cu80, gfx950
  and gfx1201. The snapshot gains feature-variant keys (see Tests), and
  the regenerated files are byte-identical to ones generated with the
  upstream base's aiter package.
- When a8w8_pt runs a call in v2, it launches the same kernels with the
  same parameters and inputs as legacy. It also prints the same log lines,
  raises the same exceptions (including legacy's RuntimeError for
  unshuffled fp8 CK weights on gfx950), and gives the same outputs, within
  legacy's own run-to-run noise (see Tests).
- With AITER_MOEV2 unset or off, every call runs the legacy code.
  AITER_MOEV2=a8w8_pt (or on) enables the path.
- The path declines calls it does not reproduce, and they run on the legacy
  code. These are herd_topk, deterministic=True, a presort registered with
  register_presorted_moe, swiglu_limit, beta or linear_beta, bias, padding,
  scatter, caller-chosen activation dtypes, and AITER_ONLINE_TUNE.
- The path also declines a call whose second lookup it cannot reproduce.
  After sorting, fused_moe_2stages looks the key up again, on the
  hidden_states rows and without the activation-scales, num_local_tokens
  and scatter flags. _fused_moe_impl's _metadata_transform then puts the
  first lookup's result back, so the second lookup only logs, but it can
  raise. v2 resolves it before emitting anything, and declines when it
  raises (legacy raises after the sort) or when v2 declines it (v2 could
  not emit its lines). Example: gfx950, unshuffled fp8, 2 topk_ids rows
  and 3 hidden_states rows, where the 2-token row is ASM stage 1 + CK
  stage 2 with no kernelName2 and the 4-token row is a tuned CK row: the
  second lookup raises the gfx950 shuffle error.

What changed:
- aiter/moev2 adds:
  - problem.py: MoeProblem, which round-trips the legacy get_2stage_cfgs key;
  - dispatch/{ops,buf,plan,kernel_names,tuned,resolver,overrides,ranking,
    profile};
  - segments/{base,sort,quant,ck,asm,whole_graph,defaults};
  - execute/{executor,metadata,output};
  - migration/a8w8_pt.py: claims, declines and path registration.
- aiter/moev2/README.md: describes the new files (purpose, permanent or
  removed after the migration) and how a call flows through a path.
- Moved from fused_moe.py and imported back under the same names. Each
  definition is AST-identical to the current one it replaces:
  - execute/output.py: _validate_output_buffer_metadata,
    _validate_output_buffer_no_overlap, _return_output;
  - execute/metadata.py: MOEMetadata, and AsmMoeMode (the type of its flat
    field);
  - shapes.py: nextPow2, _PADDED_M_TIERS, get_padded_M, _is_row_major_2d;
  - policy.py: _normalize_mxfp4_activation_params;
  - segments/asm.py: asm_stage1;
  - segments/ck.py: ck_moe_stage1, _require_shuffled_gfx950_fp8;
  - segments/defaults.py: BLOCK_SIZE_M, get_block_size_M, get_ksplit,
    use_nt;
  - dispatch/tuned.py: _ACT_TYPE_DISABLED_KEY, plus the tuned-table
    reader. fused_moe.py's get_cfg_2stages(tune_file, tag=None) calls it
    with the swiglu_limit tag filter unchanged.
- v2 mirrors the legacy changes made upstream after this work branched.
  They change code that v2 copies rather than calls, so they raised no
  merge conflicts:
  - #6736 (gfx950 fp8 CK needs shuffled weights): the resolver raises
    legacy's RuntimeError at the same two points as get_2stage_cfgs. A
    tuned CK 2-stage row raises before any log line. The default CK
    2-stage plan raises after the "run_1stage = ..." and "using 2stage
    default" lines, which v2 also logs first.
  - #7500 (row-strided activations): the executor copies hidden_states
    that is neither contiguous nor row-major before it checks the output
    buffer for overlap, and copies any other non-contiguous hidden_states
    before sorting, as legacy does.
  - #6926 (zero a2 before dynamic per-tensor quant): with per-tensor
    quant and no a2_scale, the stage 1 output is zeroed, so the a2 scale
    ignores slots stage 1 never writes (padding rows, non-local experts).
  - #5988 (gfx950 fused MXFP4 prefill): the resolver declines tuned rows
    with flat=POST_REDUCE. Only MXFP4 rows use it today, so no a8w8_pt
    key is affected.
- The legacy key now carries _exclude_mxmoe and
  _has_input_activation_scales.
  - _exclude_mxmoe becomes the problem extra exclude_mxmoe. No segment
    accepts that extra, so v2 declines such calls.
  - _has_input_activation_scales becomes the feature a1_scale, which the
    sort, quant and CK segments accept.
- aiter.moev2.fused_moe (v2's own entry point) clears a registered presort
  when the call returns or raises, as legacy fused_moe does with
  drop_presort_after.
- kernel_names parses the bare ASM symbols that tuned tables now carry
  (fmoe_..._ps_fp32gate_route), alongside the _ZN5aiter...E names.
- api.op_call passes splitk, herd_topk, herd_routed_scaling_factor and
  deterministic to fused_moe_, matching the legacy fused_moe.
- dispatch/ranking.py holds the default ranking table as entries and
  regions:
  - an entry matches by set membership on problem fields;
  - a region is an integer threshold on named scalars, and lists its
    structures best first.
  The checks that fail CI are:
  - overlapping entries or regions, or contradictory regions;
  - unknown or non-adjacent segments;
  - a last structure whose feasibility depends on the shape;
  - over the snapshot key grid (ranking_checks.py): a rankable key that
    does not land in exactly one entry and region with a feasible last
    structure, or a region that no key reaches.
- Paths:
  - graduated may be a set of archs;
  - the entry is "api" (top of fused_moe) or "op" (inside the fused_moe_
    custom op);
  - DECLINED hands the call back to legacy;
  - the api hook is skipped while torch.compile traces.
- Tuned tables: v2 reads the default table through legacy's cfg_2stages
  global. get_2stage_cfgs.cache_clear(), used by the CK tuner and tests,
  also clears v2's caches.
- Tests:
  - new: tests/test_moev2_dispatch.py, test_moev2_ranking.py,
    key_checks.py (problem/legacy key round trip; the tuned lookup returns
    legacy's row), ranking_checks.py, gpu_differential.py;
  - test_moev2_dispatch.py covers each mirrored change: the gfx950 raise
    (same message and log lines as legacy, for a default and a tuned CK
    row), both hidden_states copies, the a2 zero-fill, and the
    POST_REDUCE decline. It also covers the second lookup: one that raises
    or that v2 declines makes the call decline with no log line and no
    sort, and one that selects another plan still runs the first plan;
  - test_moev2_switch.py: v2's fused_moe drops a registered presort when
    it raises;
  - keys.py adds feature variants for the quant types in
    FEATURE_QUANT_TYPES (per_Tensor for now; each later path adds its
    own). Each base tuned and grid key gets 20 variants, the same call with
    one more get_2stage_cfgs feature: num_local_tokens, activation scales
    (with and without input scales), fp8 input with and without scales,
    scatter, unshuffled and half-shuffled weights, stage 1 or stage 2
    bias, gate interleave, gate_up_interleave, swiglu_limit 0.0 and 7.0,
    _exclude_mxmoe, q_dtype_a2, doweight_stage1, Gelu, no g1u1, and
    padding. A changed decision for one of these calls now shows up as
    its own key in the snapshot, differential, key and ranking checks.
    The golden files are regenerated with them (about 13,000-17,000 new
    keys per arch). A unit test binds every variant to the
    get_2stage_cfgs signature, so a typo cannot become an error record;
  - gpu_suites.py adds op_tests/test_moe_per_tensor_a2_init.py (from
    #6926) to the a8w8_pt suites;
  - the switch and differential tests are extended;
  - tests that read the aiter logger through caplog turn on its
    propagation, since pytest's caplog listens on the root logger;
  - the perf golden gains a dsv3_tp8_pt case.

Known differences and limits:
- swiglu_limit=0.0, which vLLM sends for "no limit", is declined like any
  other swiglu_limit value, so those calls stay on the legacy code.
- v2's per-shape caches are LRU and evict only beyond 2048 distinct
  shapes.
- The a8w8_pt ASM and whole-graph branches are verified only by the CPU
  differential. Their tuned rows are gfx942-only, and no gfx942 was
  available.
- Legacy nondeterminism found while building the GPU gate:
  - CK stage2 accumulates with atomics, so the gate compares outputs within
    a tolerance based on legacy-vs-legacy noise.
  - Some ASM stage1 kernels are not repeatable. This is a legacy bug, and
    the gate does not excuse it: a case that hits it fails.
- test_moe_2stage -q 1 reports 28 failed checks (the swiglu limit cases),
  test_moe_ep 2 and test_moe_dp_share_expert 13. They fail the same way
  with AITER_MOEV2 off and on, and in the upstream tree without this
  work.

Tests:
- CPU: tests/test_moev2_*.py and test_moe_dispatch_snapshot.py, 89 passed.
- CPU gates, on all 4 archs, 0 problems:
  - differential.py: 22,087 claimed keys (3,885 without the feature
    variants);
  - key_checks.py: 107,572 keys, 17,149 tuned rows;
  - ranking_checks.py: 29,424 ranked keys.
- With the second-lookup check disabled, both of its decline tests fail.
- With v2's gfx950 shuffle raise disabled, the differential reports 1,088
  problems on gfx950, all in the new grid unshuffled and half-shuffled
  keys. The keys without feature variants catch none of them, since
  gfx950 has no per-tensor tuned rows.
- GPU differential, gfx950, all with 0 problems (rerun after the
  second-lookup check, which declines none of these cases):
  - 15 default cases;
  - 63 cases against a synthetic CK tuned table;
  - the default cases with AITER_USE_NT=1 and again with
    AITER_BYPASS_TUNE_CONFIG=1.
- GPU suites, AITER_MOEV2=off vs a8w8_pt, with tabulate installed:
  test_moe_2stage -q 1, test_moe_per_tensor_a2_init, test_moe_sorting,
  test_moe_ep, test_moe_local_expert_ids, test_moe_dp_share_expert. Same
  exit codes and the same outcome for every check in both modes.
  AITER_MOE_EXPLAIN=1 shows v2 resolving the per-tensor calls of
  test_moe_2stage and test_moe_per_tensor_a2_init; the other four make no
  per-tensor fp8 fused_moe call. With v2's a2 zero-fill disabled, all 4
  cases of test_moe_per_tensor_a2_init fail in a8w8_pt mode. After the
  second-lookup check, test_moe_per_tensor_a2_init passes again in
  a8w8_pt mode, with v2 selecting a plan for all 4 cases.
- GPU legacy check: op_tests/test_moe_2stage.py small cases (-t 1 16 256,
  each of the 10 quant types), every fused_moe output captured, upstream
  base (db3b870) vs this commit, same JIT build, seeded inputs
  (identical in both):
  - 8410 calls; the 170 deterministic calls are bit-identical;
  - the other 8240 vary run to run in the upstream base too;
  - for quant types 1 and 4, three runs of each tree put the mean
    distance between trees at 0.997 and 1.003 of that between runs;
  - one quant type 4 call stood apart in three runs (1.55); six fresh
    runs of each tree put it at 1.10, with no call apart and a mean of
    1.003.
- perf_gfx950.json: dsv3_tp8_pt was recorded on one idle MI355 (gfx950
  cu256). --check of all cases passes right after. The same case with
  AITER_MOEV2=a8w8_pt is within 2.2% of legacy at every token count, with
  mixed signs (mean of two runs per mode).
- black and ruff (0.16.0) clean.

Co-authored-by: Cursor <[email protected]>

* [MoE] keep moev2 parity checks honest after rebase

* [MoE] harden moev2 validation coverage

* [MoE] avoid false work and unsupported GPU validation

* [MoE] use the runtime GPU for path claims

* [MoE] test the checkout, not an installed aiter

The moe_dispatch scripts run as `python tests/moe_dispatch/<name>.py`, so sys.path[0]
is their own directory and the working directory is not on the path. They inserted
`tests` for `moe_dispatch` but nothing for the repository root, so `import aiter`
resolved to whatever copy is installed: in an image that carries an amd-aiter wheel
(CI runs `python3 -m pytest -q tests` next to one), the parity gate validated the
installed package while the pytest parent validated the checkout. Insert the
repository root as well, as tests/test_flydsl_aot_replay.py and friends already do.

perf_baseline named its baseline file with get_gfx(), which follows GPU_ARCHS and
returns the last entry on a multi-target build; the numbers come from the live GPU,
so it reads get_gfx_runtime() now and cannot compare one GPU against another's
recorded baseline.

Add the missing guard for the import graph this PR inverts: aiter/fused_moe.py now
imports aiter.moev2 at module level, so one unimportable moev2 module breaks
`import aiter.fused_moe` for every downstream MoE consumer. `import aiter` does not
import fused_moe and the moev2 runtime check does not import the legacy module, so
no aiter-side check covered it. Breaking a moev2 module fails the new test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [MoE] let the live-arch claim test see the real chip info

tests/test_moev2_dispatch.py wraps every test in `simulated_arch("gfx950")`, which
replaces chip_info.get_gfx and get_gfx_runtime with plain functions. The test added
for the multi-target build case then called `chip_info.get_gfx.cache_clear()` on a
lambda and failed with AttributeError, so `python3 -m pytest -q tests` was red. CI
had not caught it: on the previous head the MI35X shard 0 job was cancelled before
the focused regression step ran.

Give that one test a way out of the simulation: `_gfx950` steps aside when a test
requests `live_chip_info`, and that fixture hands over the real module with its
caches cleared before and after. A test about which chip-info helper dispatch calls
cannot run inside a simulation that patches both of them.

The test keeps its point: with GPU_ARCHS='gfx942;gfx1250', making claims() consult
the build-time get_gfx() as well as get_gfx_runtime() fails it again.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [MoE] stop the live-arch claim test from reading GPU_ARCHS

The test set GPU_ARCHS to a two-target list, cleared the two chip-info caches it
could reach, and asserted that get_gfx() then named the last target. On the MI35X
runner it returned the live gfx950 instead: `get_gfx_custom_op` caches a layer below
`get_gfx` and `get_gfx_custom_op_core`, so what the helper returns after a clear
depends on the environment. That precondition is chip_info's own contract, not what
this test is about.

Build the disagreement directly instead: get_gfx() names an arch the path declines,
get_gfx_runtime() names one it claims, and claims() has to follow the runtime one.
Both namespaces are patched, so a path that imports get_gfx for itself is caught too
-- adding `get_gfx() not in ARCHS` to claims() fails the test again.

The `live_chip_info` teardown now skips a helper a test has replaced, which otherwise
errors after that patching.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* [MoE] moev2: fixes from the phase 0-2 PR review (not graduated)

Bugs fixed:
1. aiter/moev2/paths.py: concurrent first calls could leave the enabled
   paths off. `_load_builtin` marked loading done before importing the
   built-in modules, so a second thread making its first MoE call skipped
   the import and selected from an empty (or partial) registry. If it
   stored that selection in `_active` after the importing thread stored
   its own, the paths stayed off until the next reload(). With several
   built-in modules, its loop over `_REGISTRY` could also raise
   "dictionary changed size during iteration" in default mode.
   Fix: no lock is held across imports (an RLock held there deadlocks
   when one thread imports a path module directly while another loads:
   each waits for the other's lock). A thread arriving during the load
   waits in `import_module`; loading counts as done only once every
   built-in module's PATH is registered, so a call made while a module
   imported directly is between its loader call and its registration
   waits too. A short RLock guards the registry and the cache; reload()
   bumps a generation, and active() caches its selection only if no
   reload happened meanwhile; _select reads a snapshot.
2. aiter/moev2/dispatch/tuned.py: clear_cache() left the default-parameter
   helpers `use_nt`, `get_ksplit` and `get_block_size_M` cached, so after
   changing AITER_USE_NT / AITER_KSPLIT or the CU count, the same untuned
   key kept the old values. They are cleared by name now (they stay plain
   lru_caches: moved verbatim from legacy, which shares them).
3. tests/moe_dispatch/gpu_differential.py: `--synth-table` imported aiter
   in the parent before any sys.path setup (only the child set it), so
   with a non-editable wheel installed it built the table from the wheel.
   perf_baseline.py likewise imported aiter (to name the GPU) with no
   checkout on the path. Both now set the path at the top of main().
4. tests/moe_dispatch/*: the scripts added the checkout to sys.path only
   if it was absent, so a checkout already on the path behind another
   aiter (a .pth entry after PYTHONPATH) lost. All six scripts now put
   `tests` and the repository root first and drop later copies.
5. tests/moe_dispatch/gpu_suites.py: `--run` without `--path` ran only
   each path's own suites; the SHARED ones (sorting, EP, local expert IDs,
   shared expert) were only printed, so they could not fail an all-path
   run. A run now takes suites_for(path) for every path.
6. tests/moe_dispatch/gpu_suites.py: `--run` ignored Suite.archs and
   Suite.gpus, so an all-path run on gfx942 also ran the gfx950-only,
   gfx1250 and 8-GPU suites and reported them failed. It now reads the
   live arch and the visible GPU count, skips and lists the suites that
   do not fit, and fails a run where no suite applies.
7. tests/moe_dispatch/perf_baseline.py: `--check --case X` kept only the
   requested cases present in the baseline, so an unrecorded X compared
   nothing and passed, even when its measurement failed; a missing
   baseline file raised a traceback. `--check` now fails, before
   measuring, on a missing file or on any case it would measure (every
   case of the arch without --case) that has no recorded timings, and
   names the `--record --case ...` to run.
8. tests/moe_dispatch/perf_baseline.py: on an arch no case lists (gfx1250
   today), `--record` wrote an empty baseline and every later `--check`
   passed; `--record --case` of another arch's case measured nothing and
   rewrote the file unchanged. Both modes now refuse there and say how to
   add the arch.

Co-authored-by: Cursor <[email protected]>

* [MoE] moev2: more fixes from the phase 0-2 PR review (not graduated)

Bugs fixed:
1. tests/moe_dispatch/arch_sim.py: a module first imported inside
   simulated_arch (the FlyDSL kernel modules load at launch, e.g.
   aiter.ops.flydsl.fused_moe_gfx942 for the gfx942 whole-graph rows)
   bound that context's fake get_gfx_runtime / get_cu_num. Nothing
   restored it, and later contexts skipped it (they patch only modules
   holding the real helper), so in one process the gfx942_cu80 and gfx950
   contexts saw gfx942's 304 CUs there. No recorded decision changed
   (those helpers run at launch, which the checks stub). On exit,
   simulated_arch now points every module still bound to its fakes back
   at the real helpers.
2. tests/moe_dispatch/gpu_suites.py: `--run` started each suite with the
   caller's environment and directory. `python3 op_tests/x.py` puts
   op_tests/, not the checkout, first on sys.path, so `aiter` was whatever
   is installed: with a wheel the suites tested it and could pass without
   the proposed code; the relative suite paths also needed the caller in
   the repository root. Each child now runs with the checkout first on
   PYTHONPATH and in the checkout.

Co-authored-by: Cursor <[email protected]>

* [MoE] moev2: address the phase 0-2 PR review comments (not graduated)

One copy of the sort:
- legacy moe_sorting, _moe_sorting_impl and their helpers and flags move
  verbatim into aiter/moev2/segments/sort.py, replacing v2's partial
  copy; aiter/fused_moe.py imports them back and calls the sort helpers
  through the module, so a patch there reaches every caller. op_tests
  that patched the moved globals patch aiter.moev2.segments.sort.

CI (comment 1):
- split_tests.sh / update_split_test_times.py add tests/test_moev2_*.py
  and tests/test_moe_dispatch_snapshot.py to the aiter shards. The GPU
  output differential is opt-in (AITER_MOEV2_GPU_DIFFERENTIAL=1).
- gpu_suites.py --compare runs a path's GPU suites with AITER_MOEV2=off
  and with the path, fails where v2 fails and legacy passes, and prints
  the checkAllclose outcomes of both runs and the checks that differ
  (--run and --compare set AITER_MOEV2 themselves). Suite output follows
  its command line.

GPU differential (comments 2 and 3):
- cases for num_local_tokens, static a1/a2 scales, fp8 input, output=,
  non-contiguous input, pinned block_size_M, g1u0, swiglu_limit 0/inf
  (Silu, Gelu, Mixtral's shape). Where legacy raises, v2 must raise the
  same error. output= is NaN-filled before each run.
- compare_launches stays exact on stages, kernels, arguments, sort
  buffers and integer tensors; floating-point launch tensors pass within
  1 ulp or twice legacy's own run-to-run spread. Non-finite values must
  carry the bits of one legacy run.

Bug fixed (comment 4, found by a vLLM end-to-end run):
- a8w8_pt refused every vLLM call: vLLM passes swiglu_limit=0.0, which
  legacy reads as no clamp. a8w8_pt now treats None, 0 and inf as no
  clamp, like fused_moe_.

Diagnosis and snapshots (comment 5):
- Path.why_not; with AITER_MOE_EXPLAIN=1, a call no active path claims
  logs each path's reason once. The AITER_MOEV2 selection is logged once
  at INFO, naming AITER_MOEV2=off as the rollback; the differential
  harness leaves that line out of the dispatch lines it compares.
- snapshot.py --check / --update print every changed, new and missing
  key; --update replaces an unreadable file. .gitattributes marks the
  golden files diff=gzip.
- The snapshot files carry no file name or mtime in their gzip header, so
  their bytes depend on their content only; all six rewritten once.
- Golden refresh from main (MXMOE under expert parallelism for SiTUv2):
  six gfx950 EP keys (E=896, topk=16, a4w4 and a8w4, M 1024-8192) now
  resolve like their non-EP calls (=base) instead of the CK and FlyDSL
  defaults.

Ownership notes (comment 6):
- every aiter/moev2 module, the README, the hook sites and the legacy
  functions v2 copies in aiter/fused_moe.py, the test harness, and the
  op_tests and CI scripts that touch moev2.

Co-authored-by: Cursor <[email protected]>

* [MoE] moev2: retry a failed built-in path import (not graduated)

A failed import of a built-in path module marked loading as done before
re-raising. Python drops the failed module from sys.modules, but later
calls skipped the import, so a caller that caught the first error and
called again got a selection from an empty registry: AITER_MOEV2=on (or a
path name) silently ran legacy.

- aiter/moev2/paths.py: a failed import leaves _builtin_loaded false and
  re-raises, so the next call imports again; loading still counts as done
  only after every built-in PATH is registered.
- A module that keeps failing now raises on every call. _select ran the
  import before checking for off, so the rollback would have raised too;
  AITER_MOEV2=off now selects nothing before loading any path module.

Tests (tests/test_moev2_switch.py):
- test_a_failed_builtin_import_is_retried_by_the_next_call: the first call
  raises, the retry selects the path; fails on the old code.
- test_off_selects_nothing_without_importing_the_path_modules: off with an
  unimportable module selects nothing, on raises; fails with the old order.
CPU: tests/test_moev2_*.py and tests/test_moe_dispatch_snapshot.py 123
passed, 1 skipped; black and ruff clean.

Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Co-authored-by: zufayu <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
JohnNikolay84 pushed a commit that referenced this pull request Nov 26, 2026
…_STAGE2_FP8=1 (#8669)

* [MoE] Add a stage2 FP8 row table for AITER_FLYDSL_STAGE2_FP8=1

A tuned fmoe row serves both modes of AITER_FLYDSL_STAGE2_FP8. For some
shapes, the fastest row depends on the mode. Qwen3.8 MXFP4 E 513 at 8192
to 32768 tokens: the one-stage post-reduce rows of
#5988 are the fastest with the switch
off. FlyDSL reduce rows with FP8 route rows are faster with it on.

Add the family tuned_stage2_fp8_fmoe (AITER_CONFIG_FMOE_STAGE2_FP8).
With AITER_FLYDSL_STAGE2_FP8=1, get_2stage_cfgs reads it after the main
table, like the swiglu_limit table. Its row replaces the main row when
the row is for the same token tier or a larger one.

- Add the Qwen3.8 rows: the FlyDSL reduce rows of the parent of
  #5988.
- gemm_moe_tune.py --run_config times the given table only.
- Add a dispatch test and the family to the shape collision test.

Co-authored-by: Cursor <[email protected]>

* [MoE] AOT: replay the stage2 FP8 rows when AITER_FLYDSL_STAGE2_FP8=1

The AOT build replays only the main, FHMoE and grouped tables, and it
skips each row that does not reach FlyDSL. The main rows of the stage2
FP8 shapes are one-stage ASM rows, so the build never compiled the
FlyDSL rows that the runtime selects with the switch on.

- aiter/aot/flydsl/moe.py: add the stage2 FP8 family to DEFAULT_CSVS
  when the switch is on.
- op_tests/test_moe_stage2_fp8_rows.py: check that the AOT jobs include
  the Qwen3.8 rows only with the switch on. Use get_gfx_runtime() for
  the skip. Add a __main__ entry, because aiter_test.sh runs
  "python3 <file>".

Co-authored-by: Cursor <[email protected]>

* [MoE] Use only exact act_type rows of the stage2 FP8 table

The stage2 FP8 lookup also read the act_type-agnostic dict of read_table.
Then a Silu row of the table could replace the main row of another
activation (for example SiTUv2) with the same other keys.
Keep only the primary dict. The token-tier fallback stays.
Add a SiTUv2 regression test.

Review: #8669
Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
jcaraban pushed a commit that referenced this pull request Nov 26, 2026
…_STAGE2_FP8=1 (#8669)

* [MoE] Add a stage2 FP8 row table for AITER_FLYDSL_STAGE2_FP8=1

A tuned fmoe row serves both modes of AITER_FLYDSL_STAGE2_FP8. For some
shapes, the fastest row depends on the mode. Qwen3.8 MXFP4 E 513 at 8192
to 32768 tokens: the one-stage post-reduce rows of
#5988 are the fastest with the switch
off. FlyDSL reduce rows with FP8 route rows are faster with it on.

Add the family tuned_stage2_fp8_fmoe (AITER_CONFIG_FMOE_STAGE2_FP8).
With AITER_FLYDSL_STAGE2_FP8=1, get_2stage_cfgs reads it after the main
table, like the swiglu_limit table. Its row replaces the main row when
the row is for the same token tier or a larger one.

- Add the Qwen3.8 rows: the FlyDSL reduce rows of the parent of
  #5988.
- gemm_moe_tune.py --run_config times the given table only.
- Add a dispatch test and the family to the shape collision test.

Co-authored-by: Cursor <[email protected]>

* [MoE] AOT: replay the stage2 FP8 rows when AITER_FLYDSL_STAGE2_FP8=1

The AOT build replays only the main, FHMoE and grouped tables, and it
skips each row that does not reach FlyDSL. The main rows of the stage2
FP8 shapes are one-stage ASM rows, so the build never compiled the
FlyDSL rows that the runtime selects with the switch on.

- aiter/aot/flydsl/moe.py: add the stage2 FP8 family to DEFAULT_CSVS
  when the switch is on.
- op_tests/test_moe_stage2_fp8_rows.py: check that the AOT jobs include
  the Qwen3.8 rows only with the switch on. Use get_gfx_runtime() for
  the skip. Add a __main__ entry, because aiter_test.sh runs
  "python3 <file>".

Co-authored-by: Cursor <[email protected]>

* [MoE] Use only exact act_type rows of the stage2 FP8 table

The stage2 FP8 lookup also read the act_type-agnostic dict of read_table.
Then a Silu row of the table could replace the main row of another
activation (for example SiTUv2) with the same other keys.
Keep only the primary dict. The token-tier fallback stays.
Add a SiTUv2 regression test.

Review: #8669
Co-authored-by: Cursor <[email protected]>

---------

Co-authored-by: Cursor <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants