Skip to content

fix(moe): keep fused decode-MoE partials in f32 until the final K-sum (#886) - #911

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-886-fused-moe-decode-parity
Jul 24, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-886-fused-moe-decode-parity

Conversation

@inureyes

Copy link
Copy Markdown
Member

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 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 #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 bug: Gemma 4 26B A4B multi-turn corruption from numerically unfaithful fused decode-MoE kernel #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

  • 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)
  • 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
  • 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
  • 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 (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

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
@inureyes inureyes added type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority status:review Under review labels Jul 24, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make the fused single-token decode-MoE MOE_DOWN kernel (CUDA + Metal) numerically faithful by keeping the K per-expert partials in f32 and rounding to the activation dtype exactly once after the host K-sum, fixing the near-cancellation rounding blowup that corrupted long gemma-4-26b-a4b greedy decodes (#886).

Verdict

No blocking findings. The numeric fix is correct and complete, and the CUDA/Metal twins are semantically identical. Verified by static analysis, a clean cargo check -p mlxcel-core --tests, and a second independent review pass.

Property checks (requested)

  1. Numeric correctness (round once, f32 accumulation): PASS. Both affected host wrappers pass the down kernel output dtype as float32, pass scores as float32, sum the K partials in f32, and cast to the activation dtype exactly once: run_fused_moe_two_kernel (astype(sum(rB[0], 0), T)) and the MLXCEL_FUSED_MOE_RELU2 fc2 site in fused_moe_forward (reshape(astype(sum(rB[0], 0, false), T), {1, din})). The only two out[eslot * Din + h] = ... writers now emit (float)scores[eslot] * d (no (T) cast). No path rounds a partial before the sum; the gather_qmm fallback is intentionally untouched.

  2. CUDA/Metal mirror: PASS. MOE_DOWN_CUDA_SOURCE and MOE_DOWN_METAL_SOURCE write the byte-identical store out[eslot * Din + h] = (float)scores[eslot] * d; after a full-warp reduction (simd_sum on Metal, the 0xffffffffu 16..1 __shfl_down_sync ladder on CUDA). Output/scores dtypes and the host K-sum are shared between the twins. No divergence.

  3. Escape hatches: PASS. MLXCEL_FUSED_MOE, MLXCEL_FUSED_MOE_SGY, and MLXCEL_FUSED_MOE_MAX_DFF are unchanged (only doc comments added in switch_layers.rs); the kernel stays on by default. The new MLXCEL_FUSED_MOE_PARITY_CHECK probe is OFF by default (static env read defaults to 0) and fully gated behind if (parity_check), so the normal path costs one static-int branch per call and runs no extra evals.

  4. Performance: PASS. The change adds only an f32 [K, Din] staging buffer (about 90 KB at gemma4 shapes) plus one elementwise cast per call; no extra device round-trips, no new evals on the hot path. This is a faithfulness fix, not a gating/disable.

  5. Test quality: PASS. fused_moe_parity_tests.rs compares the fused kernel to an all-f32 dense reference (dequantize + f32 matmul + tanh-approx GeGLU) and to the production gather_qmm fallback at exact gemma-4-26b-a4b decode shapes (Din 2816, Dff 704, K 8, 4-bit, gs 64, bf16), with the dense reference rounded to bf16 once so the assertion isolates kernel math. The nrms_dense < 5e-4 bound sits well above the post-fix f32-summation-order floor (~1e-6) and below the pre-fix pre-sum-rounding error (~1e-3 for these random cases, 5-13% on the real cancelling decode calls), so the test fails on the pre-fix code. The CPU-only fused_moe_kernel_source_structure guard additionally fails deterministically on pre-fix source (asserts exactly two f32-partial writers and absence of the (T)( rounding). Bitwise rerun-determinism (24 reruns under allocator churn) and SGY-invariance (SGY 1..32 including non-divisor guard-row values) tests are meaningful and match the disproven-race diagnosis.

Notes

  • The residual 26B corruption tracked in 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 (reproduces with the fused kernel disabled) is out of scope and correctly deferred; this PR does not touch the gather_qmm combine path.
  • The MLXCEL_FUSED_MOE_RELU2 fc2 site continues to resolve the Metal-only moe_down_kernel_fn() (no CUDA variant selection); this is pre-existing behavior for that experimental Metal-focused path and is not a regression from this change.
  • Orchestrator still owns the GPU parity run (cargo test -p mlxcel-core --release --features cuda fused_moe -- --test-threads=1) and the repro battery.

Verification

  • All stated requirements implemented (f32 partials, single rounding, both call sites, both twins)
  • No placeholder/mock code (the probe is a real, gated diagnostic)
  • Integrated into project code flow (tests wired via lib.rs; kernel on by default)
  • Project conventions followed
  • Existing modules reused (shared moe_down kernel, gather_qmm/dequantize references)
  • No unintended structural changes
  • Tests pass (compiles clean; GPU parity run delegated to orchestrator)

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (blast radius, DoS, memory safety)

Scope: the f32-accumulation change to the fused single-token decode-MoE kernel (MOE_DOWN CUDA/Metal twins, run_fused_moe_two_kernel, and the MLXCEL_FUSED_MOE_RELU2 fc2 call site in fused_moe_forward). #910 is out of scope. Verdict: no security, DoS, or memory-safety findings. Safe to land from these three angles.

1. Cross-MoE-model blast radius: no regression risk

The 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 scores input are now f32, the K-sum runs in f32, and the result is cast to the activation dtype T exactly once. T stays x.dtype() (bf16/f16/f32), so the FFI return dtype contract to every caller is unchanged. No gemma4-specific constant is introduced: K, Din, Dff, expert count, group_size, and bits all flow from the caller, and both activation branches (act=0 SwiGLU, act=1 GeGLU) plus the 4/6/8-bit down paths are untouched. Qwen3-30B-A3B, dots.llm1, nemotron-h, and any other MoE hitting this path see only tighter rounding.

MLX types the out buffer from output_dtypes and the scores input from the array's runtime dtype, both independent of the template T (confirmed in MLX custom_kernel.cpp for CUDA and metal_kernel.cpp for Metal). So { float32 } makes out a float* and astype(scores, float32) makes scores a const float*; there is no T-vs-buffer type mismatch. The compiled-kernel cache key includes the input and output dtype strings, so the f32 switch produces a distinct JIT specialization with no stale-cache collision against any pre-fix bf16 variant.

The RELU2 fc2 call site is consistent with the primary path: scores f32, output f32, astype(sum(..., 0), T). Both down-kernel call sites (and the diagnostic rerun) were audited; all request f32 output and cast once.

2. Performance / DoS: no hot-path regression

The [K, Din] down output buffer doubles from bf16 to f32 (~90 KB at gemma4 shapes; the gate/up [K, Dff] staging was already f32). K and Din are model config constants, not request-controlled, so there is no attacker-scalable allocation. The K-sum and the final cast are appended to the MLX lazy graph and run on-device; the non-probe path adds no .eval(), so there is no added per-token device round-trip or sync. Extra work per call is one f32 K-element score cast and one Din-element output cast, negligible against the GEMV. Decode throughput is unchanged within noise.

3. Memory safety: clean

The down grid (32, round_up(Din, sgy), K) writes out[eslot*Din + h] for every eslot in [0,K), h in [0,Din), with h >= Din guard rows returning before any store, so the full [K, Din] buffer is initialized and the subsequent sum reads no uninitialized element. No OOB on the staging buffer.

Probe (MLXCEL_FUSED_MOE_PARITY_CHECK)

Off by default (getenv returns 0 when unset), read once into a function-local static, and env-only: it cannot be toggled by an untrusted inference request. When off, the guard is a single cached-int branch with no getenv per call and zero added cost. The heavy diagnostic block (two extra evals, gather_qmm reference, f32 ground truth) runs only when a developer sets the env var. The host-vector length assumptions inside the probe hold because all four buffers are structurally [Din]; not reachable in production.

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
@inureyes

Copy link
Copy Markdown
Member Author

PR Finalization Complete

Summary

  • Tests: no changes needed. The 4 GPU-gated parity tests in src/lib/mlxcel-core/src/fused_moe_parity_tests.rs and the CPU-side fused_moe_kernel_source_structure guard were already in place and are sound; re-ran the CPU-side guard locally (cargo test -p mlxcel-core --lib fused_moe_kernel_source_structure), passes.
  • Documentation: the design doc (docs/benchmark_results/fused-moe-decode-kernel-design.md) reads cleanly and is accurate, no changes needed there. Added two missing rows to docs/environment-variables.md (the canonical MLXCEL_* reference) for the new MLXCEL_FUSED_MOE_PARITY_CHECK / MLXCEL_FUSED_MOE_PARITY_THRESHOLD diagnostic probe introduced by this PR, which were undocumented. No populated Korean docs tree exists (docs/ko/ is absent), so no translation work applies.
  • Lint/Format: cargo fmt --all -- --check was already clean across the workspace. cargo clippy -p mlxcel-core --lib -- -D warnings is clean (no warnings). cargo check -p mlxcel-core --tests compiles cleanly. No fixes were needed.

All checks passing. Ready for merge.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Jul 24, 2026
@inureyes
inureyes merged commit f5d46ad into main Jul 24, 2026
4 checks passed
@inureyes
inureyes deleted the fix/issue-886-fused-moe-decode-parity branch July 24, 2026 06:04
@inureyes inureyes self-assigned this Aug 31, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: Gemma 4 26B A4B multi-turn corruption from numerically unfaithful fused decode-MoE kernel

1 participant