Repository navigation
perf: batch RoPE and paged KV write launches in batched decode - #3691
Merged
Merged
Conversation
inureyes
marked this pull request as ready for review
December 2, 2026 09:16
This was referenced Dec 3, 2026
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
On CUDA, batched decode now runs RoPE and the paged KV append as one launch per op per layer for the whole batch, instead of one slice, one op and one concatenate per row. The per-row code stays as the Metal, ROCm and no-GPU path and as the fallback. One backend gate,
MLXCEL_BATCHED_DECODE_LAUNCHES, selects between them and defaults on only for CUDA. Part of epic #3671.Changes
Array-offset RoPE FFI:
fast_rope_offsetsandfast_rope_offsets_with_freqsexpose MLX'sfast::ropeoverload that takes a[B]int32 offset array.rope_offsets_arraybuilds that array once per step.Batched RoPE: when the gate holds,
fast_rope_batchedandfast_rope_batched_with_freqsmakexcontiguous and make one call. Makingxcontiguous separates the batch stride from the sequence stride on the transposed[B, H, 1, D]decode tensor. The same applies torope_proportional::apply_proportional_rope_batchedfor full-head input, which is the Gemma 4 full-attention decode path. The// Used by:comments are updated.Batched paged KV write:
PagedBlockPool::write_decode_rows(newcache/paged_batch_write.rs) keeps the per-row host bookkeeping:append_tokens(1);It then groups the rows by target slab and issues one indexed write per side per slab. A row goes through the batched write when four conditions hold:
Other rows take the existing per-row
write_block.paged_decode_rowscalls it forB > 1when the gate holds and keeps the per-row loop otherwise, including when two rows share one sequence state.In-place indexed write kernel:
mlxcelverse/kernels/kv_inplace_scatter.{h,cpp}addsInplaceScatterRows, an MLX primitive whose output shares the destination slab's buffer, following the soundness argument of the existing in-place slice write. A JIT CUDA kernel copies the row bits for each(src_row, dst_row)pair. It is compiled only for CUDA builds, andinplace_scatter_rows_available()reports false elsewhere. The issue suggested MLXscatter, butscatterreturns a new array, so it would copy the whole slab every step. That is why the write uses this primitive instead.Gate:
mlxcel_core::memory::batched_decode_launches()readsMLXCEL_BATCHED_DECODE_LAUNCHES(1/true/on/yes, 0/false/off/no) and otherwise defaults tobackend == Cuda. It is documented indocs/environment-variables.md.Parts of the issue that needed no code or do not apply
gemma4_batched.rs::heads_batched_decode) already applies q_norm, k_norm and v_norm to the whole[B, 1, H, D]tensor before any per-row split. nsys confirmsrms_normlaunches per step do not depend on the batch (339 per step at c=1, 8 and 32 on both arms below).k_normand partial RoPE, V getsv_normand no RoPE, so the cached K and V differ and are written separately (same finding as perf: plan CUDA server memory at startup with per-layer KV slabs #3680).apply_rope_per_rowandcompiled_q_path_proportional_per_row: these serve the MTP verify forward withL > 1, which the issue's edge cases leave untouched. Batched decode goes throughrotate_batched_decode, which now takes the one-launch forms.Where the batched KV write runs by default on CUDA
Since #3676 (after this issue was written), Gemma 4 scheduler sequences on CUDA keep their layers in dense per-sequence caches rather than the paged pool (
MLXCEL_PAGED_SLIDINGdefaults off on CUDA). So by default on CUDA the batched paged write runs for the pooled families: Llama 3, Qwen 2/2.5/3, Helium and the VLMs built on them. Gemma 4 reaches it withMLXCEL_PAGED_SLIDING=1, which is the path #3667 and #3668 are making the default again.On the default dense Gemma 4 path, RoPE is batched. The remaining per-row copies come from the per-row dense attend (row slices of q, k and v plus the output concatenate in
attend_batched_rows). The issue's launch-count criterion therefore holds for RoPE and norm, and for copies only on the paged path. On the dense path the copy count still scales with the batch, which is a documented exception, not a pass. Batching that attend over separate per-sequence buffers needs the paged layout and is left to #3667/#3668.Metal unchanged
batched_decode_launches_fromreturns true only forGpuBackendKind::Cudaunless the variable forces it.test_batched_decode_launches_gate_is_cuda_onlywalksGpuBackendKind::ALL. The in-place indexed write is CUDA-only, so a forced gate on another backend still writes per row.Validation on GB10 (sm_121, 128 GB unified)
The baseline is
mainataa52c2f6e(post-#3680), built the same way as the branch binary.Launches per decode step (nsys,
--cuda-graph-trace=node)One batch of c distinct requests, 128 tokens each with
ignore_eos, after one warmup request.--parallel 32 --ctx-size 32768. Counts are divided by the number of forward steps (one greedyarg_reduceper step), because the two c=32 runs did not take the same number of steps. Every rope, copy and norm kernel is counted, including prefill.Gemma 4 12B 4-bit, default CUDA flags (dense rows):
Llama 3.1 8B 4-bit, default CUDA flags (pooled paged decode, c=8):
Gemma 4 12B 4-bit,
MLXCEL_PAGED_SLIDING=1(pooled paged decode, c=8):mlxcel_kv_scatter_rowskernel replaces the per-row writes: copies per step fall from 1661 to 515 (Llama) and from 2028 to 214 (Gemma 4 paged).B == 1keeps the scalar path.Six NVRM
refcntRequestReference_IMPLlines appeared in the kernel log, one per nsys session, at session teardown. None of them isNV_ERR_NO_MEMORY, and that count was unchanged (258) across every run in this PR.Greedy parity (temperature 0, 64 tokens, mlxcel-server)
MLXCEL_PAGED_SLIDING=1(batched write active)mainis self-consistent on a repeat run in every case. WithMLXCEL_BATCHED_DECODE_LAUNCHES=0, the branch binary matchesmainon every row (31B 12/12, 12B paged 12/12).To isolate the 12B divergences, I also ran the branch with
MLXCEL_KV_INPLACE_WRITE=0. That routes every row through the per-row write while keeping batched RoPE, and it diverged on exactly the same rows. So the divergences come from RoPE, not from the KV write. The new unit testtest_batched_rope_bf16_no_less_accurate_than_per_rowmeasures the difference on bf16[4, 8, 1, 256]decode input with the Gemma 4 proportional table:The generic
rope/rope_freqskernel andrope_single_freqsevaluate the same expression, and the last-bit difference comes from the compiler's handling of the two kernels.Every divergence is a near-tie in
main's own top-2 logprobs (bf16 logprob granularity is 0.125):Serving, Gemma 4 31B NVFP4 (1 round, see below)
models/gemma-4-31b-it-nvfp4,--parallel 32 --ctx-size 32768, random ~512-token prompts, 128 output tokens withignore_eos(16 requests at c=1, 4c otherwise), one warmup request first. On this default CUDA path Gemma 4 rows are dense, so this table measures the batched RoPE change only.Only round 1 completed, so n=1. After the branch arm, the kernel log showed one new
NV_ERR_NO_MEMORYline (18:12:20, during that arm's c=32 cell; host-wide peak 81.6 GiB, against 83.4 GiB for themainarm). The run stopped there, per the rule of stopping after any NVRM out-of-memory event on this host. The host was shared with other sessions' workloads: the 1-minute load average was 4.3 at the start of themainarm and 2.3 at the start of the branch arm, with 109 and 104 GiB available. With n=1 on a shared host these numbers are indicative only. Within this noise neither direction is claimed, and they do not gate the merge. The c=1 cell is within the issue's 2% bound, though with n=1 that is not a measurement of it.Tests
cargo test --profile test-fast --features cuda -p mlxcel-core --lib:rope: 57 passed. This includes the array-offset tests on the transposed decode layout (allclose1e-3 with distinct offsets),test_fast_rope_batched_non_contiguous_t1_symmetric, and the bf16 accuracy test.cache::paged: 160 passed. This includeswrite_decode_rows_matches_per_row_writes_{f32,f16}, which runs 4 sequences with prompt lengths 1, 2, 5 and 4 over 4-token blocks for 2 steps. It checks the gathered KV and the pool slab byte for byte against per-rowwrite_prefill, and it checks the batched and per-row routing counts.batched_decode_launches: 1 passed.cargo test --profile test-fast --features cuda -p mlxcel --lib gemma4 -- --test-threads=1: 314 passed, 41 ignored.cargo clippy --profile test-fast --features cuda -p mlxcel-core --lib --tests -- -D warningsand-p mlxcel --lib: clean.cargo fmt --all --checkandscripts/ci/check_env_var_docs.py: clean.Deferred to the B200 follow-up measurement issue
scripts/bench/serving_compare.py(c=1, 8, 32) and the nsys capture onnvidia/Gemma-4-31B-IT-NVFP4at 512/128.Closes #3665