Repository navigation
gpu: select and attend a ubatch's selecting rows in one launch each - #753
Conversation
There was a problem hiding this comment.
Verdict: MUST_FIX: The graph harness is duplicated and two new accessors have unnecessary public visibility.
Must fix
1. Run both graph entries through one harness
crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs:3727 repeats the pool/selection chain and graph checks at crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs:3611. R14 requires one owner.
Later contract changes would require two edits.
Replace both graph sections, from the first let cs through the second ok &= graph_ok, using the existing SelFlash:
let mut pooled_g = DeviceBuffer::from_host(stream, &pooled.to_host_vec(stream)?)?;
let mut pv = DeviceBuffer::<f32>::zeroed(stream,
listed_partials_v_len_256(MAX_ROWS, N_HEAD_Q38, WIDTH))?;
let mut pms = DeviceBuffer::<f32>::zeroed(stream,
listed_partials_ms_len(MAX_ROWS, N_HEAD_Q38, WIDTH))?;
for (entry, counts, seed) in [
(SelFlash::Pass, (SEL_ROWS0..=SEL_N).collect::<Vec<_>>(), 631),
(SelFlash::Fold, wide_counts(), 633),
] {
let cs: Vec<u32> = counts.into_iter().map(u32::try_from)
.collect::<Result<_, _>>()?;
let m = cs.len();
let qi = DeviceBuffer::from_host(stream, &idx_queries(m, seed))?;
let qa = DeviceBuffer::from_host(stream, &activations(HEAD, m * N_HEAD_Q38, seed + 1)
.iter().map(|v| v * SEED_Q_SCALE).collect::<Vec<_>>())?;
let nk = DeviceBuffer::from_host(stream, &cs)?;
let mut ya = DeviceBuffer::<f32>::zeroed(stream, m * w)?;
let mut yg = DeviceBuffer::<f32>::zeroed(stream, m * w)?;
let mut chain = |s: &CudaStream, y: &mut DeviceBuffer<f32>| -> Result<(), GpuError> {
qk.enqueue_pool(s, PoolArgs {
raw: &idx.raw_d, gain: &idx.gk_d, table: &idx.table_d,
n_keys: &nk, eps: EPS, ctx: SEL_CTX, m, fault: unl,
pooled: &mut pooled_g,
})?;
qk.enqueue_select(s, SelectArgs {
q: &qi, gain: &idx.gq_d, table: &idx.table_d, n_keys: &nk,
pooled: &pooled_g, eps: EPS, ctx: SEL_CTX, kept: KEPT, m,
fault: unl, scratch: &mut scratch,
})?;
let attn = GqaFoldArgs {
q: &qa, kc: &c.kc, vc: &c.vc, list: &scratch.list,
n_sel: &scratch.n_sel, width: WIDTH, scale: scale(),
n_kv: N_KV, ctx: SEL_CTX, m, fault: unl, y,
};
match entry {
SelFlash::Pass => k.enqueue_pass_256_p12_sel(s,
GqaSelArgs { attn, part_v: &mut pv, part_ms: &mut pms }, N_HEAD_Q38),
SelFlash::Fold => k.enqueue_fold_256_p12_sel(s, attn, N_HEAD_Q38),
}
};
chain(stream, &mut ya)?;
stream.synchronize()?;
let eager = ya.to_host_vec(stream)?;
let graph = gpu.capture(|s| chain(s, &mut yg))?;
graph.launch(stream)?;
stream.synchronize()?;
let same = bits_equal(&yg.to_host_vec(stream)?, &eager);
let (kernel, nodes, segments) = match entry {
SelFlash::Pass => ("gqa_flash_seg_mma_256_p12_sel", 5, listed_segments(WIDTH)),
SelFlash::Fold => ("gqa_flash_fold_mma_256_p12_sel", 4, 1),
};
let grid = [u32::try_from(m * N_KV * segments)?, 1, 1];
let block = [u32::try_from(PACK_12 * 32)?, 1, 1];
let shape = graph.nodes()?.into_iter().filter_map(|n| n.kernel)
.find(|n| n.name.starts_with(kernel))
.is_some_and(|n| n.grid == grid && n.block == block);
let pass = same && graph.node_count() == nodes && shape;
println!("qsa chain {kernel} m={m}: eager={same} shape={shape} {}", verdict(pass));
ok &= pass;
}2. Keep the new scratch accessors inside the crate
crates/gpu/src/qsa.rs:1297 and crates/gpu/src/qsa.rs:1304 export rows and row_bytes, but every caller is inside bloomery_gpu. R13 permits pub only for actual callers in another crate.
Narrow them before external callers depend on them. Replace each definition:
pub(crate) fn rows(&self) -> usize {
self.rows
}pub(crate) fn row_bytes(ctx: usize, kept: usize) -> usize {
4 * (HEADS * DIM + pools_for(ctx) + list_width(kept) + 1)
}Checked
Both graph chains were read; the shared loop removes duplicated setup, enqueues and graph checks without adding a helper. Accessor callers are confined to bloomery_gpu. Both inline suggestions target added lines and preserve those calls. No escape-catalog exception applies. GPU tests were not run here.
Notes
Dryer excluded gpu and gpu-gates. The submitted attention run disabled clause 6 and exited 1; gate evidence predates this head and omits exact model filenames.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu/src/arch/qwen3moe/program38.rs, crates/gpu/src/arch/qwen3moe/scratch38.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 most rows one selection into this scratch takes. | ||
| #[must_use] | ||
| pub fn rows(&self) -> usize { |
There was a problem hiding this comment.
R13: every caller is inside bloomery_gpu; keep this accessor crate-private.
| pub fn rows(&self) -> usize { | |
| pub(crate) fn rows(&self) -> usize { |
| /// Device bytes a scratch over a cache of `ctx` rows keeping `kept` | ||
| /// pools holds a row: its query heads, scores, list and length, 4 B each. | ||
| #[must_use] | ||
| pub fn row_bytes(ctx: usize, kept: usize) -> usize { |
There was a problem hiding this comment.
R13: every caller is inside bloomery_gpu; keep this byte calculation crate-private.
| pub fn row_bytes(ctx: usize, kept: usize) -> usize { | |
| pub(crate) fn row_bytes(ctx: usize, kept: usize) -> usize { |
586cd83 to
ab73b1b
Compare
There was a problem hiding this comment.
Since the last review:
- Graph harness duplication: fixed. Both entries use one loop.
- Scratch accessor visibility: fixed. rows and row_bytes are crate-private.
Verdict: CLEAN: Both earlier findings are fixed, and the interdiff introduces no proven defect.
Checked
Duplicates: 0 new named items; the existing SelFlash owns dispatch. Dryer reported 0 pairs; manual comparison confirms the two graph harnesses now share setup and checks (R14).
Complexity: sel_flash_check consolidates existing graph branches. The other crapper flags (bench_select, select_check, deep_check, run, qsa_score, enqueue_select) are unchanged by this interdiff.
Silent failure: 0 new default or discarded-error sites. Fallible enqueues, capture, replay, synchronization and readback propagate errors; absent kernel nodes fail the shape check.
Tests: static mutation check at the retained graph assertions: dropping the merge launch at flash_gqa.rs:6058 fails the node count; halving the fold grid at flash_gqa.rs:6095 fails the geometry check. Eager/replay bit comparisons remain for both entries. GPU tests were not run here.
Gates: no pins moved or clauses removed in the interdiff; five-node pass and four-node fold expectations remain.
Adversarial checks: pass partials cover its eight rows; selection scratch covers the fold's twenty rows; replay completes before captured buffers drop. The partial final score group is bounded by the remaining row count.
Escape catalog: C1–C4 do not match these changes.
Notes
Dryer excluded gpu and gpu-gates. The submitted attention run disabled clause 6 and exited 1. GPU evidence predates this head and omits exact model filenames; gpu.json records evidence=false.
Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs, crates/gpu/src/arch/qwen3moe/program38.rs, crates/gpu/src/arch/qwen3moe/scratch38.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의 4K prompt에서 attention이 고르는 행을 8행씩 끊어 launch하던 것을 한 번에 고르고 한 번에 attention하게 해서 launch 수를 줄이는 작업입니다.
Part of #565.
What and why
In a Qwen3.8 prompt, the rows whose key list is longer than 2,051 entries go through top-k selection and then selected flash attention. The ubatch walk cut those rows into runs of 8 and launched four kernels for each run:
qsa_score,qsa_topk,gqa_flash_seg_mma_256_p12_selandgqa_flash_merge_256. A 4,096-token prompt has about 2,045 such rows, so each kernel ran 258 times a layer, 3,096 launches over 12 layers.This PR runs a whole run of selecting rows with one selection and one attention launch:
qsa_scoretakesmrows as⌈m/8⌉groups of 8 in one launch. A row's head and score are the same in any group and any launch, which the gate checks bit for bit.QsaScratch::newloses itsrows <= 8limit and refuses by name a row count whose bytes overflow (row_bytes,rows()).gqa_flash_fold_mma_256_p12_sel(fold_mma_ps) gives each (row, key head) block the whole segment walk. It cuts segments with the sameseg_spanas the old pass, and folds each segment's(max, sum of exp, sum of exp times V)in the old merge'sonline_foldorder, skipping empty segments as the merge did. The output, fault rows and NaN rows are therefore bit-identical to the old pass and merge, and no partial buffers are needed. The segment body moved into the macroslisted_query_tile!andlisted_seg_tiles!, shared withseg_mma_ps. One check,check_listed_256, serves both enqueue paths.select_run(rows, ctx)rows at a time (SELECT_RUN_BYTES / row_bytes, a multiple of 8, at least 8, at mostrows). The ubatch arena no longer holds partial buffers (Arena38::widetakes(select_run, 0)).place.rsownsSELECT_RUN_BYTES = 22,000,000. TheUBATCH_FIXED_BYTESderivation now reads router 8,577,028 + mix 379,520 + 22,000,000 = 30,956,548 B. The value stays 32 MiB, so the meta pin does not move.program38) keep pass and merge. With 8 rows or fewer the fold grid (m * n_kvblocks) does not fill the card: the kernel bench below shows the fold slower at 8 rows (0.308 ms against 0.113 ms).tools/ref/ptx-shapes*.tsvtables gain the new entry, andtools/unsafe-ratchet.txtmoves from 2268 to 2272 blocks and from 281 to 282 functions with aPIN(2026-10-24)line.Release notes: Changed: Qwen3.8 prompt attention launches the rows that use top-k selection in one selection and one attention launch per run instead of four launches per 8 rows, 12,384 launches down to 168 on a 4,096-token prompt; end-to-end prefill speed is inside the run-to-run spread.
Code shape
check_listed_256.GqaSelArgsholds the sharedGqaFoldArgsand adds only the two segment partials, so the pass and the fold take their twelve common fields from one struct. The gate builds those fields once for both entries.SELECT_ROWSand its assert are removed, and the ubatch arena no longer allocates partial buffers.QsaScratch::newrefuses zero rows and a byte overflow by name before allocating. A head group other than 12 heads per key head is refused by name in the fold as in the pass.PIN.cargo fmtandcargo clippyare clean on what I touched; the lint count did not go up.Duplication found or removed (
path:line), or "none": the duplicate scan flaggedcrates/gpu/src/flash_gqa.rs:2551against:2435(the fold and the segment pass share the query tile and segment walk through the two macros; what is left differs in grid, in the loop over live segments and in the output) and the kernel entry at:4568against:4487and:4878(every entry in the file takes its arguments flat and declares its own shared arrays). I left those as they are.What I ran
Output is unchanged
gate_qwen35moe_attnon the head runs 19 clauses with 210 PASS lines and no FAIL line. New lines it checks:qsa select wide m=20 (3 groups of 8): the head and score of 20 rows in one launch equal the host bit for bit, and each group of 8 equals a launch of only that group.qsa scratch refusal rows=18014398509481983: a byte overflow is refused before allocation.fold = selected bit for biton every selected-flash line of clauses 11, 12, 13 and the deep case: the fold output equals the old pass and merge output for the same list and cache, including cache rows outside the list that hold NaN and fault rows.qsa fold chain graph m=20: the four-node graph equals the eager run bit for bit.qsa fold group refusal 16/48 heads over 2: a group other than 12 heads is refused by name.shape kernel=gqa_flash_fold_mma_256_p12_sel local_depot=false ld_local=0 st_local=0.gate_qwen4exp_e2eat the fixture tier ran 26 clauses with 171 PASS lines, 0 FAIL and rc 0. The walk of 3,000 ids in two units and in one unit give the same tokens, last logits, store and PLE ring, and 949 selecting rows go through the new fold path.The unmodified
just gate-gpu-qwen35moe-attnwas not run: it reaches its clause 6, which needs the Qwen3.6 reference fixture set, and no machine I could use holds that set. I ran the same gate binary through the same gate runner with only that one call to clause 6 disabled, so the process exits 1 on its "a clause did not run" line. The other 19 clauses ran. Clause 6 is code this PR does not touch.FAIL-first
I planted three mutants in one build and ran the same gate: PASS 191, FAIL 19, and no red line unrelated to the three.
qsa_scorereads a group's query from group 0 (let at = base;):qsa select wide m=20fails.seg_span(limit, 1, ..)): 13 fold comparison lines fail (dense edge 512, 2051, 2044..2051, the one-row cases, verify, wide, the fault cases and the deep cases). The green fold lines are the ones whose rows already fit one segment (counts 1 and 5), eager against graph, the group refusals and the depot line.qsa scratch refusalfails withDriverError(1, "invalid argument").Speed
Kernel bench on one DGX Spark (
gate_qwen35moe_attn --bench-kernels), 4,224-row cache, selecting rows only, selection plus attention.pass8is the old walk (8 rows a run: score, top-k, pass, merge);foldtakes all rows as one run (score, top-k, fold). Both arms' outputs were bit-identical at every row count.At the 2,045 selecting rows of a 4,096-token prompt this saves about 9.9 ms a layer. The server walk splits the rows at
select_run(1,512 rows at a cache of 4,224), so a 4,096-token prompt takes two runs.End to end on one DGX Spark: FP4-Local and NVFP4 Qwen3.8,
bloomery-serve --parallel 4 --ctx-size 16896, draft off, three 4096-id code windows (offsets 0, 4096, 8192), 128 greedy tokens, one request at a time. Each checkpoint started with a discarded warm load; FP4-Local ran head then main, NVFP4 main then head. A host settle and a read probe preceded each arm. Greedy tokens of head and main are equal per window on the same checkpoint.Delta (head against main): FP4-Local prefill -1.0% (1311 to 1298 tok/s), inside the spread of this sitting; the attention kernel bench takes 18.646 ms a layer in place of 28.512 ms at 2045 selecting rows.
The end-to-end prefill result is inside the noise: the per-window head minus main differences were -120, +66 and +86 ms, and the head arm's own spread was 175 ms. I claim no prefill speed-up from this measurement. The 2.3% decode difference equals the 2.3% difference between the two arms' read probes, so I read it as card state; decode runs the pass and merge path, which this PR does not change.
The NVFP4 pair is not a comparison. The main arm's decode witness was 20.5 tok/s against 22.5 and 23.0 tok/s on the other two NVFP4 loads, 9% lower, so I discarded that arm and did not rerun it. The NVFP4 arms did run under a profiler for one extra request (offset 16384, 2 tokens) after the timed requests. Kernel times for that request:
gqa_flash_seg_mma_256_p12_selgqa_flash_merge_256qsa_scoreqsa_topkgqa_flash_fold_mma_256_p12_selThe head's 24 fold launches are 12 layers times two runs (1,512 and 533 rows). The 48 score and top-k launches and the 24 pass and merge launches include the 2 decode steps of the request. The discarded main arm's other kernels were also 1.20 times slower than the head's (3,407 ms against 2,828 ms), so the table's whole difference is not this change's. Dividing the main arm's path time by 1.20 gives about 310 ms.
PTX comparison
just ptx-compare 2a7005b8a gate_qwen35moe_attn(sm_86, JIT compute capability 12.1): main 329 entries, head 330, one added (gqa_flash_fold_mma_256_p12_sel), none removed, one changed:qsa_score(registers 68 to 76, JIT registers 69 to 81), because its body now takes group rows. The other 328 entries match in every column, includinggqa_flash_seg_mma_256_p12_selandgqa_flash_seg_mma_p16_blocks, whose bodies moved into the macros. The new entry has no local memory.Measured head against the PR head
The checks above ran on commit
c8bbb6e8cover base2a7005b8a. The PR head is586cd83a7on current main501db04fe. Against the measured commit it differs in three ways. First, a rebase: main's changes between the two bases touch none of the files this change edits. Second, the host-side argument structs:GqaSelArgsnow holdsGqaFoldArgs, and the gate builds the shared fields once (3 files, +112 -171 against the previous PR head). Third, oneSAFETYcomment infold_mma_psnow states the bound it relies on. Device code and the kernel argument order are unchanged. I did not rerun the timings or the gates on this head. The whole-workspacecargo check --all-targetswith all features ran with rc 0 on the head before the comment change; the comment change touches no code.Hardware
DGX Spark (GB10), GPU, driver and CUDA lines from
nvidia-smiof the same job:Models: Qwen3.8 FP4-Local and NVFP4. Build:
cargo oxide build --arch sm_121. The whole-workspacecargo check --all-targetswith all features ran on an RTX 5090 machine atc8bbb6e8cand atfd7cf8ffa, rc 0 both times.What I ran into
None of this blocks the PR.
gate_qwen35moe_attnclause 6 did not run, for the reason given above.qsa_scoreuses more JIT registers (69 to 81). Decode selection uses the same kernel at one launch a layer, and I did not isolate its effect on decode.AI help
AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.