Skip to content

gpu: gdn_delta_prepared keeps its state transposed, so each product's accumulator is the next one's A operand - #957

Merged
juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-fp4l-prefill-routed-sum
Oct 29, 2026
Merged

juliankang4 merged 1 commit into
midagedev:mainfrom
juliankang4:dgx-spark-q38-fp4l-prefill-routed-sum

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Qwen3.8 FP4-Local의 prefill에서 GDN 재귀 커널이 state를 전치해 레지스터에 두도록 바꿔, 4096 토큰 prefill을 약 3% 줄입니다.

What and why

gdn_delta_prepared, the Gated DeltaNet recurrence of the prompt path, wrote each product's accumulator to shared memory and read it back as the next product's operand. It now keeps the state transposed in registers, so each product's accumulator is the next product's A operand and no state round trip remains. The high and residual products and their order are unchanged; only the operand roles move. The next chunk's rows are prefetched after the state projection, and a chunk costs three barriers.

On a DGX Spark, Qwen3.8 FP4-Local prefill is 2.8% to 3.1% faster and TTFT p95 is 2.8% to 3.0% lower, with sample ranges that do not overlap. Decode is within the spread. The kernel output and state are bit for bit the same as the base on the four digest cases below.

Release notes: Changed: Qwen3.8 prompt prefill on DGX Spark is about 3% faster.

Code shape

The review reads these first. A box left unticked needs one line of why.

  • No second copy. The change rewrites one kernel in place; the new helpers frag_a, frag_mma, split_mma and prepared_reads are used only by it.
  • Model code holds only architecture facts. The shared kernel gained no per-model branch, flag or trait method.
  • Dead code is gone. The state staging, the projection round trip and the packed solved rows are removed with the change.
  • No silent failure. No new input path; the launcher's existing alignment and shape refusals are unchanged.
  • Comments state what is true now. No dates, issue numbers or how a bug was found.
  • No relaxed gate. gate_linear keeps its band for the prompt cases at 2e-4 (it was 2e-2). tools/ref/ptx-shapes/sm_121a-cc12.1.tsv re-pins gdn_delta_prepared from spill 0 and JIT local 0 to 172 B and 72 B with a PIN(2026-10-29): line, because the state now lives in registers; tools/unsafe-ratchet.txt re-pins gpu from 2812 blocks and 378 fns to 2795 and 381 with its reason.
  • 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": none.

What I ran

Timed runs use one DGX Spark, bloomery-serve with --parallel 1 --ctx-size 16896, and nvidia/Qwen3.8-Flash-Next-FP4-Local at revision b9ce18a6887e18c089fdea8509a33e63429a3300. A request is a 4096-token prompt with 128 generated tokens, on eight prompt windows of the code corpus (and of the prose corpus for the MTP prose arm). Each side has three recorded rounds after one discarded warm-up round. Base is 5fc77e823dafa857e00823ceb06192c428effbbe, head is 1431e88d96b86b35020db5825e4166b52273eafa, each built in its own checkout.

git -C base checkout 5fc77e823dafa857e00823ceb06192c428effbbe
git -C head checkout 1431e88d96b86b35020db5825e4166b52273eafa
./head/target/release/bloomery-serve -m <folder> --parallel 1 --ctx-size 16896

Each cell is the median of three rounds with its range in parentheses.

Metric Base Head Difference Ranges overlap
Prefill, MTP, code, tok/s 2335.2 (2328.9 to 2345.7) 2401.0 (2385.7 to 2404.6) +65.8 (+2.8%) no
Prefill, MTP, prose, tok/s 2405.6 (2404.0 to 2421.4) 2480.5 (2445.9 to 2485.6) +75.0 (+3.1%) no
Prefill, draft off, code, tok/s 2475.4 (2464.2 to 2481.0) 2548.8 (2532.8 to 2557.9) +73.4 (+3.0%) no
TTFT p95, MTP, code, ms 1760.9 (1752.2 to 1765.5) 1712.2 (1709.6 to 1723.5) -48.7 (-2.8%) no
TTFT p95, MTP, prose, ms 1709.3 (1697.8 to 1710.1) 1657.8 (1654.9 to 1681.6) -51.5 (-3.0%) no
TTFT p95, draft off, code, ms 1661.3 (1657.2 to 1668.6) 1613.6 (1608.2 to 1622.9) -47.7 (-2.9%) no
Decode, MTP, code, tok/s 58.61 (58.53 to 58.92) 58.54 (58.33 to 58.64) -0.06 (-0.1%) yes
Decode, MTP, prose, tok/s 42.44 (41.94 to 42.60) 42.23 (42.09 to 42.55) -0.21 (-0.5%) yes
Decode, draft off, code, tok/s 31.93 (31.85 to 31.99) 31.93 (31.91 to 32.31) -0.01 (-0.0%) yes

