Repository navigation
Description
Summary
gemma-4-26b-a4b-it-4bit (MoE) produces corrupted tokens during long multi-turn generation: stray foreign-script characters mid-word ("During the Middleも Ages", "Middle ልጅ") or wrong words ("Middle War", "Middlehood"). The corruption is caused by the fused single-token-decode MoE kernel. Disabling it (MLXCEL_FUSED_MOE=0) makes the exact repro clean in 5/5 runs; leaving it on corrupts every time. Reproduces on both CUDA and Apple Silicon.
The goal of this issue is to fix the essential cause: make the fused decode-MoE kernel numerically faithful to the reference MoE path so it can remain enabled by default without corrupting output. Default-disabling the kernel is acceptable only as an interim mitigation, not as the resolution.
Reproduction
printf '%s\n' \
"Remember this secret code: PARETO-7391. Now write a detailed 160-word paragraph about the history of coffee." \
"Now write a detailed 160-word paragraph about the history of tea." \
"Write a detailed 160-word paragraph about the history of chocolate." \
"Write a detailed 160-word paragraph about the history of wine." \
"Write a detailed 160-word paragraph about the history of bread." \
"/bye" | ./target/release/mlxcel run <path>/gemma-4-26b-a4b-it-4bit -t 0 -n 256
Corruption appears reliably in the 4th (wine) paragraph at "During the Middle ___ Ages". Detect programmatically with grep -oP '[\p{Han}\p{Hiragana}\p{Katakana}\p{Ethiopic}\p{Hangul}\p{Cyrillic}\p{Arabic}]' plus watching for wrong words.
- Baseline (fused on, default): 3/3 default-setting runs corrupted.
MLXCEL_FUSED_MOE=0: 5/5 runs clean, "During the Middle Ages" correct every time.
Root cause
The fused single-token-decode MoE path deviates numerically from the reference MoE path beyond the safe f16-jitter margin, and does so non-deterministically.
- Call site:
SwitchGeGLU::forward_fused_kernel,src/models/gemma4.rs:625-686, invoked fromExperts::forward(src/models/gemma4.rs:1051-1058) wheneverb*s == 1(single-token decode) andfused_moe_enabled()(src/models/switch_layers.rs:42-62) is true (the default). - Kernel:
fused_moe_geglu_kernel->run_fused_moe_two_kernel,src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp:1800-1902; the hand-written two-kernel GEMV pairMOE_GATEUP_CUDA_SOURCE/MOE_DOWN_CUDA_SOURCE(~lines 1570-1680, with Metal twins) accumulates gate/up/down products via strided per-lane partial sums plus a__shfl_down_sync/simd_sumtree reduction. - Reference path:
compiled_switch_qgeglu_forward/gather_qmm,src/models/gemma4.rs:577-612.
The doc comment at src/models/switch_layers.rs:28-39 states the kernel was validated as "byte-identical or within the documented f16 jitter class" on the validated MoE set. That margin is too thin for Gemma 4's GeGLU (act=1) decode path during long, structurally-repetitive multi-turn generation, where the model's next-token confidence at a recurring pattern is already marginal; the kernel's extra deviation flips the near-tied decision. Because the deviation depends on how work is split across warp lanes / threadgroups, the result varies with MLXCEL_FUSED_MOE_SGY and is non-deterministic run-to-run at a fixed config (two runs with identical settings produced clean vs. corrupted output). Run-to-run non-determinism at fixed launch config points beyond pure rounding order toward a reduction/synchronization correctness problem (lane-mask coverage in the shuffle reduction, shared-memory sync, or partial-sum initialization), which must be audited as part of the fix.
Discriminating experiments (already run)
- Huge sliding window (temporary hack, reverted): corruption persisted 3/3 -> not the
RotatingKVCache/ sliding window. MLXCEL_FUSED_MOE=0: 5/5 clean -> decisive, the fused kernel is the cause.MLXCEL_FUSED_MOE_SGYsweep (1/4/8/16/32): sgy 1 and 16 corrupted, sgy 32 clean, sgy 4 clean then corrupted on an immediate identical repeat -> genuine run-to-run non-determinism tied to this kernel.
Consistency: dense Gemma 4 (12b, e2b) never hit this (no experts, the fused path is unreachable); MLX_USE_CUDA_GRAPHS=0 does not fix it (not a graph-cache issue); short / single-turn / large-prefill generations are clean (no near-tied repeated-pattern decision to flip); device-independence follows from the shared C++/Metal kernel orchestration.
Required resolution (fix the essential cause)
- Root-cause the numeric deviation and the non-determinism in
run_fused_moe_two_kernel/MOE_GATEUP/MOE_DOWN:- Audit the
__shfl_down_sync/simd_sumtree reduction for full lane-mask coverage and correct active-lane handling; verify shared-memory reductions are properly synchronized; verify partial-sum buffers are initialized. - Verify the accumulation dtype (accumulate gate/up/down and the reduction in fp32, not fp16) and the GeGLU (
act=1) activation ordering matches the reference. - Compare the fused kernel's intermediate gate/up/down and final expert output against
gather_qmm/compiled_switch_qgeglu_forwardfor the failing decode step and quantify the deviation.
- Audit the
- Bring the fused kernel within a defined tolerance of the reference path (deterministic modulo documented f16 jitter that does not flip greedy argmax), on both CUDA and Metal.
- Keep
MLXCEL_FUSED_MOE=0and anyMLXCEL_FUSED_MOE_SGY/MLXCEL_FUSED_MOE_MAX_DFFcontrols as escape hatches, but the default-on fused path must be correct.
Acceptance criteria
- A numeric parity unit test (fused kernel vs
gather_qmmreference) over randomized MoE inputs, including GeGLUact=1single-token decode across the SGY configs, passes within the defined tolerance, on CUDA and Metal, and runs in CI. - With the fused kernel ENABLED (default), the 5-paragraph multi-turn repro on
gemma-4-26b-a4b-it-4bitis clean across at least 10 consecutive runs (no foreign-script tokens, "During the Middle Ages" correct), and output no longer varies run-to-run at a fixed config beyond argmax-stable f16 jitter. - No regression on the previously validated MoE model set.
Interim mitigation (until the above lands)
Default-disable the fused kernel for Gemma 4's act=1 (GeGLU) call site (e.g. SwitchGeGLU::forward_fused_kernel returns None unless explicitly opted in), analogous to the existing MLXCEL_FUSED_MOE_MAX_DFF per-model gating in src/models/switch_layers.rs. This stops shipping corrupted output while the kernel is being fixed. It is a stopgap, not the resolution.
Notes / environment
- Linux GB10 (CUDA, sm_121) and Apple Silicon both affected. HEAD of
main. - Investigation transcripts (baseline vs
MLXCEL_FUSED_MOE=0vs SGY sweep) were captured during triage and can be regenerated with the repro above. - Independent from the Gemma 4 sliding-window server
<unused>collapse (bug: Gemma 4 sliding-window server output collapses to reserved <unused> tokens under chunked prefill #885, chunked-prefill mask drop; that model is dense) and from the Gemma 4<|channel>thoughtCLI reasoning-channel leak (bug: Gemma 4 reasoning channel leaks into CLI output as raw tokens #884).
Activity
inureyes commentedon Jul 24, 2026
Fix is up in PR #911. Three findings from the investigation, each with direct evidence:
The suspected reduction/synchronization race does not exist. A per-call in-situ probe (
MLXCEL_FUSED_MOE_PARITY_CHECK=1, added in the PR) re-ran the fused kernel pair on identical inputs at every MoE call across the full 5-turn repro: 0 bitwise mismatches in 25600+ calls. Isolated tests additionally show the fused output is byte-identical across the entireMLXCEL_FUSED_MOE_SGYrange (1..32, including non-divisor values), so the SGY-dependent behavior observed during triage cannot have come from the kernel math.The kernel's real defect was numeric:
MOE_DOWNrounded each per-expert partialscore_k * down_k(act)to bf16 BEFORE the host summed the K partials. Expert outputs routinely near-cancel during decode, so that pre-sum rounding reached 5-13% relative error on the layer's residual update (97 of ~25600 calls above 5% vs the gather_qmm reference in one pre-fix repro run, worst 12.9%, concentrated where the output RMS was smallest), and that run reproduced "During the Middleも Ages". The fix keeps partials and the K-sum in f32 with a single final rounding; post-fix the same probe shows worst fused-vs-f32-truth of 3.3e-3 over a clean full run, and the isolated parity tests match the all-f32 dense reference at nrms 1.9e-6 / 0 (bitwise) / 6.2e-8, roughly 1000x tighter than the gather_qmm fallback's own ~4e-3 distance from truth. The fused path stays enabled by default.The residual repro instability is not this kernel. On the fixed build,
MLXCEL_FUSED_MOE=0runs also diverge bitwise run-to-run and one of two produced "During the Middle 이루어진 Middle Ages";MLXCEL_FUSED_MOE=0 MLX_USE_CUDA_GRAPHS=0still diverges; even a single-turn fused-disabled control diverges bitwise. The fused-off 5/5-clean discriminator from triage does not hold on current main, so the 10-consecutive-clean-runs acceptance gate is blocked by a pipeline-level defect, filed as 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 with the full evidence matrix.docs: document the #886 fused-MoE parity probe env vars
fix(moe): keep fused decode-MoE partials in f32 until the final K-sum (…
chore(release): v0.4.3
update(rocm): port the fused MoE decode kernels to HIP
update(rocm): port the fused MoE decode kernels to HIP (#2098)
fix(moe): keep fused decode-MoE partials in f32 until the final K-sum (…
chore(release): v0.4.3