Skip to content

[FlyDSL] fix(fused_moe): make the MXFP4 MoE stage2 epilogue deterministic by default - #4

Closed
Qubitium wants to merge 1 commit into
mainfrom
fix/mxfp4-stage2-deterministic
Closed

Qubitium wants to merge 1 commit into
mainfrom
fix/mxfp4-stage2-deterministic

Conversation

@Qubitium

@Qubitium Qubitium commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

Problem

The gfx950 MXFP4 MoE stage-2 (flydsl_moe2_layout_*) tuned rows mostly select the atomic epilogue. That epilogue accumulates one token's routed contributions with BF16 read-modify-write adds into a shared output row, so the rounding of every partial sum depends on the order in which the contributing workgroups reach that row. Two launches with identical inputs can return different bits.

This is a numerical correctness and reproducibility bug. Order-dependent rounding can change repeated target logits and undermine multi-token prediction (MTP), speculative decoding, and prefix/radix cache reuse when they rely on reproducible execution. The GPU validation below reproduces the output nondeterminism with identical inputs. Full-model accuracy and speculative acceptance were not measured.

Default policy: accuracy before speed

Accuracy, numerical correctness, and repeatability must always take precedence over performance in the default configuration. Deterministic reduce remains the default for the covered kernels, including when atomic benchmarks faster. A latency regression alone must never silently switch a deployment to order-dependent accumulation.

A deployer may explicitly opt into AITER_MXFP4_ATOMIC_STAGE2=1 only if they accept the loss of repeatability and the risk of potentially severe downstream accuracy/correctness impact, particularly for MTP/speculative decoding and cache reuse. That tradeoff belongs to the deployer after validation of their own workload. The override does not waive the MTP/speculative verification correctness requirements below. The small tensor-error differences measured here must not be taken as a bound on full-model impact; these tests do not establish the size of any model-level accuracy loss.

MTP/speculation correctness is mandatory

MTP/speculative decoding accuracy gates must always be honored. No speedup, however large, justifies weakening verification, bypassing rejection/correction, or allowing inconsistent teacher/student execution. Establish correctness first; performance optimization is follow-up work and must preserve the same gates.

Teacher/target and student/draft consistency requires:

  • Consistent context: each proposed token and its verification must use the correct logical prefix, token position, attention visibility, and cache state for that prefix. Each model's internal tensors may differ, but their token history must agree.
  • Correct verification: greedy verification must preserve the intended target model's token decisions. Exact sampled speculation must use the draft probabilities that actually generated the proposals and the corresponding target probabilities in its acceptance and correction steps. Draft predictions may disagree with the target; those disagreements must be handled by the algorithm's verification rules.
  • Preserved target behavior: validate ordinary target decoding against multi-token verification across draft lengths, batch layouts, and cache reuse. Repeating one fixed shape is insufficient to establish this invariance. Greedy equivalence and preservation of the sampled target distribution require their respective checks.

This PR removes one demonstrated source of target-output nondeterminism. The MI355X operator tests below do not establish that the full-model MTP/speculation gates have passed; those checks remain required before claiming end-to-end correctness. Future speed improvements must pass those checks without relaxing the accuracy or acceptance criteria.

Change

aiter/ops/flydsl/mxfp4_kname.py adds deterministic_v2_gemm2_name(name), which returns the epilogue-only reduce sibling of a v2 GEMM2 name (..._atomic_sbm16 -> ..._reduce_sbm16) and None for every other name family. The epilogue alternation is the only part of _FLYDSL_V2_GEMM2_RE that changes, so the substituted name always re-parses.

aiter/fused_moe.py runs _apply_mxfp4_stage2_determinism_policy on the resolved tuned row inside get_2stage_cfgs, before the validation chain, so every later check and the returned MOEMetadata are built from the kernel that will actually run. The policy keys on the stage-2 name alone: the nondeterminism belongs to that kernel, and every stage-1 family that can select a flydsl_moe2_layout_ GEMM2 (flydsl_mxmoe_g1_, flydsl_moe1_, opus_moe1_) reaches it through the same epilogue-driven wrapper. Gating on the MXMOE stage-1 prefix instead would leave 498 of the 649 affected rows on the atomic epilogue.

The cached tuning dict is never mutated (a copy is returned), so a later request for the same row still sees the tuned epilogue.

AITER_MXFP4_ATOMIC_STAGE2=1 is an explicit deployer debug/rollback override and logs a warning when used. It restores the tuned atomic epilogue with the accuracy and repeatability risks described above; there is no automatic performance-based opt-in. get_2stage_cfgs is lru_cached, so the switch must be set before the first dispatch for a shape (or the cache cleared).

The reduce epilogue is not new: mxfp4_moe_gemm2 compiles the same GEMM2 body for epilog="atomic"|"reduce" from the same tile/dtype parameters, _flydsl_v2_stage2_wrapper already allocates the per-route buffer for reduce, stage2_uses_route_reduce() already feeds moe_sorting(accumulate=...), and 64 distinct _reduce stage-2 names are already shipped in the tuned configs, covering all three (a_dtype, b_dtype) pairs this rewrite produces.

Scope: this changes the epilogue of tuned layout-v2 stage-2 rows only. It does not make the model deterministic end to end -- the rest of the graph keeps whatever behaviour it has today.

Dropped routes

moe_sorting only places a route whose router id is non-negative, and under EP only when the expert is in the mask; GEMM2 never writes the per-route slots it did not place. The reduce kernel now takes skip_invalid_ids and zeroes those routes itself, clamping before the EP mask gather so a dropped -1 cannot index expert_mask[-1]. The wrapper zero-fills the per-route buffer only when it has no ids to hand the kernel, which also removes the unconditional fill the EP path used to pay for.

AOT agrees with the runtime on that specialization: _run_moe_reduction derives skip_invalid_ids from its arguments rather than taking it as a parameter, aiter/aot/flydsl/moe.py and aiter/aot/flydsl/mxfp4_moe.py pass a real int32 topk_ids placeholder, and parse_csv rewrites an atomic layout-v2 row to its reduce sibling before keying the job. Before this, the runtime specialization was absent from every AOT CSV, so FLYDSL_RUNTIME_RUN_ONLY=1 raised instead of loading a cache entry.

topk_ids (and expert_mask under EP) now also reach the v2 wrapper through the MXMOE stage-1 front-end; _is_flydsl_v2_layout_stage2 is the single predicate for both dispatch spellings and for the FP8 route-out gate.

Blast radius

Counted over aiter/configs/**/*.csv:

  • 951 tuned rows select a flydsl_moe2_layout_* stage-2 kernel; 649 of them select the atomic epilogue (88 distinct names) and are rewritten.
  • 151 of the 649 rows use the flydsl_mxmoe_g1_* stage-1 front-end; the other 498 use flydsl_moe1_* (497) or opus_moe1_* (1). All of them reach the same epilogue-driven v2 wrapper.
  • 44 of the 88 distinct atomic names already have their epilogue-only _reduce sibling dispatched by some row in the same config set.
  • The native flydsl_moe2_* and opus_* stage-2 families (310 atomic rows) are different kernels with their own epilogue handling and are not part of this policy.

This PR does not touch the CSVs. For every rewritten atomic row, the us/err columns still describe the original atomic kernel; the presence of a reduce sibling elsewhere does not validate those measurements. The GPU results below cover representative shapes, and broader tuning-row validation remains useful before upstreaming.

One interaction worth knowing about: _flydsl_stage2_fp8_enabled() (AITER_FLYDSL_STAGE2_FP8, default off) only takes effect with epilog="reduce", so a row that is switched here can now take the FP8-intermediate path when that env var is set. That is pre-existing reduce behavior, not something this PR introduces.

Testing

Latest validation: 2026-10-14, commit c9113298, on a VM with 1 x AMD Instinct MI355X GPU exposed as a VF (gfx950, 256 CUs). Environment: ROCm SDK 10.0, PyTorch 2.13.0+rocm10.0.0 (HIP 7.15.26333), Python 3.14.7, and FlyDSL 0.3.4.1.

python -m pytest op_tests/test_mxfp4_stage2_epilogue_determinism.py op_tests/test_moe_glm5_fp4_ep_dispatch.py -q
python -m pytest op_tests/flydsl_tests/test_flydsl_moe.py -q

74 tests passed, zero skipped (40 policy/dispatch/regression tests and 34 existing FlyDSL MoE tests). Both gfx950 tests in the new regression file executed on the GPU. black --check, ruff check (CI pin 0.16.0), and git diff --check passed.

