Repository navigation
fix(moe): keep fused decode-MoE partials in f32 until the final K-sum (#886) - #911
Conversation
The fused single-token decode-MoE kernel was blamed for corrupted tokens in long gemma-4-26b-a4b greedy runs (stray foreign-script tokens such as "During the Middleも Ages", wrong words such as "Middle War"), with a reduction/synchronization race as the suspected mechanism. An in-situ per-call probe (MLXCEL_FUSED_MOE_PARITY_CHECK=1, added here) over the full 5-turn repro on GB10 disproves the race: re-running the fused pair on identical inputs at every call produced 0 bitwise mismatches in 25600+ calls, and the isolated kernel tests show byte-identical output across the entire MLXCEL_FUSED_MOE_SGY range including non-divisor values. The kernel did carry a real numeric-faithfulness defect: MOE_DOWN rounded each per-expert partial score_k * down_k(act) to the activation dtype (bf16) BEFORE the host summed the K partials. Expert outputs routinely near-cancel during decode, so the pre-sum rounding error scales with the large partials rather than the small cancelled sum; measured in-situ it reached 5-13% relative error on the layer's residual update (97 of ~25600 MoE calls above 5% deviation vs the gather_qmm reference, worst 12.9%, concentrated on the calls whose output RMS was smallest). Fix: MOE_DOWN (both the CUDA and Metal kernel twins) now emits f32 partials with the score folded in f32, the host K-sum runs in f32, and the result is rounded to the activation dtype exactly once at the end, which bounds the error at the output's own bf16 quantum regardless of how strongly the experts cancel. Measured over a full in-situ repro run the worst fused-vs-f32-ground-truth deviation drops from the 5-13% tail to 3.3e-3, while the gather_qmm reference path itself keeps a 9.7e-2 worst-case tail on the same cancelling calls, i.e. the fused path is now strictly closer to ground truth than the fallback it was originally validated against. The MLXCEL_FUSED_MOE_RELU2 fc2 call site is updated identically; the MLXCEL_FUSED_MOE / MLXCEL_FUSED_MOE_SGY / MLXCEL_FUSED_MOE_MAX_DFF escape hatches are unchanged and the fused path stays enabled by default. Scope finding recorded for follow-up: with this fix in place, A/B repro runs show the residual corruption and the run-to-run non-determinism reproduce WITH THE FUSED KERNEL DISABLED as well (MLXCEL_FUSED_MOE=0 produced "During the Middle 이루어진 Middle Ages" in one of two runs, and MLXCEL_FUSED_MOE=0 MLX_USE_CUDA_GRAPHS=0 runs still differ run-to-run), so the remaining instability is a pipeline-level defect independent of this kernel and is tracked separately. Also added: the MLXCEL_FUSED_MOE_PARITY_CHECK / MLXCEL_FUSED_MOE_PARITY_THRESHOLD in-situ probe (per-call fused re-run determinism check, gather_qmm reference, and all-f32 dequantize+matmul ground truth with per-call deviation reporting), and fused_moe_parity_tests in mlxcel-core pinning: numeric parity vs an all-f32 dense reference at gemma-4-26b-a4b decode shapes, bitwise re-run determinism under allocator churn, byte-identical output across SGY 1..32, and a CPU-side structural guard on the kernel sources (full-warp shuffle masks, complete reduction ladder, f32 partial emission). Refs #886
Implementation Review SummaryIntent
VerdictNo blocking findings. The numeric fix is correct and complete, and the CUDA/Metal twins are semantically identical. Verified by static analysis, a clean Property checks (requested)
Notes
Verification
|
Security and performance review (blast radius, DoS, memory safety)Scope: the f32-accumulation change to the fused single-token decode-MoE kernel ( 1. Cross-MoE-model blast radius: no regression riskThe change is model-agnostic. The kernel accumulates in f32 as before; the only externally observable change is that the down-projection output buffer and the MLX types the The RELU2 fc2 call site is consistent with the primary path: scores f32, output f32, 2. Performance / DoS: no hot-path regressionThe 3. Memory safety: cleanThe down grid Probe (
|
The f32-accumulation fix in this PR added MLXCEL_FUSED_MOE_PARITY_CHECK and MLXCEL_FUSED_MOE_PARITY_THRESHOLD for in-situ corruption triage, but the environment-variables.md reference table (the canonical MLXCEL_* variable list) did not list them yet. Add rows next to the existing MLXCEL_FUSED_MOE* entries describing the bitwise-determinism/reference-deviation probe and its threshold, matching the diagnostic-variable convention used by the neighboring rows. Validation: - cargo fmt --all -- --check: clean - cargo clippy -p mlxcel-core --lib -- -D warnings: clean - cargo test -p mlxcel-core --lib fused_moe_kernel_source_structure: passes Refs #886
PR Finalization CompleteSummary
All checks passing. Ready for merge. |
…lablup#886) (lablup#911) ## Summary Makes the fused single-token decode-MoE kernel numerically faithful: the down kernel (CUDA and Metal twins) now emits f32 per-expert partials and the K-sum runs in f32 with a single final rounding to the activation dtype, instead of rounding every per-expert partial to bf16 before the sum. The fused path stays enabled by default; no gating stopgap is involved. The suspected reduction/synchronization race is disproven with direct evidence, and the residual repro instability is shown to be a separate pipeline-level defect that reproduces with the fused kernel disabled (tracked in lablup#910). ## Root cause The issue hypothesized a reduction/synchronization race because the corruption appeared non-deterministic and SGY-dependent. A new in-situ per-call probe (`MLXCEL_FUSED_MOE_PARITY_CHECK=1`, added in this PR) run over the full 5-turn repro on GB10 disproves that: the fused pair re-run on identical inputs at every one of 25600+ calls produced 0 bitwise mismatches, and the isolated kernel tests show byte-identical output across the entire `MLXCEL_FUSED_MOE_SGY` range (1..32, including non-divisor values that force round_up guard rows). The kernel was always deterministic. The kernel's real defect was numeric. `MOE_DOWN` computed `out[eslot*Din+h] = (T)(score * d)`, rounding each per-expert partial to bf16 before the host summed the K=8 partials. The K expert outputs routinely near-cancel during decode, so the pre-sum rounding error, which scales with the large partials rather than the small cancelled sum, reached 5-13% relative error on the layer's residual update: over one pre-fix repro run, 97 of ~25600 MoE calls exceeded 5% normalized RMS deviation vs the gather_qmm reference (worst 12.9%), all concentrated on the calls whose output RMS was smallest, and the run produced the characteristic corruption ("During the Middleも Ages"). Rounding once AFTER the K-sum bounds the error at the output's own bf16 quantum regardless of cancellation. Post-fix, the same in-situ probe over a full repro run shows worst fused-vs-f32-ground-truth deviation of 3.3e-3 across all 25000+ calls (vs the 5-13% tail before), while the gather_qmm reference path itself keeps a 9.7e-2 worst-case tail on those same cancelling calls, and the run was clean. In the isolated parity tests at exact gemma-4-26b-a4b decode shapes the fixed kernel now matches the all-f32 dense reference at nrms 1.9e-6 / 0 (bitwise) / 6.2e-8 across three seeds after the single mandatory output rounding, roughly 1000x tighter than the production gather_qmm fallback's own ~4e-3 distance from the same ground truth. ## Scope finding (recorded for follow-up) With the fix in place, A/B repro runs on this build show the residual corruption and run-to-run non-determinism reproduce with the fused kernel DISABLED as well: `MLXCEL_FUSED_MOE=0` produced "During the Middle 이루어진 Middle Ages" in one of two runs and differs bitwise run-to-run, and `MLXCEL_FUSED_MOE=0 MLX_USE_CUDA_GRAPHS=0` runs also differ bitwise run-to-run. The remaining instability is therefore a pipeline-level defect independent of this kernel (base-op non-determinism flipping near-tied greedy decisions at a recurring n-gram hotspot), which means the issue's original discriminating experiment (fused-off 5/5 clean) does not hold on current main and the "10 consecutive clean runs" acceptance gate is blocked by that separate defect, not by this kernel. Follow-up issue lablup#910 filed with the full evidence matrix, including a single-turn fused-disabled control that still diverges bitwise run-to-run. ## What changed - `src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp`: `MOE_DOWN_CUDA_SOURCE` and `MOE_DOWN_METAL_SOURCE` write f32 partials with the score folded in f32; `run_fused_moe_two_kernel` passes scores as f32, takes f32 kernel output, sums the K partials in f32, and casts to the activation dtype once; the `MLXCEL_FUSED_MOE_RELU2` fc2 call site in `fused_moe_forward` is updated identically; new env-gated in-situ probe `MLXCEL_FUSED_MOE_PARITY_CHECK` / `MLXCEL_FUSED_MOE_PARITY_THRESHOLD` (per-call fused re-run determinism check, gather_qmm reference, and all-f32 dequantize+matmul ground truth with per-call deviation reporting) kept for future corruption triage; design-comment updates. - `src/lib/mlxcel-core/src/fused_moe_parity_tests.rs` (new) plus wiring in `src/lib/mlxcel-core/src/lib.rs`: numeric parity vs an all-f32 dense reference and vs the production gather_qmm fallback at exact gemma-4-26b-a4b decode shapes (Din 2816, Dff 704, K 8, 4-bit, gs 64, bf16), bitwise re-run determinism under allocator churn, byte-identical output across `MLXCEL_FUSED_MOE_SGY` 1..32, and a CPU-side structural guard on the kernel sources (full-warp `__shfl_down_sync` masks, complete 16..1 reduction ladder, f32 partial emission). GPU tests self-skip on CPU-only builds and run on either Metal or CUDA. - `src/models/switch_layers.rs`: `fused_moe_enabled` doc updated with the lablup#886 hardening record; all `MLXCEL_FUSED_MOE` / `MLXCEL_FUSED_MOE_SGY` / `MLXCEL_FUSED_MOE_MAX_DFF` controls unchanged. - `docs/benchmark_results/fused-moe-decode-kernel-design.md`: dated section documenting the root cause, the in-situ measurements, the fix, and the verification commands. ## Test plan - [x] `MLX_CUDA_ARCHITECTURES=121 cargo test -p mlxcel-core --release --features cuda fused_moe -- --test-threads=1` on GB10: 4/4 pass (parity nrms 1.9e-6 / 0 / 6.2e-8 vs dense f32 reference; gather_qmm within the documented 5e-3 class; bitwise re-run determinism; SGY invariance; source structure) - [x] Pre-fix in-situ probe over the full 5-turn 26B repro: corruption reproduced ("During the Middleも Ages"), 97/25600 calls above 5% deviation, worst 12.9%, 0 non-deterministic re-runs - [x] Post-fix in-situ probe over the same repro: output clean, worst fused-vs-truth 3.3e-3 across 25000+ calls, 0 non-deterministic re-runs - [x] Post-fix default-config repro runs clean of foreign-script tokens in probe run and first A/B run; residual near-tie instability shown to reproduce with `MLXCEL_FUSED_MOE=0` (separate defect, see scope finding) - [ ] Orchestrator: re-run `cargo test -p mlxcel-core --release --features cuda fused_moe` and the repro battery; note the 10-consecutive-clean-runs gate is blocked by the follow-up pipeline defect, which reproduces with the fused kernel disabled on current main (lablup#910) Closes lablup#886
Summary
Makes the fused single-token decode-MoE kernel numerically faithful: the down kernel (CUDA and Metal twins) now emits f32 per-expert partials and the K-sum runs in f32 with a single final rounding to the activation dtype, instead of rounding every per-expert partial to bf16 before the sum. The fused path stays enabled by default; no gating stopgap is involved. The suspected reduction/synchronization race is disproven with direct evidence, and the residual repro instability is shown to be a separate pipeline-level defect that reproduces with the fused kernel disabled (tracked in #910).
Root cause
The issue hypothesized a reduction/synchronization race because the corruption appeared non-deterministic and SGY-dependent. A new in-situ per-call probe (
MLXCEL_FUSED_MOE_PARITY_CHECK=1, added in this PR) run over the full 5-turn repro on GB10 disproves that: the fused pair re-run on identical inputs at every one of 25600+ calls produced 0 bitwise mismatches, and the isolated kernel tests show byte-identical output across the entireMLXCEL_FUSED_MOE_SGYrange (1..32, including non-divisor values that force round_up guard rows). The kernel was always deterministic.The kernel's real defect was numeric.
MOE_DOWNcomputedout[eslot*Din+h] = (T)(score * d), rounding each per-expert partial to bf16 before the host summed the K=8 partials. The K expert outputs routinely near-cancel during decode, so the pre-sum rounding error, which scales with the large partials rather than the small cancelled sum, reached 5-13% relative error on the layer's residual update: over one pre-fix repro run, 97 of ~25600 MoE calls exceeded 5% normalized RMS deviation vs the gather_qmm reference (worst 12.9%), all concentrated on the calls whose output RMS was smallest, and the run produced the characteristic corruption ("During the Middleも Ages"). Rounding once AFTER the K-sum bounds the error at the output's own bf16 quantum regardless of cancellation.Post-fix, the same in-situ probe over a full repro run shows worst fused-vs-f32-ground-truth deviation of 3.3e-3 across all 25000+ calls (vs the 5-13% tail before), while the gather_qmm reference path itself keeps a 9.7e-2 worst-case tail on those same cancelling calls, and the run was clean. In the isolated parity tests at exact gemma-4-26b-a4b decode shapes the fixed kernel now matches the all-f32 dense reference at nrms 1.9e-6 / 0 (bitwise) / 6.2e-8 across three seeds after the single mandatory output rounding, roughly 1000x tighter than the production gather_qmm fallback's own ~4e-3 distance from the same ground truth.
Scope finding (recorded for follow-up)
With the fix in place, A/B repro runs on this build show the residual corruption and run-to-run non-determinism reproduce with the fused kernel DISABLED as well:
MLXCEL_FUSED_MOE=0produced "During the Middle 이루어진 Middle Ages" in one of two runs and differs bitwise run-to-run, andMLXCEL_FUSED_MOE=0 MLX_USE_CUDA_GRAPHS=0runs also differ bitwise run-to-run. The remaining instability is therefore a pipeline-level defect independent of this kernel (base-op non-determinism flipping near-tied greedy decisions at a recurring n-gram hotspot), which means the issue's original discriminating experiment (fused-off 5/5 clean) does not hold on current main and the "10 consecutive clean runs" acceptance gate is blocked by that separate defect, not by this kernel. Follow-up issue #910 filed with the full evidence matrix, including a single-turn fused-disabled control that still diverges bitwise run-to-run.What changed
src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp:MOE_DOWN_CUDA_SOURCEandMOE_DOWN_METAL_SOURCEwrite f32 partials with the score folded in f32;run_fused_moe_two_kernelpasses scores as f32, takes f32 kernel output, sums the K partials in f32, and casts to the activation dtype once; theMLXCEL_FUSED_MOE_RELU2fc2 call site infused_moe_forwardis updated identically; new env-gated in-situ probeMLXCEL_FUSED_MOE_PARITY_CHECK/MLXCEL_FUSED_MOE_PARITY_THRESHOLD(per-call fused re-run determinism check, gather_qmm reference, and all-f32 dequantize+matmul ground truth with per-call deviation reporting) kept for future corruption triage; design-comment updates.src/lib/mlxcel-core/src/fused_moe_parity_tests.rs(new) plus wiring insrc/lib/mlxcel-core/src/lib.rs: numeric parity vs an all-f32 dense reference and vs the production gather_qmm fallback at exact gemma-4-26b-a4b decode shapes (Din 2816, Dff 704, K 8, 4-bit, gs 64, bf16), bitwise re-run determinism under allocator churn, byte-identical output acrossMLXCEL_FUSED_MOE_SGY1..32, and a CPU-side structural guard on the kernel sources (full-warp__shfl_down_syncmasks, complete 16..1 reduction ladder, f32 partial emission). GPU tests self-skip on CPU-only builds and run on either Metal or CUDA.src/models/switch_layers.rs:fused_moe_enableddoc updated with the bug: Gemma 4 26B A4B multi-turn corruption from numerically unfaithful fused decode-MoE kernel #886 hardening record; allMLXCEL_FUSED_MOE/MLXCEL_FUSED_MOE_SGY/MLXCEL_FUSED_MOE_MAX_DFFcontrols unchanged.docs/benchmark_results/fused-moe-decode-kernel-design.md: dated section documenting the root cause, the in-situ measurements, the fix, and the verification commands.Test plan
MLX_CUDA_ARCHITECTURES=121 cargo test -p mlxcel-core --release --features cuda fused_moe -- --test-threads=1on GB10: 4/4 pass (parity nrms 1.9e-6 / 0 / 6.2e-8 vs dense f32 reference; gather_qmm within the documented 5e-3 class; bitwise re-run determinism; SGY invariance; source structure)MLXCEL_FUSED_MOE=0(separate defect, see scope finding)cargo test -p mlxcel-core --release --features cuda fused_moeand the repro battery; note the 10-consecutive-clean-runs gate is blocked by the follow-up pipeline defect, which reproduces with the fused kernel disabled on current main (bug: Gemma 4 26B A4B temp-0 decode is non-deterministic run-to-run and corrupts near-tied tokens independently of the fused MoE kernel #910)Closes #886