Repository navigation
gemm: speed up the routed NVFP4 expert GEMMs on long prompts - #760
Conversation
There was a problem hiding this comment.
Verdict: CLEAN: No must-fix finding remains.
Non-blocking
⚠ Complete the measurement evidence for the final head: crates/gpu/src/gemm/kernels32.rs:839. The added scan reads 4 × n_slots bytes per fused launch: 163,840 bytes at 40,960 slots [derived]. The PR states that its bench, A/B and profile predate this scan. The AGENTS change class “fold a launch into a neighbour” requires a timed A/B. Attach final-head measurements with the tested base/head hashes, card and driver, exact model paths, commands and output before reusing the speed claim.
Checked
Duplicates: dryer reports 0 pairs in crates/gpu; gpu-gates was excluded. Both NVFP4 entries share gemm32_block!. The fold reuses the quantizer, SiLU and launch checks.
Complexity: diagnostics report new nvfp4_swiglu_case (96) and swiglu_sides (24), nvfp4_gemm_arm 25→39, and g32::run 17→18. The new gate covers fixtures, plane/fault comparisons, replay and host refusals.
Silent failure: the new clamp repeats the last live block for quantizer padding. Invalid places raise ExpertId; refused quantizer groups raise QuantColumn. The launcher rejects mismatched K and short gate/place buffers with shape errors.
Tests: the gate compares planes and faults across the reference, eager fold and graph replay, with separate poisoned up scratch. The PR reports FAIL-first runs for wrong-slab, missing-K-check, dropped refused-slot fault and omitted-scan mutants. CUDA gates were not rerun during validation.
Gates: changed spill and unsafe ratchets have dated PINs and reasons.
Escape catalog: C1–C4 do not match the changed Rust and table files.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu/src/arch/qwen3moe/wide38.rs, crates/gpu/src/gemm/act32.rs … and carries no gate run on a card (CONTRIBUTING's evidence list); a maintainer adds gpu-verified after one.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
|
The review is done and the contribution check passed, so I'm merging this. |
Qwen3.8의 routed expert NVFP4 GEMM을 빠르게 만들어, W4A8 경로(
sm_86,sm_121build)에서 4K 프롬프트의 prefill 시간을 줄입니다.Part of #565.
What and why
On a prompt, each Qwen3.8 MoE layer runs three NVFP4 routed GEMMs (gate, up and down) and a SwiGLU pass between them that quantizes its output for the down GEMM. In a profile of a 4,096-token prompt
gemm_nvfp4pis the largest kernel, 28.5% of the kernel time on main. This PR has three commits: the two below and a third that recounts the unsafe-block pins on the rebased tree.Which builds this reaches:
gemm_nvfp4pand the fold run on the W4A8 path, which ansm_86orsm_121build takes for NVFP4 and FP4-Local routed weights, on a GB10 and on other cards. Since #758 a GB10 build selectssm_121aby default, and there the routed prompt GEMM takes the native FP4 path (gemm_nvfp4_mma), which this PR does not change. The measurements below were taken withsm_121builds on both sides, before #758.gemm: copy the NVFP4 routed weights two steps ahead and decode them at the fragment read.gemm_nvfp4p(crates/gpu/src/gemm/gemm32.rs,kernels32.rs) used to move its weights through registers. Nowcp.asynccopies the raw weights into three stages (NV_STAGES), two steps ahead of the compute, and each warp decodes its own rows' nibbles and sub-block scales when it reads the fragment (nv_copy,nv_frags). The weight load no longer sits in registers while the step computes.gemm: fold the routed SwiGLU quantization into the NVFP4 up GEMM. The new kernelgemm_nvfp4p_swigluwalks the up weights likegemm_nvfp4pand changes only the store. It does not write the up values. It reads the gate GEMM's rowg, formssilu(g) * uin a staging tile, and each warp quantizes its columns with the same group rule asswiglu_quant32_sel(quant32_group), writing the down GEMM's activation plane directly. A 128-row slab holds four Q8 blocks, which is one quantizer group, so a group never crosses thread blocks and the order of operations matches the two-launch path. The host entry isGemm32Kernels::enqueue_up_swiglu32(gemm32.rs). Before the table walk, block 0 of the fused kernel reads the place of every slot and raisesExpertIdfor a place at or above the card count and below the host marker. The scan covers slots the route omits, so a bad place is refused whether or not a tile reaches it, asswiglu_quant32_seldoes for the two-launch path. The store and refused-slot arms no longer raiseExpertIdthemselves; the refused-slot arm writes its block throughquant32_groupand raisesQuantColumnonce per block. For a weight type other than NVFP4, or the native FP4 path, it callsenqueue_gemm32and thenenqueue_swiglu_quant32_selas before, so those paths keep their bits and faults. Its first caller isenqueue_gemm_batchincrates/gpu/src/arch/qwen3moe/wide38.rs, which now issues five launches per batch instead of six for NVFP4 weights. The grouped (K-quant) path is unchanged.quant_launchinact32.rsbecomespub(super)so the fold reuses the same plane check.The fold requires
rows == 32 * oblocks. The Qwen3.8 FF width of 640 meets it, and other widths get a named error from the host before launch.tools/unsafe-ratchet.txtraises the gpu block count from 2273 to 2293 with three dated PINs: the weight stages, the fused kernel's store, and the place scan. The refused-slot arm calls the existing quantizer,quant32_group, with a NaN group, so the refused block format has one owner. Each new block has aSAFETYline that states its invariant in place and holds one memory operation.The PTX spill tables pin both kernels with dated PIN lines, read on a GB10 (ptxas 13.3.73, driver 595.84):
gemm_nvfp4p48 spill bytes atsm_86and 64 atsm_121andsm_121a, and the newgemm_nvfp4p_swiglu0 atsm_86and 160 atsm_121andsm_121a. Both use 128 registers, 33,328 shared bytes and 256 threads. Thesm_86rows of the base table record ptxas's stack frame as the local bytes; the cc 8.6 JIT was not measured.Release notes: Changed: the routed NVFP4 expert GEMMs on Qwen3.8 prompts copy weights ahead of the compute and fold the SwiGLU quantization into the up GEMM, which shortens the routed GEMM time of a 4K prompt on the W4A8 path (
sm_86andsm_121builds).Code shape
quant32_groupfor the quantizer,quant_launchfor the plane check,Gemm32Launch::checkfor the launch check andsilu_mulfor SiLU. Its fallback calls the two existing host functions. The new kernel andgemm_nvfp4pshare onegemm32_block!body and differ only in the store arm.wide38.rsonly calls the new host entry in place of two calls it already made. The common owner gained no per-model branch.gorseland an out-of-rangen_cardwith a named error before launch. A misaligned code plane is refused byGemm32Launch::check, which reachesNvfp4Stack::experts. The kernel raises a fault for a refused slot and for the bad place of any slot, including one the route omits. No new allocation.SAFETYcomment names its own invariant and does not point at another comment.cargo fmtis clean on what I touched, andcargo clippyon the GPU crates reports 3 warnings, the same count as main.Duplication found or removed (
path:line): the scan flagged two pairs, none a copy.NV_STAGES(gemm32.rs:129) andSTAGES(f32tile.rs:70) have equal values but size different pipelines.gemm_nvfp4p_swiglu(kernels32.rs:806) repeats the argument list ofgemm_nvfp4p(:735) because device entries take flat arguments, while both bodies call the sharedgemm32_block!. The NVFP4 code-plane alignment check has one owner,Gemm32Launch::checkthroughNvfp4Stack::experts;enqueue_gemm32andenqueue_up_swiglu32do not repeat it.What I ran
Kernel bench
The bench replays 64 launches of one routed GEMM as a CUDA graph and reports the mean per launch. It uses synthetic inputs with the Qwen3.8 shapes: 640 and 2,560 rows, K of 2,560 and 640, 512 experts, top-10, 4,096 tokens, 40,960 slots. Main and head alternated for three rounds on one GB10, and the table shows the median round. The spread between the rounds of one arm was at most 0.7%. Main has no 4,096-token arms in its bench table, so I added the gate and down arms to main's copy for this measurement only. This PR adds them to the head's bench table.
On the head, the fold replaces the up GEMM and the SwiGLU quantization:
Both up arms write the same activation plane in every round (
act_q_fnv=2944078e47be9d85,act_d_fnv=b478f440dfd5f8f3). Main's two-launch up path was not timed on its own.Speed A/B
This is a 4,096-token prompt, one client, draft off, greedy, 128 generated tokens, three requests per arm. Each arm loads the server once, and main and head alternate in one session on one DGX Spark (GB10). Each checkpoint starts with a discarded warm load and the arm order is reversed between checkpoints. A read probe and the decode rate right before each arm serve as witnesses that the card state matched. The models are the Qwen3.8 NVFP4 checkpoint (revision fc694b54) and the Qwen3.8 FP4-Local checkpoint (revision b9ce18a6).
Delta (head against main): NVFP4 TTFT -5.8% (3,192.9 to 3,007.6 ms), prefill +6.2% (1,285.0 to 1,364.7 tok/s).
The witnesses matched on this checkpoint: decode 22.52 tok/s on main and 22.47 on head, read probe 235.1 and 235.7 GB/s.
The FP4-Local checkpoint shows no difference beyond noise in this session:
The head arm of this checkpoint ran on a card whose witnesses were lower than the main arm's: read probe 223.8 against 230.7 GB/s and decode 29.97 against 30.66 tok/s. The changed kernels are not on the decode path, so I read that gap as card state. I did not repeat this arm, so I make no claim about the end-to-end effect on this checkpoint.
Each arm is one session of three requests, so these are single observations and I make no significance claim. Load time is outside the numbers.
Output is identical. Per window, the greedy 128-token output hash is the same on main and head:
e137fcd8279a292c,66645d7f0f23665eand96bd4403a463e001on FP4-Local, ande137fcd8279a292c,135a9834806eb026and96bd4403a463e001on NVFP4.Kernel time of one real prompt
An
nsysrun on the FP4-Local checkpoint, one request with a 4,096-token prompt at window 16,384, shows the routed kernels:gemm_nvfp4pandswiglu_quant32_sel, orgemm_nvfp4p_swigluq38_card_sum_shared_addOn main the first row sums 144
gemm_nvfp4plaunches (883.5 ms) and 48swiglu_quant32_sellaunches (49.6 ms). On the head it sums 96gemm_nvfp4plaunches (551.2 ms) and 48gemm_nvfp4p_swiglulaunches (261.6 ms). The gain on real routing is smaller than the synthetic bench, which uses uniform routing. The profiled request's TTFT is longer than its kernel total by more on the head than on main, so part of the kernel saving shows up as idle time instead of a shorter request. I did not analyze the timeline for the cause.Gates
The fold has a new gate,
g32_nvfp4_swiglu, with its case filternvfp4_swigluincrates/gpu-gates/src/bin/gate_gemm.rs. It builds 16 card experts (every third of 24 on host) with 640-row and 160-row stacks, K of 512, shared column top-4, and T of 1, 9, 64 and 448. For each T the fold's activation plane is bit-identical to the two-launch plane, with no fault. The fused run gets its own up scratch, filled with NaN before each run, so it cannot read the up rows the reference wrote; a launcher that quantizes without running the up GEMM fails 12 of the 21 cases, while the gate without this separation passed all 21. For T of 64 and up the exact-walk path runs too. Two fault inputs are kept apart. The NaN-gate input has a NaN gate value in a card column and must raiseQuantColumn. The refused-slot input has a slot refused by the card place, a slot of an unowned place and a listed slot in[n_card, HOST), and must raiseExpertIdandQuantColumn, so the refused-slot raise is required on its own. Both paths must give the same plane and the same faults. A third group uses a route with no tile: one expert, every slot on host, with 1 and with 257 slots, once with a valid last place and once with the last slot atn_card. The valid cases raise nothing. The invalid ones must raiseExpertIdfrom the two-launch path, the fused eager launch and the graph replay, and 257 slots cover the second pass of the scan loop. Each run's fold is captured as a graph and replayed over a fresh seed, and the replay must equal eager. A wrong K, column count, shortgand shortselmust be refused before launch.just gate-gpu-gemmwas not run as a recipe, so I ran its gate step directly on each card. The existing cases for routed and dense NVFP4 bits (g32_nvfp4_routed,g32_nvfp4_dense) and for the quantizer (g32_quant) need a Qwen3 model file that the GB10 machines I used did not have, so they ran only on the RTX 5090.On the GB10 (sm_121), on the head with the place scan, all 21
g32_nvfp4_swiglulines read PASS with no FAIL:On the RTX 5090 (sm_120), the existing cases ran on the head before the place scan was added:
The fold's activation fingerprint for T of 1 and 640 rows is
56b9a33321c11a4eon both cards.cargo check --workspace --all-targetswith the GPU features finished withCHECK workspace all-targets rc=0 warnings=0on the RTX 5090, also before the place scan.FAIL first
Three planted defects, each shown to fail the gate:
QuantColumnwas deleted. The refused-slot input then failed at both row counts, with onlyExpertIdraised, and the NaN-gate input still passed:ExpertIdand the fused eager launch and graph replay raised nothing. The valid all-host inputs and the earlier cases passed:With the real source the gate passes every case (above). Commit 1 changes no output bits, and the existing
g32_nvfp4_routedandg32_nvfp4_densecases cover it. I did not plant a defect for the graph-replay check, which would fail if the fold read state from outside the captured graph.GPU evidence
The kernel bench, the GB10 gate run and the speed A/B ran on DGX Spark (GB10) machines, and the other gate run on an RTX 5090 machine.
nvidia-smilines from each:Tested head
The GB10 gate run above used the head's kernel code. The planted-defect runs, the RTX 5090 runs, the kernel bench, the speed A/B and the
nsysrun each ran on an earlier head. The bench, the A/B and thensysrun were taken before the place scan was added, so their numbers do not include it. The scan reads one u32 per slot once per launch, 163,840 bytes for 40,960 slots, and I did not time it. After those runs the branch was rebased onto newer main. Among this PR's files, main's new commits changedwide38.rsandgate_gemm.rsin other places, the PTX shape tables and the unsafe ratchet;gemm32.rs,kernels32.rsandact32.rschanged only in this PR. The third commit recounts the unsafe pins.Not run: the other
just gate-*recipes.What I ran into
None of this blocks the PR.
nsyskernel numbers.nsysnumbers above predate it.q38_card_sum_shared_add) into the down GEMM's epilogue is not possible under the current bit contract, so it is not part of this change.AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.