Repository navigation
fix(cuda): rotate broadcast RoPE inputs in a dense output - #3443
Merged
inureyes merged 1 commit intoNov 27, 2026
Merged
Conversation
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.
5 of 6 tasks
8 tasks
This was referenced Nov 26, 2026
Member
Hardening reviewTarget: #3443. Linked issue: #3442. Findings: no defects, nothing pushed.
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 Remote CI was cancelled by maintainer decision (no run was in progress at review time). Local validation on Apple M3 Ultra (Metal):
|
4 of 5 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3442
make verify-test-cudais red onmainwith 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_gpuinmlx/backend/cuda/rope.cuat 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:[64, 64, 8, 1]tile(row, [1, 1, 8, 1])[0, 0, 0, 1]broadcast_to(row, [1, 1, 8, 8])[0, 0, 0, 1]contiguous(tile(..))[64, 64, 8, 1][96, 8, 12, 1]The same for the base and for a frequency table,
traditionalon and off.In the failing test, on unmodified main (a diagnostic appended to the test file):
1.6620973is the distance between the correct cache and a reference whose eight rows were all rotated at position 16. Only thek_peprefill 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.cuonml-explore/mlxmain 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.culine, and one change inRoPE::eval_gpu. An input with a zero stride on an axis longer than one is notlayout_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: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 forrope.cu. No CMake change:mlx_apply_source_overlayscopies everything underoverlays/cuda/mlx/backend/cuda/.src/lib/mlxcel-core/src/rope_input_layout_tests.rs(new, wired inlib.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=1unless a row says otherwise. Base1c284f1f38ed28fadc569e715131358125af44a7. Tested treefb36ce5fc314de989011fcc1025a9604df42f2fd, the tree of the commit.cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 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.pysha256sumof the overlay and of_deps/mlx-src/mlx/backend/cuda/rope.cuin the build directories the tests below link agree (33bd9501...263609); on the main build that file is the pin's (79cb9ec5...894879).ml-explore/mlxclone at the pin: noDRIFTline, andrope.cuhas its base line. The fiveNO BASElines it prints are the mlxcel-authored helper headers, as on main.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.cargo test ... -p mlxcel -p mlxcel-core --lib -- --test-threads=1 rope_input_layout_tests: 3 passed.cargo test ... -p mlxcel -p mlxcel-core --lib -- --test-threads=1 deepseek rope mla glm_moe_dsa: 625 passed, 5 ignored inmlxcel; 181 passed, 1 ignored inmlxcel-core. No failure.make verify-test-cudawith a private 0700TMPDIR: 17,119 passed, 0 failed, 516 ignored over 193 test targets (196test resultlines), exit 0, 27 minutes. The tree was the tested tree before and after. Themlxcellibrary target is 12,879 passed and 254 ignored,mlxcel-core2,492 passed and 6 ignored. The target test and the three new tests areokin 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) andtests/cuda_ptx_cache_trust.rs(11 tests) failed withCUDA kernel disk cache disabled: <work dir> is group- or other-writable, which is those tests refusing the parent ofTMPDIR. I stopped it there (themlxcellibrary 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):rows_broadcast_along_the_sequence_axis_rotate_at_their_own_positionstile along the sequence axis, Rotation { dims: 8, traditional: true, table: false }: row 36 is 3.5185947 from the dense rotationinputs_broadcast_along_the_head_and_batch_axes_rotate_like_densebroadcast_to along the head axis with no other owner, Rotation { dims: 8, traditional: true, table: false }: row 2 is 3.726822 from the dense rotationstrided_views_rotate_like_denseThe 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.6620973with the environment unset (default threads and--test-threads=1), withMLX_ENABLE_TF32=0, withMLXCEL_SDPA_DETERMINISTIC=1and with both; failed withmax diff 1.6623757withMLX_ENABLE_TF32=1.The kernel probe, after
The probe from "Root cause" (an uncommitted
mlxcel-coreexample), built against the tested tree:[64, 64, 8, 1]tile, held by the caller[0, 0, 0, 1]tile, no other ownerbroadcast_to[0, 0, 0, 1]contiguous(tile(..))[64, 64, 8, 1][96, 8, 12, 1]Identical for the base and the table,
traditionalon and off (four blocks of six rows each, before and after).Tests
rope_input_layout_testsbuilds 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 unlikebase^(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 andbroadcast_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
1c284f1f3with the tested tree on three checkpoints. A DeepSeek-V3.2 checkpoint was not run:mlx-community/DeepSeek-V3.2-4bitis 378 GB and this host has 121 GB.mlx-community/Llama-3.2-1B-Instruct-4bit08231374eeacb049a0eade7922910865b8fce912fast_rope_with_freqs(rope_type: llama3table)LFM2-8B-A1B-4bit(a local copy from an earlier round,revision.txt3266a85e9dabe5a6a711f889b8389cfa0c6b08d2)fast_ropemlx-community/Kimi-VL-A3B-Thinking-4bitc4f541be1b20f835366dab8304f37ef6a8a65e7bMlaRopeon a DeepSeek-V3 MLA text model (qk_rope_head_dim64, norope_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 ofCONTRIBUTING.mdbetween an instruction and a question (9,218 bytes); the short one isName three primary colors and one use of each.I compared the reply bytes between the echoed prompt and the[Generated ...]footer.--show-reasoning--show-reasoningWithout
--show-reasoningKimi-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
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.tile,broadcast_toorrepeat. If there is one, this PR changes its output on CUDA (to the correct one).as_stridedwindow) would still share output elements.as_stridedhas one caller (src/audio/nemotron_codec/stft.rs) and it does not rotate.MLX_ENABLE_TF32=1forced, 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 underMLX_ENABLE_TF32=1printsk_pe rows 24..25: |cache - reference(dense)| 0.0001754(and0.0000001underMLX_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 pinsMLX_ENABLE_TF32=0when the variable is unset (src/lib.rs:183-186), and the gate runs that way. I left it alone.rope.cuonml-explore/mlxmain has the same allocation logic (checked 2026-11-26); twogh search issuesqueries there returned nothing. The overlay should be retired when upstream fixes it.1c284f1f3.mainmoved toa1f2aee3b(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 andgit merge-treemerges 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,#2739twice and#2462. They are already on the one-paragraph README line this PR edits; I did not rewrite them.