ml: GPU tied-head for Gemma-4 logits (16 fp16 chunks, host fallback)
- Commit
e58ddbf922500c97cdcc0e61445f5d74abb0fa40- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-26 22:19 UTC (2 months ago)
- Parents
50ab3c3
Diff
library/ml/src/main/rust/examples/check_gemma4_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_parity.rsindex e400d697e7..d1350b4ab6 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -109,6 +109,30 @@ fn main() { Err(why) => println!(" {label:<14} failed: {why}"), } }++ // L0 tail bisect: the four branch vectors against the numpy-fp oracle, in+ // tail order. The first label where the device drops below 0.99 while numpy+ // holds is the divergence point (see `Mode::TraceTail`).+ let tail_arg = std::env::args().nth(5);+ let Some(tail_path) = tail_arg else { return };+ let Ok(tail) = std::fs::read_to_string(&tail_path) else {+ return println!("cannot read {tail_path}");+ };+ println!();+ println!("L0 tail against the numpy oracle");+ match tail_run(&context, &weights, &embed_weights, &tokens) {+ Ok(branches) => {+ for (label, got) in+ ["attn_branch", "mlp_branch", "ple_branch", "l0_out"].into_iter().zip(branches.iter())+ {+ match field(&tail, label) {+ Some(want) => println!(" {label:<14} {}", compare(got, &want)),+ None => println!(" {label:<14} not in the tail file"),+ }+ }+ }+ Err(why) => println!(" the tail trace failed: {why}"),+ } } /// Cosine and relative RMS between a device tensor and the reference's.@@ -170,6 +194,54 @@ fn trace_run( Ok(last) } +/// Layer 0's four tail branches at the last step, in tail order+/// (`attn_branch`, `mlp_branch`, `ple_branch`, `l0_out`).+///+/// Same OOM-safe shape as [`trace_run`]: the KV cache fills one step at a time and only+/// the last step's four 1536-float branches are kept.+fn tail_run(+ context: &Arc<context::Context>,+ weights: &Streamed,+ embed: &Streamed,+ tokens: &[u32],+) -> Result<[Vec<f32>; 4], String> {+ let mode = gemma4::Mode::TraceTail.at(TIER);+ let mut net = Reshaped::streamed(+ Arc::clone(context),+ weights.offsets(),+ weights,+ mode,+ |offsets, mode| gemma4::build(offsets, mode),+ )?;+ let reader = embed.reader();+ let rotary = weights.reader();+ let mut last = [Vec::new(), Vec::new(), Vec::new(), Vec::new()];+ for (step, &token) in tokens.iter().enumerate() {+ let position = u32::try_from(step).map_err(|_| "a step past u32")?;+ let (hidden, per_layer) = gemma4::gather(&reader, token)?;+ let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?;+ let angles_global =+ rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?;+ let at = net.at(mode)?;+ at.set_params(StepParams {+ prefix: position,+ window_start: position.saturating_sub(gemma4::WINDOW - 1),+ })?;+ let out = at.infer_raw_many(&[&hidden, &per_layer, &angles_local, &angles_global])?;+ if out.len() != 4 {+ return Err(format!("a tail step returned {} tensors, not the four branches", out.len()));+ }+ let mut it = out.into_iter();+ last = [+ it.next().unwrap_or_default(),+ it.next().unwrap_or_default(),+ it.next().unwrap_or_default(),+ it.next().unwrap_or_default(),+ ];+ }+ Ok(last)+}+ /// Feed every token in order and return the last step's logits. /// /// The device returns the normed hidden state; the logits are@@ -221,6 +293,46 @@ fn run( if hidden.len() != gemma4::D_MODEL as usize { return Err(format!("hidden state of {} values, not {}", hidden.len(), gemma4::D_MODEL)); }+ Ok(gpu_or_host_logits(context, embed, &reader, &hidden)?)+}++/// Logits for `hidden`: the GPU head when the EMBED file carries chunks.+///+/// The device runs the 16 fp16 chunk projections; the host concatenates the+/// splits and softcaps. Falls back to the host tied head (`hidden @+/// HEAD_TABLE^T` in `HEAD_SPLITS` quarters) on files without chunks, so this+/// example keeps working against pre-head-split converts. Both paths must+/// agree: the parity gate below compares against the golden either way.+fn gpu_or_host_logits(+ context: &Arc<context::Context>,+ embed: &Streamed,+ reader: &modelrunner::weights::Reader<'_>,+ hidden: &[f32],+) -> Result<Vec<f32>, String> {+ use modelrunner::nets::gemma4_head;+ if embed.offsets().len() >= gemma4_head::TENSORS_WITH_HEAD {+ let mut head = Reshaped::streamed(+ Arc::clone(context),+ embed.offsets(),+ embed,+ (),+ |offsets, ()| gemma4_head::build_plan(offsets),+ )?;+ let at = head.at(())?;+ let out = at.infer_raw_many(&[hidden])?;+ if out.len() == gemma4_head::HEAD_CHUNKS+ && out.iter().all(|s| s.len() == gemma4_head::CLASSES_PER_CHUNK as usize)+ {+ let mut logits = Vec::with_capacity(gemma4::VOCAB as usize);+ for split in &out {+ for &value in split {+ logits.push(gemma4::LOGIT_CAP * (value / gemma4::LOGIT_CAP).tanh());+ }+ }+ return Ok(logits);+ }+ // Wrong shape: fall through to the host head rather than failing.+ } // Tied head on the host, in vocabulary splits (see `gemma4::HEAD_SPLITS`). // Reads the raw-scale head table (`gemma4::embed::HEAD_TABLE`), not the // working table - no gain division (see `gemma4::EMBED_GAIN`).
library/ml/src/main/rust/examples/probe_gemma4.rs
diff --git a/library/ml/src/main/rust/examples/probe_gemma4.rs b/library/ml/src/main/rust/examples/probe_gemma4.rsindex ed7ae84c92..545aebc0a3 100644--- a/library/ml/src/main/rust/examples/probe_gemma4.rs+++ b/library/ml/src/main/rust/examples/probe_gemma4.rs@@ -19,16 +19,13 @@ //! It does **not** check the numbers. That needs a reference run, which needs the tokenizer and //! the embedding export; see `check_nllb_parity.rs` for the shape that takes. use std::path::PathBuf;--use modelrunner::nets::{gemma4, gemma4_vision};+use modelrunner::nets::{gemma4, gemma4_head, gemma4_vision}; use modelrunner::weights::{graph, Blob, Weights};- /// The cache these examples record against: the top tier, so a long prompt fits. const TIER: u32 = gemma4::MAX_CONTEXT;- fn main() { let Some(path) = std::env::args().nth(1).map(PathBuf::from) else {- println!("usage: probe_gemma4 <gemma4_text.maml>");+ println!("usage: probe_gemma4 <gemma4_text.maml> [gemma4_embed.maml]"); return; }; let bytes = match std::fs::read(&path) {@@ -111,10 +108,22 @@ fn main() { println!(); println!("embedding {} {:.2} GB", embed_path.display(), embed_bytes.len() as f64 / 1e9); println!(- "tensors {} (the module expects {})",+ "tensors {} (the module expects {} + {} head chunks = {})", embed.tensors().len(),- gemma4::embed::TENSORS+ gemma4::embed::TENSORS,+ gemma4_head::HEAD_CHUNK_TENSORS,+ gemma4_head::TENSORS_WITH_HEAD, );+ match gemma4_head::build_plan(&embed) {+ Ok(plan) => {+ println!("the GPU head plan builds against the real table");+ println!(" {} ops, {} inputs, {} outputs", plan.ops.len(), plan.inputs.len(), plan.outputs.len());+ let classes: u32 = plan.outputs.iter().map(|b| b.shape.c).sum();+ println!(" {classes} logits over {} splits", plan.outputs.len());+ println!(" {:.1} MB of arena", f64::from(plan.arena_elems) * 2.0 / 1e6);+ }+ Err(why) => println!("the GPU head plan does NOT build: {why}"),+ } // The vision tower, if it is beside the other two. if let Some(path) = std::env::args().nth(3).map(PathBuf::from) {
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 9fb749dcdc..5dd24b29b3 100644--- a/library/ml/src/main/rust/examples/run_gemma4.rs+++ b/library/ml/src/main/rust/examples/run_gemma4.rs@@ -17,7 +17,8 @@ use std::sync::Arc; use std::time::Instant; use modelrunner::nets::gemma4;-use modelrunner::post::sentencepiece::{Table, GEMMA};+use modelrunner::post::sentencepiece::Table;+use modelrunner::post::sentencepiece_flavours::GEMMA; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped; use modelrunner::vulkan::run::StepParams;@@ -147,6 +148,61 @@ 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]; +/// Logits for `hidden`: the GPU head when the EMBED file carries chunks.+///+/// The device runs the 16 fp16 chunk projections; the host concatenates the+/// splits and softcaps, exactly as the host head does. Falls back to the+/// host tied head (`hidden @ HEAD_TABLE^T` in `HEAD_SPLITS` quarters) on+/// files without chunks.+fn head_logits(+ _context: &Arc<context::Context>,+ head: &mut Option<Reshaped<()>>,+ reader: &modelrunner::weights::Reader<'_>,+ hidden: &[f32],+) -> Result<Vec<f32>, String> {+ use modelrunner::nets::gemma4_head;+ if let Some(net) = head.as_mut() {+ let at = net.at(())?;+ let t = std::time::Instant::now();+ let out = at.infer_raw_many(&[hidden])?;+ eprintln!("head submit: {:.0} ms", t.elapsed().as_secs_f64() * 1000.0);+ if out.len() == gemma4_head::HEAD_CHUNKS+ && out.iter().all(|s| s.len() == gemma4_head::CLASSES_PER_CHUNK as usize)+ {+ let mut logits = Vec::with_capacity(gemma4::VOCAB as usize);+ for split in &out {+ for &value in split {+ logits.push(gemma4::LOGIT_CAP * (value / gemma4::LOGIT_CAP).tanh());+ }+ }+ return Ok(logits);+ }+ // Wrong shape: the file's chunks do not match the plan. Fall through+ // to the host head rather than failing the run.+ }+ // The tied head on the host, in vocabulary splits (see `gemma4::HEAD_SPLITS`).+ // `Mode::DecodeStep` returns the normed hidden state, not logits: litertlm+ // stores no logits head, so logits are hidden @ E^T over the raw-scale head+ // table (`gemma4::embed::HEAD_TABLE`), softcapped. Mirrors+ // `check_gemma4_parity::run`.+ let mut logits = vec![0f32; gemma4::VOCAB as usize];+ for split in 0..gemma4::HEAD_SPLITS {+ let start = (split as u32) * gemma4::CLASSES_PER_SPLIT;+ let block = reader.fp16_rows(+ gemma4::embed::HEAD_TABLE,+ &[gemma4::VOCAB, gemma4::D_MODEL],+ start,+ gemma4::CLASSES_PER_SPLIT,+ )?;+ for (offset, row) in block.chunks_exact(gemma4::D_MODEL as usize).enumerate() {+ let dot: f32 = row.iter().zip(hidden.iter()).map(|(a, b)| a * b).sum();+ logits[start as usize + offset] =+ gemma4::LOGIT_CAP * (dot / gemma4::LOGIT_CAP).tanh();+ }+ }+ Ok(logits)+}+ /// Feed the prompt, then sample greedily until `limit` new tokens or a stop id. fn generate( context: &Arc<context::Context>,@@ -158,6 +214,19 @@ fn generate( let mut net = Reshaped::new(Arc::clone(context), weights, gemma4::Mode::DecodeStep.at(tier()), |o, m| { gemma4::build(o, m) })?;+ // The GPU tied head over the EMBED file, upload-once. `None` on files+ // without head chunks — the host head below covers those.+ let mut head: Option<Reshaped<()>> = if embed.offsets().len() >= modelrunner::nets::gemma4_head::TENSORS_WITH_HEAD {+ Reshaped::new(+ Arc::clone(context),+ embed,+ (),+ |o, ()| modelrunner::nets::gemma4_head::build_plan(o),+ )+ .ok()+ } else {+ None+ }; let reader = embed.reader(); let rotary = weights.reader(); // The tables are read once rather than per step: 2048 rows of fp16 is a few megabytes and@@ -248,15 +317,23 @@ fn generate( if step + 1 < prompt_len { continue; }+ if out.len() != 1 {+ return Err(format!("a step returned {} tensors, not the hidden state", out.len()));+ }+ let hidden = &out[0];+ if hidden.len() != gemma4::D_MODEL as usize {+ return Err(format!(+ "hidden state of {} values, not {}",+ hidden.len(),+ gemma4::D_MODEL+ ));+ }+ let logits = head_logits(context, &mut head, &reader, hidden)?; let mut best = (f32::NEG_INFINITY, 0u32);- let mut base = 0u32;- for split in out.iter().take(gemma4::HEAD_SPLITS) {- for (offset, &value) in split.iter().enumerate() {- if value > best.0 {- best = (value, base + offset as u32);- }+ for (id, &value) in logits.iter().enumerate() {+ if value > best.0 {+ best = (value, id as u32); }- base += split.len() as u32; } if STOP.contains(&best.1) { break;@@ -304,6 +381,19 @@ fn run_chat( Ok(net) => net, Err(why) => return println!("the model did not open: {why}"), };+ // The GPU tied head over the EMBED file, upload-once (`None` on files+ // without head chunks — `head_logits` falls back to the host head).+ let mut head: Option<Reshaped<()>> = if embed.offsets().len() >= modelrunner::nets::gemma4_head::TENSORS_WITH_HEAD {+ Reshaped::new(+ std::sync::Arc::clone(&context),+ embed,+ (),+ |o, ()| modelrunner::nets::gemma4_head::build_plan(o),+ )+ .ok()+ } else {+ None+ }; let reader = embed.reader(); let rotary = weights.reader(); let (local, global) = match (@@ -383,15 +473,20 @@ fn run_chat( spent_infer += at_infer.elapsed(); let at_argmax = Instant::now();+ if out.len() != 1 || out[0].len() != gemma4::D_MODEL as usize {+ break;+ }+ let hidden = &out[0];+ let logits = match head_logits(&context, &mut head, &reader, hidden) {+ Ok(logits) => logits,+ Err(_) => break,+ };+ // Host argmax over the reassembled logits (GPU or host head alike). let mut best = (f32::NEG_INFINITY, 0u32);- let mut base = 0u32;- for split in out.iter().take(gemma4::HEAD_SPLITS) {- for (offset, &value) in split.iter().enumerate() {- if value > best.0 {- best = (value, base + offset as u32);- }+ for (id, &value) in logits.iter().enumerate() {+ if value > best.0 {+ best = (value, id as u32); }- base += split.len() as u32; } spent_argmax += at_argmax.elapsed();
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 488c6ff473..28c45f4300 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -401,6 +401,9 @@ fn log(message: &str) { /// [`Streamed`] and is gathered on the host, exactly as NLLB's tied embedding is. struct Gemma4Handle { net: Reshaped<gemma4::Pass>,+ /// The GPU tied head over the EMBED file, upload-once at construction.+ /// `None` on files without head chunks — the host head covers those.+ head: 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 c2ec9f7ca2..3a8e9d14ba 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -85,7 +85,38 @@ impl Gemma4Handle { if hidden.len() != gemma4::D_MODEL as usize { return Err(format!("hidden state of {} values, not {}", hidden.len(), gemma4::D_MODEL)); }- Ok(Some(self.tied_head_logits(hidden)?))+ Ok(Some(self.head_logits(hidden)?))+ }++ /// Logits for `hidden`, GPU head when the EMBED file carries chunks.+ ///+ /// The device runs the 16 fp16 chunk projections and the host+ /// concatenates the splits, then the same softcap + argmax path as the+ /// host head below. Falls back to `tied_head_logits` on files without+ /// chunks (or when the head net failed to build).+ fn head_logits(&mut self, hidden: &[f32]) -> Result<Vec<f32>, String> {+ let Some(head) = self.head.as_mut() else {+ return self.tied_head_logits(hidden);+ };+ let at = head.at(())?;+ let out = at.infer_raw_many(&[hidden])?;+ if out.len() != crate::nets::gemma4_head::HEAD_CHUNKS {+ return Err(format!(+ "the head returned {} splits, not {}",+ out.len(),+ crate::nets::gemma4_head::HEAD_CHUNKS+ ));+ }+ let mut logits = Vec::with_capacity(gemma4::VOCAB as usize);+ for split in &out {+ if split.len() != crate::nets::gemma4_head::CLASSES_PER_CHUNK as usize {+ return Err(format!("a head split of {} values, not {}", split.len(), crate::nets::gemma4_head::CLASSES_PER_CHUNK));+ }+ for &value in split {+ logits.push(gemma4::LOGIT_CAP * (value / gemma4::LOGIT_CAP).tanh());+ }+ }+ Ok(logits) } /// Tied-head logits on the host: `hidden @ H^T` over the raw-scale head table.@@ -255,8 +286,25 @@ impl Gemma4Handle { )); self.position += width; }- Ok(())+fn gemma4_plan(offsets: &Offsets, pass: gemma4::Pass) -> Result<Plan, String> {+ gemma4::build(offsets, pass)+}++/// 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<()>> {+ let offsets = embed.offsets();+ if offsets.len() < crate::nets::gemma4_head::TENSORS_WITH_HEAD {+ return None; }+ Reshaped::streamed(+ context::shared().ok()?,+ offsets,+ embed,+ (),+ |offsets, ()| crate::nets::gemma4_head::build_plan(offsets),+ )+ .ok() } /// Positions one prefill submit covers. Large enough that a prompt is **one** submit.@@ -405,8 +453,15 @@ fn build_gemma4<'l>( gemma4::Mode::DecodeStep.at(gemma4::CONTEXT_TIERS[0]), gemma4_plan, )?;+ // The GPU tied head, upload-once: a second net over the EMBED file that+ // runs the 16 chunked fp16 head projections per token. `None` on files+ // without the chunks (pre-head-split converts) — the caller falls back+ // to the host head. Uploading the whole EMBED file is the price: there+ // is no partial-upload path, so this is ~2.4 GB resident alongside TEXT.+ let head = gemma4_head_plan(&embed); Ok(Gemma4Handle { net,+ head, weights, embed, tokenizer,
library/ml/src/main/rust/src/nets/gemma4_head.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_head.rs b/library/ml/src/main/rust/src/nets/gemma4_head.rsnew file mode 100644index 0000000000..eab4e57d3b--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -0,0 +1,208 @@+// The Gemma-4 GPU tied head: logits on the device, LiteRT-style.+//+// The text pass (`Mode::DecodeStep`) returns the normed hidden state and the+// host computes `hidden @ HEAD_TABLE^T` in `bridge_part6::tied_head_logits` —+// 4 chunked `fp16_rows` reads that dequant 805 MB fp16->fp32 per token+// (~2 s). This pass runs the same projection on the device: one+// `[1536, 1, 1]` hidden input in, one `[16384, 1, 1]` logits split per chunk+// out, upload-once and submit-per-token.+//+// The head table lives in the EMBED file, so this plan builds over the+// EMBED offsets (one file per plan — see `Builder::new`), with every other+// EMBED tensor named via `host_tensor` (same complement pattern as+// `nllb::name_host_tensors`). The converter emits the chunks as 16 rank-4+// fp16 kernels + zero biases after the legacy rank-2 table+// (`s10_to_maml.collect_embed`); indices 0..111 are unchanged so old files+// without chunks still parse for gather — this plan then fails its `shaped`+// checks and the caller falls back to the host head.+//+// One 262144-wide fp16 tensor spans ~768 MiB, far over the ~96 MiB+// segment-window reach at guaranteed 128 MiB `maxStorageBufferRange`+// (`vulkan::segment::for_op` refuses it: "Split the tensor in the+// converter"). 16x16384 chunks are ~50 MB each — inside the window with+// margin on host and P8. Each chunk lowers to `Kind::ConvPoint`+// (`conv_point.comp`); there is no fp16 `ConvVec`, so the 1-position tiles+// run ~93.75% idle lanes — correct but wasteful, and `ConvVecF16` is the+// follow-up, not this pass.+use super::{Act, Builder, Id, Plan, Shape, WeightSource};+use super::gemma4::{D_MODEL, LAYERS, PER_LAYER, VOCAB};+use super::gemma4::embed;++/// Vocab classes per chunk: 262144 / 16.+pub const CLASSES_PER_CHUNK: u32 = 16384;++/// Head chunks the converter emits. Must match `GEMMA4_HEAD_SPLITS`.+pub const HEAD_CHUNKS: usize = 16;++/// First tensor of the chunked head: kernel of chunk 0.+///+/// Layout after the legacy rank-2 table (tensor 112): chunk `s` owns+/// `HEAD_BASE + s * 2` (fp16 kernel `[CLASSES_PER_CHUNK, 1536, 1, 1]`) and+/// `HEAD_BASE + s * 2 + 1` (fp16 zero bias `[CLASSES_PER_CHUNK]`).+pub const HEAD_BASE: usize = embed::HEAD_CHUNKS;++/// Tensors the chunked head adds: kernel + bias per chunk.+pub const HEAD_CHUNK_TENSORS: usize = HEAD_CHUNKS * 2;++/// Tensors an EMBED file with GPU-head chunks holds.+pub const TENSORS_WITH_HEAD: usize = embed::TENSORS_WITH_HEAD;++/// A `1 x 1` fp16 convolution: the device-side dot of one vocab chunk.+fn point(b: &mut Builder, at: usize, x: Id, out: u32) -> Id {+ b.conv(+ x,+ at,+ out,+ (1, 1),+ (1, 1),+ (1, 1),+ (0, 0, 0, 0),+ 1,+ Act::None,+ )+}++/// Build the head pass over the EMBED file's offsets.+///+/// One `[1536, 1, 1]` hidden-state input, one `[CLASSES_PER_CHUNK, 1, 1]`+/// fp16 output per chunk, in vocab order. The host concatenates the 16+/// splits and runs the existing softcap + argmax, exactly as it does for+/// the host-computed logits today.+pub fn build_plan(weights: &dyn WeightSource) -> Result<Plan, String> {+ let mut builder = Builder::new(weights);+ let b = &mut builder;+ // Every EMBED tensor this pass does not read, named so `finish` accepts+ // the plan. The chunks are the only tensors read; the legacy rank-2+ // table (tensor 112) stays host-side for gather-time fallback.+ for index in 0..TENSORS_WITH_HEAD {+ if index < HEAD_BASE || index >= HEAD_BASE + HEAD_CHUNK_TENSORS {+ b.host_tensor(index, &dims_of(index));+ }+ }+ let x = b.input(Shape::new(D_MODEL, 1, 1));+ let mut outs = Vec::with_capacity(HEAD_CHUNKS);+ let mut next = HEAD_BASE;+ for _ in 0..HEAD_CHUNKS {+ let at = next;+ next += 2;+ outs.push(point(b, at, x, CLASSES_PER_CHUNK));+ }+ if next != HEAD_BASE + HEAD_CHUNK_TENSORS {+ return Err(format!("the head claims {} tensors, not {HEAD_CHUNK_TENSORS}", next - HEAD_BASE));+ }+ builder.finish(&outs)+}++/// The shape of EMBED tensor `index`, derived from the layout constants.+///+/// `host_tensor` checks it against the file, so this is a second statement+/// of the table `s10_to_maml.collect_embed` writes — a converter and a+/// runtime that disagree about a shape fail here rather than on the device.+pub fn dims_of(index: usize) -> Vec<u32> {+ if index < embed::TABLES {+ // Working triple (0-2, int4 kernel + per-block scale + bias),+ // shared projection triple (3-5, int8 kernel + scale + bias),+ // shared norm (6). File kernels are rank-2 [rows, taps] (host+ // readers take rank-2 dims); only Builder::conv demands rank-4.+ if index < 3 {+ return match index {+ 0 => vec![VOCAB, D_MODEL],+ 1 => vec![VOCAB, D_MODEL.div_ceil(crate::weights::I4_BLOCK)],+ _ => vec![VOCAB],+ };+ }+ if index < 6 {+ return match index {+ 3 => vec![+ LAYERS as u32 * PER_LAYER,+ D_MODEL,+ 1,+ 1,+ ],+ 4 => vec![LAYERS as u32 * PER_LAYER],+ _ => vec![LAYERS as u32 * PER_LAYER],+ };+ }+ return vec![PER_LAYER];+ }+ if index < embed::HEAD_TABLE {+ // Per-layer mmap tables: int4 triple each (kernel rank-2+ // [VOCAB, 256], per-block scale, bias).+ return match (index - embed::TABLES) % 3 {+ 0 => vec![VOCAB, PER_LAYER],+ 1 => vec![VOCAB, PER_LAYER.div_ceil(crate::weights::I4_BLOCK)],+ _ => vec![VOCAB],+ };+ }+ if index == embed::HEAD_TABLE {+ // Legacy rank-2 fp16 head table (host path).+ return vec![VOCAB, D_MODEL];+ }+ // Chunked head: kernel, bias alternating.+ if (index - HEAD_BASE) % 2 == 0 {+ vec![CLASSES_PER_CHUNK, D_MODEL, 1, 1]+ } else {+ vec![CLASSES_PER_CHUNK]+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::nets::tests::Shapes;++ #[test]+ fn the_head_layout_matches_the_converter() {+ // `s10_to_maml.collect_embed` head section: legacy rank-2 fp16 table+ // at 112, then 16 rank-4 fp16 kernels + zero biases. Indices 0..111+ // unchanged so old files still parse for gather.+ assert_eq!(embed::HEAD_TABLE, 112);+ assert_eq!(HEAD_BASE, 113);+ assert_eq!(HEAD_CHUNKS, 16);+ assert_eq!(CLASSES_PER_CHUNK, 16384);+ assert_eq!(CLASSES_PER_CHUNK as usize * HEAD_CHUNKS, VOCAB as usize);+ assert_eq!(HEAD_CHUNK_TENSORS, 32);+ assert_eq!(TENSORS_WITH_HEAD, 145);+ assert_eq!(embed::TENSORS_WITH_HEAD, 145);+ }++ #[test]+ fn the_head_pass_builds_and_reads_every_chunk() {+ // One hidden input in, 16 vocab splits out, against the stub source+ // so `Builder::finish`'s unread-tensor invariant does the work: every+ // EMBED tensor is either a chunk this pass reads or named host-side.+ let source = Shapes::new(TENSORS_WITH_HEAD);+ let plan = build_plan(&source).expect("the head pass builds");+ assert_eq!(plan.inputs.len(), 1);+ assert_eq!(plan.inputs[0].shape, Shape::new(D_MODEL, 1, 1));+ assert_eq!(plan.outputs.len(), HEAD_CHUNKS);+ for output in &plan.outputs {+ assert_eq!(output.shape, Shape::new(CLASSES_PER_CHUNK, 1, 1));+ }+ // 16 fp16 1x1 convolutions, one per chunk.+ let mut convs = 0;+ for op in &plan.ops {+ if let crate::nets::Op::Dispatch { kind, .. } = op {+ if matches!(kind, crate::nets::Kind::Conv | crate::nets::Kind::ConvPoint) {+ convs += 1;+ }+ }+ }+ assert_eq!(convs, HEAD_CHUNKS, "one fp16 conv per chunk");+ crate::nets::tests::assert_no_aliasing(&plan);+ let sched = crate::nets::schedule::schedule(&plan);+ crate::nets::schedule::is_sound(&plan, &sched).expect("the head schedule is sound");+ }++ #[test]+ fn the_chunk_shapes_cover_the_vocabulary() {+ // Chunk s owns classes [s * 16384, (s + 1) * 16384): contiguous and+ // gap-free, so concatenating the 16 outputs is the full logits row.+ let mut covered = 0u32;+ for s in 0..HEAD_CHUNKS {+ let _ = s;+ covered += CLASSES_PER_CHUNK;+ }+ assert_eq!(covered, VOCAB);+ }+}
library/ml/src/main/rust/src/nets/gemma4_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part4.rs b/library/ml/src/main/rust/src/nets/gemma4_part4.rsindex f4f80de077..d3aad3429d 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part4.rs@@ -45,6 +45,19 @@ pub mod embed { /// Raw-scale head table (see HEAD_TABLE): the last tensor in the file. pub const HEAD_TENSOR: usize = 7 + super::LAYERS * 3; + /// First tensor of the GPU-head chunks (kernel of chunk 0).+ ///+ /// The converter appends 16 rank-4 fp16 kernels + zero biases+ /// after the legacy rank-2 table (`s10_to_maml.collect_embed`); see+ /// `crate::nets::gemma4_head` for the pass that reads them.+ pub const HEAD_CHUNKS: usize = HEAD_TABLE + 1;++ /// Tensors the chunked GPU head adds: kernel + bias per chunk.+ pub const HEAD_CHUNK_TENSORS: usize = super::super::gemma4_head::HEAD_CHUNKS * 2;++ /// Tensors an EMBED file with GPU-head chunks holds.+ pub const TENSORS_WITH_HEAD: usize = HEAD_TABLE + 1 + HEAD_CHUNK_TENSORS;+ /// Table triple for layer `i`. pub const fn table(i: usize) -> usize { TABLES + i * 3
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 3ea7ca8c4c..96b83ea03a 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_head; pub mod gemma4_vision; pub mod mobilefacenet; pub mod maia;@@ -311,6 +312,12 @@ pub enum Kind { MulScalar, /// Clamp to a `[min, max]` pair held in the weights. See `shaders/clamp.comp`. Clamp,+ /// `clamp(round(x / scale), -128, 127) * scale`, an int8 round-trip at a+ /// per-layer scale. See `shaders/quantize.comp`.+ ///+ /// S10's live attention quantizes the mixture to int8 before the O projection+ /// consumes it; the scale rides the push block like [`Kind::Softcap`]'s cap.+ Quantize, /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum. /// /// `O[h][d][i] = sum_j S[h][i][j] * V[h][d][j]`, attention's weighted sum.
scripts/ml/s10_to_maml.py
diff --git a/scripts/ml/s10_to_maml.py b/scripts/ml/s10_to_maml.pyindex 7e66bc725a..ab48894a9f 100644--- a/scripts/ml/s10_to_maml.py+++ b/scripts/ml/s10_to_maml.py@@ -38,6 +38,13 @@ from tflite.Model import Model S10 = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'analysis', 'base-sections', 'Section10_TFLiteModel_tf_lite_prefill_decode.tflite') +# GPU tied-head chunking (2026-09-26): HEAD_SPLITS rank-4 fp16 chunks of the+# head table, each small enough to fit one Vulkan segment window (~96 MiB at+# guaranteed 128 MiB maxStorageBufferRange). 16 x 16384 x 1536 x 2B ~= 50 MB+# per chunk. Overridable via GEMMA4_HEAD_SPLITS for devices whose+# maxStorageBufferRange queries smaller (raise the count, shrink the chunk).+HEAD_SPLITS = int(os.environ.get('GEMMA4_HEAD_SPLITS', '16'))+ def m_OperatorCode(sg, o): raise NotImplementedError@@ -175,7 +182,26 @@ def collect_text(rdr): # (see nets::gemma4::ONE_SLIDING). Head-dim-wide: [256] and [512]. emit_vec(layers, tensors, 'transformer.ones_sliding', np.ones(256, dtype=np.float32)) emit_vec(layers, tensors, 'transformer.ones_full', np.ones(512, dtype=np.float32))- O_SCALE, FF1_SCALE, PL_SCALE = 4.0, 256.0, 4.0+ # Track E proved the claimed runtime inverse gain does not exist for FF1+ # (hence FF1_SCALE = 1.0 below). The o and pp /4s were the same shape of+ # claim and equally uncompensated: no norm gamma in this file is+ # multiplied, and the runtime applies no inverse gain. At /4 the branches+ # ran at 1/4 trained magnitude on device; the post-branch norms erase the+ # scale but the MM/qint grids then quantize the wrong magnitudes.+ # (Proven at the o-tail: device o-quantize diverges, numpy+ # exact-arithmetic does not.)+ O_SCALE, FF1_SCALE, PL_SCALE = 1.0, 1.0, 1.0+ # NOTE (Track E, 2026-09-24): FF1_SCALE was 256.0 with a comment claiming+ # the runtime re-applies the inverse gain. That gain does not exist+ # anywhere in library/ml/src/main/rust/ (no such const; norm gammas match+ # S10 source exactly), so /256 silently ran every layer's up-path at 1/256+ # trained magnitude on device. Full-scale re-measured safe (worst 21k vs+ # fp16 max 65504).+ # NOTE (parity closure, 2026-09-25): O_SCALE and PL_SCALE were 4.0 with a+ # "Keep /4 on o/pp" note. Same finding as FF1: no compensating gain+ # exists, and the int8 grids quantize absolute magnitudes, so /4 flipped+ # codes at the o-tail. Both are 1.0 now; the quarantine record is in+ # build/gemma4-s10-fullfix/BLESSED.txt. # norm tensor ids per layer_0; other layers resolved by name scan for index in range(35): at = f'layer_{index}'@@ -392,11 +418,40 @@ def collect_embed(rdr): # Head table LAST (see TABLES): appended after the per-layer tables so # their file entries (7+i*3) match the artisan-path file exactly and old # files without a head table still parse for gather.+ #+ # GPU tied-head (2026-09-26): the head is ALSO emitted as HEAD_SPLITS+ # rank-4 fp16 chunks ([N,1536,1,1] + zero [N] bias each) that+ # Builder::conv binds directly (kernel+bias, no bias-free path exists).+ # One 262144-wide fp16 tensor spans ~768 MiB, far over the ~96 MiB+ # segment-window reach at guaranteed 128 MiB maxStorageBufferRange+ # (vulkan/segment.rs `for_op` refuses it: "Split the tensor in the+ # converter"). 16x16384 chunks are ~50 MB each — inside the window with+ # margin on both host and P8. Chunk tensors follow the legacy rank-2+ # table so old files (112 tensors, no head) still parse for gather and+ # indices 0..111 are unchanged; the runtime binds chunks when present+ # and falls back to the host head otherwise. Vocab order is preserved+ # (chunk s holds classes [s*N,(s+1)*N)), so concat(chunks) == table. head = rdr.dequant2(2698, 262144, 1536)- tensors.append(np.ascontiguousarray(head, dtype=np.float32).astype(np.float16))+ head = np.ascontiguousarray(head, dtype=np.float32).astype(np.float16)+ tensors.append(head) layers.append(mc.Layer(len(layers), 'Embedding4', 'head_table', 'Embedding4 raw-scale S10 decode table fp16', len(tensors) - 1, 1))+ n = head.shape[0]+ assert n == 262144, n+ per = n // HEAD_SPLITS+ assert per * HEAD_SPLITS == n, (n, HEAD_SPLITS)+ for s in range(HEAD_SPLITS):+ rows = head[s * per:(s + 1) * per].astype(np.float32)+ assert rows.shape == (per, 1536), rows.shape+ kernel = np.ascontiguousarray(rows.reshape(per, 1536, 1, 1))+ bias = np.zeros(per, dtype=np.float32)+ tensors.extend([kernel, bias])+ layers.append(mc.Layer(len(layers), 'Linear', f'head_split_{s}',+ f'Linear w=[{per}, 1536, 1, 1] dtype=fp16 b=[{per}]',+ len(tensors) - 2, 2))+ print(f'head_table: rank-2 fp16 [{n}, 1536] + {HEAD_SPLITS} rank-4 '+ f'fp16 chunks of [{per}, 1536, 1, 1] (+ zero bias)') fid.report(mc.MIN_INT4_COSINE) return layers, tensors