Supplemental local GPU validation, outside the PR's test files:

  • Eight reduction cases covered BF16, FP16, FP32, and FP8 route buffers, with and without expert masking. Negative IDs and masked slots were deliberately filled with NaNs: all outputs were finite and exactly matched the reference, including an all-dropped token.
  • Eleven GEMM2 cases covered FP4/FP4, FP8/FP4, FP8/FP8, BM16/32/64/128, BK128/256, persistent execution, negative IDs, expert masking, all routes dropped, and FP8 route output. Every case was bitwise identical across 100 eager repeats and 100 GPU graph replays. BF16-route reference relative L2 error was 0.260-0.297%; the optional FP8 route-output case was 2.739%; all-dropped output was exactly zero.
  • Full fused_moe execution selected the actual GLM-5, DeepSeek-V3, and DeepSeek-V4 tuning rows, covering MXMOE, FlyDSL, and Opus stage-1 front-ends. All three repeated bitwise across 100 eager launches and 100 graph replays. With the rollback switch enabled, each atomic case differed from its first output on 100/100 repeats.
  • AOT compiled a rewritten atomic CSV row into the reduce GEMM2 and guarded reducer in an empty cache. A fresh process with FLYDSL_RUNTIME_RUN_ONLY=1 loaded both and passed reference, repeatability, and graph checks. This check covers the unmasked FP4/FP4 specialization.

Latest latency and accuracy tradeoff on the 1 x MI355X VM

Full fused-MoE latency below is the median of five GPU graph measurements per epilogue (100 ms per measurement, alternating order). Both paths used identical inputs and tuning rows, with the default BF16 route output. GPU clocks were not locked. These are isolated operator timings:

Tuned MoE case Tokens Atomic (us) Reduce (us) Latency change
GLM-5 FP4 1 37.48 39.87 +6.4%
DeepSeek-V3 FP4 32 95.40 99.47 +4.3%
DeepSeek-V4 FP8/FP4 1 24.13 26.54 +10.0%

The default reduce path costs approximately 2.39 us (GLM-5), 4.07 us (DeepSeek-V3), and 2.41 us (DeepSeek-V4) per tested MoE call. In exchange, all three reduce cases were bitwise repeatable across 100 eager launches and 100 graph replays; all three atomic cases differed on 100/100 eager repeats. Reduce also had slightly lower error against the quantized PyTorch MoE reference:

Tuned MoE case Atomic relative L2 error Reduce relative L2 error
GLM-5 FP4 3.823% 3.809%
DeepSeek-V3 FP4 3.914% 3.899%
DeepSeek-V4 FP8/FP4 2.264% 2.245%

Lower reference error is better. These full two-stage comparisons include stage-1 execution and intermediate quantization; the independent GEMM2-only errors are listed above. The demonstrated benefit is repeatable output plus a small reference-error improvement. Any potentially much larger downstream accuracy impact requires full-model testing, especially with MTP/speculation and cache reuse enabled.

These results validate representative kernels on the single-GPU VM. They do not cover every rewritten tuning row, full-model MTP/speculative acceptance, prefix-cache reuse, or long-context prefills. The measured 4.3-10.0% operator latency increase does not quantify whole-model throughput loss. Deterministic reduce remains the accuracy-first default. Even an explicit atomic override does not waive MTP/speculation correctness gates; performance optimization must preserve them.

Not included

ModelCloud's stage-1 BM128 -> BM64 fallback for the GLM-5.3 high-token family is a separate change and is intentionally not part of this PR.

@github-actions github-actions Bot changed the title fix(fused_moe): make the MXFP4 MoE stage2 epilogue deterministic by default [FlyDSL] fix(fused_moe): make the MXFP4 MoE stage2 epilogue deterministic by default Oct 13, 2026
@github-actions

Copy link
Copy Markdown

🏷️ 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
ci:multi-gpu 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: DeepSeek-V4-Pro, MiniMax-M3-MXFP4
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 4 --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.

@Qubitium
Qubitium marked this pull request as draft October 13, 2026 16:28
@Qubitium
Qubitium force-pushed the fix/mxfp4-stage2-deterministic branch from fd987c2 to 41e3cb1 Compare October 13, 2026 17:14
…efault

The gfx950 MXFP4 MoE stage2 (`flydsl_moe2_layout_*`) tuned rows mostly select
the `atomic` epilogue. It accumulates one token's routed contributions with
BF16 read-modify-write adds into a shared output row, so the rounding of every
partial sum depends on the order in which the contributing workgroups reach
that row: two launches with identical inputs can return different bits. That
breaks multi-token prediction, speculative decoding and prefix/radix reuse,
which compare target logits across launches, and it is silent because nothing
in the tuned row or the kernel name says the arithmetic is order dependent.

