Skip to content

gpu: select and attend a ubatch's selecting rows in one launch each - #753

Merged
juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-prompt-attn
Oct 23, 2026
Merged

juliankang4 merged 2 commits into
midagedev:mainfrom
juliankang4:dgx-spark-q38-prompt-attn

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

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_sel and gqa_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_score takes m rows 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::new loses its rows <= 8 limit and refuses by name a row count whose bytes overflow (row_bytes, rows()).
  • A new kernel 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 same seg_span as the old pass, and folds each segment's (max, sum of exp, sum of exp times V) in the old merge's online_fold order, 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 macros listed_query_tile! and listed_seg_tiles!, shared with seg_mma_ps. One check, check_listed_256, serves both enqueue paths.
  • The ubatch walk selects and attends select_run(rows, ctx) rows at a time (SELECT_RUN_BYTES / row_bytes, a multiple of 8, at least 8, at most rows). The ubatch arena no longer holds partial buffers (Arena38::wide takes (select_run, 0)).
  • place.rs owns SELECT_RUN_BYTES = 22,000,000. The UBATCH_FIXED_BYTES derivation 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.
  • The pass-row arenas (decode, MTP verify, program38) keep pass and merge. With 8 rows or fewer the fold grid (m * n_kv blocks) does not fill the card: the kernel bench below shows the fold slower at 8 rows (0.308 ms against 0.113 ms).
  • The four tools/ref/ptx-shapes*.tsv tables gain the new entry, and tools/unsafe-ratchet.txt moves from 2268 to 2272 blocks and from 281 to 282 functions with a PIN(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

  • No second copy. The old pass and fold share the segment walk through two macros, and both enqueue paths share check_listed_256. GqaSelArgs holds the shared GqaFoldArgs and 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.
  • Model code holds only architecture facts. No common owner gained a per-model branch, flag or trait method. The run size is owned by the Qwen3.8 placement file.
  • Dead code is gone. SELECT_ROWS and its assert are removed, and the ubatch arena no longer allocates partial buffers.
  • No silent failure. QsaScratch::new refuses 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.
  • Comments state what is true now.
  • No relaxed gate. No band, tolerance or lint moved. The one ratchet change carries a dated PIN.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up.

Duplication found or removed (path:line), or "none": the duplicate scan flagged crates/gpu/src/flash_gqa.rs:2551 against :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 :4568 against :4487 and :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_attn on 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 bit on 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_e2e at 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.

BLOOMERY_TIER=fixture just gate-gpu-qwen4exp-e2e
E2E rc=0 pass=171 fail=0

The unmodified just gate-gpu-qwen35moe-attn was 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.

  • A. qsa_score reads a group's query from group 0 (let at = base;): qsa select wide m=20 fails.
  • B. The fold cuts each row into one segment (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.
  • C. The byte-overflow refusal in the scratch is removed: qsa scratch refusal fails with DriverError(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. pass8 is the old walk (8 rows a run: score, top-k, pass, merge); fold takes all rows as one run (score, top-k, fold). Both arms' outputs were bit-identical at every row count.

Selecting rows pass8 runs pass8 median ms fold median ms
8 1 0.113 0.308
64 8 0.871 0.664
256 32 3.466 2.141
2,045 256 28.512 18.646

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.

Metric (one GB10, C@1, draft off) main head change
FP4-Local prefill tok/s, median of three 4096-id prompts 1311 1298 -1.0%
FP4-Local decode tok/s 30.90 30.19 -2.3%
Kernel bench, 2045 selecting rows, ms a layer 28.512 18.646 -9.9 ms

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:

kernel main launches main ms head launches head ms
gqa_flash_seg_mma_256_p12_sel 3,096 253.80 24 0.69
gqa_flash_merge_256 3,096 30.92 24 0.09
qsa_score 3,096 58.70 48 8.70
qsa_topk 3,096 29.07 48 3.96
gqa_flash_fold_mma_256_p12_sel 24 165.84
sum 12,384 372.49 168 179.28

The 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, including gqa_flash_seg_mma_256_p12_sel and gqa_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 c8bbb6e8c over base 2a7005b8a. The PR head is 586cd83a7 on current main 501db04fe. 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: GqaSelArgs now holds GqaFoldArgs, and the gate builds the shared fields once (3 files, +112 -171 against the previous PR head). Third, one SAFETY comment in fold_mma_ps now 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-workspace cargo check --all-targets with 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-smi of the same job:

NVIDIA GB10, 595.84
| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.3     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |

Models: Qwen3.8 FP4-Local and NVFP4. Build: cargo oxide build --arch sm_121. The whole-workspace cargo check --all-targets with all features ran on an RTX 5090 machine at c8bbb6e8c and at fd7cf8ffa, rc 0 both times.

What I ran into

None of this blocks the PR.

  • gate_qwen35moe_attn clause 6 did not run, for the reason given above.
  • The end-to-end prefill gain is not shown. The kernel launch count and the kernel bench improve; the A/B stays inside its spread, and the NVFP4 main arm was discarded.
  • qsa_score uses 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 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 23, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Comment thread crates/gpu/src/qsa.rs Outdated

/// The most rows one selection into this scratch takes.
#[must_use]
pub fn rows(&self) -> usize {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R13: every caller is inside bloomery_gpu; keep this accessor crate-private.

Suggested change
pub fn rows(&self) -> usize {
pub(crate) fn rows(&self) -> usize {

Comment thread crates/gpu/src/qsa.rs Outdated
/// 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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

R13: every caller is inside bloomery_gpu; keep this byte calculation crate-private.

Suggested change
pub fn row_bytes(ctx: usize, kept: usize) -> usize {
pub(crate) fn row_bytes(ctx: usize, kept: usize) -> usize {

@juliankang4
juliankang4 force-pushed the dgx-spark-q38-prompt-attn branch from 586cd83 to ab73b1b Compare October 23, 2026 22:26

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit b8cf673 into midagedev:main Oct 23, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant