Skip to content

fix(cuda): explain the fused add+RMSNorm greedy divergence as a near-tie - #3507

Merged
inureyes merged 4 commits into
mainfrom
fix/issue-3501-fused-norm-divergence
Nov 28, 2026
Merged

inureyes merged 4 commits into
mainfrom
fix/issue-3501-fused-norm-divergence

Conversation

@inureyes

@inureyes inureyes commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Summary

The greedy divergence between the graph path and MLXCEL_FUSED_ADD_RMSNORM=1 on llama-3.2-1b-instruct-bf16 (GB10, B=1, 128-token prompt) is a near-tie from the fp32 summation order of the RMSNorm sum of squares, not a kernel defect. This PR adds the probe that measures it, pins the measured relationship in a CUDA test, and corrects the docs. The kernel is unchanged.

Findings

  • The probe reproduces both CLI digests (153e97b6c47aae0d graph, ca3dde687d118faf fused) with route counters checked. Teacher-forced, the only argmax flip in 128 steps is step 11: graph 287 and 430 tie exactly at 18.5 (margin 0); fused 430 at 18.5 over 287 at 18.375 (margin 0.125). Accumulated logit deviation at that step is at most 0.125.
  • The logits differ from step 0. The first divergent tensor is layer 1's normed in the prefill (19 of 262,144 elements, 1 bf16 ulp); new_residual never diverges first.
  • Same input, both ops: new_residual is byte-identical everywhere; normed differs on 2 of 2048 prefill rows and on no step-11 row. Each side's row is reproduced exactly by one fp32 normalizer, and a float64 reference agrees with the fused kernel on one row and the graph on the other.
  • MLX dispatches rms_norm_small<bf16, 128, 2, _, 8> at dim 2048 (ALIGNED depends on runtime pointers). Simulated in fp32 in that order and in the fused kernel's 512 lanes of 4, the two rows' sums of squares are one fp32 ulp apart, in the direction the fitted normalizers predict.
  • Against the issue's one-ulp budget: the rounded intermediate bf16(x * inv) is within one ulp. Two output elements are two ulps apart, because the gain multiply carries the intermediate's change across a binade. So the issue's literal one-ulp criterion on the output is not met. I still took the near-tie branch, because a single per-row normalizer explains both sides.

What changed

  • examples/fused_norm_divergence_probe.rs (+ tensors.rs, op_diff.rs): steps, --dump-layers, --compare, --op-diff, and a route check that refuses a mismatched arm (--expect-route is checked at parse time and honoured by --op-diff; --compare rejects it). Dump manifests are validated before any tensor is built (no path components in names, known dtype, non-negative dims, element count times dtype size equal to the file size).
  • fused_norm_parity_tests/cuda_near_tie.rs: on CUDA at bf16 dim 2048 over 6 seeds of 4096 rows (5 of 24,576 rows differ, about 3 s), new_residual is byte-identical, differing normed rows are at most 2 ulps apart, and each is reproduced by one fp32 normalizer within 32 ulps. It also asserts that some rows differ, so it fails once the kernel becomes byte-identical. It replaces the "within one ulp" test the brief asked for, because the measured output bound is two. A mutated formula (rounding w * x first) was checked to fail it.
  • Docs: the fused_add_rmsnorm_enabled comment, the evidence doc next to "One observation outside the gate", and the stale UNVALIDATED header in fused_norm.cpp. Raw CSVs are in docs/benchmark_results/issue-3501-fused-norm-divergence-gb10-2026-11-28/; the analysis script is scripts/fused_norm_normalizer_fit.py.

Changes during review

  • The normalizer-fit tool moved from the results folder to scripts/, per the results README.
  • The probe and the fit script now validate their inputs (dump manifests, --prompt-tokens 0, token ids against the vocabulary, safetensors header bounds and dtype, unsupported widths), and --op-diff reads a dump once.
  • Wording now matches the measurement: ALIGNED was not observed and selects only the load function; the intermediate is within one ulp and the output within two, which exceeds the issue's literal budget; the fit ranges are clipped at the script's 24-ulp search limit.
  • The near-tie test runs 6 seeds instead of 4, and its failure message says to check MLX's dim-2048 dispatch before switching to a byte-identity pin.

Follow-up, not done here: byte identity needs MLX's per-dim geometry (dispatch_num_chunks, 16-byte chunked loads, the looped kernel past 8192) and a regenerated cuda-oxide artifact. That artifact is a bitwise port of the current kernel, and its toolchain is not on this host.

Test plan

  • fused_norm_parity_tests (11 tests) pass on GB10 with MLXCEL_FUSED_ADD_RMSNORM unset, =0 and =1 (--test-threads=1, under gpu-lock)
  • Probe free-run digests match m1-end-to-end.csv on both arms; layer walk gives byte-identical steps.csv to the plain forward
  • clippy -D warnings on mlxcel-core --lib --tests and the probe example; cargo fmt --check; check_benchmark_raw_logs.py, check_kernel_dtype_keys.py, check_kernel_port_dispatch.py, check_benchmark_csv_schema.py, check_used_by.py, check_env_var_docs.py
  • Probe smoke run after the review fixes: fused arm step 11 margin 0.125, top-1 430; --op-diff reports layer 1; a malformed dump manifest is rejected

Closes #3501

On GB10, llama-3.2-1b-instruct-bf16 at B=1 on the 128-token prompt generates other text with MLXCEL_FUSED_ADD_RMSNORM=1. The new examples/fused_norm_divergence_probe.rs reproduces both arms' CLI token digests, teacher-forces both on the graph arm's tokens, dumps every layer's tensors at a chosen step, diffs two dumps, and feeds one arm's join inputs to graph_add_rms_norm and the fused launcher in one process.

The only argmax flip is step 11, where the graph's top two are an exact bf16 tie (margin 0; fused margin 0.125, accumulated logit deviation at most 0.125). The arms first part in the prefill at layer 1's normed. On the same input new_residual is byte-identical and normed differs on 2 of 2048 prefill rows, each side reproduced by one fp32 normalizer, the float64 reference agreeing with each side once. Simulated in fp32, MLX's rms_norm_small<bf16, 128, 2, _, 8> and the fused kernel's 512 lanes of 4 sum the squares one fp32 ulp apart on both rows. The intermediate differs by one bf16 ulp, the output by up to two.

No kernel change: making it byte-identical needs MLX's launch geometry and a regenerated cuda-oxide artifact. A CUDA test pins the relationship, the fused_add_rmsnorm_enabled doc, the evidence doc and the stale UNVALIDATED header cite it, and raw results are recorded as CSV.

Refs #3501
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:medium Medium priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific labels Nov 28, 2026
docs/benchmark_results/README.md says maintained harnesses belong in scripts/ and result folders hold data, which is where #2834 put its oxide_fused_norm tools. The fit script that explains the two differing prefill rows now lives at scripts/fused_norm_normalizer_fit.py with the shebang and Apache header of its siblings, and the results README points at the new path.

Re-ran it on the probe's layer 1 and layer 11 op-diff dumps: output matches normalizer-fit-prefill.csv.

Refs #3501
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Explain the graph vs fused add+RMSNorm greedy divergence on GB10 (#3501), document it as a near-tie, and pin the measured relationship without touching the kernel.

Findings Addressed

Remaining Items

  • Four in-tree sites (results README, evidence doc, fused_norm.cpp comment, cuda_near_tie.rs doc) write rms_norm_small<bf16, 128, 2, true, 8> as observed, while the PR body and issue comment say ALIGNED was not observed. ALIGNED only picks the load function in rms_norm.cu, so the conclusion holds; the wording should match (MEDIUM)
  • cuda_near_tie.rs: the differing_rows > 0 pin rests on 4 of 16384 rows, so an MLX change to the reduction order could reach zero by chance; the message asserts byte identity and should instead say to check the dim-2048 dispatch against fused_norm_threads first (MEDIUM)
  • The layers.rs comment says a normed element lands "one bf16 ulp away (two after the gain multiply)"; normed is the post-gain output, so it is the intermediate that is one ulp away (LOW)
  • The evidence doc says "one or two bf16 ulps" but does not say this exceeds the issue's one-ulp budget; the results README does (LOW)
  • Probe: --op-diff prints no route, and in a non-oxide build --expect-route fused is satisfied by the switch alone. The committed runs used counters, so the data is unaffected (LOW)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (fused_norm_parity_tests 11/11 on GB10 with the switch unset, =0 and =1; 4 of 16384 rows differ in each; clippy -D warnings on the probe and mlxcel-core --lib --tests, fmt clean)

@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH findings, so nothing was changed or pushed. Every probe and script input (--out, --tokens, --op-diff, --compare, the Python script's arguments) comes from the operator on their own host, and neither #3501 nor this PR sends dump files across a trust boundary. The layers.rs and fused_norm.cpp changes are comment-only, and the CUDA launcher rejects mismatched shapes, dtypes and weight length before any kernel runs.

Remaining Items

  • examples/fused_norm_divergence_probe/tensors.rs:80-88,102-104: read_dump takes the shape from manifest.csv and never checks it against the .bin length or for negative dims. to_array then calls from_bytes, which copies prod(shape) elements from the slice pointer with no length check (mlx_cxx_bridge.cpp:500), so a manifest whose shape is larger than its file makes --op-diff read past the heap buffer. A check like validate_raw_tensor (src/distributed/kv_cache_serde/types.rs:487) in read_dump would close it (MEDIUM)
  • tensors.rs:88: the manifest name goes into dir.join unchecked, so an absolute or .. name reads a .bin outside the dump directory. Read-only (LOW)
  • tensors.rs:94-99 with op_diff.rs:81-82: read_one re-reads and re-parses the whole dump for each lookup, two lookups per layer, so about 32 full reads (roughly 1.3 GB for the 1B prefill dump). Read the dump once and index it by name (LOW)
  • fused_norm_divergence_probe.rs:261: --prompt-tokens 0 gives an empty prompt, and prompt.len() - 1 underflows before the empty-prompt check at line 274. Reject 0 at argument parsing (LOW)
  • fused_norm_divergence_probe.rs:218-227: --tokens ids are parsed as i32 with no range check against the vocab (LOW)
  • scripts/fused_norm_normalizer_fit.py: read_weight trusts the safetensors header length and offsets, does not check that the entry is BF16, and assumes a single-file checkpoint. mlx_small_sum hardcodes 128x2x8, so a dim other than 2048 raises IndexError or gives the wrong sum, and argv is not validated. No eval, subprocess or pickle (LOW)
  • --out truncates existing steps.csv and dump files under the chosen directory. File names are fixed formats, so the writes cannot leave that directory (informational)

Measured

cuda_fused_add_rms_norm_differs_from_the_graph_only_by_its_normalizer (4096x2048, 4 seeds) on GB10, release --features cuda, under gpu-lock: 2.14 s, 764 MB max RSS, 4 of 16384 rows differ. The test's runtime is not a concern.

The results README, evidence doc, fused_norm.cpp header comment and cuda_near_tie.rs doc wrote `rms_norm_small<bf16, 128, 2, true, 8>` as if the ALIGNED argument had been observed. Only the block size, chunk count and read width were read from MLX's dispatcher; ALIGNED selects the load function, not the summation order, so those sites now say it was not observed and does not change the conclusion.

The layers.rs comment now says the rounded intermediate bf16(x * inv) is one ulp away and the post-gain normed output up to two. The evidence doc and README state that the two-ulp output exceeds the issue's one-ulp budget and why the near-tie verdict still holds (one fp32 normalizer per side reproduces each row, a float64 reference splits). The README notes that the normalizer fit ranges are clipped at the script's 24-ulp search limit. The new results folder is added to docs/benchmark_results/README.md.

Comment and doc changes only; the kernel string is untouched.

Refs #3501
…cript

read_dump now checks each manifest entry before from_bytes trusts it: the tensor name cannot hold a path separator or `..`, the dtype is one the probe dumps, no dimension is negative, and element count times element size equals the .bin size. --op-diff reads the dump once and looks tensors up by name instead of re-reading it per lookup.

The probe rejects --prompt-tokens 0 and --expect-route values other than graph, fused or oxide at parse time, checks --tokens ids against the logits width, prints the route for --op-diff and honours --expect-route there, and rejects --expect-route with --compare. fused_norm_normalizer_fit.py checks the safetensors header length, entry dtype (BF16) and data offsets, validates argv, and exits with a message for any width other than the 2048 geometry it models.

cuda_near_tie.rs runs six seeds instead of four (5 of 24576 rows differ, 3.0 s) and its zero-rows failure message now tells the reader to compare MLX's dim-2048 dispatch with fused_norm_threads before switching to a byte-identity pin.

Validation: clippy -D warnings on the probe example and mlxcel-core --lib --tests, cargo fmt --check, fused_norm_parity_tests 11/11 on GB10 with the switch unset and =1 under gpu-lock, probe smoke run (teacher-forced prefill dump, --op-diff) and the benchmark and used-by and env-var checks.

Refs #3501
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
@inureyes
inureyes merged commit f0d06f5 into main Nov 28, 2026
33 checks passed
@inureyes
inureyes deleted the fix/issue-3501-fused-norm-divergence branch November 30, 2026 14:01
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers area:inference Generation, sampling, decoding (incl. speculative, DRY) platform:linux Linux (CUDA / packaging) specific priority:medium Medium 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.

fix(cuda): Greedy output differs between graph path and fused add+RMSNorm on Llama 3.2 1B

1 participant