Skip to content

fix(cuda): rotate broadcast RoPE inputs in a dense output - #3443

Merged
inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/deepseek-v32-yarn-cache-rope
Nov 27, 2026
Merged

inureyes merged 1 commit into
lablup:mainfrom
Jaeyeong-CHOI:fix/deepseek-v32-yarn-cache-rope

Conversation

@Jaeyeong-CHOI

Copy link
Copy Markdown
Contributor

Summary

Closes #3442

make verify-test-cuda is red on main with one test, models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context (cached k_pe at positions 16..24 must be YaRN-rotated (max diff 1.6620973)). The cache that test inspects is correct. Its reference is wrong on CUDA, because MLX's CUDA RoPE kernel returns one rotation for every row of a broadcast input, and the test builds its reference rows by tiling one cached row.

This PR fixes the kernel with a CUDA overlay and adds a regression test for it in mlxcel-core. The DeepSeek test is not touched and passes.

Root cause

RoPE::eval_gpu in mlx/backend/cuda/rope.cu at the pin (fc344c986c4169d99f76b5d95ae6b4a58a359a63), lines 281-303: for an input of at most four dimensions it rotates a donatable input in place, and otherwise allocates the output with the input's data size and strides (out.set_data(..., in.data_size(), in.strides(), in.flags())). A broadcast input (tile, broadcast_to) has a zero stride on the broadcast axis and holds one copy of the data. Its output therefore has one element for every index along that axis, while the rotation differs per position (rope_impl, line 119).

Measured on unmodified main 1c284f1f3 (GB10), one 8-feature row repeated over 8 rows and rotated at positions 16..23, against a rotation computed on the host in f64:

Input Strides CUDA CPU stream
dense [64, 64, 8, 1] rows at 16..23, max error under 1e-6 same
tile(row, [1, 1, 8, 1]) [0, 0, 0, 1] all 8 rows are the rotation at position 16, max error 1.57 to 4.49 rows at 16..23
broadcast_to(row, [1, 1, 8, 8]) [0, 0, 0, 1] all 8 rows are the rotation at position 16 rows at 16..23
contiguous(tile(..)) [64, 64, 8, 1] rows at 16..23 same
last 8 of 12 features, transposed (the layout the MLA forward rotates) [96, 8, 12, 1] rows at 16..23 same

The same for the base and for a frequency table, traditional on and off.

In the failing test, on unmodified main (a diagnostic appended to the test file):

k_pe: cache rows 0..25 vs host f64 YaRN rotation of row 0: worst row 1 diff 0.0000001
k_pe rows 16..24: tiled reference input strides [0, 0, 0, 1], dense copy strides [64, 64, 8, 1]
k_pe rows 16..24: |cache - reference(tiled)| 1.6620973   |cache - reference(dense)| 0.0000000
k_pe rows 16..24: reference(tiled) rows equal the host YaRN rotation at positions [16 16 16 16 16 16 16 16]
indexer key: cache rows 0..25 vs host f64 YaRN rotation of row 0: worst row 24 diff 0.0000000
indexer key rows 16..24: reference(tiled) rows equal the host YaRN rotation at positions [16 17 18 19 20 21 22 23]

1.6620973 is the distance between the correct cache and a reference whose eight rows were all rotated at position 16. Only the k_pe prefill assertion is hit: the indexer key rotates 8 of its 12 features, and a partial rotation that is not donated is copied to a dense output first; the decode assertions tile a single row, which is not a broadcast.

