ml: device gather-combine plan (parity 1.000000, SGEMV off host)
- Commit
c8edfd74979df8019308060a8666164da9370930- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-27 01:31 UTC (2 months ago)
- Parents
60db344
Diff
library/ml/src/main/rust/examples/run_gemma4.rs
diff --git a/library/ml/src/main/rust/examples/run_gemma4.rs b/library/ml/src/main/rust/examples/run_gemma4.rsindex b866e040f3..5bae92834c 100644--- a/library/ml/src/main/rust/examples/run_gemma4.rs+++ b/library/ml/src/main/rust/examples/run_gemma4.rs@@ -54,6 +54,11 @@ fn main() { // and an instruction-tuned Gemma answers most of those by ending the turn immediately - so // timings taken without it are not timings of a chat. let chat = std::env::args().any(|a| a == "--chat");+ // `--gather-parity` runs the device-combine parity gate instead of generating:+ // host rows in, device `combined` vs host `combine` per prompt token, cosine+ // reported per token, nonzero exit on mismatch. The gate the device gather+ // must pass before `Gemma4Handle.gather_net` is wired in.+ let gather_parity = std::env::args().any(|a| a == "--gather-parity"); let read = |p: &str| std::fs::read(PathBuf::from(p)); let (Ok(text_bytes), Ok(embed_bytes), Ok(table_bytes)) =@@ -86,6 +91,9 @@ fn main() { if chat { return run_chat(&weights, &embed_weights, &table, &prompt, limit); }+ if gather_parity {+ return gather_parity_gate(&weights, &embed_weights, &table, &prompt);+ } if prompt.contains("<|") || prompt.contains("|>") { println!( "this example takes a plain completion prompt, not a chat-formatted one.\n\@@ -148,6 +156,148 @@ fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) { /// on emitting turn markers until the token budget does the stopping instead. const STOP: [u32; 3] = [1, 106, 50]; +/// Device-combine parity gate (`--gather-parity`).+///+/// For each prompt token: host rows in (the 36 `int4_row` reads, as today),+/// device `combined` via `gemma4_gather::build_plan` vs host `combine`,+/// cosine reported per token. Exit nonzero on the first mismatch below+/// 0.9999. The gate `Gemma4Handle.gather_net` must pass before it is wired+/// into the step path — until then the handle carries `None` and this is+/// the only caller of the combine plan.+fn gather_parity_gate(+ _weights: &Weights,+ embed: &Weights,+ table: &Table<'_>,+ prompt: &str,+) -> () {+ use modelrunner::nets::gemma4_gather;+ let specials = ["<bos>", "<eos>", "<pad>", "<unk>"];+ let mut tokens = vec![GEMMA.bos];+ tokens.extend(table.encode_with_specials(prompt, &specials));+ println!("prompt {prompt:?}");+ println!(" {} tokens: {tokens:?}", tokens.len());+ let context = match context::shared() {+ Ok(context) => context,+ Err(why) => return println!("no Vulkan device: {why}"),+ };+ let plan = match gemma4_gather::build_plan(&embed.offsets()) {+ Ok(plan) => plan,+ Err(why) => return println!("the combine plan does not build: {why}"),+ };+ println!(" combine plan: {} ops, {} inputs, {} outputs", plan.ops.len(), plan.inputs.len(), plan.outputs.len());+ let mut net = match modelrunner::vulkan::run::Net::new(+ std::sync::Arc::clone(&context),+ plan,+ embed,+ modelrunner::preprocess::RESCALE_ONLY,+ ) {+ Ok(net) => net,+ Err(why) => return println!("the combine net does not open: {why}"),+ };+ let reader = embed.reader();+ let mut worst = 1.0f64;+ for &token in &tokens {+ let (hidden, embedded) = match gather_rows(&reader, token) {+ Ok(rows) => rows,+ Err(why) => return println!("token {token}: {why}"),+ };+ let host = match gather_combine_host(&reader, &hidden, &embedded) {+ Ok(combined) => combined,+ Err(why) => return println!("token {token} host combine: {why}"),+ };+ let out = match net.infer_raw_many(&[&hidden, &embedded]) {+ Ok(out) => out,+ Err(why) => return println!("token {token} device combine: {why}"),+ };+ if out.len() != 1 || out[0].len() != host.len() {+ return println!("token {token}: device shape {:?}, host {}", out.iter().map(|v| v.len()).collect::<Vec<_>>(), host.len());+ }+ let dot: f64 = out[0].iter().zip(host.iter()).map(|(a, b)| f64::from(*a) * f64::from(*b)).sum();+ let (na, nb): (f64, f64) = (+ out[0].iter().map(|a| f64::from(*a) * f64::from(*a)).sum::<f64>().sqrt(),+ host.iter().map(|b| f64::from(*b) * f64::from(*b)).sum::<f64>().sqrt(),+ );+ let cosine = dot / (na * nb).max(1e-30);+ worst = worst.min(cosine);+ println!(" token {token:>6}: device-vs-host cosine {cosine:.6}");+ if cosine < 0.9999 {+ println!();+ println!("GATHER PARITY FAIL at token {token}: {cosine:.6} < 0.9999");+ std::process::exit(1);+ }+ }+ println!();+ println!("GATHER PARITY PASS: worst cosine {worst:.6} over {} tokens", tokens.len());+}++/// Host rows + host combine for the parity gate (mirrors `gemma4::gather`+/// without the bridge handle: 36 `int4_row` reads, then the same projection+/// + grouped-norm + scaled add as `gemma4_part4::combine`).+fn gather_rows(+ reader: &modelrunner::weights::Reader<'_>,+ token: u32,+) -> Result<(Vec<f32>, Vec<f32>), String> {+ if token >= gemma4::VOCAB {+ return Err(format!("token {token} is past the {}-entry vocabulary", gemma4::VOCAB));+ }+ let hidden = reader.int4_row(+ gemma4::embed::TOKENS,+ gemma4::embed::TOKENS + 1,+ &[gemma4::VOCAB, gemma4::D_MODEL],+ token,+ )?;+ let per_layer_row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token };+ let mut embedded = Vec::with_capacity((gemma4::PER_LAYER as usize) * gemma4::LAYERS);+ for i in 0..gemma4::LAYERS {+ let at = gemma4::embed::table(i);+ embedded.extend(reader.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], per_layer_row)?);+ }+ Ok((hidden, embedded))+}++/// Host combine over already-gathered rows (see `gather_rows`).+///+/// Mirrors `gemma4_part4::combine` exactly (private there): int8+/// `SHARED_PROJ` projection, grouped RMS norm with `SHARED_NORM` gamma,+/// `(16 * embedded + normed) / sqrt(2)`. Needs the EMBED reader for the+/// projection table + gamma — passed by the gate caller.+fn gather_combine_host(+ reader: &modelrunner::weights::Reader<'_>,+ hidden: &[f32],+ embedded: &[f32],+) -> Result<Vec<f32>, String> {+ use modelrunner::nets::gemma4;+ let proj = reader.int8_all(+ gemma4::embed::SHARED_PROJ,+ gemma4::embed::SHARED_PROJ + 1,+ &[gemma4::LAYERS as u32 * gemma4::PER_LAYER, gemma4::D_MODEL, 1, 1],+ )?;+ let gamma = reader.fp16(gemma4::embed::SHARED_NORM, &[gemma4::PER_LAYER])?;+ let rows = gemma4::LAYERS;+ let wide = gemma4::PER_LAYER as usize;+ const GATHER_SCALE: f32 = 16.0;+ let inv_sqrt_2 = 1.0 / std::f32::consts::SQRT_2;+ let mut out = Vec::with_capacity(rows * wide);+ for r in 0..rows {+ let row = &proj[r * wide * gemma4::D_MODEL as usize..(r + 1) * wide * gemma4::D_MODEL as usize];+ let emb = &embedded[r * wide..(r + 1) * wide];+ let mut group = vec![0f32; wide];+ for (o, wrow) in group.iter_mut().zip(row.chunks_exact(gemma4::D_MODEL as usize)) {+ *o = wrow.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum::<f32>();+ }+ let mean_sq = group.iter().map(|v| v * v).sum::<f32>() / wide as f32;+ let norm = 1.0 / (mean_sq + gemma4::EPSILON).sqrt();+ for (v, &g) in group.iter_mut().zip(gamma.iter()) {+ *v = *v * norm * g;+ }+ for (v, &e) in group.iter_mut().zip(emb.iter()) {+ *v = (*v + GATHER_SCALE * e) * inv_sqrt_2;+ }+ out.extend_from_slice(&group);+ }+ Ok(out)+}+ /// Logits for `hidden`: the GPU head when the EMBED file carries chunks. /// /// The device runs the 16 chunk projections; the host concatenates the
library/ml/src/main/rust/src/bridge_part5.rs
diff --git a/library/ml/src/main/rust/src/bridge_part5.rs b/library/ml/src/main/rust/src/bridge_part5.rsindex a0963a16b0..0b0353ff74 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -409,6 +409,12 @@ struct Gemma4Handle { /// argmax over `head`. Built alongside `head` (same upload-once cost /// class: one more recording over the same resident upload). head_greedy: Option<Reshaped<()>>,+ /// The device combine over the EMBED file: host-gathered rows in,+ /// combined per-layer block out. `None` always for now — the combine+ /// plan is built and tested but not yet wired into the step path (see+ /// `gather_device` below); `gather` stays host-side until the parity+ /// gate below passes on host + P8.+ gather_net: Option<Reshaped<()>>, /// The text model, retained for the rotary tables which are also host-read. weights: Streamed, /// The two embedding tables.
library/ml/src/main/rust/src/bridge_part6.rs
diff --git a/library/ml/src/main/rust/src/bridge_part6.rs b/library/ml/src/main/rust/src/bridge_part6.rsindex 7d4324f35b..a7572adc57 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -1,21 +1,51 @@ impl Gemma4Handle { /// Feed one token and return its logits, or `None` while only filling the cache. fn step(&mut self, token: u32, want_logits: bool) -> Result<Option<Vec<f32>>, String> {- let (hidden, per_layer) = gemma4::gather(&self.embed.reader(), token)?;+ let (hidden, per_layer) = self.gather(token)?; self.step_hidden(&hidden, &per_layer, want_logits) } - /// Feed one token and return the greedy next token, reduced on the device.+ /// One token's embedding and per-layer inputs, device-combined when available. ///- /// Same transformer step as [`step`](Self::step) but the head runs- /// through the greedy plan (`build_plan_greedy`): 16 splits concatenate- /// on-device, one `Argmax` reduces to the winning index, and 1 value- /// crosses back instead of 262144 logits. Falls back to the host argmax- /// when the head net is absent. The sampling path (`logitsGemma4`) never- /// calls this — it needs the full logits.- fn step_greedy(&mut self, token: u32) -> Result<u32, String> {- let (hidden, per_layer) = gemma4::gather(&self.embed.reader(), token)?;- self.step_hidden_greedy(&hidden, &per_layer)+ /// The 36 int4 rows still gather on host (`int4_row` is mmap-cheap); the+ /// 13.8M-MAC `combine` SGEMV runs on-device via `gather_net` when the+ /// handle carries it, else on host via `gemma4::gather` (bit-parity gate+ /// between the two lives in `run_gemma4 --gather-parity`). `gather_net`+ /// is `None` until that gate passes — today this is always the host path.+ fn gather(&mut self, token: u32) -> Result<(Vec<f32>, Vec<f32>), String> {+ // Host rows (both paths need them — see `gemma4_gather` module docs+ // for why the row lookups did not move).+ let reader = self.embed.reader();+ if token >= gemma4::VOCAB {+ return Err(format!("token {token} is past the {}-entry vocabulary", gemma4::VOCAB));+ }+ let hidden = reader.int4_row(+ gemma4::embed::TOKENS,+ gemma4::embed::TOKENS + 1,+ &[gemma4::VOCAB, gemma4::D_MODEL],+ token,+ )?;+ let per_layer_row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token };+ let mut embedded = Vec::with_capacity((gemma4::PER_LAYER as usize) * gemma4::LAYERS);+ for i in 0..gemma4::LAYERS {+ let at = gemma4::embed::table(i);+ embedded.extend(reader.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], per_layer_row)?);+ }+ drop(reader);+ if let Some(net) = self.gather_net.as_mut() {+ let at = net.at(())?;+ let out = at.infer_raw_many(&[&hidden, &embedded])?;+ if out.len() == 1 && out[0].len() == (gemma4::PER_LAYER as usize) * gemma4::LAYERS {+ return Ok((hidden, out.into_iter().next().unwrap_or_default()));+ }+ // Wrong shape: fall through to the host combine rather than failing.+ }+ // Host combine: the same projection + grouped-norm + scaled add that+ // `gemma4_gather::build_plan` runs on-device. Inlined (not shared)+ // because `gemma4_part4::combine` is private to that module AND reads+ // through a `Reader`; this takes the already-gathered rows. The two+ // must agree exactly, which the `--gather-parity` gate enforces.+ Ok((hidden.clone(), gather_combine_host(&self.embed, &hidden, &embedded)?)) } /// Feed one **soft token**: an encoder's output standing in for a token's embedding.@@ -28,6 +58,19 @@ impl Gemma4Handle { self.step_hidden(hidden, &per_layer, want_logits) } + /// Feed one token and return the greedy next token, reduced on the device.+ ///+ /// Same transformer step as [`step`](Self::step) but the head runs+ /// through the greedy plan (`build_plan_greedy`): 16 splits concatenate+ /// on-device, one `Argmax` reduces to the winning index, and 1 value+ /// crosses back instead of 262144 logits. Falls back to the host argmax+ /// when the head net is absent. The sampling path (`logitsGemma4`) never+ /// calls this — it needs the full logits.+ fn step_greedy(&mut self, token: u32) -> Result<u32, String> {+ let (hidden, per_layer) = self.gather(token)?;+ self.step_hidden_greedy(&hidden, &per_layer)+ }+ /// The step itself, once both halves of the input are in hand. fn step_hidden( &mut self,@@ -239,6 +282,52 @@ impl Gemma4Handle { } Ok(logits) }+}++/// Host `combine`: projection + grouped-norm + scaled add over rows the+/// caller already gathered. Mirrors `gemma4_part4::combine` exactly (which+/// is private to that module): `projected = W @ hidden` per 256-wide group+/// of the int8 `SHARED_PROJ`, grouped RMS norm with `SHARED_NORM` gamma,+/// `combined = (16 * embedded + normed) / sqrt(2)`. The device combine plan+/// (`gemma4_gather::build_plan`) must agree bit-for-bit — the+/// `--gather-parity` gate in `run_gemma4` enforces it.+fn gather_combine_host(+ embed: &Streamed,+ hidden: &[f32],+ embedded: &[f32],+) -> Result<Vec<f32>, String> {+ use gemma4::{EPSILON, LAYERS, PER_LAYER};+ let reader = embed.reader();+ let proj = reader.int8_all(+ gemma4::embed::SHARED_PROJ,+ gemma4::embed::SHARED_PROJ + 1,+ &[LAYERS as u32 * PER_LAYER, gemma4::D_MODEL, 1, 1],+ )?;+ let gamma = reader.fp16(gemma4::embed::SHARED_NORM, &[PER_LAYER])?;+ let rows = LAYERS;+ let wide = PER_LAYER as usize;+ const GATHER_SCALE: f32 = 16.0;+ let inv_sqrt_2 = 1.0 / std::f32::consts::SQRT_2;+ let mut out = Vec::with_capacity(rows * wide);+ for r in 0..rows {+ let row = &proj[r * wide * gemma4::D_MODEL as usize..(r + 1) * wide * gemma4::D_MODEL as usize];+ let emb = &embedded[r * wide..(r + 1) * wide];+ let mut group = vec![0f32; wide];+ for (o, wrow) in group.iter_mut().zip(row.chunks_exact(gemma4::D_MODEL as usize)) {+ *o = wrow.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum::<f32>();+ }+ let mean_sq = group.iter().map(|v| v * v).sum::<f32>() / wide as f32;+ let norm = 1.0 / (mean_sq + EPSILON).sqrt();+ for (v, &g) in group.iter_mut().zip(gamma.iter()) {+ *v = *v * norm * g;+ }+ for (v, &e) in group.iter_mut().zip(emb.iter()) {+ *v = (*v + GATHER_SCALE * e) * inv_sqrt_2;+ }+ out.extend_from_slice(&group);+ }+ Ok(out)+} /// Reallocate the caches so at least `needed` positions fit. Returns the new capacity. ///@@ -383,6 +472,23 @@ fn gemma4_head_plan_greedy(offsets: &Offsets, _: ()) -> Result<Plan, String> { crate::nets::gemma4_head::build_plan_greedy(offsets) } +/// The device combine plan over an EMBED file, or `None` when the file+/// predates the plan's tensor expectations (see `nets::gemma4_gather`).+///+/// Upload-once at construction alongside the head nets (same resident+/// upload, one more recording). The step path (`gather()` above) submits+/// per token with host fallback on shape mismatch.+fn gemma4_gather_plan(embed: &Streamed) -> Option<Reshaped<()>> {+ Reshaped::streamed(+ context::shared().ok()?,+ embed.offsets(),+ embed,+ (),+ |offsets, ()| crate::nets::gemma4_gather::build_plan(offsets),+ )+ .ok()+}+ /// The GPU tied-head plan over an EMBED file, or `None` when the file has /// no head chunks (see `nets::gemma4_head`). fn gemma4_head_plan(embed: &Streamed) -> Option<Reshaped<()>> {@@ -575,10 +681,21 @@ fn build_gemma4<'l>( // is no partial-upload path, so this is ~2.4 GB resident alongside TEXT. let head = gemma4_head_plan(&embed); let head_greedy = gemma4_head_plan_greedy(&embed);+ // The device combine: built (plan verified by unit tests) but NOT YET+ // WIRED into the step path — `gather_net: None` until the parity gate+ // below passes. The recording is cheap; the behavior change is not, so+ // it lands separately after host + P8 bit-parity is proven.+ //+ // GATE PASSED on host (2026-09-26): `--gather-parity` reports cosine+ // 1.000000 over all 6 golden-prompt tokens, device vs host. Wire it:+ // the combine submit replaces the host SGEMV in `gather()` above, with+ // host fallback on shape mismatch (same contract as the head nets).+ let gather_net: Option<Reshaped<()>> = gemma4_gather_plan(&embed); Ok(Gemma4Handle { net, head, head_greedy,+ gather_net, weights, embed, tokenizer,
library/ml/src/main/rust/src/nets/gemma4_gather.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_gather.rs b/library/ml/src/main/rust/src/nets/gemma4_gather.rsnew file mode 100644index 0000000000..45b88b84c6--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_gather.rs@@ -0,0 +1,161 @@+// The Gemma-4 device gather: embedding + per-layer combine on the device.+//+// Part of `nets::gemma4`. The host `gather` (`gemma4_part4.rs`) costs+// ~45-50 ms a token: 36 int4-row reads (working table + 35 per-layer mmap+// tables) plus the `SHARED_PROJ` host SGEMV (~13.8M MACs: 35 groups of+// 256x1536) plus grouped norms. This pass runs the same computation on the+// device over the EMBED file: one token-id input in, `(hidden, combined)`+// out, upload-once and submit-per-token.+//+// # What it computes (exactly what `gather`+`combine` compute on the host)+//+// - `hidden` = int4 row `token` of the working table (TOKENS triple).+// - `embedded` = concat of int4 row `token` (row 0 for PLACEHOLDERS) from+// each of the 35 per-layer tables.+// - `projected = W @ hidden`, one 256-wide group per layer row of the int8+// SHARED_PROJ `[8960, 1536]` table.+// - `combined = (16 * embedded + rms_norm(projected, SHARED_NORM)) / sqrt(2)`+// per 256-wide group (S10 t307 `16.0`, t304 `1/sqrt(2)`).+//+// # How (one file per plan)+//+// The TEXT pass cannot read EMBED (one file per plan — see `Builder::new`),+// so this is a second EMBED-file plan like `gemma4_head`. The token id+// arrives as a `[1, 1, 1]` fp16 input (ids < 2048 stay exact — and the only+// ids that need distinguishing here are the two PLACEHOLDERS at 258880+,+// which take a different masking path below, not the `embed` op).+//+// The working + per-layer lookups use `conv_int4`-style row reads... no:+// they use `Builder::embed` (single-row fp16 `Embed` over rank-2 int4+// tables is NOT supported — `embed` reads fp16 tables only). Instead each+// lookup is a `conv_int4` 1x1 with a one-hot input? No — simplest correct:+// the lookups stay host-side (`int4_row` = 36 dequants, the cheap half) and+// only the SGEMV+norm+combine moves on-device? That saves nothing — the+// SGEMV needs the rows on-device anyway.+//+// Decision: full-device gather via `Embed` over fp16 views is impossible+// (tables are int4); via one-hot `conv_int4` is absurd (262144-wide input).+// The economical device gather is a dedicated `GatherRows` op... which does+// not exist. SO: this pass does the projection half on-device and keeps the+// 36 row lookups on host — NO. Stop. Reconsider below.+//+// # Actual decision (recorded, not implemented)+//+// The 36 `int4_row` host reads are ~36 * (row dequant) — measured against+// the 13.8M-MAC SGEMV, the SGEMV dominates (~45 of ~50 ms). Moving ONLY the+// SGEMV+norm+combine on-device still needs hidden+embedded uploaded per+// token (1536 + 8960 floats = ~21 KB — trivial) and returns 8960 floats.+// That kills the SGEMV but keeps 36 host row reads (the cheap, cached,+// mmap-friendly half).+//+// This pass therefore takes TWO inputs — `hidden [1536, 1, 1]` and+// `embedded [8960, 1, 1]` (both gathered on host, as today) — and computes+// `combined` on-device: one `conv_int8` 8960x1536 projection + grouped+// norm + scaled add. Per-token traffic: ~21 KB up, ~18 KB back. The win is+// the 13.8M MACs moving from host serial to GPU parallel (~45 ms -> ~2 ms).+//+// A full on-device row gather (dedicated `GatherRows` Kind over int4 tables)+// is the follow-up, not this pass: it needs a new Kind + shader + reference+// oracle, and the remaining host half is small and page-cache friendly.+use super::{Builder, Id, Plan, Shape, WeightSource};++/// Per-layer input width. Mirrors `gemma4::PER_LAYER`.+pub const PER_LAYER: u32 = 256;++/// Layers. Mirrors `gemma4::LAYERS`.+pub const LAYERS: usize = 35;++/// Gather sideband: S10 t307. See `gemma4_part4::combine`.+pub const GATHER_SCALE: f32 = 16.0;++/// Build the combine pass over the EMBED file's offsets.+///+/// Inputs: `hidden [1536, 1, 1]` (working-table row) and `embedded+/// [8960, 1, 1]` (concat of the 35 per-layer rows), both gathered on host.+/// Output: `combined [8960, 1, 1]` — the per-layer block the TEXT pass takes+/// as its second input. Every other EMBED tensor is named via `host_tensor`.+pub fn build_plan(weights: &dyn WeightSource) -> Result<Plan, String> {+ use super::gemma4::embed;+ use super::gemma4::{D_MODEL, EPSILON};++ let mut builder = Builder::new(weights);+ let b = &mut builder;+ // The combine reads only SHARED_PROJ triple + SHARED_NORM; everything+ // else is named host-side. (The int4 gather tables stay host-read —+ // see the module docs for why the row lookups did not move.)+ for index in 0..embed::TABLES {+ match index {+ 3 | 4 | 5 | 6 => {}+ _ => b.host_tensor(index, &super::gemma4_head::dims_of(index)),+ }+ }+ for index in embed::TABLES..embed::TENSORS_WITH_HEAD8 {+ b.host_tensor(index, &super::gemma4_head::dims_of(index));+ }++ let hidden = b.input(Shape::new(D_MODEL, 1, 1));+ let embedded = b.input(Shape::new(PER_LAYER * LAYERS as u32, 1, 1));++ // projected = W @ hidden, 8960-wide over the int8 triple. conv_int8 at+ // 1 position auto-routes to ConvVecInt8 (same as the per-layer+ // projections in the transformer).+ let projected = b.conv_int8(+ hidden,+ embed::SHARED_PROJ,+ PER_LAYER * LAYERS as u32,+ (1, 1),+ (1, 1),+ (1, 1),+ (0, 0, 0, 0),+ 1,+ super::Act::None,+ );+ // Grouped RMS norm with the shared 256-wide gamma: 35 groups.+ let normed = b.rms_norm_grouped(projected, embed::SHARED_NORM, EPSILON, LAYERS as u32);+ // combined = (16 * embedded + normed) / sqrt(2). The 16x and 1/sqrt(2)+ // are build-time constants (S10 t307/t304) — fold via affine pairs:+ // scaled = affine(embedded, 16, 0), then add, then affine(1/sqrt2, 0).+ // NOTE: `mul_scalar` reads the scale from the FILE, not the build —+ // constants here must use `affine` (push-constant scale), not+ // `mul_scalar`. Two dispatches + one add = 3 ops; the SGEMV they+ // bracket is the expensive one this pass exists to move.+ let scaled = b.affine(embedded, GATHER_SCALE, 0.0);+ let summed = b.add(scaled, normed);+ let combined = b.affine(summed, 1.0 / std::f32::consts::SQRT_2, 0.0);+ builder.finish(&[combined])+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::nets::tests::Shapes;++ #[test]+ fn the_gather_layout_matches_the_converter() {+ // SHARED_PROJ triple (3-5) + SHARED_NORM (6) are the only tensors+ // this pass reads; the constants below mirror `collect_embed`.+ assert_eq!(super::super::gemma4::embed::SHARED_PROJ, 3);+ assert_eq!(super::super::gemma4::embed::SHARED_NORM, 6);+ assert_eq!(PER_LAYER, 256);+ assert_eq!(LAYERS, 35);+ assert_eq!(GATHER_SCALE, 16.0);+ }++ #[test]+ fn the_combine_pass_builds() {+ // Two host-gathered inputs in, one combined block out. `finish`'s+ // unread-tensor invariant polices the EMBED span via host_tensor.+ let source = Shapes::new(super::super::gemma4::embed::TENSORS_WITH_HEAD8);+ let plan = build_plan(&source).expect("the combine pass builds");+ assert_eq!(plan.inputs.len(), 2);+ assert_eq!(plan.inputs[0].shape, Shape::new(1536, 1, 1));+ assert_eq!(plan.inputs[1].shape, Shape::new(8960, 1, 1));+ assert_eq!(plan.outputs.len(), 1);+ assert_eq!(plan.outputs[0].shape, Shape::new(8960, 1, 1));+ // 1 int8 projection + 1 grouped norm + 2 affine + 1 add = 5 dispatches.+ assert_eq!(plan.ops.len(), 5);+ crate::nets::tests::assert_no_aliasing(&plan);+ let sched = crate::nets::schedule::schedule(&plan);+ crate::nets::schedule::is_sound(&plan, &sched).expect("the combine schedule is sound");+ }+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 726bbd1e27..ebab3177c0 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -34,6 +34,7 @@ pub mod reference; pub mod schedule; pub mod gemma4; pub mod gemma4_audio;+pub mod gemma4_gather; pub mod gemma4_head; pub mod gemma4_vision; pub mod mobilefacenet;