Skip to content

feat(cuda): make fused add+RMSNorm byte-identical to MLX rms_norm - #3512

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-3510-cuda-fused-norm-byte-identity
Nov 28, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-3510-cuda-fused-norm-byte-identity

Conversation

@inureyes

@inureyes inureyes commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Summary

  • On CUDA, fused_add_rms_norm now returns the bytes of the default add + fast_rms_norm pair for every dtype pair and row width, so MLXCEL_FUSED_ADD_RMSNORM=1 no longer changes greedy text (fix(cuda): Greedy output differs between graph path and fused add+RMSNorm on Llama 3.2 1B #3501). The kernel reads a row as MLX's rms_norm does: compute dtype promote_types(activation, weight), vectors of 16 / sizeof(compute) elements, the block of dispatch_num_chunks (64, 128, or 1024 for the looped kernel), thread t summing vectors t, t + block, ... in order.
  • The cuda-oxide kernel follows the same contract and the artifact is regenerated (PTX ed470a19c4848893, cubin 390fcc2833e532ef). Manifests record fused_norm_cuda_block(dim, n_reads) and n_reads; the adapter refuses an artifact built for the old rule or another vector width.
  • FUSED_ADD_RMSNORM_DEFAULT is unchanged. The Metal and ROCm bodies, geometry and template args are unchanged.
  • scripts/env.sh in both spike packages can be sourced from zsh.

Differences from the issue text

  • bf16 under an f32 weight computes in bf16 (n_reads 8, weight rounded to bf16), not f32: this tree's promotion table makes bf16 with f32 bf16. The same holds for f32 under a bf16 weight.
  • The CUDA geometry is selected by MLXCEL_BRIDGE_CUDA_BACKEND, because verify-kernel-port-dispatch forbids gpu_kernel_backend() == in a launcher.
  • The cubin ceiling in the binary-assets check goes from 80 to 100 KB (the cubin is 89.8 KB).
  • Six widths were added to the parity matrix (768, 1280, 1536, 1792, 2560, 3584) to reach the 64-thread multi-chunk branch, and a second oxide test launches the artifact on the branches the 130-case matrix misses.

Kernel time

The matching geometry is slower. With the #2834 M4 method (bf16, width 2048) the fused and cuda-oxide kernels take 1.3 to 2 times their earlier time (3.4 against 2.2 µs at one row, 12.7 against 6.5 µs at 128 rows, 186 against 140 µs at 2048 rows), while the graph path's kernels are unchanged, so the graph path is now faster at all five shapes. One end-to-end round shows no difference above 1.5 %. A CI job overlapped the stage and it was not repeated on an idle host. Rows and table: docs/benchmark_results/cuda-fused-norm-byte-identity-gb10-2026-11-28/.

Changes during review

  • Review and security passes found nothing at CRITICAL or HIGH. A follow-up commit fixes the stale PTX digest and JIT module name in the adapter evidence page (now labelled as the 2026-11-26 values next to ed470a19...), points two comments at kernels/fused_norm_cuda.h for fused_norm_cuda_block, and documents host_model as a tolerance model rather than a summation-order model. These spike edits are comment-only; the committed PTX has no .loc or .file directives, so the artifact bytes are unchanged.
  • Main was merged in to resolve a CHANGELOG conflict; the parity tests were rerun on the merged tree.

Known limits, not addressed here

  • The Rust artifact validator checks n_reads but not compute_dtype (the Python tool checks both). It compiles only in the opted-in oxide build, and the PTX digest pin covers the committed artifact.
  • Rows sit on grid.z, so an opted-in launch with more than 65535 rows fails with a launch error. This predates the PR; changing it means editing the kernel body and regenerating the artifact.
  • A faster kernel with the same summation order (16-byte vector loads, row kept in registers, as rms_norm_small does) was not attempted.

Test plan

  • cuda_byte_identity (8 dtype pairs, 21 widths at 1 and 33 rows, the fix(cuda): Greedy output differs between graph path and fused add+RMSNorm on Llama 3.2 1B #3501 seeds, Gemma fold, eps 1e-5, spread row scales, signed zeros, non-finite rows): 270 failing cases on main, passes now.
  • fused_norm_parity_tests with MLXCEL_FUSED_ADD_RMSNORM unset, =0, =1: 13 passed each, release, GB10.
  • cuda_oxide in an opted-in build: 33 passed; matrix cases=130 failed=0 bitwise_identical_to_fused_cuda=130, graph equality on finite rows.
  • Spike build.sh, run.sh (130 cases, launch check), compare.sh (130 bitwise), bench.sh, check-lint.sh, check-clean-build.sh. The oracle ran from the release-built example, not through oracle.sh.
  • Six Benchmark cuda-oxide RMSNorm and record the adoption decision #2834 cells: one tokens_sha256_16 per cell across graph, fused, oxide, routes matching each arm; B=1 / 128 is 153e97b6c47aae0d on all three.
  • Probe: --compare of the two arms' prefill dumps byte-identical, --op-diff 0 differing elements on 16 layers.
  • cargo clippy -p mlxcel-core --features cuda --all-targets -- -D warnings with and without the oxide build flag, cargo fmt --check, verify-kernel-dtype-keys, verify-kernel-port-dispatch, verify-binary-assets.
  • Not run: Metal parity tests, Compute Sanitizer on the new artifact, any CUDA architecture other than sm_121.

Closes #3510

The CUDA fused kernel swept a row with its own geometry (ceil(dim/4) lanes of four elements), so the fp32 sum of squares was reduced in another order than MLX's rms_norm and a normed element could land one or two bf16 ulps away, enough to break an exact logit tie the other way with MLXCEL_FUSED_ADD_RMSNORM=1 (#3501).

The CUDA body now takes MLX's geometry: compute dtype promote_types(activation, weight), vectors of 16 / sizeof(compute) elements, the block width of dispatch_num_chunks and the eval_gpu threshold (fused_norm_cuda_block), and the per-thread strided vector order. This tree's promotion table makes bf16 with f32 bf16, so that pair computes in bf16, not f32 as the issue assumed. The geometry is chosen by the CUDA build flag because the port-dispatch check forbids comparing the backend kind in a launcher. Metal and ROCm are unchanged.

The cuda-oxide kernel follows the same contract and its artifact is regenerated (PTX ed470a19c4848893, cubin 390fcc2833e532ef). Manifests record fused_norm_cuda_block(dim, n_reads) and each entry's n_reads, and the adapter refuses an artifact built for the old rule or another vector width. The cubin ceiling in the binary-assets check goes from 80 to 100 KB.

cuda_byte_identity.rs replaces cuda_near_tie.rs: eight dtype pairs, 21 widths over every dispatch branch, the #3501 seeds, the Gemma fold, signed zeros and non-finite rows. It fails on the previous kernel (270 cases) and passes now. The oxide matrix test requires bit identity with the kernel on all 130 cases and with the graph on finite rows.

Both env.sh files now work when sourced from zsh.

Refs #3510
After the kernel change the graph, fused and cuda-oxide arms give one token digest per cell on the six #2834 cells of llama-3.2-1b-instruct-bf16 (B=1 / 128 is 153e97b6c47aae0d on all three, where the fused arms used to stop after 98 tokens), the probe's prefill dumps of the two arms are byte-identical, and its op diff reports no differing element on any layer. The rows are in docs/benchmark_results/cuda-fused-norm-byte-identity-gb10-2026-11-28/, and the spike's compare and bench results are from the regenerated artifact.

The evidence documents of #2832, #2833 and #2834 get dated notes with the new artifact digests instead of rewritten tables, the environment-variable reference and the CHANGELOG state that opting in on CUDA no longer changes output, and the dated #2834 and #3501 result directories are untouched.

Refs #3510
…hange

The #2834 M4 method (nsys, CUDA graphs off, bf16 width 2048) on GB10 shows the cost of matching MLX's summation order: with MLX's 128-thread block the fused kernel and the cuda-oxide kernel take 1.3 to 2 times their 2026-11-27 time at the five model shapes (3.4 against 2.2 us at one row, 186 against 140 us at 2048 rows). The graph path's kernels read the same as before, so the change is the kernel's, and the graph path is now faster at every shape. One end-to-end round shows no difference above 1.5 %.

The CSVs and the table are in the new results directory, and the benchmark evidence note, the results index and the CHANGELOG state the regression. A CI job overlapped the stage and it was not repeated on an idle host.

Refs #3510
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions 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
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Make the CUDA fused add+RMSNorm byte-identical to add + fast_rms_norm for every accepted dtype pair and width, and regenerate the cuda-oxide artifact to stay bit-identical to it (#3510).

Findings Addressed

No CRITICAL or HIGH findings; no fixes pushed.

Remaining Items

  • docs/mlxcelverse/cuda-oxide-mlx-adapter-evidence.md:20 and :64 still describe the artifact and JIT module name with the old PTX digest b54c1c93... in present-tense prose. The dated update note above them covers it, but the module-name sentence reads as current (LOW).
  • host_model in spike/cuda-oxide-fused-norm/src/main.rs keeps its sequential f64 summation, while issue section 2 says it must mirror the new order. Defensible, since it is a tolerance model independent of the device order, but undeclared (LOW).
  • Several comments (cuda_byte_identity.rs module doc, main.rs fused_norm_cuda_block doc) place fused_norm_cuda_block in kernels/fused_norm.cpp; it lives in fused_norm_cuda.h (LOW).
  • The promotion table is restated in four places (Lane::n_reads_under, spike Case::compute, oxide_artifact.py::compute_dtype, the standalone bench), and an_entry_compiled_for_another_vector_width_is_refused recomputes the same expression it checks. An overlay table change would be caught only by the GPU matrix, not by the validator (LOW).
  • Kernel time was measured with a CI job overlapping and not repeated, as the PR states; the unchanged graph-kernel controls make the attribution reasonable (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 (locally on GB10, release, --test-threads=1: fused_norm_parity_tests 13/13 with MLXCEL_FUSED_ADD_RMSNORM unset, =0, =1; make verify-kernel-dtype-keys verify-kernel-port-dispatch and check_binary_assets.py pass. Oxide tests were not rerun here because they need the opted-in build; CI status not checked)

Checked against the MLX source at the pin: fused_norm_cuda_block equals dispatch_num_chunks plus the N_READS * 1024 threshold of RMSNorm::eval_gpu; the per-thread vector walk, FMA accumulation, two-stage xor butterfly (cg::reduce on a 32-wide tile is shfl_xor 16 to 1) and cast points match rms_norm_small and rms_norm. The pre-change binary's cuda_near_tie test still passes, so the #3501 seeds differ on the old kernel and the new zero-difference assertion fails there. The three declared deviations hold: the launcher calls the runtime promote_types, and the CUDA overlay table makes bf16 with f32 bf16; check_kernel_port_dispatch.py rejects gpu_kernel_backend() == in a launcher, and the ROCm branch already keys on its build flag; the cubin is 92,000 bytes against the new 100 KB ceiling. Metal body, ROCm geometry, FUSED_ADD_RMSNORM_DEFAULT and the 2026-11-27 results directory are unchanged. All five manifests and schemas carry the new rule, the expected n_reads (4/8/8/4/8) and the committed digests, and compare-sm_121.json reports 130 of 130 bitwise.

@inureyes

Copy link
Copy Markdown
Member Author

Security and Performance Review

No CRITICAL or HIGH findings; no fixes pushed.

Checked

  • fused_norm_cuda.h body: d = v * n_reads + j is guarded by d < dim in both stages, so a row whose width is not a multiple of the vector width, a short row (dim 1, 3) and the looped 1024-thread case past n_reads * 1024 all stay in bounds. Loads are scalar, so no alignment assumption. base is 64-bit. local_sums[32] covers 1024 threads, and every block width (64, 128, 1024) is a whole number of warps, so the full-mask shuffles and barriers are reached by every lane.
  • Launcher: compute and the TC/RoundX/RoundW template args are under the same CUDA-only guard; Metal and ROCm template args and cache keys are unchanged.
  • Oxide route: indices are usize, the host rejects more than 2^32-1 elements, the five committed manifests pin the PTX digest (ed470a19..., matches sha256sum), and the validator refuses the pre-feat(cuda): make the fused add+RMSNorm kernel byte-identical to MLX rms_norm and regenerate the cuda-oxide artifact #3510 block rule and a wrong or missing n_reads.
  • env.sh (both spikes): the eval strings are constant single-quoted literals, so no injection. Sourcing by absolute and relative path works in bash and zsh (also with CDPATH set), executing exits 2, and dash is refused with a message.
  • Default path: FUSED_ADD_RMSNORM_DEFAULT is still off on CUDA and Metal, so the declared kernel-time regression of the fused kernel only affects runs that opt in. No default-path code changed.
  • cuda_byte_identity (3 tests) passes on GB10 with the release binary.

Remaining Items

  • Pre-existing, not introduced here: the grid puts rows on grid.z, which CUDA caps at 65535, and rows is an int. An opted-in prefill with more than 65535 rows fails the launch (an MLX error, not an out-of-bounds access). Fixing it means moving the row index off blockIdx.z in the body, which would also need an oxide artifact regeneration (LOW).
  • The Rust validator checks the manifest's n_reads but not its compute_dtype field, which oxide_artifact.py does check. The PTX digest pin makes this moot for the committed artifact (LOW).
  • fused_add_rms_norm has no dtype check of its own; a non-float input would now pick n_reads from size_of(promote_types(...)). Model norm inputs are always f32/f16/bf16, so this is not reachable from the model path (LOW).
  • cuda_oxide_artifact_tests only compile with the opt-in oxide build, so this review did not run them; the new refusal tests were read, not executed.

The adapter evidence page stated the pre-regeneration PTX digest and the JIT module name built from it in present tense; they now read as the 2026-11-26 values next to the current digest `ed470a19...`. Comments in the byte-identity test and the spike pointed at `kernels/fused_norm.cpp` for `fused_norm_cuda_block`, which lives in `kernels/fused_norm_cuda.h`. `host_model` in the spike now says it is a tolerance model, not a summation-order model.

The spike edits are comment-only and the committed PTX carries no `.loc` or `.file` directives, so the artifact bytes are unaffected. The Rust artifact validator is compiled only under `MLXCEL_BUILD_CUDA_OXIDE_FUSED_NORM=1`, so the compute_dtype check was not added here.

Validation: cargo fmt --all --check; clippy -p mlxcel-core --features cuda --lib --tests -D warnings; verify-kernel-dtype-keys, verify-kernel-port-dispatch, verify-binary-assets, verify-env-var-docs; check_benchmark_raw_logs.py.

Refs #3510
…da-fused-norm-byte-identity

# Conflicts:
#	CHANGELOG.md
@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 28, 2026
@inureyes
inureyes merged commit 3da507f into main Nov 28, 2026
33 checks passed
@inureyes
inureyes deleted the feature/issue-3510-cuda-fused-norm-byte-identity 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:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(cuda): make the fused add+RMSNorm kernel byte-identical to MLX rms_norm and regenerate the cuda-oxide artifact

1 participant