Skip to content

perf: batch RoPE and paged KV write launches in batched decode - #3691

Merged
inureyes merged 5 commits into
mainfrom
update/issue-3665-batched-decode-launches
Dec 2, 2026
Merged

inureyes merged 5 commits into
mainfrom
update/issue-3665-batched-decode-launches

Conversation

@inureyes

@inureyes inureyes commented Dec 2, 2026

Copy link
Copy Markdown
Member

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_offsets and fast_rope_offsets_with_freqs expose MLX's fast::rope overload that takes a [B] int32 offset array. rope_offsets_array builds that array once per step.

  • Batched RoPE: when the gate holds, fast_rope_batched and fast_rope_batched_with_freqs make x contiguous and make one call. Making x contiguous separates the batch stride from the sequence stride on the transposed [B, H, 1, D] decode tensor. The same applies to rope_proportional::apply_proportional_rope_batched for 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 (new cache/paged_batch_write.rs) keeps the per-row host bookkeeping:

    • window settle;
    • append_tokens(1);
    • span presize;
    • copy-on-write of shared blocks.

    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:

    • the pool is FP16;
    • the in-place write is enabled;
    • its target block is already owned and exclusive;
    • the geometry matches.

    Other rows take the existing per-row write_block. paged_decode_rows calls it for B > 1 when 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} adds InplaceScatterRows, 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, and inplace_scatter_rows_available() reports false elsewhere. The issue suggested MLX scatter, but scatter returns 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() reads MLXCEL_BATCHED_DECODE_LAUNCHES (1/true/on/yes, 0/false/off/no) and otherwise defaults to backend == Cuda. It is documented in docs/environment-variables.md.

Parts of the issue that needed no code or do not apply

  • q/k norm: the Gemma 4 batched decode path (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 confirms rms_norm launches per step do not depend on the batch (339 per step at c=1, 8 and 32 on both arms below).
  • K == V write once: in Gemma 4 only the raw projection is shared. K gets k_norm and partial RoPE, V gets v_norm and 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_row and compiled_q_path_proportional_per_row: these serve the MTP verify forward with L > 1, which the issue's edge cases leave untouched. Batched decode goes through rotate_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_SLIDING defaults 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 with MLXCEL_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_from returns true only for GpuBackendKind::Cuda unless the variable forces it. test_batched_decode_launches_gate_is_cuda_only walks GpuBackendKind::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 main at aa52c2f6e (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 greedy arg_reduce per 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):

arm c steps rope/step copy/step kv_scatter/step rms_norm/step launches/step GPU ms/step
main-aa52c2f6e 1 137 97 106 0 339 1272 68.2
3665 1 137 97 106 0 339 1272 71.3
main-aa52c2f6e 8 144 689 2243 0 339 4816 105.0
3665 8 144 97 1058 0 339 3038 102.5
main-aa52c2f6e 32 295 1336 4528 0 338 8628 98.6
3665 32 168 97 3595 0 339 7852 118.3

Llama 3.1 8B 4-bit, default CUDA flags (pooled paged decode, c=8):

arm c steps rope/step copy/step kv_scatter/step rms_norm/step launches/step GPU ms/step
main-aa52c2f6e 8 144 459 1661 0 64 3288 67.5
3665 8 144 63 515 56 64 1722 63.0

Gemma 4 12B 4-bit, MLXCEL_PAGED_SLIDING=1 (pooled paged decode, c=8):

arm c steps rope/step copy/step kv_scatter/step rms_norm/step launches/step GPU ms/step
main-aa52c2f6e 8 144 689 2028 0 339 4525 105.5
3665 8 144 97 214 81 339 2200 103.5
  • RoPE launches per step stay flat at the c=1 count (97 per step for Gemma 4) at every batch size.
  • On the paged paths the new mlxcel_kv_scatter_rows kernel replaces the per-row writes: copies per step fall from 1661 to 515 (Llama) and from 2028 to 214 (Gemma 4 paged).
  • At c=1 the kernel list is identical on both arms, because B == 1 keeps the scalar path.

Six NVRM refcntRequestReference_IMPL lines appeared in the kernel log, one per nsys session, at session teardown. None of them is NV_ERR_NO_MEMORY, and that count was unchanged (258) across every run in this PR.

Greedy parity (temperature 0, 64 tokens, mlxcel-server)

model / path 4 identical prompts 8 distinct prompts
Gemma 4 31B NVFP4, default CUDA 4/4 identical 7/8 identical, 1 near-tie
Llama 3.1 8B 4-bit, default CUDA (pooled, batched write active) 4/4 identical 8/8 identical
Gemma 4 12B 4-bit, MLXCEL_PAGED_SLIDING=1 (batched write active) 0/4, one shared near-tie 5/8 identical, 3 near-ties

main is self-consistent on a repeat run in every case. With MLXCEL_BATCHED_DECODE_LAUNCHES=0, the branch binary matches main on 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 test test_batched_rope_bf16_no_less_accurate_than_per_row measures the difference on bf16 [4, 8, 1, 256] decode input with the Gemma 4 proportional table:

  • the batched results are bit-identical to the per-row results except one element at one bf16 ulp (7.6e-6), in the uniform-offset proportional case;
  • that element sits at the same distance from an f32 reference on both forms.

The generic rope/rope_freqs kernel and rope_single_freqs evaluate 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):