Checks on the code of this branch, on a DGX Spark at arch=sm_121a. just gate-gpu-linear builds and runs gate_linear; the prompt cases of the head and the base give the same output and state digests:

prompt-digest m=16 o=435ea0be5920e680 state=d59a0cf7e668ef95
prompt-digest m=1000 o=728d740f47789451 state=078f046227caa838
prompt-digest m=4096 o=690b24b05030034a state=1fd12fa718d9ae1e
prompt-digest m=4096, keys near one direction o=e770745d8cce94f6 state=98c2df56fa7c3251
BITS head==base True (4 cases)
gate_linear: 164 clauses, 0 failed — PASS

The 4096-token prompt cases against the oracle, with the band at 2e-4:

prompt m=4096 on lane 2 of 4: o rel_l2 6.636e-6, lane 2 at its last whole chunk rel_l2 5.164e-6 (band 2e-4) ... PASS
prompt m=4096, keys near one direction on lane 2 of 4: o rel_l2 2.195e-5, lane 2 at its last whole chunk rel_l2 2.205e-5 (band 2e-4) ... PASS

Six mutants of the kernel (dropping the state, qk, inverse, causal or solved residual term, and prefetching the same chunk) each make gate_linear fail, and compute-sanitizer --tool racecheck on the gate reports 0 hazards.

cargo clippy -p bloomery-gpu --all-targets on a DGX Spark (NVIDIA GB10, driver 595.84) reports 0 warnings.

Hardware (if the change is for a machine)

  • Card: NVIDIA GB10 (DGX Spark), compute capability 12.1
  • Driver: 595.84
  • CUDA: 13.3
  • Model: nvidia/Qwen3.8-Flash-Next-FP4-Local

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app 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 29, 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 kernel rewrite checks out against the old math, but this diff leaves chunk_mma and chunk_product with a dead K parameter.

Must fix

1. chunk_mma and chunk_product keep a const generic with one instantiation (kind B, unneeded element)

crates/gpu/src/linear/delta.rs:569, :614. This diff removes the only chunk_product::<16> calls. The one caller left is chunk_product::<HEAD> at :1450. So K, the if K == HEAD { PSTRIDE } else { K / 2 } branch and the "K / 2 otherwise" lines in both docs are dead.
Cost: the next reader must work out that the K / 2 stride is unreachable. The next kernel that adds a K can reuse the dead branch without anyone testing it.
Fix: drop the parameter. The HEAD instantiation stays the same, so ptx-scan stays identical.

/// A warp's 16 × 8 product `A·Bᵀ + c` over [`HEAD`] columns: `a` sixteen packed
/// rows, `b` eight, each `HEAD / 2` pairs at stride [`PSTRIDE`]. `c` and the
/// result are the MMA's accumulator fragment: lane `l` holds rows `l / 4` and
/// `l / 4 + 8`, columns `2·(l % 4)` and the next.
///
/// # Safety
///
/// `a` and `b` address initialized shared words of those shapes, and every
/// lane of the warp executes the call.
#[inline(always)]
#[allow(
    clippy::needless_range_loop,
    reason = "a range `for` is the loop the unroller recognizes; an iterator loop keeps its array in a local depot"
)]
unsafe fn chunk_mma(a: *const u32, b: *const u32, mut c: [f32; 4]) -> [f32; 4] {
    let lane = thread::threadIdx_x() as usize % 32;
    let r = lane / 4;
    let k = lane % 4;
    let mut base = 0;
    while base < HEAD / 2 {
        let mut af = [0; 4];
        for i in 0..4 {
            let at = (r + (i % 2) * 8) * PSTRIDE + base + k + (i / 2) * 4;
            // SAFETY: rows r and r + 8 of A's sixteen, pair k or k + 4 of
            // this step's eight.
            af[i] = unsafe { *a.add(at) };
        }
        let mut bf = [0; 2];
        for i in 0..2 {
            let at = r * PSTRIDE + base + k + i * 4;
            // SAFETY: row r of B's eight, pair k or k + 4 of this step's.
            bf[i] = unsafe { *b.add(at) };
        }
        // SAFETY: every lane runs this step with its documented fragments.
        c = unsafe { cuda_device::wmma::mma_m16n8k16_f32_bf16(c, af, bf) };
        base += 8;
    }
    c
}

In chunk_product, drop <const K: usize>, call chunk_mma(...) in its three lines, and say "stride PSTRIDE" in the Safety doc. Change the call at :1450 to chunk_product(.

Non-blocking

⚠ Bool at the call (R33): crates/gpu/src/linear/delta.rs:635 frag_a(.., false) and frag_a(.., true) read as nothing at six call sites. chunk_qk_store has the same shape, so this matches the file. Rename the argument at the call, or leave it.

⚠ Spill moved from 0 to 172 B (JIT local 72 B): the pin has its date and reason, and the PR body shows a net gain. Please confirm on a second card that the gain holds. The pin file is for sm_121a only.

Checked

  • Duplicates: 5 new items checked (frag_a, frag_mma, split_mma, prepared_reads, USTRIDE), none duplicated. split_mma repeats chunk_product's three-term order with the roles swapped; two short copies, not a finding. dryer: 0 pairs.
  • Complexity: crapper flagged nothing. The kernel body is #[kernel], so it was read for correctness only.
  • Kernel read against the old math: A fragment layout in frag_a, B rows (8·tt+g)·PSTRIDE + 8·kb + q and b + 4, term order, the shared offsets (Q_LOW, KT, KT_LOW, IP, IP_LOW, D, B, END) against PREPARED_WORDS (all agree), three barriers per chunk with no read-after-overwrite across chunks, prefetch bound start + CHUNK < all against chunks (the launch contract keeps it inside work), and all == 0 (the contract gives chunks ≥ 1). All blocked.
  • Silent failure: 3 sites followed (the prefetch bound, meta zero for tid ≥ 48, zero rows past count). The finite checks on y and on the state are unchanged.
  • Tests: gate_linear prompt clauses protect the residual terms. Mutant: drop the kp residual part (part == 1) and the error is ~2e-3, above the 2e-4 band, so the gate turns red. Mutant: prefetch the same chunk, red per the PR body.
  • Gates: PROMPT_BAND 2e-2 → 2e-4 with PIN(2026-10-29), measured values and a derivation. ptx-shapes spill pin dated. unsafe-ratchet pin dated.
  • Escape catalog: no shell code in the diff; no pattern matched.

Notes

  • The PR body's timing and digest runs name head 1431e88d, base 5fc77e82. The PR head is dae1e5d9, base e85f0c8c. Please state whether the kernel is the same code.
  • There is no nvidia-smi line, only card, driver and CUDA fields.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_linear.rs, crates/gpu/src/linear/delta.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
juliankang4 force-pushed the dgx-spark-q38-fp4l-prefill-routed-sum branch from dae1e5d to 4a6b88d Compare October 29, 2026 09:29
@juliankang4
juliankang4 force-pushed the dgx-spark-q38-fp4l-prefill-routed-sum branch from 4a6b88d to 6e289b9 Compare October 29, 2026 10:50

@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: the dead K parameters, unreachable stride branch and obsolete documentation are fixed in crates/gpu/src/linear/delta.rs:568 and its caller.

Verdict: CLEAN: the interdiff specializes the remaining HEAD-only products without changing their indexing or arithmetic.

Non-blocking

⚠ Still open: boolean argument (R33), crates/gpu/src/linear/delta.rs:633. Calls such as frag_a(rt[0], rt[1], false) leave the high/residual choice unnamed. Use a high/residual enum to name that choice. This is the unchanged advisory from the previous review.

Checked

  • Duplicates: 0 new items in the interdiff; repository search confirms one remaining chunk_product caller. dryer reported 0 pairs; gpu-gates was excluded from its scan.
  • Complexity: crapper flagged no functions. Specialization removes a constant branch.
  • Silent failure: 0 new sites. Both edited definitions match the former HEAD specialization, including all three products.
  • Adversarial checks: no compact-stride caller remains; all lanes' A/B offsets, including the last pair and second B half, stay within their tiles. The compile-time assertion fixes HEAD at 128. Product order and inline attributes are unchanged.
  • Tests: no test changes in the interdiff. The prior review's residual-drop and repeated-chunk mutation results are unchanged. GPU gates were not rerun here.
  • Gates: no pins or bands moved in the interdiff.
  • Escape catalog: no patterns matched.

Notes

The PR still lacks a nvidia-smi line. Its timing and gate evidence names base 5fc77e82 and head 1431e88d, rather than this review's commits. Identify the tested source relative to the current head. Attach identical ptx-scan output for the move-class specialization.

Card check: needs-gpu. This pull request changes crates/gpu-gates/src/bin/gate_linear.rs, crates/gpu/src/linear/delta.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 0c0cf7e into midagedev:main Oct 29, 2026
7 checks passed
midagedev added a commit that referenced this pull request Oct 29, 2026
…d 16 B JIT local, after #957 kept its state transposed

gate-ptx-spill went red on this row alone in the 0.3.11 release batch; #957 re-pinned only the sm_121a table.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 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