Skip to content

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

Done

Description

@inureyes

Part of #3671.

Problem / Background

An nsys profile of mlxcel-server decoding 8 concurrent requests of nvidia/Gemma-4-31B-IT-NVFP4 on one B200 (PR #3650, docs/benchmark_results/Gemma4_sm100_Optimization_Report.md) shows small per-row kernels dominating launch counts: copy_v 218k launches, copy_gg_nd 119k, rope_single 99k, rms_norm_small 52k, gather 4k. Their count grows linearly with the batch, so a step at c=32 issues roughly 32x the launches of a step at c=1 for work that is a single tensor operation over the batch. vLLM and SGLang run each of these as one launch per layer for the whole batch. This is one reason mlxcel-server's c=32 TPOT is 190.5 ms against vLLM's 10.43 ms.

Already batched and out of scope: the paged attention itself (mlxcel_paged_attention_v2_partial plus merge_states, src/lib/mlxcelverse/kernels/paged_attention_v2.cpp) and the NVFP4 GEMV for 2 to 32 rows (fp_qmv_tc_multi, from #3650).

Current Behavior

  • RoPE. mlxcel_core::fast_rope_batched and fast_rope_batched_with_freqs (src/lib/mlxcel-core/src/lib.rs:4326-4460) slice the batch into [1, H, T, D] rows, call the scalar-offset fast_rope per row, and concatenate the results. The comment there explains why: on the transposed [B, H, 1, D] decode tensor the batch stride equals the sequence stride, and MLX's Metal rope kernel then assigns position offset + b to row b. Gemma 4 has its own per-row loops, apply_rope_per_row and compiled_q_path_proportional_per_row (src/models/gemma4.rs:2128-2200). Each row costs a slice (copy_v/copy_gg_nd), a rope (rope_single), and a concatenate. Each per-row scalar offset is also a fresh host-created array.
  • KV write. paged_decode_rows (src/lib/mlxcel-core/src/cache/paged_batch_decode.rs:406-445) loops for (b, cache) in caches.iter_mut().enumerate() with slice_row(k_batched, b) and cache.write_paged(&k_i, &v_i), so each layer issues 2 slices plus 2 scatter/copy writes per row.
  • q/k norm. Gemma 4 applies RMSNorm to q and k per head; on the batched decode path these launch rms_norm_small per row wherever the batched tensor is split before the norm.
  • The pinned MLX already supports per-row offsets: mlx::core::fast::rope(x, dims, traditional, base, scale, const array& offset, freqs) accepts an offset array of shape [B] (mlx/fast.cpp at the pin, the offset.size() > 1 branch), and the CUDA rope kernel in the overlay src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/rope.cu:110-130 reads offset[batch_idx * offset_stride]. mlxcel's FFI does not expose that overload.

Proposed Solution

All three replacements are CUDA-default with the current per-row code kept as the Metal path and as a fallback, selected by one backend gate (mlxcel_core::memory::step_cache_clear_policy in src/lib/mlxcel-core/src/memory.rs:266-296 shows the pattern). Metal may switch to the batched forms later only with a measurement.

  1. Batched RoPE. Add FFI fast_rope_offsets(x, dims, traditional, base: Option<f32>, scale, offsets: &MlxArray, freqs: Option<&MlxArray>) in src/lib/mlxcel-core/src/lib.rs and the bridge, calling the array-offset overload. Inside fast_rope_batched and fast_rope_batched_with_freqs, on CUDA, make x contiguous (ffi::contiguous) so the batch stride differs from the sequence stride, build one [B] int32 offsets array, and make one call. Replace Gemma 4's apply_rope_per_row and compiled_q_path_proportional_per_row loops on the decode path with the same single call (for the proportional path, pass the offsets array into the compiled window instead of a scalar). The offsets array comes from a persistent per-step input buffer once the allocation-free decode sub-issue (perf: Remove device and managed allocations from the CUDA decode step #3667) lands; until then build it once per step, not once per row.
  2. Batched paged KV write. Add PagedBlockPool::write_paged_batched(layer_idx, k: &MlxArray /*[B, Hkv, 1, D]*/, v, slots: &MlxArray /*[B] int32 physical row*token index*/) in src/lib/mlxcel-core/src/cache/paged.rs, implemented as one scatter (or slice_update with an index array) per side into the layer's slab, and call it from paged_decode_rows in place of the per-row loop when every row's target block lives in the layer's first slab (the same condition the fused kernel already requires); otherwise keep the per-row loop. The block-table bookkeeping (PagedSequenceState lengths, block acquisition) stays on the host as today; only the tensor writes are batched. For K==V layers write once.
  3. Batched q/k norm. On the Gemma 4 batched decode path, apply q and k RMSNorm on the full [B, L, H, D] tensor before any per-row split (mlxcel_core::fast_rms_norm broadcasts over leading axes), so one launch serves the batch.

Rejected: a hand-written fused "rope + KV write + norm" kernel. The MLX primitives above already give one launch per op per layer; a fused kernel is a later optimization if the profile still shows them, and it would need a Metal twin.

Scope

In scope: src/lib/mlxcel-core/src/lib.rs and src/lib/mlxcel-core/cpp/ (FFI for the array-offset rope), src/lib/mlxcel-core/src/cache/paged.rs and paged_batch_decode.rs (batched write), src/models/gemma4.rs (rope and norm on the batched decode path). Update the // Used by: comments on fast_rope_batched and fast_rope_batched_with_freqs (shared hotspot, see docs/code-guidelines.md).

Out of scope: the attention kernel, the GEMVs, the CUDA graph capture of the whole step (#3668, which will capture whatever this one leaves), and Metal default changes.

Implementation Notes

  • Reuse: the existing slice_row loop remains the fallback; ffi::fast_rope for B == 1; MLX scatter through the existing mlxcel_core scatter wrapper rather than a new kernel.
  • Constraints: greedy tokens must be identical to the per-row path at temperature 0; the test_fast_rope_batched_non_contiguous_t1_symmetric regression (ffi_tests) must pass on the new path, which is why x is made contiguous first.
  • Edge cases: B == 1 keeps the scalar path; rows whose slot lies outside the first slab fall back to the per-row write for that layer and step; speculative verify (L > 1) is untouched.
  • Error handling: a shape mismatch between offsets and B is a panic with the shapes, like today's assert_eq!.

Acceptance Criteria

  • nsys on the server at c=8 and c=32 (512/128) shows rope_single/rope launches, copy_v/copy_gg_nd launches attributable to per-row slicing, and rms_norm_small launches per decode step independent of the batch size (report launches per step at c=1, 8, 32).
  • Per-step GPU time at c=32 within 1.5x of c=1 for the decode step (nsys GPU kernel sum per step), or the PR documents which remaining op breaks the bound.
  • Unit tests: fast_rope_offsets on a non-contiguous [4, H, 1, D] tensor with distinct offsets equals four per-row fast_rope calls within 1e-3 (fails if x is not made contiguous); write_paged_batched produces a pool slab identical to the per-row loop for 4 rows across 2 blocks.
  • Greedy parity: 64 tokens for 4 concurrent identical prompts through mlxcel-server match the pre-change server output.
  • Serving table (c=1, 8, 32) from scripts/bench/serving_compare.py before and after in the PR body; c=1 not slower by more than 2%.
  • Metal unchanged: the per-row code paths are what Metal executes (unit test on the backend gate).
  • Integrated: the batched forms run on the mlxcel-server batched decode path for Gemma 4, confirmed by the nsys launch counts.

Verification

cargo build --release --features cuda
cargo test --profile test-fast --features cuda -p mlxcel-core ffi_tests::test_fast_rope -- --test-threads=1
cargo test --profile test-fast --features cuda -p mlxcel-core cache::paged -- --test-threads=1
cargo test --profile test-fast --features cuda gemma4 -- --test-threads=1
cargo clippy --workspace --all-targets --features cuda -- -D warnings
cargo fmt --check
nsys profile -t cuda,nvtx -o /tmp/decode_c8 --duration 25 ./target/release/mlxcel-server -m models/Gemma-4-31B-IT-NVFP4 --parallel 32 --ctx-size 65536 --port 8080
nsys stats --report cuda_gpu_kern_sum /tmp/decode_c8.nsys-rep

Test policy

Cancel remote CI on the PR. Run only the tests for the touched area locally with cargo test --profile test-fast --features cuda <module filter> -- --test-threads=1, plus the serving benchmark from the harness sub-issue (#3663) for performance claims, then merge. The PR body must include the serving table (c=1, 8, 32) before and after.

Activity

  1. added
    type:performance
    priority:high
    status:ready
    area:core
    area:models
    platform:linux
    on Dec 2, 2026
  2. added
    status:done
    and removed
    status:ready
    on Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corearea:modelsplatform:linuxpriority:highstatus:donetype:performance

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions