Repository navigation
Description
Problem / Background
On GB10 (sm_121) with llama-3.2-1b-instruct-bf16, the unfused graph path and the existing fused residual-add + RMSNorm kernel produce different greedy output on the 128-token synthesized prompt at B=1. "Graph path" here means the add + fast_rms_norm composition in graph_add_rms_norm (src/lib/mlxcel-core/src/layers.rs:1207-1215), not CUDA Graph capture. Found during #2834 (PR #3477) and recorded, uninvestigated, in docs/mlxcelverse/cuda-oxide-benchmark-evidence.md:186 ("One observation outside the gate").
Measured facts, from docs/benchmark_results/cuda-oxide-fused-norm-gb10-2026-11-27/m1-end-to-end.csv:
- CLI B=1 and server B=1, prompt 128, max 128: the
grapharm (MLXCEL_FUSED_ADD_RMSNORMunset) generates 128 tokens (tokens_sha256_16=153e97b6c47aae0d); thefusedarm (MLXCEL_FUSED_ADD_RMSNORM=1),fused-nulland the cuda-oxide route all stop on EOS id 13 after 98 tokens (ca3dde687d118faf). Each arm is deterministic across all 7 rounds. - The first 11 generated tokens are identical. The first divergence is generated index 11 (0-based):
graphpicks 287,fusedpicks 430. That token comes from the width-one decode step whose input sits at absolute position 138 (128 prompt + 10 generated). - Server B=4 / 128, B=1 / 2048 and B=4 / 2048 are identical across all four arms. Row 0 at B=4 / 128 picks 287 at index 11, as
graphdoes at B=1, and then departs from B=1graphat index 26. Only B=1 / 128 separates the arms. env_cuda_graphswas unset in every arm.- The M2 teacher-forced traces of
graph,fusedandoxideare byte-identical (m2-logit-trace-comparison.txt). They use a different text,tests/fixtures/bench/fused-moe-dff-prompt-439-words.txt, with a 256-token forward and 112-token width-one decode chunks (run.sh:312-344), so they never cover this prompt, a 128-token prefill, or KV length 128-139.
The difference predates cuda-oxide: it is the existing fused kernel against the graph path. FUSED_ADD_RMSNORM_DEFAULT is off on CUDA (layers.rs:1012), so default users are on the graph path. Anyone who opts in gets different text, and the #2834 throughput comparison between graph and fused on this cell compares runs of different length.
Current Behavior
- Call sites:
TransformerBlock::forward(src/models/llama3.rs:1063-1064) andforward_batched(llama3.rs:1107) callmlxcel_core::layers::fused_add_rms_norm(layers.rs:1172-1200). When the switch is on and the inputs are eligible, that dispatchesffi::fused_add_rms_norm; otherwise it callsgraph_add_rms_norm. - CUDA kernel:
FUSED_ADD_RMS_NORM_CUDA_SOURCE(src/lib/mlxcelverse/kernels/fused_norm.cpp:178-250). It sums in fp32, rounds the sum to T, storesnew_residual, accumulates the square of the rounded value, reduces via__shfl_xor_syncplus shared memory, and computesrsqrtf(total / dim + eps). It then forms(T)(sr * inv_mean)and multiplies by the gain. The header comment atfused_norm.cpp:159still says "UNVALIDATED"; it is stale and should be corrected or removed as part of this issue. - Documented stance: the doc comment on
fused_add_rmsnorm_enabled(layers.rs:1040-1046) says the two paths differ only by rounding of the residual sum and that a near-tie flip is "not a regression". The ROCm port is asserted byte-identical to its graph (fused_norm_parity_tests.rs:567). CUDA has no byte-identity test:fused_add_rms_norm_matches_graph_across_dtypes_and_shapes(:217) uses the bf16 tolerance(1.6e-2, 7e-2)fromtolerance_for(:58), and the greedy test at:463is synthetic f16 at dim 1024.
Proposed Solution
Investigate first, then fix if a defect is found.
- First divergent step and margin. Add
examples/fused_norm_divergence_probe.rs. It loads the checkpoint, builds the prompt withmlxcel::server::engine_probe::prompt::synthesize_prompt_tokens(tokenizer, 128)(src/server/engine_probe/prompt.rs:61:LONG_PROMPT_CORPUSrepeated, BOS, truncated, no chat template), prefills it in one forward, and then runs width-one decode steps teacher-forced on a token stream read from a file (thegrapharm's 128 tokens from the CSVfirst_row_tokens). Per step it prints position, argmax, top-2 ids and logits, and the top-1 minus top-2 margin. Run it once per arm, in separate processes, because the switch is process-global. Teacher-forcing keeps both arms on the same text, so every step stays comparable after the flip. Record the margin at index 11 on both arms. - Per-layer localization. In the same probe, behind
--dump-layers <step>, walkLlama3Model.embed_tokens,layers[i]andnorm(public atllama3.rs:1165-1168) at the given step. For every layer, dump the raw bytes ofattn_out, the residual after the first join (h), thenormedMLP input and the block output, then diff the two arms' dumps offline. Report the first layer and the first tensor that are not byte-identical, with max abs and RMS deviation, and whethernew_residualornormeddiverges first. To isolate the join, feed that layer's graph-arm inputs into bothgraph_add_rms_normand the fused launcher and diff the outputs. - Decide by this criterion, from the feat(xla): define operator-level MLX/IREE numeric contracts #932 contract (per-op same-input parity plus greedy token-exactness on a reference is the gate; accumulated drift is recorded, not gating):
- Near-tie. Step 2's same-input op diff is within one bf16 ulp per element, and the graph arm's margin at the flip is at or below the accumulated logit deviation. Document it: amend
layers.rs:1040-1046to cite this measurement, add a paragraph with the numbers to the evidence doc next to line 186, and do not change the kernel. - Defect. The kernel computes something different from
graph_add_rms_normon the same inputs beyond that budget. Candidates: eps applied differently, residual sum or output dtype, accumulation precision, gain rounding order ((T)(sr * inv_mean)then* gainversus MLX'sfast_rms_normorder), orweight_biashandling. Fix the kernel or its launcher (fused_norm.cpp) so the outputs match MLX's CUDArms_norm.
- Near-tie. Step 2's same-input op diff is within one bf16 ulp per element, and the graph arm's margin at the flip is at or below the accumulated logit deviation. Document it: amend
Scope
In scope: the probe example; src/lib/mlxcelverse/kernels/fused_norm.cpp (CUDA source and launcher) if a defect is found; src/lib/mlxcel-core/src/fused_norm_parity_tests.rs; the doc comment at layers.rs:1040-1046; the stale comment at fused_norm.cpp:159; the evidence doc paragraph.
Out of scope: changing FUSED_ADD_RMSNORM_DEFAULT; the Metal and ROCm kernels (unless step 2 shows the same formula error in the Metal body, in which case note it in a follow-up issue); the cuda-oxide route (it is bitwise identical to the fused kernel per M2(c)).
Implementation Notes
- Reuse:
synthesize_prompt_tokens, the model loader the checkpoint bench uses (examples/oxide_fused_norm_checkpoint_bench.rs),fused_norm_route_snapshot()to print the route each probe process took,graph_add_rms_normas the reference, andraw_bytes/normalized_deviationfromfused_norm_parity_tests.rs:106-128for diffs. - Constraints: the probe must refuse to run when its route counters do not match the requested arm, like
--expect-routein the checkpoint bench. Keep the dumps out of the checkout (write them to a--outdir). - Edge cases: if steps 0-10 are not byte-identical under teacher-forcing, report the earliest differing step rather than index 11. If the arms agree at every step of the probe, the probe does not reproduce the CLI path (check prefill chunking and the cache type the CLI uses) and that must be resolved before step 3.
Acceptance Criteria
- The root cause is stated in a comment on this issue, with the step-1 margins for both arms and the step-2 first divergent layer and tensor, plus the deviation numbers.
- Near-tie outcome:
layers.rs:1040-1046and the evidence doc cite the measurement, and the probe example is committed so the measurement can be repeated. - (n/a, near-tie outcome) Defect outcome: the
fusedandgrapharms produce identical greedy token ids on the 128-token prompt at B=1 (becomes identical) and B=4 (stays identical), on both the CLI and server paths, on GB10. - (n/a, near-tie outcome; fix(cuda): explain the fused add+RMSNorm greedy divergence as a near-tie #3507 adds
cuda_near_tie.rsinstead) Defect outcome: a new CUDA testfused_add_rms_norm_is_byte_identical_to_the_cuda_graphinfused_norm_parity_tests.rs, modeled on the ROCm one at:567, covers bf16 at dim 2048. It fails on current code and passes after the fix. - Existing
fused_norm_parity_testspass with the switch on and off. - The "UNVALIDATED" comment at
fused_norm.cpp:159is corrected.
Verification
GPU work on GB10 must run under gpu-lock. Build outside the lock, and run CUDA tests with --test-threads=1.
MLXCEL_BUILD_CUDA_OXIDE_FUSED_NORM=1 MLXCEL_CUDA_ARCHITECTURES=121 cargo build --release --features cuda --example oxide_fused_norm_checkpoint_bench --example fused_norm_divergence_probe
# reproduce (expect 128 vs 98 tokens today)
env -u MLXCEL_FUSED_ADD_RMSNORM gpu-lock run --tag fused-norm-div -- target/release/examples/oxide_fused_norm_checkpoint_bench --model models/llama-3.2-1b-instruct-bf16 --path cli --batch 1 --prompt-tokens 128 --max-tokens 128 --warmup-tokens 16 --label graph --expect-route graph
MLXCEL_FUSED_ADD_RMSNORM=1 gpu-lock run --tag fused-norm-div -- target/release/examples/oxide_fused_norm_checkpoint_bench --model models/llama-3.2-1b-instruct-bf16 --path cli --batch 1 --prompt-tokens 128 --max-tokens 128 --warmup-tokens 16 --label fused --expect-route fused
# repeat both with --path server --batch 1 and --path server --batch 4
MLXCEL_CUDA_ARCHITECTURES=121 cargo test --release -p mlxcel-core --lib --features cuda --no-run
gpu-lock run --tag fused-norm-div -- cargo test --release -p mlxcel-core --lib --features cuda fused_norm_parity_tests -- --test-threads=1
MLXCEL_FUSED_ADD_RMSNORM=0 gpu-lock run --tag fused-norm-div -- cargo test --release -p mlxcel-core --lib --features cuda fused_norm_parity_tests -- --test-threads=1
cargo clippy --release --features cuda --all-targets -- -D warnings && cargo fmt --checkA pass after a fix is the same tokens_sha256_16 for graph and fused in every cell. A pass after a near-tie finding is the recorded margins plus the doc updates.
Activity
inureyes commentedon Nov 28, 2026
Root cause: a near-tie from the fp32 summation order of the RMSNorm sum of squares, not a kernel defect. Measured on GB10 with
examples/fused_norm_divergence_probe.rsin PR #3507 (baseda347a2b, driver 580.178.04, oxide build so every process printed its route counters). Raw data:docs/benchmark_results/issue-3501-fused-norm-divergence-gb10-2026-11-28/.Reproduction. Free-running, the probe gives the CLI digests of
m1-end-to-end.csvexactly: graph153e97b6c47aae0d(128 tokens, 0 fused joins), fusedca3dde687d118faf(98 tokens, 1584 native joins, 0 oxide). It uses the same one-forward prefill scored at the last position and the samemake_cachescaches as the CLI.Step 1, margins (both arms teacher-forced on the graph tokens). The only argmax flip in 128 steps is generated index 11 (position 138). Graph: 287 = 430 = 18.5, an exact bf16 tie broken to the lower id, margin 0. Fused: 430 at 18.5, 287 at 18.375, margin 0.125. Step 10 margin is 1.75 on both. The logits are not identical before step 11: they differ from step 0, the prefill. At step 11 the logit deviation is max abs 0.125 and RMS 0.0283 (reference RMS 2.76), so the graph margin (0) is below it.
Step 2, localization. In the prefill dump, everything through layer 1's
his byte-identical. The first divergent tensor is layer 1'snormed(MLP input): 19 of 262,144 elements, each 1 bf16 ulp (max abs 1.95e-3, RMS 7.0e-6).new_residualnever diverges first. At step 11 the first divergent tensor is layer 2'sattn_out, which reads the prefill KV.Same-input op diff (graph-arm inputs into
graph_add_rms_normand the fused launcher in one process).new_residualis byte-identical on all 16 layers.normeddiffers on 2 of 2048 prefill rows: layer 1 row 124 (19 elements, 1 ulp) and layer 11 row 47 (27 elements, 25 at 1 ulp, 2 at 2 ulps). It differs on none of the step-11 decode rows. Against a float64 reference, the fused kernel is exact and the graph misses 19 on layer 1; on layer 11 it is the reverse (27 vs 0). Each differing row of each side is reproduced exactly bybf16(w * bf16(x * inv))with one fp32inv, and the sides fall on opposite sides of a rounding boundary. Layer 1: graph needs 0..+24 fp32 ulps from the rounded exact normalizer, fused -24..-1. Layer 11: +1..+24 and -24..0. Under those normalizers the intermediatebf16(x * inv)differs by at most 1 bf16 ulp. The 2-ulp outputs are the gain multiply carrying that across a binade.Why. MLX CUDA
rms_normat bf16 dim 2048 dispatchesrms_norm_small<bf16, BLOCK_SIZE=128, N_CHUNKS=2, ALIGNED, N_READS=8>(viadispatch_num_chunks, nvec 256; nsys in #2834 shows a 128-threadrms_norm_smallblock;ALIGNEDdepends on pointers and was not observed). Each thread sums[8t, 8t+8)then[1024+8t, ...),cg::reducebutterflies each warp (xor 16 down to 1), then four warp partials. The fused kernel runs 512 lanes of 4 with the same butterfly and folds 16 warp partials. Simulated in fp32 in those two orders, the sums of squares of the two rows are one fp32 ulp apart (3.1238654 vs 3.1238656; 74.0694 vs 74.069405). The smaller MLX sum means the larger normalizer, which is the graph's side in both fits.Decision. Near-tie branch, with one caveat against the literal budget. The intermediate is within one ulp, but two output elements are two ulps apart, so "within one bf16 ulp per element" does not hold for the output. There is no formula difference: one per-row normalizer reproduces both sides, and the float64 reference sides with each arm once. The kernel is unchanged. The CUDA test added in #3507 pins the measured relationship: byte-identical
new_residual,normedwithin 2 ulps, every differing row fitted by one normalizer, and at least one differing row.Follow-up if byte identity is wanted (not filed). Port MLX's geometry into
FUSED_ADD_RMS_NORM_CUDA_SOURCEand its launcher. That meansdispatch_num_chunks' block size and chunk count per dim, 16-byte vector loads with the per-thread chunk order, and the loopedrms_norm<T, 1024, N_READS>path pastN_READS * 1024, as the ROCm port did with its overlay's 256-thread block. The cuda-oxide artifact is a bitwise port of the current kernel and its tests assert bitwise equality, so that change also needs the artifact regenerated with the cuda-oxide toolchain. That toolchain is not installed on this host.chore: move the #3501 normalizer-fit tool from results into scripts
docs: align the #3501 wording with what was measured
fix(probe): validate dumps and arguments in the #3501 probe and fit s…
fix(cuda): explain the fused add+RMSNorm greedy divergence as a near-…
feat(cuda): make fused add+RMSNorm byte-identical to MLX rms_norm (#3512