The per-route `reduce` epilogue is not new: `mxfp4_moe_gemm2` compiles the same
GEMM2 body for `epilog="atomic"|"reduce"` from the same tile/dtype parameters,
`_flydsl_v2_stage2_wrapper` already allocates the per-route buffer for
`reduce`, `stage2_uses_route_reduce()` already feeds `moe_sorting(accumulate=)`
and 64 distinct `_reduce` stage-2 names are already shipped in the tuned
configs, covering all three (a_dtype, b_dtype) pairs this rewrite produces.

- aiter/ops/flydsl/mxfp4_kname.py: add `deterministic_v2_gemm2_name(name)`,
  which returns the epilogue-only `reduce` sibling of a v2 GEMM2 name
  (`..._atomic_sbm16` -> `..._reduce_sbm16`) and `None` for every other name
  family. The epilogue alternation is the only part of `_FLYDSL_V2_GEMM2_RE`
  that changes, so the substituted name always re-parses. Also home the
  rollback switch (`ATOMIC_STAGE2_ENV`, `atomic_stage2_opt_in()`) here so the
  runtime policy and the AOT parser read the same flag.
- aiter/fused_moe.py: `get_2stage_cfgs` runs
  `_apply_mxfp4_stage2_determinism_policy` on the resolved tuned row before the
  validation chain, so every later check and the returned `MOEMetadata` are
  built from the kernel that will actually run. The policy keys on the stage-2
  name alone: the nondeterminism belongs to that kernel, and every stage-1
  family that can select a `flydsl_moe2_layout_` GEMM2 (`flydsl_mxmoe_g1_`,
  `flydsl_moe1_`, `opus_moe1_`) reaches it through the same epilogue-driven
  wrapper. Gating on the MXMOE stage-1 prefix instead left 498 of the 649
  atomic layout rows in `aiter/configs` on the atomic epilogue.
- The cached tuning dict is never mutated (a copy is returned), so a later
  request for the same row still sees the tuned epilogue.
- `AITER_MXFP4_ATOMIC_STAGE2=1` restores the atomic epilogue as a rollback
  switch for a shape that regressed in performance or has not been validated
  against the reduce epilogue, and logs a warning when it is used. The
  atomic epilogue is a debug/rollback path, not a supported mode.

Review follow-ups:

- Dropped routes no longer leak into the reduction. `moe_sorting` only places a
  route whose router id is non-negative (and, under EP, whose expert is in the
  mask), and GEMM2 never writes the per-route slots it did not place. The
  reduce kernel now takes `skip_invalid_ids` and zeroes the contribution of
  those routes itself, clamping before the EP mask gather so a dropped `-1`
  cannot index `expert_mask[-1]`. The wrapper only zero-fills the per-route
  buffer when it has no ids to hand the kernel, which also removes the
  unconditional fill the EP path used to pay for.
- AOT precompiles the kernel the runtime dispatches. `_run_moe_reduction`
  derives `skip_invalid_ids` from its arguments instead of taking it as a
  parameter, `aiter/aot/flydsl/moe.py` and `aiter/aot/flydsl/mxfp4_moe.py` pass
  a real int32 `topk_ids` placeholder, and `parse_csv` rewrites an atomic
  layout-v2 row to its reduce sibling before keying the job. Previously the
  runtime specialization was absent from every AOT CSV, so
  `FLYDSL_RUNTIME_RUN_ONLY=1` raised instead of loading a cache entry.
- `topk_ids` (and `expert_mask` under EP) now reach the v2 wrapper through the
  MXMOE stage-1 front-end too; `_is_flydsl_v2_layout_stage2` is the single
  predicate for both dispatch spellings and for the FP8 route-out gate.
- Policy logging is one bounded `lru_cache` call instead of an unbounded set.

Tests: op_tests/test_mxfp4_stage2_epilogue_determinism.py covers the name
substitution, the policy rewrite for all three stage-1 families, the rollback
switch, the native `flydsl_moe2_*_atomic` family as a no-op, the dispatch
through `get_2stage_cfgs` against the glm5, dsv3 and dsv4 tuned configs, the
reduce specialization name, the target zero-fill decision, the MXMOE front-end
argument forwarding, and AOT/runtime agreement on the dispatched name. The
dispatch tests pin the gfx950 fp8 dtype and clear the rollback env var so they
do not depend on the host arch or the caller's environment. Two gfx950-gated
tests cover the dropped-route guard and bitwise repeatability of the reduce
path plus its numerics against `torch_moe_stage2`; the swap's on-device
numerics still need a gfx950 run, which this host cannot provide.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant