Skip to content

gpu, gpu-gates: the head-512 rope append and prefill flash of EmbeddingGemma 2's global layers, with their gate - #233

Merged
juliankang4 merged 6 commits into
midagedev:mainfrom
juliankang4:dgx-spark-emb2-head512
Oct 15, 2026
Merged

juliankang4 merged 6 commits into
midagedev:mainfrom
juliankang4:dgx-spark-emb2-head512

Conversation

@juliankang4

@juliankang4 juliankang4 commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #59 (plan and PR order in #190), E4: the head-512 rope append and prefill flash of the global layers.

What and why

Release notes: Added: two kernel entries at heads of 512 that EmbeddingGemma 2's global layers need; no engine path calls them yet.

EmbeddingGemma 2 has 24 layers. Its four global layers (5, 11, 17 and 23) use heads of 512 values: 4 query heads over 1 key/value head, and a NEOX rope that turns all 512 values at θ 1e6. The engine's NEOX rope append and GQA prefill flash have entries for heads of 256, and neither stretches to 512:

  • The rope body (norm_partial_append) turns at most the first 64 values and reads the query from q+gate rows at a stride of twice the head.
  • The 256 prefill flash keeps each warp's query fragments in registers and stages 64-key tiles in 96 KB of shared memory. At 512 values both would double, past the register file and the block's shared-memory limit.

This PR adds one entry for each. No engine path calls them yet; the model body comes in a later PR (E5 in #190).

Scope:

  • The global layers attend over every key, with no window. The sliding layers' window is gqa_prefill_flash_256_p2_lower, already on main; the 512 entry expands the shared macros with that lower bound off.
  • The model normalizes V with a gainless RMS norm before attention. The rope entry appends V as it receives it, so the calling body applies that norm before the launch.
  • The attention scale is 1: llama.cpp sets f_attention_scale = 1 for this architecture, because the query norm stands in for the scale. The gate also runs one launch at 1/16, so the scale argument is tested.

The PR has five commits, plus tools: the gate path table includes the rebased tree's missing gates, which regenerates tools/gate-paths.tsv:

  1. gpu: norm_partial_append reads a query head at a const span, so plain query rows share the body (a move). A const Q_SPAN names the stride of the query rows; the two 256 entries pass 2 * HEAD_256. The 256 launchers' shape and buffer refusals move into one private helper, partial_launch.

  2. gpu: the prefill flash's tile softmax, and the packed body's row counts and store, are one macro each (a move). The online softmax over a tile was written out four times in flash_gqa_prefill.rs. The copies differ only in the packed body's first-key mask, which the _lower entry turns on; the macro takes that mask as an optional argument. It is now prefill_softmax!. The packed body's row-count walk and its final store become prefill_pack_counts! and prefill_pack_store!. They are macros, as dequant_row! already is in that file, so every expansion keeps its constants.

  3. gpu-gates: the flash gates' exact attention and prefill band have one owner, and par_map moves to the lib. The f64 exact attention and the prefill flash's first-order bound were copied in gate_qwen3moe_flash and gate_qwen35moe_attn. They move to crates/gpu-gates/src/flash_band.rs (exact_attn, prefill_bound) with the head and key tile as arguments and the sums in the same order. par_map moves into the crate's lib, and gate_qwen3moe_flash's band check runs on it instead of its own worker pool.

  4. The two entries and their gate.

    • head_norm_neox_append_512 is norm_partial_append at ROT = HEAD = 512 over plain query rows: 256 threads, one per NEOX pair (i, i + 256). Two tokens at one position would write the same cache row from two blocks, so the launcher is an unsafe fn whose # Safety section asks for distinct positions, as the 256 whole-turn entry in E5 does.
    • gqa_prefill_flash_512_p4 (new file crates/gpu/src/flash_gqa_prefill_512.rs) is the prefill flash at heads of 512 and packs of 4 query heads. A block of 4 warps holds 32 query rows (8 positions × 4 heads) in shared memory as f16 and walks 32-key tiles. Each warp scores its 256-dim half of the key on mma.m16n8k16 and adds its partner's half through shared memory, so both warps of a pair hold the same score bits. The 512 output values split over two blocks of the grid, each recomputing the scores and writing one half. One copy macro stages both the key tile and the block's value half. Dynamic shared memory is 90,112 bytes, inside the 101,376-byte opt-in window of a cc 8.6 card (a const assert).
    • The packed launchers' refusals move into one helper, checked_packed, which the 256 launcher and the 512 launcher call. It refuses by name a group that is not a multiple of the pack a key head, a short buffer and a misaligned q, kc or vc.
    • The staged layout's address rule in flash_gqa_prefill.rs becomes one macro, staged!, which the 256 helpers and the 512 body expand.
    • The gates' shared parts get one owner each: the host head norm and NEOX turn (rounding::neox_head), the host rope expectation (rope_gate::expected), the rope launch and read-back with its distinct-position check (rope_gate::run), the rope clause with its cache-height fault (rope_gate::check), the seeded cache with its NaN-padded twin (prefill_gate::cache) and the misaligned-window refusals (prefill_gate::window_refusals). gate_qwen35moe_attn calls all of them in place of its own copies; gate_qwen3moe_flash calls the seeded cache, the window refusals and the host cache type.
    • gate_gemma_embedding2_head512 (recipe gate-gpu-gemma-embedding2-head512) checks both entries model-less at the model's shapes (below).
    • The PTX shape tables pin both entries at 0 spill and 0 JIT local bytes (sm_121-cc12.1.tsv, sm_86-cc12.1.tsv, and ptx-shapes.tsv for cc 8.6, whose rows come from ptxas at sm_86 and not from a cc 8.6 card; a comment line above each says so).
  5. gpu-gates: the prefill flash gates judge their band through one flash_band function. The per-row band check (exact attention, the bound, the largest measured over bound with a NaN read as infinite) was written out in gate_qwen3moe_flash and in the new gate. Both now call flash_band::judge_prefill.

The new flash body lives in its own file instead of a third instance of prefill_256_p. The 256 body's register-resident query and its 64-key tile are the parts that change, so a shared generic would carry a branch for each. The two bodies share the three macros, the launch check and the staged layout and fragment row helpers of flash_gqa_prefill.rs.

Code shape

  • No second copy. The rope entry is the one shared body and launcher at new const arguments. The flash entry's row counts, softmax and store are the macros the existing prefill entries expand, its launch check is theirs, and its address rule is theirs. The gates' band model, par_map, head rule, host rope expectation, rope runner, rope clause, seeded cache and window refusals are the crate's. The copies that remain are listed below.
  • Model code holds only architecture facts. No model code changes.
  • Dead code is gone. The two gates' local band models, window checks and seeded caches are removed, and so are gate_qwen35moe_attn's head rule, rope runner, rope clause, host rope rule and cache builder.
  • No silent failure. A count of zero or past the cache raises key_count and leaves that row NaN; a position at the cache's height raises cache_pos, leaves the token's heads NaN and appends nothing; the launchers refuse bad shapes and windows by name; the rope runner refuses repeated positions before the unsafe call.
  • Comments state what is true now.
  • No relaxed gate. tools/unsafe-ratchet.txt moves gpu from 1788 to 1814 blocks and 196 to 198 fns, and gpu-gates from 116 to 121 blocks, each with a PIN(2026-10-15): line that counts the new blocks by kind. No band moved.
  • cargo fmt and cargo clippy are clean on what I touched; the lint count did not go up (44 at this head and 44 at main, below).

Duplication found or removed (path:line):

  • Removed: the tile softmax in four prefill bodies (now prefill_softmax!, crates/gpu/src/flash_gqa_prefill.rs:611); the packed body's count walk and store (now :719 and :800); the packed launchers' refusals (now checked_packed, :2984); the 256 rope launchers' refusals (now partial_launch, crates/gpu/src/rope_neox.rs:1816); the band model of gate_qwen3moe_flash and gate_qwen35moe_attn (now crates/gpu-gates/src/flash_band.rs:37 and :96); the per-row band check (now judge_prefill, crates/gpu-gates/src/flash_band.rs:142); par_map (now crates/gpu-gates/src/lib.rs:524); the head rule (now crates/gpu-gates/src/rounding.rs:38); the host rope rule (now crates/gpu-gates/src/rope_gate.rs:43); the rope clause (now crates/gpu-gates/src/rope_gate.rs:83); the seeded cache (now crates/gpu-gates/src/prefill_gate.rs:28); the window refusals (now crates/gpu-gates/src/prefill_gate.rs:95).
  • Remaining: gate_qwen35_dspark.rs keeps its own par_map (a &dyn Fn form, crates/gpu-gates/src/bin/gate_qwen35_dspark.rs:157). gate_qwen3moe_flash's fault clause builds its two cache planes inline (crates/gpu-gates/src/bin/gate_qwen3moe_flash.rs:1552), the same planes prefill_gate::cache builds from seed 92; it needs no padded twin.

What I ran

Every run below is at the head cde08465e7bee9b31cd0282b2e2fb1ab536134e5 on the base 6390fd49c41cc2569d315e52f3a5583ceeb827d6. git merge-tree of the head with main at 73c307c4 is clean. The DGX Spark runs used the project's dev container; the RTX 5090 runs used an x86_64 Linux host without a container. The static checks ran on an Apple Silicon Mac.

just contrib-check (tier t1) on the RTX 5090 machine:

DONE tier=t1 total=102 red=1 wall=318s red: check-recipes

The red unit is check-recipes, where one case of the ref/load-groups self-test fails:

FAIL stall-term: got [post 0 rc=124], want [post 0 rc=143]

That host's timeout (uutils) returns 124 after TERM, and the self-test expects 143. Main at ccd03f7b fails the same case on the same machine.

just mac-static on the Mac is red only in lint:

mac-static: fmt-check rc 0 in 12 s — rustfmt diff blocks: 0
mac-static: lint rc 1 in 43 s — mac-check: lint ^warning: 44, above the ratchet 41 in tools/lint-ratchet.txt
mac-static: check-unsafe rc 0 in 2 s
mac-static: red steps: lint (rc 1)

Main at 6390fd49 on the same Mac also counts lint ^warning: 44, above the ratchet 41 and ends mac-static: red steps: lint (rc 1), so this PR adds no warning.

The gates just affected selects, run with BLOOMERY_ARCH=sm_121 in the dev container on the DGX Spark, at the head and, for every gate red at the head, at the base:

affected: 6390fd49c..(working tree) 20 changed files, 127 of 164 gate-recipes selected, 0 of 8 weekly-recipes by a trigger
gates-affected: 136 gates, ok 24, same as base 111, differs 1
  • gate-gpu-gemma-embedding2-head512 passes (head 0).
  • The 111 gates that are red at the head are red the same way at the base.
  • gate-gpu-qwen3moe-flash and gate-gpu-qwen35moe-attn are among them. gate-gpu-qwen3moe-flash stops at the head and at the base on its fixture set ref_qwen3moe_step4_every_node, before any prefill band is judged, so its call of judge_prefill did not run on our cards.
  • The one difference is gate-ptx-spill. It ends violations=3 FAIL at the head and at the base, with the same three unpinned entries (embed_rows_q5_0, gqa_flash_seg_g5, mamba2_step) and the same nonzero list. Only the entry counts move, by this PR's two pinned entries: generate_ds41 from entries=306 pinned=303 to entries=308 pinned=305, gate_e2e from entries=239 pinned=236 to entries=241 pinned=238.

just canon-check 6390fd49 on the DGX Spark (sm_86 scans of the head and the base):

canon-check: bloomery-serve-ds41 gqa_prefill_flash_512_p4: only in new
canon-check: bloomery-serve-ds41 head_norm_neox_append_512: only in new
canon-check: gate_kquant gqa_prefill_flash_512_p4: only in new
canon-check: gate_kquant head_norm_neox_append_512: only in new
canon-check: gate_swap gqa_prefill_flash_512_p4: only in new
canon-check: gate_swap head_norm_neox_append_512: only in new
canon-check: 3 bins, 811 entries: 805 identical, 0 reordered-only, 0 differs, 6 only-on-one-side; rows equal (jit columns not compared: no-jit both)

Every entry of the base is the same program at the head; the six one-sided entries are the two new entries in each of the three binaries. The recipe exits 1 on one-sided entries.

just gate-gpu-gemma-embedding2-head512 on the RTX 5090 with BLOOMERY_BOX_LOCAL=1 BLOOMERY_ARCH=sm_120 (and CUDA_OXIDE_LLC set to LLVM 21.1.8's llc). The model's shape for the global layer: 4 query heads over 1 key head of 512, θ 1e6, eps 1e-6, scale 1, seeded inputs. The rope clause also runs 8 query heads over 2 key heads; the flash clause also runs 16 query heads over 2 key heads, one launch at scale 1/16, and one where the count equals the cache (T=33, ctx=33, no padding rows). Every check line of the run:

gate_gemma_embedding2_head512: device NVIDIA GeForce RTX 5090: 4/1 heads of 512, rope over 512 at θ 1e6, scale 1e0, key tile 32
rope m=9 positions 31.. ctx=40 head 512 rot 512: q (read at head stride 512) bit_exact_host=true k in place bit_exact_host=true planes_exact=true rerun=true PASS
rope fault: token 8 at position 40 (the cache's height), layer 11: word Some(Fault { layer: 11, code: 11, sites: 2048, arch: None }) (want Some(Fault { layer: 11, code: 11, sites: 2048, arch: None })), its heads NaN true, nothing appended true, other tokens bit-identical true, clean rerun and word clean true PASS
rope-512 heads 4/1 PASS
rope m=9 positions 31.. ctx=40 head 512 rot 512: q (read at head stride 512) bit_exact_host=true k in place bit_exact_host=true planes_exact=true rerun=true PASS
rope fault: token 8 at position 40 (the cache's height), layer 11: word Some(Fault { layer: 11, code: 11, sites: 2048, arch: None }) (want Some(Fault { layer: 11, code: 11, sites: 2048, arch: None })), its heads NaN true, nothing appended true, other tokens bit-identical true, clean rerun and word clean true PASS
rope-512 heads 8/2 PASS
prefill encoder T=1 ctx=41: measured/bound 0.000e0 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=8 ctx=48: measured/bound 2.121e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=31 ctx=71: measured/bound 2.174e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=33 ctx=73: measured/bound 1.335e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=100 ctx=140: measured/bound 8.952e-2 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=512 ctx=552: measured/bound 1.401e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill causal T=17 p0=0 ctx=57: measured/bound 2.417e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill causal T=9 p0=31 ctx=80: measured/bound 2.384e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill causal T=40 p0=32 ctx=112: measured/bound 1.221e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill causal T=9 p0=1000 ctx=1049: measured/bound 1.072e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill causal T=5 p0=2047 ctx=2092: measured/bound 5.210e-2 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill scattered T=24 ctx=134: measured/bound 1.996e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=40 scale 0.0625 ctx=80: measured/bound 2.618e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill causal T=17 p0=40 heads 16/2 ctx=97: measured/bound 1.797e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill encoder T=33 unpadded ctx=33: measured/bound 2.150e-1 band=true rows_alone_differing=0 rerun=true nan_padding_same=true PASS
prefill fault: counts 121 (past ctx 120) and 0 at rows 3, 10: word Some(Fault { layer: 65535, code: 10, sites: 1024, arch: None }) (want Fault { layer: 65535, code: 10, sites: 1024, arch: None }), those rows NaN true, other rows bit-identical true PASS
prefill graph T=17 p0=63: eager_vs_graph_bit_identical=true graph_nodes=1 PASS
prefill refusal n_head=3 over n_kv=1: flash_gqa_prefill_512::enqueue_p4: the kernel packs 4 query heads a block, so the group must be a multiple of 4; got 3 heads over 1 PASS
prefill refusal n_head=4 over n_kv=2: flash_gqa_prefill_512::enqueue_p4: the kernel packs 4 query heads a block, so the group must be a multiple of 4; got 4 heads over 2 PASS
prefill flash 512 p4 PASS
prefill windows at aligned offsets: accepted, bit-identical to the plain launch true PASS
prefill refusal q window 4 bytes past an 8-byte boundary: refused by name PASS
prefill refusal kc window 8 bytes past a 16-byte boundary: refused by name PASS
prefill refusal vc window 8 bytes past a 16-byte boundary: refused by name PASS
prefill windows PASS
gate_gemma_embedding2_head512: PASS

FAIL-first on the DGX Spark. Each mutant is a one-line patch, reverted after its run:

Mutant Exit Output
two tokens of the rope gate's launch at one position (pos[1] = pos[0]) 101 rope gate: positions must be distinct (refused before the launch)
the device's position refusal one place early (p + 1 >= ctx) 1 rope-512 heads 4/1 FAIL
the flash count refusal at c >= ctx instead of c > ctx 1 prefill encoder T=33 unpadded ctx=33: measured/bound inf band=false
the cache row without the key head's plane (p for kh * ctx + p) 1 rope-512 heads 8/2 FAIL

With the patches reverted, the gate passes again and the tree is clean.

Hardware (if the change is for a machine)

DGX Spark: NVIDIA GB10, 595.84, 12.1 (name, driver, compute capability from nvidia-smi), aarch64 Linux, the project's dev container with CUDA 13.3.1.

RTX 5090: NVIDIA GeForce RTX 5090, 595.99.02, 12.0 (from nvidia-smi), Linux 7.0.0-38-generic x86_64, AMD Ryzen 9 9950X 16-Core Processor.

What I ran into

None of this blocks the PR.

  • The cc 8.6 rows of tools/ref/ptx-shapes.tsv come from ptxas at sm_86 and were not read on a 3090. gqa_prefill_flash_512_p4 is the entry a reading there is most likely to move. If a reading differs, the row changes to it (model: EmbeddingGemma and EmbeddingGemma 2 on a side seat #190, open question 1).
  • gate-ptx-spill on a GB10 is red on main too: embed_rows_q5_0, gqa_flash_seg_g5 and mamba2_step have no row in the cc 12.1 tables, so generate_ds41 and gate_e2e end violations=3 FAIL at the base and at the head alike. Rows for them would close it. I left that out of this PR.
  • just mac-static counts 44 lint warnings on main at 6390fd49, above the ratchet of 41 in tools/lint-ratchet.txt, so its lint step is red on main too.
  • gate-gpu-qwen35moe-attn's set comparison and gate-gpu-qwen3moe-flash need fixture sets that a maintainer's workstation holds, so the Qwen3 call of judge_prefill has not run on our cards.

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 15, 2026
@midagedev

Copy link
Copy Markdown
Owner

시작하셨군요 화이팅입니다!

@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: duplicated fixtures and an unneeded generic interface remain.

Must fix

1. Share the cache fixture (kind B, R14)

crates/gpu-gates/src/bin/gate_gemma_embedding2_head512.rs:327 copies crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs:859, with the same types, padding and conversions. Sharing them now prevents drift.
Put these in prefill_gate; delete local copies and import them. Add HEAD after stream at Gemma calls, and HEAD, N_KV at Qwen calls:

/// Host values of the f16 cache planes.
pub struct HostCache { pub kf: Vec<f32>, pub vf: Vec<f32>, pub ctx: usize }
/// Seeded planes, padded twins and host values.
pub struct Cache {
    pub kc: DeviceBuffer<u16>, pub vc: DeviceBuffer<u16>,
    pub kn: DeviceBuffer<u16>, pub vn: DeviceBuffer<u16>,
    pub host: HostCache, pub kb: Vec<u16>, pub vb: Vec<u16>,
}
/// Build the seeded f16 cache and its NaN-padded twin.
pub fn cache(stream: &CudaStream, head: usize, n_kv: usize,
    ctx: usize, live: usize, seed: u32) -> Result<Cache, GateError> {
    use gguf::quant::{f32_to_f16_bits, half_to_f32};
    let plane = |s| crate::activations(head, n_kv * ctx, s)
        .into_iter().map(f32_to_f16_bits).collect::<Vec<_>>();
    let (kb, vb) = (plane(seed), plane(seed + 1));
    let pad = |b: &[u16]| b.iter().enumerate().map(|(i, &v)|
        if (i / head) % ctx >= live { crate::NAN_F16 } else { v }
    ).collect::<Vec<_>>();
    let widen = |b: &[u16]| b.iter().copied().map(half_to_f32).collect();
    Ok(Cache {
        kc: DeviceBuffer::from_host(stream, &kb)?,
        vc: DeviceBuffer::from_host(stream, &vb)?,
        kn: DeviceBuffer::from_host(stream, &pad(&kb))?,
        vn: DeviceBuffer::from_host(stream, &pad(&vb))?,
        host: HostCache { kf: widen(&kb), vf: widen(&vb), ctx }, kb, vb,
    })
}

2. Share the host rope walk (kind B, R14)

crates/gpu-gates/src/bin/gate_gemma_embedding2_head512.rs:136 repeats crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs:442. The token/head walk and cache placement need one owner before another copy.
Replace both rope_host copies with this rope_gate function. Use <HEAD, HEAD, HEAD> for Gemma and <HEAD, ROT, { 2 * HEAD }> for Qwen with its RopeShape:

/// Expected heads and cache planes under the host NeoX rule.
pub fn expected<const H: usize, const R: usize, const Q: usize>(
    inp: &RopeIn, pos: &[u32], s: RopeShape,
) -> RopeOut {
    let (nh, nk, ctx) = (s.n_head, s.n_kv, s.ctx);
    let mut out = RopeOut {
        q: vec![0.0; pos.len() * nh * H],
        k: vec![0.0; pos.len() * nk * H],
        ck: vec![SENTINEL; nk * ctx * H],
        cv: vec![SENTINEL; nk * ctx * H],
    };
    for (t, &p) in pos.iter().enumerate() {
        let cs = &inp.table[p as usize * R..(p as usize + 1) * R];
        for h in 0..nh {
            let src = (t * nh + h) * Q;
            let dst = (t * nh + h) * H;
            out.q[dst..dst + H].copy_from_slice(
                &crate::rounding::neox_head::<H, R>(
                    &inp.qg[src..src + H], &inp.gq, cs, s.eps));
        }
        for h in 0..nk {
            let at = (t * nk + h) * H;
            let y = crate::rounding::neox_head::<H, R>(
                &inp.k[at..at + H], &inp.gk, cs, s.eps);
            out.k[at..at + H].copy_from_slice(&y);
            let row = (h * ctx + p as usize) * H;
            for d in 0..H {
                out.ck[row + d] = gguf::quant::f32_to_f16_bits(y[d]);
                out.cv[row + d] = gguf::quant::f32_to_f16_bits(inp.v[at + d]);
            }
        }
    }
    out
}

3. Remove the unneeded generic interface (kind B)

crates/gpu/src/flash_gqa_prefill_512.rs:185 has only the pack-4/four-position instance (line 605). Both generic parameters can be local constants.

--- a/crates/gpu/src/flash_gqa_prefill_512.rs
+++ b/crates/gpu/src/flash_gqa_prefill_512.rs
@@ -185 +185 @@
-unsafe fn prefill_512_p<const PACK: usize, const SLICE_POS: usize>(
+unsafe fn prefill_512_p(
@@ -197,0 +198,2 @@
+    const PACK: usize = PACK_4;
+    const SLICE_POS: usize = SLICE_ROWS / PACK;
@@ -605 +607 @@
-            prefill_512_p::<PACK_4, { SLICE_ROWS / PACK_4 }>(
+            prefill_512_p(

Non-blocking

⚠ Supply the move-class proof: crates/gpu/src/flash_gqa_prefill.rs:584 needs base/head ptx-scan --no-jit: unchanged old entries plus two additions. Attach spill FAIL-first and the existing family gates' complete runs before engine integration.

Checked

Confirmed both duplicate pairs and the single fixed-argument kernel call. Each shared gate helper replaces more code than it adds. All primary citations are added lines in this full review. No escape-catalog pattern applies to these findings; no ledger lessons are in force.

Notes

No GPU run here; card evidence lacks nvidia-smi and the base hash.

Card check: needs-gpu. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gemma_embedding2_head512.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.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-emb2-head512 branch from 075f289 to 621cc26 Compare October 15, 2026 10:24
… query rows share the body

Q_SPAN names the query stride. The two head-256 entries use twice the head
width; plain query rows can use the head width itself.

partial_launch owns the shared shape and length refusals and the checked
launch values of the partial NeoX append entries.
…ts and store, are one macro each

The prefill bodies use prefill_softmax for their tile max, rescale, weights
and running sums. prefill_pack_counts and prefill_pack_store own the packed
body's count walk and final output. Each macro expands inside its caller.
… owner, and par_map moves to the lib

flash_band owns the exact attention and the terms used by the flash gates'
prefill bounds. Each gate derives its other kernel bounds from those terms.
The attention and band results are marked must_use.

The ordered worker map, par_map, moves to the gate library and is marked
must_use. spawn-allow names that owner and gate-paths names the flash gates.
…ngGemma 2's global layers, with their gate

Add a whole-head NeoX append over plain query rows and a prefill flash that
stages queries in shared memory, scores two dimension halves and splits
the value output between two grid blocks. The flash reuses the common
counts, softmax, store, staged layout and fragment row mapping.

The append requires distinct positions through an unsafe contract. The
gates share neox_head, the rope launch/readback and prefill window checks.
The head-512 gate covers encoder, causal and scattered counts, alternate
scale, replay, faults and named refusals, with an unpadded encoder at the
cache limit and rope launches through the last position with two KV heads.

Register the gate recipe and its paths, the PTX shape rows and the unsafe
sites required by the entries and gate helpers. No engine path calls the
new entries.
@juliankang4
juliankang4 force-pushed the dgx-spark-emb2-head512 branch from 621cc26 to a7c970d Compare October 15, 2026 10:34

@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 new gate duplicates an existing prefill-band judge.

Must fix

1. Give prefill-band judging one owner (kind B, R14)

gate_gemma_embedding2_head512.rs:182 repeats gate_qwen3moe_flash.rs:967: query/key-head mapping, exact attention, the prefill bound, and verdict reduction. Head width, tile width and head counts are inputs to the same rule. Both already use the arithmetic now owned by flash_band.

Move the judge and its doc comment into flash_band.rs. One function replaces two, so future changes to this contract require one edit. Keep the function behind gpu, since HostCache is feature-gated. Use this definition:

#[cfg(feature = "gpu")]
pub fn judge_prefill<const H: usize, const TILE: usize>(
    q: &[f32],
    counts: &[usize],
    cache: &crate::prefill_gate::HostCache,
    y: &[f32],
    scale: f32,
    (n_head, n_kv): (usize, usize),
) -> (bool, f64) {
    crate::par_map(counts.len() * n_head, |i| {
        let n = counts[i / n_head];
        let plane = (i % n_head / (n_head / n_kv)) * cache.ctx * H;
        let vh = &cache.vf[plane..plane + n * H];
        let ex = exact_attn(
            &q[i * H..(i + 1) * H],
            &cache.kf[plane..plane + n * H],
            vh, H, n, scale,
        );
        let bound = prefill_bound(&ex, vh, H, TILE);
        let (mut ok, mut worst) = (true, 0.0f64);
        for d in 0..H {
            let e = (f64::from(y[i * H + d]) - ex.o[d]).abs();
            ok &= e <= bound[d];
            worst = worst.max(if e.is_nan() {
                f64::INFINITY
            } else {
                e / bound[d]
            });
        }
        (ok, worst)
    })
    .into_iter()
    .fold((true, 0.0f64), |(ok, w), (o, x)| (ok && o, w.max(x)))
}

Import judge_prefill in both gates. Replace Gemma's call with:

let (band, worst) = judge_prefill::<HEAD, KEY_TILE_512>(
    &q, &cu, &c.host, &y, scale, heads,
);

Replace Qwen3's two band_rows calls with these respective calls:

let (band, worst) = judge_prefill::<HEAD, PREF_TILE>(
    &rows, &cu, &hc, &all, g.scale, (g.n_kv * GROUP, g.n_kv),
);
let (band, worst) = judge_prefill::<HEAD, PREF_TILE>(
    &q, &cu, &c.host, &y, g.scale, (g.n_kv * GROUP, g.n_kv),
);

Delete the local judge and band_rows definitions and unused imports.

Non-blocking

⚠ Current-head validation: flash_gqa_prefill.rs:611. The reported PTX comparison and Qwen gate runs precede the final macro/helper changes. These macros serve existing engine paths. Attach a current-head/base scan comparison with unchanged old entries and exactly two additions, spill FAIL-first for the additions, and the affected Qwen gate outputs. This supplies the move/add proof before more callers depend on it.

Checked

Duplicates: both cited judges and their shared arithmetic read; consolidation removes one function in an existing module.
Complexity: diagnostics report prefill_check 39, prefill_512_p 30, rope_gate::check 29, window_refusals 19 and rope_gate::run 17. No kernel split requested.
Silent failure: both judges reject NaN outputs through the band comparison.
Tests: the PR reports FAIL-first for repeated positions, early position/count refusal and a dropped cache plane. The validator did not run GPU tests.
Gates: both unsafe-count increases have dated PIN reasons. The new bin declares required-features.
Escape catalog: C1–C4 do not match changed shell code. No ledger lessons are in force.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gemma_embedding2_head512.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs … and carries a gate run on the author's card, which counts as verified.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@github-actions github-actions Bot added gpu-evidence Verified on the author's card: the pull request carries the gate run and its output and removed needs-gpu Changes code a card must check, and carries no gate run on a card labels Oct 15, 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.

Since the last review:

  • Must-fix 1: fixed. flash_band.rs:142 owns prefill judging, and both gates call it.
  • Validation question: partly answered. The PR supplies current-head scans; Qwen3 execution of the changed judge remains unverified at the call below.

Verdict: CLEAN: the shared judge preserves head mapping, band calculations and verdict propagation; no must-fix finding remains.

Non-blocking

⚠ Complete Qwen3 validation: gate_qwen3moe_flash.rs:852. The PR reports that missing fixtures stop the gate before the changed judge runs. Run just gate-gpu-qwen3moe-flash with the required fixtures and attach the output to verify this caller.

Checked

Duplicates: 1 new item checked by Grep; the shared judge replaces both copies. Both dryer pairs read: module-specific bundle loaders, unchanged in this increment.
Complexity: diagnostics list prefill_check 39, prefill_512_p 30, rope_gate::check 29, window_refusals 19 and rope_gate::run 17. This increment replaces calls and removes local judges. No kernel split requested.
Silent failure: the NaN-handling site was followed through all 3 calls to their verdicts. NaN outputs fail the band comparison.
Tests: the PR reports the Gemma gate passing at this head and FAIL-first for early position/count refusal and a dropped cache plane. The validator did not run GPU tests.
Gates: no bands, pins or cases changed in this increment.
Escape catalog: C1–C4 do not match this diff. No ledger lessons are in force.

Notes

Dryer did not search gpu-gates; the new item was checked manually.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/Cargo.toml, crates/gpu-gates/src/bin/gate_gemma_embedding2_head512.rs, crates/gpu-gates/src/bin/gate_qwen35moe_attn.rs … and carries a gate run on the author's card, which counts as verified.

🔨 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.

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 gpu-evidence Verified on the author's card: the pull request carries the gate run and its output tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants