Repository navigation
perf(cuda): keep graphs whole across the audited expert-stack kernel reads - #3496
Merged
inureyes merged 5 commits intoNov 28, 2026
Merged
Conversation
…reads Issue lablup#3387 asks which kernels, besides the fused paged-attention ones of lablup#3406, are handed a whole preallocated buffer while reading part of it. On DGX Spark (sm_121) the CUDA encoder counts such an input at its full `data_size()` and commits the graph once the count passes 25 << 20 elements, so the launch cuts the graph on its own. An nsys audit on GB10 (`--cuda-graph-trace=node`, default budget against `MLX_MAX_MB_PER_BUFFER=1000`) found no custom kernel left to exempt among the issue's three candidates: paged sparse decode is covered by the lablup#3406 name match, the pool gather is the builtin `take`, and the MLA absorbed-decode kernels have no CUDA port. The kernels that do pay are the fused decode-MoE pair, `moe_gateup_kernel_cu` and `moe_down_kernel_cu`. They take a layer's expert stacks and read the experts their index names, 8 of 128 on Qwen3-30B-A3B, and each launch cut the graph in every layer. The `custom_kernel.cpp` overlay now charges each expert stack for the experts the index names, through `set_input_rows_read` in the `device.cpp` overlay. An index that names every expert reads the stacks whole and is charged whole, as before, and the paged-attention kernels keep the form lablup#3406 measured. The issue proposed leaving the inputs out by name; charging the rows read gives the same result at 8 of 128 and cannot hide a launch that reads its whole input. - Graph launches per decode step at B=1 on GB10: Qwen3-30B-A3B-4bit 147.0 to 62.1 (60.1 with the raised budget), LFM2-8B-A1B-4bit 48.0 to 30.0 (29.0). Qwen3-0.6B-4bit on the paged path is unchanged at 26 / 42 / 55 / 68 for B = 1 to 4. - Decode rate against `main` with a null arm, three rounds: Qwen3-30B-A3B +10.2% and +17.7% at a 256-token prompt, +4.5% and +6.0% at 8192 (two runs); LFM2-8B-A1B +0.8% and +0.5%, inside the null; Gemma 4 26B-A4B, which runs with graph capture off (lablup#688), +0.2% and -0.1%; the paged control -0.1% at B=1 and -0.6% at B=4 inside the main range. Reply text is byte-identical in every cell. - `cuda_graph_commit_tests` reads a graph-launch counter added to the encoder: over-budget stacks with a small index launch one graph for the gate/up and down launches (three before the change), and an index naming every expert still cuts it. The byte-budget arithmetic is tested at its boundaries. - `scripts/nsys_cuda_graph_launches.py` counts graphs per decode step and the kernels in the graphs cut short. The record is `docs/benchmark_results/cuda-graph-commit-audit-gb10-2026-11-27.md`. - The pool gather and `gather_qmm` are affected builtins (58 against 27 graph launches per step on a short Qwen3 chat, 281 against 90 at B=4) and are left to a follow-up issue, as lablup#3387 asks. Closes lablup#3387
4 tasks
The merge of origin/main put the entry under v0.9.0-beta.3, which was already tagged at 25b82c0 without it. It now sits in a new Unreleased section above the release.
# Conflicts: # src/lib/mlxcel-core/cpp/mlx_cxx_bridge.h # src/lib/mlxcel-core/src/lib.rs # src/lib/mlxcelverse/overlays/cuda/README.md
# Conflicts: # CHANGELOG.md
Member
Hardening reviewReviewed against #3387. Keeping graphs whole is safe: Pushed (
|
5 of 6 tasks
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
Closes #3387.
The audit the issue asks for, on GB10, and the one fix it led to.
Of the three candidate paths in the issue, none has a custom kernel left to exempt on CUDA: paged sparse decode is already covered by the #3406 name match, the pool gather is a builtin, and the MLA absorbed-decode kernels have no CUDA port. Going through every
cuda_kernelregistration found the two kernels that do pay:moe_gateup_kernel_cuandmoe_down_kernel_cu, the fused decode-MoE pair. They take a layer's whole expert stacks and read the experts their index names, 8 of 128 on Qwen3-30B-A3B, so on DGX Spark each of the two launches cut the graph in every layer. This PR charges a stack for the experts the index names.Graph launches per decode step at B=1 on GB10: Qwen3-30B-A3B-4bit 147.0 to 62.1 (60.1 with
MLX_MAX_MB_PER_BUFFER=1000), LFM2-8B-A1B-4bit 48.0 to 30.0 (29.0 raised). Decode rate againstmain: Qwen3-30B-A3B +10.2% and +17.7% at a 256-token prompt and +4.5% and +6.0% at 8192 tokens (two runs, three rounds each with a null arm), LFM2-8B-A1B +0.8% and +0.5% (inside the null), reply text byte-identical everywhere.The pool gather and
gather_qmmare affected builtins and are written up in #3495 instead of being changed here, as the issue asks. The full table is in the issue comment and indocs/benchmark_results/cuda-graph-commit-audit-gb10-2026-11-27.md.What changed
src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/custom_kernel.cpp:rows_read_of_inputs(name, inputs)replaces the single name test. Formoe_gateup_kernel_cu(inputs{x, indices, gate_w, gate_s, gate_b, up_w, up_s, up_b}) andmoe_down_kernel_cu({indices, down_w, down_s, down_b, act_g, scores}) each three-dimensional stack input is charged forindices.size()of itsshape(0)experts.x,indices,act_gandscoresare read whole and counted whole. Themlxcel_paged_attention*kernels keep what perf(cache): reduce paged attention execution overhead #3406 gave them, every input left out. The comment above the function says, per kernel, why the bytes read are bounded by the index.src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/device.cpp:set_input_rows_read(rows_read, rows)andcounted_input_elements(data_size, rows_read, rows).set_input_arrayaddscounted_input_elements(arr.data_size(), ...);set_input_bytes_uncounted(bool)is nowset_input_rows_read(uncounted ? 0 : 1, 1), so its one caller behaves as before. Two test hooks:graph_launch_count(), an atomic counter bumped at bothcudaGraphLaunchsites ofcommit_impl, anddefault_graph_limits().src/lib/mlxcel-core: the bridge functionscuda_graph_commit_statsandcuda_graph_counted_input_elements(cpp/mlx_cxx_ext.cpp,cpp/mlx_cxx_bridge.h,src/lib.rs),CudaGraphCommitStatsinsrc/cuda_graph_budget.rs, and the tests insrc/cuda_graph_commit_tests.rs.scripts/nsys_cuda_graph_launches.py: graphs per decode step, and the kernels held by the graphs that were cut short, from an exported--cuda-graph-trace=nodetrace.docs/benchmark_results/cuda-graph-commit-audit-gb10-2026-11-27.mdwith its rows, the overlay README,docs/benchmark_results/README.mdandCHANGELOG.md.Why the two kernels read only the rows their index names
Both bodies are in
src/lib/mlxcel-core/cpp/mlx_cxx_kernels.cpp(MOE_GATEUP_CUDA_SOURCE,MOE_DOWN_CUDA_SOURCE). The grid's z axis is the expert slot,eslot = blockIdx.z < K, and the only way either body forms an address into a stack isfollowed by reads at
gwr[p]withp < Din_pandgsr[grp]withgrp < G. So a launch touchesKwhole expert slices of each stack and nothing else of it:K * Dff * Din_pofE * Dff * Din_ppacked words, and the same share of the scale and bias stacks. The launcher (run_fused_moe_two_kernel) passesindiceswithKentries and sizes the grid's z axis toK.Where this differs from the issue text
data_size / E * K. With 8 of 128 experts that is under the budget and the graph is no longer cut, which is the effect the issue wants. With an index that names every expert the launch reads the stacks whole and is charged whole, so the rule cannot hide a launch that reads its whole input, and an index that names enough experts to be over the budget on its own still cuts the graph. The paged-attention kernels keep the all-or-nothing form perf(cache): reduce paged attention execution overhead #3406 measured. Charging them by share would, by the same arithmetic, bring the cuts back at long context (four 8K requests name half of a 134M-element pair of slabs), which is a different decision from the one perf(cache): reduce paged attention execution overhead #3406 made and measured.cuda_kernelregistration. The three candidates turned out as: already exempt (sparse decode), a builtin (the gather), and not launched on CUDA at all (MLA).gather_qmmbuiltin. The sparse path could only be launched through the synthetic bench at batch 1. Prompt-lookup verification at B=4 has no window in which all four rows stream; that cell is reported as a whole-cell total.mainGemma 3 is not pool-backed. The known case was reproduced on Qwen3-0.6B instead, against the profile perf(cache): reduce paged attention execution overhead #3406 committed.Verification
Spark2: NVIDIA GB10 (sm_121), driver 580.178.04, CUDA 13.0.88, Ubuntu 24.04.5, Linux 7.0.0 aarch64, rustc 1.97.1 (the pinned toolchain),
--features cuda. Base944dbfc2ddd6ccab2b051dadc995e99d9d796c83. Tested treeeb5058712ed25f7f084adebf176df11258da7dfe, the tree of the commit.cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.sh,python3 scripts/insert_apache_header.py --check, and the otherscripts/cichecks (check_env_var_docs.py,check_kernel_dtype_keys.pyand its test,check_cross_repo_refs.py,check_benchmark_raw_logs.pyand its test,check_benchmark_csv_schema.py,check_kernel_port_dispatch.py,check_native_env_writes.py,check_binary_assets.py,check_windows_reserved_paths.py,check_crate_versions.py): all exit 0.cargo test --locked -p mlxcel-core --profile test-fast --features cuda --lib <filter> -- --test-threads=1:cuda_graph_commit3 passed,fused_moe6 passed,paged268 passed and 1 ignored,cuda_graph_budget8 passed.make verify-test-cudawith a private 0700TMPDIR: 17,409 passed, 5 failed, 517 ignored over 199test resultlines. The five failures are all in themlxcellibrary target and all Raon:models::raon1_mini::speculative::tests::{a_steered_verify_block_applies_the_alpha_exactly_as_decode_does, a_verify_block_equals_the_decode_chain_byte_for_byte, rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens, the_exactness_probe_passes_on_the_tiny_model}andmodels::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit. This PR does not touch Raon; the same five fail with the same messages on unmodifiedmainin the gate runs of our other open PRs on this host (fix(vision): build the DeepSeek-OCR prompt as the reference does #3482, fix: keep the boundary snapshot when a prompt-cache warm-up extends it #3492), and fix(models): keep Raon DFlash2 verify blocks byte-exact on CUDA #3476 is open for the speculative ones. The tree waseb5058712before and after the gate.Tests
New file
src/lib/mlxcel-core/src/cuda_graph_commit_tests.rs, compiled with--features cuda. The launch tests need a device whose byte budget the test stacks exceed, which is DGX Spark at MLX's default; elsewhere they skip with a message namingMLX_MAX_MB_PER_BUFFER=25.a_partly_read_input_is_charged_for_the_rows_read: the encoder's owncounted_input_elements, through the bridge, with no launch. A 33,554,432-element stack with 0, 1, 8, 127, 128, 129 andu64::MAXof 128 rows read;1 of 1and0 of 1(the two forms the paged kernels use);rows == 0; an empty input and an input smaller than its row count;u64::MAXin each argument; and a sweep that holds the result to never exceed the input, never decrease in the rows read, and stay withinrows_readof the exact share.moe_expert_stacks_over_the_byte_budget_do_not_cut_the_graph: stacks of 128 experts,Din2048,Dff1024, 4-bit, tiled from 16 random quantized experts, so each weight stack is 33.5M elements, over the budget on its own. For both launchers (SwiGLUfused_moe_expert_kernel, GeGLUfused_moe_geglu_kernel) and for an index of 1 and of 8 experts, one eval of one fused call, which is the gate/up launch followed by the down launch, launches exactly one graph, and its output is byte-for-byte the output of the same experts taken from the 16-expert stack, which is under the budget.an_index_over_the_byte_budget_still_cuts_the_graph: with all 128 experts named the same eval launches at least 3 graphs, and with 64 named at least 2 (the gate and up stacks are then charged 41.9M elements).Every graph count is the minimum over five repetitions with the stream drained before each, so graphs launched by another test thread can only make a test fail, not pass.
Before and after,
cargo test --locked -p mlxcel-core --profile test-fast --features cuda --lib cuda_graph_commit -- --test-threads=1:custom_kernel.cppofmain(hook and tests only, the state before the change)moe_expert_stacks_over_the_byte_budget_do_not_cut_the_graph,swiglu, 1 of 128 experts: the two launches must share one graph,left: 3,right: 1moe_down_kernel_cubranch removed)left: 2moe_gateup_kernel_cubranch removed)left: 2an_index_over_the_byte_budget_still_cuts_the_graphcounted_input_elementswithout therows_read >= rowsclampa_partly_read_input_is_charged_for_the_rows_read,left: 33816576,right: 33554432The six existing
fused_moetests (parity against the f32 reference andgather_qmm, determinism, SGY invariance), which now run through the new accounting, pass on the commit.The four review lessons
a_partly_read_input_is_charged_for_the_rows_readpins it at 0, 1, the last row before all, all, one past all,rows == 0, an empty input, an input smaller than its row count, andu64::MAXin each position. Writing those cases is what removed my first form,data_size / rows * rows_read + data_size % rows * rows_read / rows: its second product wraps oncerowspasses 2^32. The shipped form takes the quotient first and cannot wrap; it is short of the exact share by less thanrows_readelements, against a budget counted in units of 2^20. On the launch side the index is tested at 1, 8, 64 and all 128 experts. An index naming no expert is charged nothing by the arithmetic test, and is not a launch the kernels support: the launcher sizes the grid's depth toK, and a probe on the commit's tree showedfused_moe_expert_kernelreturning a lazy[Din]array for an empty index whose eval aborts the process incuGraphAddKernelNode(invalid argument). That is the launcher's existing behaviour, no model passestop_k = 0, and this PR does not change it.inputs.size()entries per custom-kernel launch, none of which grows with a tensor, and one atomic increment per graph. A decode step runs about a hundred custom-kernel launches.scripts/nsys_cuda_graph_launches.pyis one pass over the kernels with a bisect per kernel: 1.0 s and 184 MB on the largest export of the audit (1.02M kernels, 2.68M API calls, 1.1 GB). The test stacks are built once per test; the arithmetic sweep is about 30,000 bridge calls.set_input_bytes_uncountedhas one caller, the paged-attention branch ofcustom_kernel.cpp, and it now goes throughrows_read_of_inputswith{0, 1}: traces of the change give 26 / 42 / 55 / 68 graph launches per step at B = 1 to 4 on Qwen3-0.6B, the same asmain, with identical text.CommandEncoder::set_input_arrayis called from 93 sites of the CUDA overlay and the rest of the backend; they see the thread-local at1 of 1, which returnsdata_sizeunchanged, andeval_gpuresets it after its loop as before. The two MoE kernels are reached fromfused_moe_expert_kernel(SwitchGLU families,qwen3_next),fused_moe_geglu_kernel(gemma4) and, for the down kernel only,fused_moe_forward's squared-ReLU branch, which has no CUDAfc1port and so does not run on CUDA; all pass the stacks in the registered order. Every othercuda_kernelregistration is listed in the issue comment with why it stays counted. The same count exists in the ROCm overlay (rocm/device.cpp:591, fixed budget 200, no exemption for any kernel) and is not changed here: no ROCm host.cargo fmt --all -- --checkon the committed tree: passes.Measurements
All on GB10, release builds copied aside with their sha256, one server at a time under a memory watchdog, no build or test beside a measurement. Method and every row:
docs/benchmark_results/cuda-graph-commit-audit-gb10-2026-11-27.mdand the two CSVs beside it.The known case. With the #3406 name match turned off, Qwen3-0.6B-4bit fused paged decode at 8,193 tokens costs 29 / 57 / 57 / 85 graph launches per step at B = 1 to 4;
maincosts 26 / 42 / 55 / 68, and so do both binaries under the raised budget. The #3385 profile (47.8 before, 37.6 after) was taken over a window of varying batch size; its own kernel counts give the mix (33% of steps at B=1, mean batch 1.74), and weighting the rows above by it gives 47.8 to 48.7 and 37.6.Graph launches per decode step,
main, default budget againstMLX_MAX_MB_PER_BUFFER=1000.MLXCEL_PAGED_ATTENTION_NATIVE=0gather_qmm)gather_qmm)With the change, default budget. Qwen3-30B-A3B at B=1: 62.1 (96 of
main's 99 short graphs per step held one of the two MoE kernels; 3 short graphs remain). LFM2-8B-A1B at B=1: 30.0. Qwen3-0.6B paged decode: 26 / 42 / 55 / 68 at B = 1 to 4, asmain. Qwen3-30B-A3B at B=4 (gather_qmm, not touched): 290.0, asmain. Reply text is identical tomainin each of these cells.Decode rate,
mainagainst the change (bench_decode.pyof the #3385 record; armsmain-a/ change /main-brotated per round; three rounds, two samples per cell and round, four in run 2; tok/s medians):The reply text is byte-identical across the three arms in every sample of every cell.
main(-1.8%): both main arms of that round started 3 to 4 tok/s above the other rounds.mainmoves between server starts on this model (57 to 71 tok/s at the short prompt); I did not find out why. The second run has four samples per cell and round and all three rounds ahead.main's and the added work is one small vector and three substring searches per custom-kernel launch, so I do not have a mechanism for it and did not repeat the cell. It is listed under doubts in the limits below.Verification limits
rocm/device.cpp:591) under a fixed budget of 200 and was not changed.qwen3_moe(Qwen3-30B-A3B) andlfm2_moe(LFM2-8B-A1B). The same kernels serve the other SwitchGLU families andqwen3_nextat B=1 (afmoe, bailing_moe, cohere2_moe, dbrx, dots.llm1, granitemoehybrid, klear, kolibri1, laguna, mellum, minimax, olmoe, phimoe, qwen2_moe, qwen3_vl_moe, the qwen3_omni_moe thinker and talker); none of those was run. perf(cuda): evaluate raising the MLX graph ops budget on GB10 (sm_121) #1798 found that raising both budgets for everything has a different sign per family. This change is narrower (two kernels' inputs, op budget unchanged at 20), but that is an argument, not a measurement, for the families I did not run.cudaGraphLaunch, 1,041 direct kernel launches per step). The GeGLU form of the gate/up kernel is therefore covered by the commit test only, on synthetic stacks.SwitchGLU::forward_fused_kerneltakes one token; batched decode runsgather_qmmand is untouched (290.0 graph launches per step at B=4 before and after).set_input_bytes_uncountednow goes throughset_input_rows_read; the evidence that the paged kernels are still left out is the 26 / 42 / 55 / 68 trace and identical text, not a commit test over a pool slab.4612ee77…2516674), so those measurements apply to the commit as is.main's Qwen3-30B-A3B rate varies between server starts. An index that names no expert aborts in the launcher today; I left it alone.