Description
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_batchedandfast_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-offsetfast_ropeper row, andconcatenatethe 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 positionoffset + bto rowb. Gemma 4 has its own per-row loops,apply_rope_per_rowandcompiled_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) loopsfor (b, cache) in caches.iter_mut().enumerate()withslice_row(k_batched, b)andcache.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_smallper 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.cppat the pin, theoffset.size() > 1branch), and the CUDA rope kernel in the overlaysrc/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/rope.cu:110-130readsoffset[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.
- Batched RoPE. Add FFI
fast_rope_offsets(x, dims, traditional, base: Option<f32>, scale, offsets: &MlxArray, freqs: Option<&MlxArray>)insrc/lib/mlxcel-core/src/lib.rsand the bridge, calling the array-offset overload. Insidefast_rope_batchedandfast_rope_batched_with_freqs, on CUDA, makexcontiguous (ffi::contiguous) so the batch stride differs from the sequence stride, build one[B]int32 offsets array, and make one call. Replace Gemma 4'sapply_rope_per_rowandcompiled_q_path_proportional_per_rowloops 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. - 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*/)insrc/lib/mlxcel-core/src/cache/paged.rs, implemented as onescatter(orslice_updatewith an index array) per side into the layer's slab, and call it frompaged_decode_rowsin 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 (PagedSequenceStatelengths, block acquisition) stays on the host as today; only the tensor writes are batched. For K==V layers write once. - 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_normbroadcasts 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_rowloop remains the fallback;ffi::fast_ropeforB == 1; MLXscatterthrough the existingmlxcel_corescatter 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_symmetricregression (ffi_tests) must pass on the new path, which is whyxis made contiguous first. - Edge cases:
B == 1keeps 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
offsetsandBis a panic with the shapes, like today'sassert_eq!.
Acceptance Criteria
- nsys on the server at c=8 and c=32 (512/128) shows
rope_single/ropelaunches,copy_v/copy_gg_ndlaunches attributable to per-row slicing, andrms_norm_smalllaunches 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_offsetson a non-contiguous[4, H, 1, D]tensor with distinct offsets equals four per-rowfast_ropecalls within 1e-3 (fails ifxis not made contiguous);write_paged_batchedproduces 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.pybefore 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-serverbatched 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-repTest 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
feat: store the paged KV pool in FP8 E4M3 on CUDA (#3693)