Repository navigation
gpu: run Qwen3.8 prompt layers on tensor cores and fold the attention gate into the flash store - #812
Conversation
gemm_nvfp4_mma and gate_up_nvfp4_mma load each K64 step's weight codes, activation codes and scale words into registers one step ahead and store them into one of two shared stages after the barrier, so a step's global load has only one step's MMAs to hide behind. The shared walk now copies a step's planes by cp.async into one of three stages two steps ahead. After the wait for its own copies, each thread turns its weight half of the step's stage into the MMA's nibble order in place (packed_pair, as before), and the step's barrier publishes it. The staged bytes, the K64 MMA order and the store are unchanged, so every output keeps its bits. Shared memory per block grows from 19,968 B to 29,952 B (gate_up_nvfp4_mma: 47,360 B with its SwiGLU tile). The routed NVFP4 benchmark lines print their output's hash so two builds can be compared.
On GB10 the prompt router's logits (513 rows of a BF16 weight, K = 2560, up to 2048 tokens a launch) ran on the exact F32 tile. With a BF16 weight at the wide instance on a cc 12.1 device the ubatch logits now run qwen35moe_router_logits_512_bf16_mma, the dense MMA tile's body (bf16_mma_body: the weight's words, each activation rounded once to BF16, F32 accumulation, a refused row or column replayed on the exact owner) over the router's rows. The fused decode launch must leave each token the ubatch pair's bits, so it moves to the same arithmetic: qwen35moe_router_fused_512_bf16_mma runs the router's rows sixteen a block through bf16_mma_narrow, one m16n8 fragment that copies the rows and up to eight tokens with cp.async and runs one m16n8k16 chain over K in the tile's order. A row or token the tensor cores refuse takes the fused entry's row sum, the exact tile's bits the ubatch replay leaves. Other devices and the F32 weight keep the exact entries. dense_mma names the device rule once for q8f32, the router and the gates. The router gate's BF16 case adds a subnormal to one weight row and one token, and on cc 12.1 holds the fused launch and the ubatch pair to the dense MMA tile then the routing alone, and the ubatch pair to the fused launch per token.
A Qwen3.8 prompt ubatch ran its delta step through gdn_delta_lanes, one token after another over the whole ubatch. An in-place prompt call now takes the chunked form: gdn_chunk_prepare builds each 16-token chunk's inverse (forward substitution in f32), causal product and decays from the chunk's own rows, all chunks at once, and gdn_delta_prepared walks the chunks in order with the state in registers, its products on BF16 tensor cores. The ubatch walk gives the chunk records the room of the q·k·v rows the conv has already read. A token's bits do not depend on how a prompt is cut into calls. The chunks start at multiples of 16 from the prompt's first position. A call that ends inside a chunk leaves the state the chunk starts from in its lane and the chunk's rows in a carry beside the lanes, which gdn_carry_keep writes. The next call from that position runs the carried rows through the chunk again and writes outputs for its own rows only; a step, pass or verify runs them through gdn_delta_lanes first. The carry is part of each delta store (497,296 B a layer), so checkpoints, saved prefixes and slot copies move it with the state, and the store and placement byte counts include it. gate_linear's new prompt clause holds the form to the f32 rule within a band, also where a head's keys lie near one direction, with its stamps, lanes, faults and refusals. Its cut clauses hold a prompt cut into calls at 8, at 50 and at 1, 2, 17, 32, 40, 41 and 77 to the same prompt in one call bit for bit (output, lanes, stamps and carry), and a step on the four rows the last cut prompt carries to the one-lane rule.
…h row's list The ubatch walk ran its selecting rows through the folded selected flash, one block of twelve warps a (row, key head) that walks the segment pass's segments and folds them. `gqa_prefill_flash_256_p12_sel` runs the dense pack-of-four prefill walk over each row's list instead: one block of eight warps a (row, key head), the twelve query heads in one m16 fragment, the tile's scores split over key quarters and dim halves and its value product over dims, the next key tile staged under the softmax and the value product. Over the list 0 .. n a row's bits are the `_p4` prefill flash's at count n. The fold and its entry are gone. At 2,045 selecting rows of a 4,096-position prompt, the bench's selection and attention (medians) go from 18.37 to 8.93 ms on GB10 (sm_121) and from 3.77 to 2.22 ms on the RTX 5090 (sm_120).
There was a problem hiding this comment.
Verdict: MUST_FIX: the fused attention store leaves an unused device buffer allocated in every ubatch arena.
Must fix
1. Stop allocating the retired ubatch flash output
scratch38.rs:291 still calls alloc, whose line 328 allocates rows * ATTN floats for flash. The changed wide38::qsa writes directly into attn; no ubatch path consumes flash anymore. This is an unneeded buffer (kind B): 100,663,296 device bytes per ubatch arena at 4,096 rows [derived: 4,096 × 24 heads × 256 values × 4 bytes].
Removing it now avoids preserving the dead allocation in the new placement pins. The existing parts argument is rows for step/pass arenas and zero for ubatch arenas. Replace the flash initializer in Arena38::alloc with:
flash: DeviceBuffer::zeroed(stream, parts * geo::ATTN)?,Non-blocking
⚠ Complete the GPU witness: flash_gqa_prefill.rs:5102 adds the gated-store test, but the PR body supplies no run output for it and says the full gate-gpu-lib suite was not run. Attach its result and the changed attention/router/norm gates' output, with the tested commit hash. The launch-fold and precision classes require runtime gates; the current witness names the comparison base but omits the tested head hash.
Optimization headroom
- E, Less work: wide38.rs:2504 still projects queries/gates and indexer queries for unread final-layer rows. Restrict those projections to the existing
keepsuffix, retaining every store-writing row. This avoids 51,200 output bytes per discarded row [derived: (12,288 + 512) f32 values], plus their projection work.
Checked
Allocation: Arena38::new passes parts = rows; Arena38::wide passes zero. The remaining flash consumers are in program38's decode/pass attention path. The proposed initializer preserves those buffers.
Tests: the cited GPU test compares both gated entries against the unfused output bit for bit, checks NaN fault metadata, and asserts named refusal of a short gate buffer. No CUDA tests were executed during validation.
Headroom: Q_ROWS = 12,288 and IDX_HEADS * IDX_DIM = 512; qsa projects all rows before narrowing to keep.
Rules: this is a full review of a regular PR. No escape-catalog pattern applies to these findings. No ledger lessons were in force.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_bf16.rs, crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/bin/gate_hc_gated.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)
… as far as its stores A prompt's ubatch walk ran its last layer over every row: the flash, the gate, the output projection and the feed-forward block of a layer whose outputs only the head's row reads (and, on a checkpoint, the point row). Nothing after the walk reads the other rows' streams. On the walk's last layer, when it runs without a host leg and no route tap records it, a unit now runs every row through the mixer's projections and store writes (the K/V and indexer-key appends, the pool; a delta layer's whole mixer) and the rest of the layer over its rows among the walk's last read ones alone (WideParts::kept). The unit is cut to them (UnitRows38::narrow: each window re-taken from the unit's row m - keep, the scalars moved with it) and its one-expert table refilled for them. The selecting layer's flash and select runs and the out gate read the arena's queries and the flash's output at the cut's offset. A unit that keeps no row runs nothing past its mixer, finals combines only the rows a unit kept, and the head refuses a walk that read no row. walk_gemm takes the rows read after the walk (the head's, a point row, a tap's every row) instead of the finals flag; a tapped call reads every row, so the route taps, the MTP target rows and the host legs keep the full layer. The e2e gate's whole plan checks the cut on D3K's prefill: the last walk's last layer runs 1 row when the plan's last layer has no host leg (the walk's ubatch with the route taps armed), and the cut run is bit for bit the run with every row kept (the tokens, the last logits, the stores and the PLE ring). A mutant that keeps every row fails the row count; one that drops the cut's offset fails the logits.
… prefill flash The ubatch walk's selecting layers ran the prefill flash into the arena's flash rows, then q38's out gate read them back with the gate half of the query projection and wrote the gated rows the output projection reads: at 4,096 rows a 100.7 MB write and read of the flash rows and one launch per layer for a product the flash's store can make. The prefill flash's store (prefill_pack_store!) now takes a gate (OutGate): Ungated writes each value as before, so the existing entries' bodies are unchanged; SigmoidGate writes v * sigmoid(gate) with the gate of the value's row read from the [q | gate] rows, raising f32_product on a non-finite value, gate or product, as q38's out gate does. gqa_prefill_flash_256_p4_gated and gqa_prefill_flash_256_p12_sel_gated are the pack-of-four and listed entries over it, launched through enqueue_packed and enqueue_listed. The walk's selecting layer runs both into the output projection's input and the out gate launch is gone. hw_gated_entries_are_the_flash_under_the_out_gate holds both gated entries bit for bit to their plain entry followed by the out gate, over gates in [-8, 8) with query halves the store must not read, a NaN gate's fault and value, and a short gate buffer refused by name.
0e90f16 to
89e588d
Compare
There was a problem hiding this comment.
Since the last review:
Must-fix 1: fixed. scratch38.rs:330 allocates flash output only for step/pass arenas.
GPU witness question: still open at flash_gqa_prefill.rs:5102.
Verdict: CLEAN: the allocation defect is fixed, and the interdiff introduces no must-fix finding.
Non-blocking
⚠ Complete the GPU witness: flash_gqa_prefill.rs:5102 still has no supplied gated-store test result. Attach that result and the changed attention/router/norm gates' output with the tested head hash. The body supplies card output and a comparison base, but omits the tested head hash. The launch-fold and precision classes require the owning runtime gates.
Checked
Duplicates: 0 new functions, types or constants in the interdiff; dryer reports 0 pairs. Existing byte constants remain their owners.
Complexity: all 15 crapper signals concern previously reviewed patches. The interdiff adds no branches or complex functions.
Silent failure: 0 new defaulting or discarded-result sites. Allocation errors still propagate through ?.
Tests: static mutation analysis links the revised placement assertions to place.rs:1144 and qwen38_cards.rs:259. Restoring either old scratch term makes its dependent pins fail. Removing gate_gemm.rs:3986's length check fails the test newly selected by the recipe. No CUDA tests were executed here.
Gates: revised byte and context pins have dated allocation derivations. No numerical band changes. Arithmetic checks match the scratch pins at 512 and 4,096 rows.
Adversarial: step/pass flash readers retain their buffers; both dense and listed ubatch attention write into attn. A one-row ubatch also uses the wide path. Card routing and draft reserves remain included. The removed allocation saves 24,576 B per row, or 100,663,296 B at 4,096 rows [derived: 24 heads × 256 values × 4 B × rows].
Escape catalog: C1–C4 match no interdiff hunk.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_bf16.rs, crates/gpu-gates/src/bin/gate_gemm.rs, crates/gpu-gates/src/bin/gate_hc_gated.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 prompt 처리 경로의 GDN 층, attention, router, NVFP4 routed GEMM을 GB10의 tensor core에 맞춰 바꾸고 아무도 읽지 않는 계산을 없애서 prefill과 첫 token 지연 시간을 줄이는 작업입니다.
Part of #565.
What and why
This PR moves the GDN delta step, the selecting attention layers, the router and the routed NVFP4 GEMM of the Qwen3.8 prompt path on a DGX Spark (GB10) onto tensor-core code, and it removes work whose result nothing reads. In every configuration I measured, prefill is faster and TTFT p95 is lower (table under "Speed").
The change has ten commits, one per step of the prompt path:
gemm_nvfp4_mma,gate_up_nvfp4_mma): the K64 walk copies each step's weight codes, activation codes and scale words with cp.async into one of three shared stages, two steps ahead, in place of loading them into registers one step ahead. The staged bytes and the MMA order are unchanged, so every output keeps its bits. The bench lines for the routed NVFP4 GEMM now print an output hash so two builds can be compared.gate_up_nvfp4_mma.hc_gated_up_mma_mix_4,hc_gated_lo_4x320) now takes BF16 activation columns formed from the bottleneck.qwen35moe_router_logits_512_bf16_mmaon the dense MMA tile. Each activation is rounded once to BF16, the accumulation is F32, and a refused row or column is replayed on the exact path. The fused decode launchqwen35moe_router_fused_512_bf16_mmauses the same arithmetic, so a token gets the same bits in both. Other devices and the F32 weight keep the exact entries.gdn_chunk_preparebuilds the record of every 16-token chunk at once,gdn_delta_preparedwalks the chunks in order with the state in registers and BF16 tensor-core products, andgdn_carry_keepstores the rows of an unfinished chunk in a carry beside the lanes. A token's bits do not depend on where a prompt is cut into calls, because chunks start at multiples of 16 from the prompt's first position.docs/research/tierengine.mdcarries the re-derived size of a sealed state's checkpoints, 296.1 MB.gdn_delta_recovery) until their commit.gqa_prefill_flash_256_p12_sel) in place of the folded selected flash. One block of eight warps takes a (row, key head), with the twelve query heads in one m16 fragment. Over the list 0 to n, a row's bits are those of the pack-of-four prefill flash at count n. The fold and its entry (gqa_flash_fold_mma_256_p12_sel) are gone.OutGate).Ungatedwrites each value as before.SigmoidGatewrites the value times sigmoid of the gate, read from the[q | gate]rows, and raisesf32_producton a non-finite value, gate or product.gqa_prefill_flash_256_p4_gatedandgqa_prefill_flash_256_p12_sel_gatedrun the flash under it, so the separate out-gate launch and its round trip through memory are gone.bf16_mma_norm_gate) finishes with the shared head norm, whichgdn_norm_gateandgdn_norm_gate_sigmoidnow call.WideParts::kept,UnitRows38::narrow).Arena38::allocwithparts = 0; the step and pass arenas keep theirs). A ubatch position holds 24,576 B less (6,144 f32), which is 100,663,296 B at 4,096 positions, andUBATCH_TOKEN_BYTESis 644,345.tools/ref/ptx-shapes.tsvand its three per-arch files) gain the new kernels, andtools/unsafe-ratchet.txtis recounted under datedPINlines, each new block with itsSAFETYline. The byte pins in the tests (body38.rs,seqstate.rs,bind.rs) follow the new checkpoint size. The stage scratch inqwen38_cards.rsand the card tables inqwen4exp_meta.rsandqwen4exp_mtp_meta.rsare re-pinned to the planner's output under datedPINlines. Thegate-gpu-gemmrecipe's test filter namesnan_bits_equal_takes_the_length_and_any_nan, so a recipe runs that test.Release notes: Changed: Qwen3.8 prompt processing on DGX Spark (GB10) has higher prefill throughput and a lower time to first token, and a Qwen3.8 sequence checkpoint is larger because it now carries the GDN chunk rows.
Code shape
bf16_mma_bodyand the dense MMA launch geometry. Both gated flash entries go through one store (prefill_pack_store) with the gate as their only variation. The per-token delta update stays inrule_row. The MTP gate's store check usesbloomery_gpu_gates::bits_equal, and the norm-gate case ofgate_gemmuses the existing NaN-tolerant owner, now namednan_bits_equal, in place of a second inline comparison. The new call site gains the length check it lacked: a shortexpectednow counts as a difference.linear/delta.rs,flash_gqa_prefill.rs,gemm/). The Qwen3.8 files gained the carry buffers, the calls and the row cut. No common owner gained a per-model branch, flag or trait method.f32_product, and a short gate buffer is refused by name. The GDN delta launchers refuse a qkv, state or carry window that is not 16-byte aligned, by name and before launch, since the kernels read those buffers with 128-bit loads.tools/check-comments.shwas not run on this head.PINlines.cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up.cargo fmt --all -- --checkis clean on this head.cargo clippyis clean on five crates includingbloomery-gpu-gates;bloomery-gpuneeds CUDA and is not linted on the Mac, so the GB10 lint covers it.Duplication found or removed (
path:line), or "none": none left. The duplicate scan lists 21 candidates. Each one either calls a single shared owner (for examplebf16_mma_bodyfor the router and the dense GEMM, ordelta_lanes_bodyfor the per-head and per-key delta entries) or differs in its arithmetic or index contract.What I ran
The placement tests, the model and meta tests and the fixture budget below ran on this head's tree. The alignment gate ran on a tree whose files differ from this PR's head in
unsafeblock comments, the two gate comparison helpers named below and their callers, and the ubatch arena's flash allocation. The speed runs, the class gate, the unit tests, the PTX scan and the spill ratchet ran on a head whose product code on these paths equals this PR's head except for those comments and that allocation. The bit comparison and the PTX comparison against main ran on a head that differs from this one in three files and that allocation: the GDN launchers' alignment checks (crates/gpu/src/linear/delta.rs), their gate clauses (crates/gpu-gates/src/bin/gate_linear.rs) and the Qwen3.8 stage scratch with its placement pins (crates/placement/src/placement/qwen38_cards.rs). The allocation changes one buffer's size and no kernel or launch, so I carried those runs over and did not repeat them. The only change on main since is the packing reserve of the part read on the load path.The test
bits_equal_takes_the_length_and_every_bitincrates/gpu-gates/src/lib.rspasses on a CPU-only machine (test result: ok. 1 passed; 0 failed). With the length check removed frombits_equal, it panics and exits with code 101.The test
nan_bits_equal_takes_the_length_and_any_naningate_gemmpasses on an RTX 5090 machine (test result: ok. 1 passed; 0 failed). With the length check removed fromnan_bits_equal, it panics and exits with code 101.cargo check -p bloomery-gpu-gates --features gpu --binsexits 0 with no warnings.cargo fmt --all -- --checkexits 0 on this head.just gate-gpu-linearpasses on an RTX 5090 machine with 130 clauses and 0 failures (output under "GPU Evidence"). Thirty-three of them refuse aqkv,stateorcarrywindow that sits 4, 8 or 12 bytes past a 16-byte boundary, for each launcher that takes the buffer, and check thatstateandoare unchanged after a refusal. With the check reading no address, all 33 fail with"launched"and the gate exits with code 1.The
qwen38_cardsplacement tests pass on a CPU-only machine:test result: ok. 28 passed; 0 failed. With the stage scratch and the ubatch bytes set back to their values before the arena change, four of them fail andtest result: FAILED. 24 passed; 4 failedis printed.just gate-fixture-budgeton the re-made qwen38 fixture passes:qwen38: budget 9409921024, experts a layer [256, 256, 256, 256].python3 tools/recipes.py orphan-testsprintsorphan-tests: ok (4027 tests, each run by a gate-* or lab-* recipe).The NVFP4 class gate on GB10 passes (output under "GPU Evidence"). The last argmax equals the oracle's on both batch sets, and at position 3000 of the D3K set it is token 423, the oracle's. All route flips are in the allowed set.
The end-to-end gate holds the cut of the walk's last layer to the run with every row kept, bit for bit.
On an RTX 5090 machine the checkpoint test and the 12
cache_rambyte tests pass with the new checkpoint size (output under "GPU Evidence").The
seqstatetests pass on a CPU-only machine:test result: ok. 32 passed; 0 failed.The spill ratchet passes for sm_86, sm_121 and sm_121a, with every entry pinned.
The PTX comparison of this head against main covers six binaries on sm_86 and sm_121a. It lists ten kernels added, one removed (
gqa_flash_fold_mma_256_p12_sel) and the changed ones, and each change matches a commit above.gqa_prefill_flash_256_q8andgqa_prefill_flash_256_p12_seldiffer in instruction order only.The new walk of the NVFP4 routed GEMM keeps main's output bits. I built this head and the same tree with main's
nvfp4mma.rs, and compared the gate hashes and the routed bench output hashes at the prompt shape:All three bench hashes (gate, down, gate_up q8) are equal, and the head's own NVFP4 gates pass with 37, 5 and 21 cases and 0 failures.
Not run on this head: the full t0 check set, the complete
gate-gpu-libsuite, and the GB10 runs of the lib, qwen35moe attention, qwen3moe router, qwen35moe MoE, gemm, linear and bf16 gates. Those GB10 gates run after publication.GPU Evidence
DGX Spark (GB10), driver 595.84, CUDA 13.3
The gate runs the NVFP4 checkpoint through its batch sets, with the route flips counted per layer, and through the D3K position-3000 set.
The spill ratchet, one line per target:
RTX 5090, driver 595.99.02, CUDA 13.2
The alignment gate on the same card model, driver 595.99.02:
Speed
The four configurations run
bloomery-serveon one DGX Spark (GB10) with one slot. NVFP4 usesnvidia/Qwen3.8-Flash-Next-NVFP4and FP4-Local usesnvidia/Qwen3.8-Flash-Next-FP4-Local, both with the draft model off. The MTP rows run FP4-Local with the MTP draft on. Each round starts a fresh server, sends two warm-up requests and then four timed requests. Each timed request carries a different 4,096-token window of a code corpus (the MTP rows add an English prose corpus) and generates greedily at temperature 0. Three rounds per side alternate between main and head, and the table shows the medians. Prefill and decode come from the server's timings, and TTFT p95 from the client clock. Main is0c768d47c.Delta (head against main): with the NVFP4 checkpoint, prefill rises from 1717.82 to 1959.34 tok/s (+14.06%) and TTFT p95 falls from 2390.96 to 2097.56 ms (-12.27%); the other three configurations move the same way.
Prefill and TTFT p95 move the same way in all four configurations, and every one of those changes is larger than the smallest resolvable effect of its run.
The decode changes of -0.20% (NVFP4), -0.16% (FP4-Local) and +0.61% (MTP, code) lie inside the smallest resolvable effect, so I read them as not resolved. MTP on prose decodes 3.59% faster, which is resolved.
Hardware
DGX Spark (GB10), driver 595.84, CUDA 13.3, build
sm_121a, for the speed runs, the class gate and the bit comparison. An RTX 5090 machine, driver 595.99.02, CUDA 13.2, for the unit tests and the sm_86 ptxas scan, with ptxas 13.3.73.AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.