The Metal kernel (mlx/backend/metal/rope.cpp) and the ROCm overlay (rope.hip) always allocate a dense output or copy, which is why the test passes on Metal (nightly of 2026-11-23) and on ROCm (#3279). rope.cu on ml-explore/mlx main differs from the pin only by an early return for an empty input, so a pin bump does not fix this.

What changed

  • src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/rope.cu (new overlay): the pin's file, Apple's header kept, the // Modified from upstream MLX fc344c98... mlx/backend/cuda/rope.cu line, and one change in RoPE::eval_gpu. An input with a zero stride on an axis longer than one is not layout_ok, so it takes the existing branch that copies it into a dense output (copy_gpu(in, out, CopyType::General, s)) and rotates it there. The diff against the pin is the 8-line header and this, under a four-line comment:

      bool broadcast = false;
      for (int i = 0; i < ndim; ++i) {
        broadcast = broadcast || (in.shape(i) > 1 && in.strides()[i] == 0);
      }
      bool layout_ok = !broadcast && (ndim <= 4 || in.flags().row_contiguous);

    Every input without such a stride takes the branch it took before.

  • src/lib/mlxcelverse/overlays/cuda/README.md: 34 to 35 files, one entry for rope.cu. No CMake change: mlx_apply_source_overlays copies everything under overlays/cuda/mlx/backend/cuda/.

  • src/lib/mlxcel-core/src/rope_input_layout_tests.rs (new, wired in lib.rs): three tests, described below.

No model code and no existing test changed. No CHANGELOG entry: I found no production path that rotates a broadcast array (see "Verification limits").

Verification

Spark2: NVIDIA GB10, driver 580.178.04, CUDA 13.0.88, Linux 7.0.0 aarch64, rustc 1.97.1 (the pinned toolchain), --features cuda, --profile test-fast, MLX_CUDA_ARCHITECTURES=121, MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1 unless a row says otherwise. Base 1c284f1f38ed28fadc569e715131358125af44a7. Tested tree fb36ce5fc314de989011fcc1025a9604df42f2fd, the tree of the commit.

  • cargo fmt --all -- --check
  • cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings
  • python3 scripts/ci/check_used_by.py, bash scripts/ci/check_used_by_test.sh, python3 scripts/insert_apache_header.py --check, python3 scripts/ci/check_env_var_docs.py, python3 scripts/ci/check_kernel_dtype_keys.py
  • The overlay is what the MLX build compiled: sha256sum of the overlay and of _deps/mlx-src/mlx/backend/cuda/rope.cu in the build directories the tests below link agree (33bd9501...263609); on the main build that file is the pin's (79cb9ec5...894879).
  • The CONTRIBUTING drift check against the fetched ml-explore/mlx clone at the pin: no DRIFT line, and rope.cu has its base line. The five NO BASE lines it prints are the mlxcel-authored helper headers, as on main.
  • The target test, source unchanged, cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- --test-threads=1 --exact models::deepseek_v32::rope_tests::prefill_and_decode_cache_yarn_rotated_keys_past_the_original_context: passed three times; also with the environment unset, and with the default number of test threads.
  • The new tests, cargo test ... -p mlxcel -p mlxcel-core --lib -- --test-threads=1 rope_input_layout_tests: 3 passed.
  • The modules around it, cargo test ... -p mlxcel -p mlxcel-core --lib -- --test-threads=1 deepseek rope mla glm_moe_dsa: 625 passed, 5 ignored in mlxcel; 181 passed, 1 ignored in mlxcel-core. No failure.
  • make verify-test-cuda with a private 0700 TMPDIR: 17,119 passed, 0 failed, 516 ignored over 193 test targets (196 test result lines), exit 0, 27 minutes. The tree was the tested tree before and after. The mlxcel library target is 12,879 passed and 254 ignored, mlxcel-core 2,492 passed and 6 ignored. The target test and the three new tests are ok in that log.

An earlier run of the same gate on the same tree was stopped and is not counted: my work directory had been created 0775, and tests/cuda_custom_kernel_disk_cache.rs (1 test) and tests/cuda_ptx_cache_trust.rs (11 tests) failed with CUDA kernel disk cache disabled: <work dir> is group- or other-writable, which is those tests refusing the parent of TMPDIR. I stopped it there (the mlxcel library target had finished, 12,879 passed and 0 failed), set the directory to 0755 and ran the gate again from the start; that second run is the one above.

Failing first

The new tests on the tested tree with the overlay file held out of the working tree, so that the build compiles the pin's rope.cu (cargo test --locked --profile test-fast -p mlxcel-core --features cuda --lib -- --test-threads=1 rope_input_layout_tests):

Test Pinned kernel With the overlay
rows_broadcast_along_the_sequence_axis_rotate_at_their_own_positions failed: tile along the sequence axis, Rotation { dims: 8, traditional: true, table: false }: row 36 is 3.5185947 from the dense rotation passed
inputs_broadcast_along_the_head_and_batch_axes_rotate_like_dense failed: broadcast_to along the head axis with no other owner, Rotation { dims: 8, traditional: true, table: false }: row 2 is 3.726822 from the dense rotation passed
strided_views_rotate_like_dense passed passed

The second failure is the in-place case: with the input held by the caller, a head-axis broadcast happens to come out right on the pinned kernel, because every head writes the same value to the shared element; with no other owner it does not.

The target test on unmodified main, same host, alone, three runs per setting: failed with max diff 1.6620973 with the environment unset (default threads and --test-threads=1), with MLX_ENABLE_TF32=0, with MLXCEL_SDPA_DETERMINISTIC=1 and with both; failed with max diff 1.6623757 with MLX_ENABLE_TF32=1.

The kernel probe, after

The probe from "Root cause" (an uncommitted mlxcel-core example), built against the tested tree:

Input Strides CUDA, main CUDA, this PR
dense [64, 64, 8, 1] rows at 16..23 rows at 16..23
tile, held by the caller [0, 0, 0, 1] all rows at 16 rows at 16..23, max error under 1e-6
tile, no other owner n/a all rows at 16 rows at 16..23, max error under 1e-6
broadcast_to [0, 0, 0, 1] all rows at 16 rows at 16..23, max error under 1e-6
contiguous(tile(..)) [64, 64, 8, 1] rows at 16..23 rows at 16..23
transposed slice [96, 8, 12, 1] rows at 16..23 rows at 16..23

Identical for the base and the table, traditional on and off (four blocks of six rows each, before and after).

Tests

rope_input_layout_tests builds each input twice, once held by the test and once with no other owner (the case the kernel may rotate in place), and rotates it under eight settings: the base or a frequency table (periods unlike base^(2i/dims)), both conventions, and all 8 or the first 4 of 8 features, at offset 16 over 8 rows. Each result must be within 1e-5 of the rotation of a dense buffer holding the same values, and that dense rotation within 1e-3 of one computed on the host in f64. The input values are read back through a contiguous copy, not through the rotation.

  • rows_broadcast_along_the_sequence_axis_rotate_at_their_own_positions: [1, 5, 1, 8] tiled and broadcast_to [1, 5, 8, 8], and a 3-D [1, 1, 8] to [1, 8, 8]. Five heads leave a partial group in the kernel's four-heads-per-thread loop.
  • inputs_broadcast_along_the_head_and_batch_axes_rotate_like_dense: [1, 1, 8, 8] to [1, 5, 8, 8], and [1, 5, 8, 8] to [3, 5, 8, 8].
  • strided_views_rotate_like_dense: [1, 8, 5, 12] sliced to its last 8 features and transposed to [1, 5, 8, 8]. This is the layout attention rotates; it was right before and has to stay on the branches that do not copy.

Real checkpoints, main against fix

The changed file is the RoPE kernel every CUDA model uses, so I compared a build of unmodified 1c284f1f3 with the tested tree on three checkpoints. A DeepSeek-V3.2 checkpoint was not run: mlx-community/DeepSeek-V3.2-4bit is 378 GB and this host has 121 GB.

Checkpoint Revision RoPE entry point
mlx-community/Llama-3.2-1B-Instruct-4bit 08231374eeacb049a0eade7922910865b8fce912 fast_rope_with_freqs (rope_type: llama3 table)
LFM2-8B-A1B-4bit (a local copy from an earlier round, revision.txt 3266a85e9dabe5a6a711f889b8389cfa0c6b08d2) fast_rope
mlx-community/Kimi-VL-A3B-Thinking-4bit c4f541be1b20f835366dab8304f37ef6a8a65e7b MlaRope on a DeepSeek-V3 MLA text model (qk_rope_head_dim 64, no rope_scaling, so the base path)

Command: mlxcel generate -m MODEL -p PROMPT -n 128 --temp 0. The long prompt is the first 9,000 bytes of CONTRIBUTING.md between an instruction and a question (9,218 bytes); the short one is Name three primary colors and one use of each. I compared the reply bytes between the echoed prompt and the [Generated ...] footer.

Checkpoint Prompt main vs fix
Llama-3.2-1B long identical (589 bytes)
Llama-3.2-1B short identical (567 bytes)
LFM2-8B-A1B long identical (548 bytes)
LFM2-8B-A1B short identical (326 bytes, 79 tokens)
Kimi-VL-A3B-Thinking long, --show-reasoning identical (595 bytes)
Kimi-VL-A3B-Thinking short, --show-reasoning identical (626 bytes)

Without --show-reasoning Kimi-VL puts all 128 tokens in the reasoning channel and both builds print the same placeholder, so that pair says nothing; the rows above are the rerun with the reasoning shown. The replies are coherent text about the prompt on all three.

Verification limits

  • Metal and ROCm were not built or run. Everything here is CUDA on one GB10. The new tests are not gated to CUDA and will run in the macOS nightly and in make verify-rocm. I expect them to pass from reading the Metal kernel at the pin and the ROCm overlay (both allocate a dense output or copy, and the DeepSeek test, which rotates a tiled input, passes on both), but they have not run there. The tolerances are 1e-5 between two rotations on the same backend and 1e-3 against the host.
  • The claim that no production path rotates a broadcast array is a reading of call sites, not a proof: I went through the files that both rotate and call tile, broadcast_to or repeat. If there is one, this PR changes its output on CUDA (to the correct one).
  • Only zero strides are detected. A layout that overlaps without one (an as_strided window) would still share output elements. as_strided has one caller (src/audio/nemotron_codec/stft.rs) and it does not rotate.
  • No DeepSeek-V3.2 checkpoint was run (378 GB against 121 GB of memory), and no checkpoint with a YaRN block. The real-checkpoint table shows unchanged output on the paths that do not copy; it does not exercise the changed branch, which only a broadcast input reaches. That branch is covered by the unit tests and the probe.
  • Reply bytes, not logits. The comparison is greedy text for 128 tokens on two prompts per checkpoint. No logit trace and no perplexity run.
  • No timing measurement. The change adds one loop over the input's dimensions per RoPE evaluation on the host. The generate footers are single runs and were not meant as a benchmark.
  • That the in-place path is what breaks a head-axis broadcast is inferred from the held input passing and the unowned one failing on the pinned kernel; I did not instrument the kernel to confirm which branch each took.
  • With MLX_ENABLE_TF32=1 forced, the target test still fails, at its decode assertion: cached k_pe at positions 24..25 must be YaRN-rotated (max diff 0.00017541647) against a 1e-4 tolerance. This is not the broadcast defect and not new: a diagnostic build of unmodified main under MLX_ENABLE_TF32=1 prints k_pe rows 24..25: |cache - reference(dense)| 0.0001754 (and 0.0000001 under MLX_ENABLE_TF32=0), so the decode step's row differs from the prefill's row 0 by that much when TF32 is on. On main the earlier assertion fails first and hides it. The library test process pins MLX_ENABLE_TF32=0 when the variable is unset (src/lib.rs:183-186), and the gate runs that way. I left it alone.
  • Not reported upstream. rope.cu on ml-explore/mlx main has the same allocation logic (checked 2026-11-26); two gh search issues queries there returned nothing. The overlay should be retired when upstream fixes it.
  • The second CUDA host that showed the same failure in earlier gate runs was not used here.
  • Base. The commit is on 1c284f1f3. main moved to a1f2aee3b (fix(models): preserve NVFP4 scales when stacking Nemotron-H experts #3315, Nemotron-H files only) while this was being verified; the two do not touch a common file and git merge-tree merges them without conflict, but nothing was re-run on top of it.
  • python3 scripts/ci/check_cross_repo_refs.py (advisory) lists four bare references, #1564, #2739 twice and #2462. They are already on the one-paragraph README line this PR edits; I did not rewrite them.

MLX's CUDA RoPE kernel rotates a donatable input in place and otherwise
gives the output the input's strides and data size. A broadcast input (tile,
broadcast_to) has a zero stride on the broadcast axis, so every index along
that axis shared one output element. Eight rows broadcast along the sequence
axis and rotated at positions 16..23 all came back as the rotation at
position 16, with the base and with a frequency table, and an input
broadcast along the head axis came back wrong when nothing else owned it.

The DeepSeek V3.2 YaRN cache test builds its reference rows that way (one
cached row, tiled), so on CUDA its prefill assertion failed in
make verify-test-cuda with "cached k_pe at positions 16..24 must be
YaRN-rotated (max diff 1.6620973)". The cache was right: every cached k_pe
and indexer-key row equals a host f64 YaRN rotation of row 0 within 1e-6.
The Metal kernel and the ROCm overlay allocate a dense output, and the test
passes there.

The new overlay overlays/cuda/mlx/backend/cuda/rope.cu is the pin's file
with one change: an input with a zero stride on an axis longer than one
takes the existing copy branch and is rotated in a dense output. Every other
input takes the branch it took before.

rope_input_layout_tests rotates inputs broadcast along the sequence, head
and batch axes, held by the caller and with no other owner, and a transposed
slice, with the base and a table, both conventions, full and partial dims.
Each must match the rotation of a dense buffer of the same values, which is
checked against a host f64 rotation. Two of its three tests fail on the
pinned kernel; the DeepSeek test passes unchanged.
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Target: #3443. Linked issue: #3442.

Findings: no defects, nothing pushed.

  • rope.cu overlay diffed against the pinned MLX file (fc344c98, taken from a local build's _deps/mlx-src). The only changes are the provenance header and the broadcast check that feeds layout_ok. A broadcast input now goes to the existing copy_gpu(in, out, CopyType::General, s) branch. That branch already handled non-contiguous inputs with more than 4 dims: it allocates a dense row-contiguous output, sets donated = true, and reads and writes through out.strides(), so the index math, bounds and dtype dispatch are the upstream ones. An input with no zero stride on an axis longer than 1 takes the same branch as before, so the in-place, same-strides and partial-rotation fast paths are unchanged. single requires row_contiguous, which a broadcast input never has, so the single-row kernels are never reached with it. Metal (rope.cpp) and the ROCm overlay already allocate densely, which matches the new CUDA behavior.
  • The overlay README count (35) matches the 35 files under overlays/cuda/mlx/backend/cuda. The CUDA overlay has no manifest or hash list beyond the README and the per-file Modified from upstream line, and both are present.

The CUDA kernel was reviewed line by line but not compiled or executed on CUDA hardware. This host has no CUDA. The author's GB10 results in the PR body are the only CUDA evidence.

Security: no new inputs, sizes or allocations driven by requests. Performance: one host-side loop over ndim per RoPE eval, and only broadcast inputs take the extra copy.

Remote CI was cancelled by maintainer decision (no run was in progress at review time). Local validation on Apple M3 Ultra (Metal):

  • cargo fmt --all -- --check: pass
  • cargo clippy -p mlxcel-core --all-targets --features metal,accelerate -- -D warnings: pass
  • cargo test -p mlxcel-core --profile test-fast --features metal,accelerate rope_input_layout -- --test-threads=1: 3 passed
  • make verify-rocm-overlay, scripts/ci/check_used_by.py, scripts/insert_apache_header.py --check, scripts/ci/check_kernel_dtype_keys.py: pass

@inureyes
inureyes merged commit b9894a8 into lablup:main Nov 27, 2026
33 checks passed
@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 platform:linux Linux (CUDA / packaging) specific priority:medium Medium priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cuda): MLX CUDA RoPE gives every row of a broadcast input the same rotation, failing make verify-test-cuda on main

2 participants