Repository navigation
perf(cuda): charge MLX Gather and GatherQMM for the rows they read - #3560
Conversation
On DGX Spark a paged KV pool slab or a layer's expert stack is over the 25 << 20-element graph budget on its own, so a take of a few pool rows or a gather_qmm over a few experts committed the CUDA graph it was encoded into. A take along axis 0 now charges its source for the rows its index names, and the gather_qmv and qmm_naive GatherQMM launchers charge the weight, scale and bias stacks for the experts rhs_indices names, through set_input_array_rows_read and set_input_stack_rows_read in the device.cpp overlay. A source that is not row-contiguous, and an index with as many entries as rows, stay charged whole. qmm_sm80 keeps charging its stacks whole: charged by expert it showed no consistent decode gain on GB10 (measured at MLX fc344c98, before the pin moved). Closes lablup#3495.
Hardening reviewReviewed this PR against #3495. I merged Correctness. I read the change against MLX
Drift. Diffing Security and performance. No new input-driven allocation or panic path. The charge is O(1) per launch. One low-risk point I left alone: the thread-local rows state is reset without RAII, so a Local validation (macOS). All exited 0:
Not verified here. The overlay C++/CUDA does not compile on this Mac. Remote CI on the merge commit was cancelled by maintainer decision. The local commands above stand in for it. |
Summary
Closes #3495.
Two MLX builtins named in #3495,
Gather(take) andGatherQMM(gather_qmm), now charge the CUDA graph's byte budget only for the rows their index names, not the whole source. #3496 did the same for the fused decode-MoE kernels. On GB10 (DGX Spark), a paged KV pool slab, or one layer's expert stack, is over the25 << 20-element budget by itself. So each gather of a few rows from one committed the graph it was encoded into.Graph launches per decode step on GB10, main → this PR (main with
MLX_MAX_MB_PER_BUFFER=1000in parentheses, as the ceiling):Greedy text is byte-identical. Decode throughput, each session three rounds against a main null arm; two sessions on the previous MLX pin
fc344c98:qmm_sm80is the batched bf16/f16gather_qmmlauncher, used for MoE decode at B>1. It keeps charging its stacks whole. When it was charged by expert, its graph counts fell (Qwen3-30B-A3B at B=4 from 290 to 194), but decode showed no consistent gain. That was measured on the previous MLX pinfc344c98. Details are below.What changed
src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/device.cpp: two helpers on top of perf: Audit other pool-slab kernels for per-launch CUDA graph commits #3387'sset_input_rows_read.set_input_array_rows_read(encoder, arr, rows_read, rows)registersarrcharged forrows_readof itsrowsleading slices. It does this only whenarris row-contiguous, because only then does slicerown exactly the elements[r * data_size / rows, (r + 1) * data_size / rows). Any other layout is still charged whole. A broadcast array's slices all alias the same data, and a strided view's data need not split intorowsparts.set_input_stack_rows_read(encoder, stack, experts_read)does the same for aGatherQMMweight, scale or bias stack[..., n, k], whose slices are the[n, k]matrices. A stack of two dims or fewer is one matrix and is charged whole.counted_input_elements, unchanged. An index with at least as many entries as the source has rows is charged whole, and the charge never exceeds the source.src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/indexing.cpp: new overlay. It is upstream5a48f9cc(the MLX pin since update: advance MLX pin to 5a48f9cc #3517) plus one block inGather::eval_gpuand the declaration it calls. A take along axis 0 (nidx == 1,axes_ == {0},slice_sizes_[0] == 1) charges its source forindices.size()of itsshape(0)rows. Every other gather, and the index itself, is still charged whole.quantized/qmm/qmv.cu(gather_qmv) andquantized/qmm/qmm_naive.cu(when givenrhs_indices): the weight, scale and bias stacks are charged forrhs_indices.size()experts. Still charged whole:x, the indices and a global scale.rhs_indices).src/lib/mlxcel-core/src/cuda_graph_commit_tests.rs: six launch tests, listed under Verification.## [Unreleased].Why the bytes each launch reads are bounded by the index
Gather(device/gather.cuh). Output elementout_idxreadssrc[elem_to_loc(out_idx % slice_size, slice_sizes, src_strides) + idx * src_strides[0]], whereidxis index elementout_idx / slice_size. Withslice_sizes[0] == 1, the first term stays inside row 0, since every coordinate is below its slice size. The second term moves it to rowidx. So a row-contiguous source hasindices.size()rows read, each ofdata_size / shape(0)elements.gather_qmv_kernel(qmv.cu). Grid slicelsetsw_idx = rhs_indices[l].qmv_kernel_implthen offsetsw,scalesandbiasesby(row + n * w_batch) * widthwithrow < n. That stays inside expertw_idx's[n, width]block.qmm_naive_kernel. Grid slicel_coordtakesb_batch = rhs_indices[l_coord]. It buildsmB,mSandmZas(_, _, b_batch)of tensors with batch striden * k(in scale groups forSandZ). The grid's z extent isrhs_indices.size().Not changed, and why
qmm_sm80withrhs_indices(bf16/f16gather_qmmof 8 rows or more, MoE decode at B>1). Its kernel reads only the named experts too, and the first version of this change charged it that way:qmm_sm80charged whole, the same cell was +3.4% in one session and −2.3% in another. All of these medians are inside main's own spread on that cell across the four sessions, 73.2 to 81.3 tok/s, so neither a gain nor a loss is established.qmm_sm80_kerneltook 14% (Kimi-VL-A3B) and 12% (Qwen3-30B-A3B) longer per step once it shared the larger graphs. In the same traces, wall time per decode step went from 52.8 to 48.6 ms on Kimi-VL-A3B at B=4 and from 63.5 to 63.9 ms on Qwen3-30B-A3B at B=4.fc344c98. update: advance MLX pin to 5a48f9cc #3517 moved the pin to5a48f9cc, which also changedqmm_sm80upstream (the 128-row tile from [CUDA] Add 128-row variant for qmm ml-explore/mlx#4851), and the per-expert variant was not re-measured there. So this decision rests on the old pin.gather_qmm_rhs_sm80(sorted floating-point modes) andfp_gather_qmv(fp_qmv.cu, not overlaid). They read only the named experts as well, but no measured checkpoint runs a floating-point quantization mode, and no test here builds one. Their stacks are still charged whole.GatherQMM::eval_gpu. It dequantizes the whole expert stack, so it reads the stack whole and is charged whole.GatherMM(gemms/gather_gemm.cu, unquantized MoE),GatherAxis(take_along_axis),Scatter,ScatterAxisandMaskedScatter. None of the paths in perf(cuda): charge MLX Gather and GatherQMM for the rows they read so pool-slab and expert-stack gathers stop committing the CUDA graph on GB10 #3495 runs them.overlays/rocm/mlx/backend/rocm/device.cpp) has no per-row charge and a200 << 20-element budget. The Qwen3-0.6B pool slab (67.1M elements) and the Qwen3-30B-A3B weight stack (25.2M) are both under it. Nothing changed there, and nothing was run on ROCm.Cells that stay above the raised ceiling
MLXCEL_PAGED_ATTENTION_NATIVE=0at 8,193 tokens, B=4 (309 → 165, raised 97). Each K or V gather really copies about 257 blocks, 8.4M elements, and the attention that reads both copies counts them again. One row's layer passes the budget by itself, so those cuts come from bytes actually read.qmm_sm80, which is left as it was (see above).Verification
All on GB10 (DGX Spark): NVIDIA GB10, CUDA 13.0, driver 580.178.04, sm_121. A private 0700
TMPDIRwas used.Trees. This commit is on main
506ef099d, tree1260e6e25f471c77f1edfa1bf17f5739c7d92049. Its parent, #3517, moved the MLX pin fromfc344c98to5a48f9cc. So the rebase regenerated theindexing.cppoverlay from upstream5a48f9cc, which picks up the one line upstream added (SliceUpdate::eval_gpunow gives an empty output an allocation before returning). The rebase also took the new pin hash into thedevice.cppheader. Verification and benchmarks used the following revisions:1260e6e25, MLX5a48f9cc):cargo fmt --all -- --check: 0.cuda_graph_committests: 9 passed. Thegather_qmmtests: 2 passed.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: 0.ccb28eb39),make verify-test-cuda: 17,829 passed, 0 failed, 517 ignored, over 202 test binaries.scripts/cichecks: 31 of 35 pass (34 CI scripts plus the license-header check). The four failures are the binary-assets and Helm ones described below.4f4db5cb4(treed08e32515, MLXfc344c98): the full suite, the main-side test run and the rest of the checks below.ed9ec2acd(MLXfc344c98): the nsys traces and decode A/B. Across both rebases the CUDA charging logic is unchanged;indexing.cppwas regenerated and comments were updated. The test file differs: onegather_qmmtest was later split into agather_qmvand aqmm_naivetest.Tests that fail on main. I took unmodified main
4f4db5cb4with only this commit'scuda_graph_commit_tests.rsandlib.rsand ran:Result: 5 passed, 4 failed.
builtin_take_charges_the_pool_slab_for_the_rows_named,builtin_take_of_a_source_past_i32_charges_the_rows_named,builtin_gather_qmv_charges_the_stacks_for_the_experts_namedandbuiltin_gather_qmm_naive_charges_the_stacks_for_the_experts_named. Each failed on itsgraphs == 1assertion.Same command on this commit's tree: 9 passed, 0 failed.
The launch tests did not skip: GB10's default budget is
25 << 20elements. The tests are:builtin_take_charges_the_pool_slab_for_the_rows_named: one row, row 0, the last row, repeated rows and four rows, two takes sharing one graph with the expected bytes. An empty index (an empty output). The budget edge, where the largest row count that fits stays in one graph and one more row cuts.builtin_take_still_charges_whole_reads_whole: every row; indexes of 128 and 129 entries naming one row; a take along axis 1; a broadcast source; a strided (transposed) view. Each is charged whole and cuts.builtin_take_of_a_source_past_i32_charges_the_rows_named: a row-contiguous source of 2,147,483,904 elements, which takes the kernel's 64-bit index path, still charged by rows.builtin_gather_qmv_charges_the_stacks_for_the_experts_named: one expert, expert 0, the last expert, repeats, and 7 experts (the mostgather_qmvtakes). Output is byte-identical to the under-budget 16-expert stack.builtin_gather_qmm_naive_charges_the_stacks_for_the_experts_named: 8 rows with repeats, 16 experts, and the budget edge (82 experts fit, 84 cut).builtin_gather_qmm_still_charges_whole_reads_whole: every expert, and one expert named 128 times (qmm_naive); aqmm_sm80launch; and a plainquantized_matmulover the same weights as one 2-D matrix. Each cuts.a_partly_read_input_is_charged_for_the_rows_readstill passes. It covers theu64extremes of the shared arithmetic.Formatting and checks:
cargo fmt --all -- --check: 0.python3 scripts/insert_apache_header.py --check: 0.python3 scripts/ci/check_used_by.pyandbash scripts/ci/check_used_by_test.sh: 0.scripts/ci/check_*.pyandscripts/ci/*_test.sh: 0, except four:check_binary_assets.py, and therepository-as-committedcase ofcheck_binary_assets_test.sh, fail on main's undeclaredtests/fixtures/audio/speech.flac, which this PR does not touch (fix(ci): declare the d1-omni speech clip as a binary asset #3548).check_helm_chart.pyandhelm_chart_package_test.shneed ahelmbinary the host does not have.Clippy (pinned toolchain 1.97.1),
cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings:4f4db5cb4tree: one error,clippy::needless_range_loopin main'ssrc/server/router_webui_playwright_harness_tests.rs(feat(webui): restructure Chat as a workspace with scoped controls #3552). Main has since changed that file.Full suite:
make verify-test-cudarunscargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1. It gave 17,829 passed, 0 failed, 517 ignored over 202 test binaries, on bothccb28eb39(before the CHANGELOG-only amendment) and the4f4db5cb4tree.Graph launches per decode step. Same method, cells, checkpoints and analyzer as the #3387 audit:
nsys profile --cuda-graph-trace=nodearoundmlxcel-server --parallel 4 --no-prompt-cache -c 65536./v1/completionswithignore_eos, a 4 GiB MLX cache cap.scripts/nsys_cuda_graph_launches.pyover the steady decode window.Main and main-raised are main's traces, taken on main
42a391c6b(MLXfc344c98). This PR's traces are on mained9ec2acd(MLXfc344c98). A cell counts as reproduced when it is within 1% of the #3387 record with the same per-step kernel counts; all 18 did.MLXCEL_PAGED_ATTENTION_NATIVE=0MLXCEL_PAGED_ATTENTION_NATIVE=0gather_qmv)qmm_sm80, unchanged)qmm_sm80, unchanged)qmm_naive)¹ Per emitted token; the other rows are per decode step.
Every generated-text SHA-256 in the nine traces matches main's trace of the same cell. The prompts are a repeated eight-word sentence, though, so this parity check is weak. The decode runs below compare text too.
Decode tok/s against main. The driver is
bench_decode.pyfrom the #3385 record:--parallel 4 --no-prompt-cache -c 65536, greedy,ignore_eos.The three cells that gain, per session:
Both sessions used MLX
fc344c98; the first build additionally changed the batchedqmm_sm80path, which none of these three cells uses.The full matrix of the second old-pin session (
server-final, the C++/CUDA change on mained9ec2acd, MLXfc344c98):MLXCEL_PAGED_ATTENTION_NATIVE=0MLXCEL_PAGED_ATTENTION_NATIVE=0qmm_sm80, unchanged)qmm_sm80, unchanged), first runqmm_sm80, unchanged), repeatqmm_naive)The pool-gather B=4 cell is noisy on main (null arms 184.0 and 195.6 in this session, 189.3 and 228.9 in the first). Even so, in every session every run of this PR beats every main run.
The first Qwen3-30B-A3B B=4 run put all three runs of this PR below main's range. That cell launches the same graphs per step on both sides (290 against 290): its expert gather is
qmm_sm80, which this PR leaves alone. So I repeated it with the same binaries. Both arms then fell into two bands, near 63 and near 69 tok/s, and the cell came out +1.3%. I read it as host noise, not a change.LFM2-8B-A1B at B=4 is +1.8% here against a null spread of 1.4 tok/s, and was +0.2% in the first session, so it counts as flat.
Unchanged controls were measured with the first build of this change, which also charged
qmm_sm80by expert. They used the same driver and showed no effect beyond the null:Peak memory on a 2,048-token prefill chunk (#3495 acceptance item 4). Main
506ef099dagainst this commit, both built on MLX5a48f9cc:mlxcel-bench-decode -m MODEL -p benchmark --prompt-tokens 2048 --warmup-tokens 1 -n 1 --ignore-eoswithMLXCEL_PREFILL_CHUNK=2048. The tool resets the MLX allocator's high-water mark before each phase and prints it after. Each phase is one 2,048-token prefill chunk plus one token. Two runs per arm, alternating. GB is 10^9 bytes.Each figure is the larger of a run's two prefill phases, the warm-up and the measured pass; it is also the run's whole MLX peak, load included. The two arms agree to within 0.02 GB. This tool runs the plain KV cache, so it exercises
gather_qmmbut not the paged pool'stake.For the paged-pool path, a fresh server (
--parallel 4 --no-prompt-cache -c 65536) served a 64-token warm-up, then a greedy request with exactly 2,048 prompt tokens and one output token. We sampled process VmRSS every 10 ms during the request and for 0.5 s after it. Two runs per arm in main/change/change/main order gave:These are sampled host RSS peaks, not CUDA allocation peaks. On the shared host even the sign of the system-wide available-memory change varied; it cannot isolate this server's GPU memory.
Limits
gather_qmm_rhs_sm80andfp_gather_qmvare left counted whole, and no floating-point-mode checkpoint was measured.qmm_sm80decision rests on noisy B=4 cells (Kimi-VL-A3B's main spread on this host is about 10%), and on the old pinfc344c98. update: advance MLX pin to 5a48f9cc #3517's pin5a48f9ccchangedqmm_sm80upstream, and the per-expert variant was not re-measured there.fc344c98(the same C++/CUDA change on mained9ec2acd). There is no current-pin decode figure: the shared host did not provide three uncontested rounds with no other GPU compute or cargo/rustc activity. Interrupted rounds were discarded; the optional Kimi and verify repeats were not completed.mlxcel-bench-decode, which has no paged pool. On the paged-pool server path the MLX peak is not exposed. The sampled RSS comparison above cannot rule out an increase in device allocations.scripts/cichecks could not pass on this host: the Helm checks needhelm, and the binary-assets check fails on main itself (tests/fixtures/audio/speech.flac, fix(ci): declare the d1-omni speech clip as a binary asset #3548).Hardening checks
Boundaries. For
take: an empty index, one row, row 0 and the last row, repeats, every row, indexes as long as and one longer than the source that name one row, the budget edge, and a source pasti32::MAXelements. Forgather_qmm: one expert, expert 0, the last expert, repeats, the mostgather_qmvtakes, 16 experts, every expert, one expert named 128 times, and the budget edge. Not covered by a test, only by reading the code: a source with zero rows, or a stack whose[n, k]matrix is empty, reachescounted_input_elementswithrows == 0and is charged whole, which is zero elements.Time complexity. The charge is O(1) per launch. It reads
indices.size()and the source's shape, and never scans the index.Other callers.
set_input_rows_readhas three users:custom_kernel.cpp'srows_read_of_inputsloop (unchanged).set_input_bytes_uncounted(unchanged).set_input_array_rows_read.On main's CUDA backend,
grepfinds 230set_input_arraycalls in 51 files. The gathers among them that read only part of a large input are listed under "Not changed". The budget itself (get_graph_limits,needs_commit) is unchanged. The ROCm encoder is covered above.Formatting.
cargo fmt --all -- --checkpasses on the final tree. Existing comments are kept. The CHANGELOG entry is under## [Unreleased].