model, row token main top-2 branch top-2
31B, row 5 27 '.' -0.625, ' to' -0.875 ' to' -0.75, '.' -0.75
12B paged, row 0 (and all 4 same-prompt rows) 60 ' components' -0.5, ' principles' -0.875 ' principles' -0.625, ' components' -0.75
12B paged, row 1 3 ' had' -0.625, ' was' -0.75 ' was' -0.625, ' had' -0.75
12B paged, row 6 56 ' the' -0.75, ' Hamlet' -0.75 ' Hamlet' -0.625, ' the' -0.875

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 with ignore_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_MEMORY line (18:12:20, during that arm's c=32 cell; host-wide peak 81.6 GiB, against 83.4 GiB for the main arm). 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 the main arm 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.

c ok/failed (main / branch) TPOT median ms (main / branch, delta) TTFT median ms (main / branch) output tok/s (main / branch)
1 16/0 / 16/0 155.0 / 156.9 (+1.2%) 795 / 790 6.26 / 6.18
8 32/0 / 32/0 280.9 / 265.5 (-5.5%) 3563 / 3484 26.12 / 27.54
32 128/0 / 128/0 536.9 / 477.7 (-11.0%) 13236 / 12842 50.28 / 55.70

Tests

  • cargo test --profile test-fast --features cuda -p mlxcel-core --lib:
    • filter rope: 57 passed. This includes the array-offset tests on the transposed decode layout (allclose 1e-3 with distinct offsets), test_fast_rope_batched_non_contiguous_t1_symmetric, and the bf16 accuracy test.
    • filter cache::paged: 160 passed. This includes write_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-row write_prefill, and it checks the batched and per-row routing counts.
    • filter 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 warnings and -p mlxcel --lib: clean.
  • cargo fmt --all --check and scripts/ci/check_env_var_docs.py: clean.

Deferred to the B200 follow-up measurement issue

  • Per-step GPU time at c=32 within 1.5x of c=1 on B200 with the paged Gemma 4 path. On GB10 with the default dense path, GPU time per step is 71 ms at c=1 and 118 ms at c=32 (1.66x). The op that breaks the bound there is the per-row dense attend described above.
  • The B200 serving table from scripts/bench/serving_compare.py (c=1, 8, 32) and the nsys capture on nvidia/Gemma-4-31B-IT-NVFP4 at 512/128.

Closes #3665

@inureyes inureyes added status:done Completed type:performance Performance improvements priority:high High priority area:models Model architectures, weights, loading, metadata area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific labels Dec 2, 2026
@inureyes
inureyes marked this pull request as ready for review December 2, 2026 09:16
@inureyes
inureyes merged commit 11f1c0a into main Dec 2, 2026
1 of 36 checks passed
@inureyes
inureyes deleted the update/issue-3665-batched-decode-launches branch December 2, 2026 09:16
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:models Model architectures, weights, loading, metadata platform:linux Linux (CUDA / packaging) specific priority:high High priority status:done Completed type:performance Performance improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: Batch per-row RoPE, KV write and norm launches in batched decode

1 participant