ml: gemma4 text file carries the per-layer combine, prefill combines in-plan
- Commit
756a5b70c9c1ff2efe4a8e127eb22f20b2ed1c0b- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 19:13 UTC (1 month ago)
- Parents
95ec684
Diff
library/ml/src/main/rust/examples/bake_gemma4_prefix.rs
diff --git a/library/ml/src/main/rust/examples/bake_gemma4_prefix.rs b/library/ml/src/main/rust/examples/bake_gemma4_prefix.rsindex beb32e3633..f0c61cd555 100644--- a/library/ml/src/main/rust/examples/bake_gemma4_prefix.rs+++ b/library/ml/src/main/rust/examples/bake_gemma4_prefix.rs@@ -53,6 +53,13 @@ const MARKERS: [&str; 11] = [ "<|tool_response>", "<tool_response|>", "<|\"|>", ]; +/// Whether the text file carries the combine, so plans take raw per-layer rows.+static FUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++fn gather_in(reader: &modelrunner::weights::Reader<'_>, token: u32) -> Result<(Vec<f32>, Vec<f32>), String> {+ gemma4::gather_input(reader, token, FUSED.load(std::sync::atomic::Ordering::Relaxed))+}+ fn main() { // Reads gemma4_embed.maml whole (3.6 GB of host RAM): an OOM kernel panic on a Pixel 8. if cfg!(target_os = "android") {@@ -83,6 +90,7 @@ fn main() { ) else { return println!("the weights do not parse"); };+ FUSED.store(gemma4::combines_in_plan(&weights), std::sync::atomic::Ordering::Relaxed); let table = match Table::parse_with(&table_bytes, GEMMA) { Ok(table) => table, Err(why) => return println!("the tokenizer does not parse: {why}"),@@ -130,7 +138,7 @@ fn main() { for (offset, &token) in chunk.iter().enumerate() { let column = offset as u32; let position = base + column;- let Ok((h, p)) = gemma4::gather(&reader, token) else {+ let Ok((h, p)) = gather_in(&reader, token) else { return println!("token {token} is not in the embedding"); }; place(&mut hidden, &h, column, width);@@ -256,7 +264,7 @@ fn argmax_next( token: u32, position: u32, ) -> Option<u32> {- let (hidden, per_layer) = gemma4::gather(reader, token).ok()?;+ let (hidden, per_layer) = gather_in(reader, token).ok()?; let from = (position * gemma4::HEAD_DIM) as usize; let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec(); let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;@@ -321,7 +329,7 @@ fn argmax_at( token: u32, position: u32, ) -> Option<u32> {- let (hidden, per_layer) = gemma4::gather(reader, token).ok()?;+ let (hidden, per_layer) = gather_in(reader, token).ok()?; let from = (position * gemma4::HEAD_DIM) as usize; let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec(); let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
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 1f4733a178..2040307bc4 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -75,6 +75,18 @@ fn gemma4_plan(offsets: &modelrunner::weights::Offsets, pass: gemma4::Pass) -> R gemma4::build(offsets, pass) } +/// Whether the text file carries the combine, so plans take raw per-layer rows (set in `main`).+static FUSED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++fn fused() -> bool {+ FUSED.load(std::sync::atomic::Ordering::Relaxed)+}++/// One token's text-plan inputs 0 and 1 for this run's text file.+fn gather_in(embed: &modelrunner::weights::Reader<'_>, token: u32) -> Result<(Vec<f32>, Vec<f32>), String> {+ gemma4::gather_input(embed, token, fused())+}+ fn head_plan(offsets: &modelrunner::weights::Offsets, out: HeadOut) -> Result<modelrunner::nets::Plan, String> { modelrunner::nets::gemma4_head::build_plan_standalone(offsets, out) }@@ -137,6 +149,8 @@ fn main() { Ok(w) => w, Err(why) => return println!("the text model does not stream: {why}"), };+ FUSED.store(gemma4::combines_in_plan(&weights.offsets()), std::sync::atomic::Ordering::Relaxed);+ println!("text plans combine the per-layer rows: {}", fused()); let embed_weights = match open_streamed(&embed, graph::GEMMA4_EMBED) { Ok(w) => w, Err(why) => return println!("the embedding does not stream: {why}"),@@ -283,7 +297,7 @@ fn trace_run( let mut last = (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 (hidden, per_layer) = gather_in(&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)?;@@ -317,7 +331,7 @@ fn tail_run( 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 (hidden, per_layer) = gather_in(&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)?;@@ -367,6 +381,12 @@ fn decode_one( ) -> Result<Option<u32>, String> { use std::time::Instant; let (hidden_in, per_layer, gtimes) = match gather {+ _ if fused() => {+ let tick = Instant::now();+ let (hidden, embedded) = gemma4::gather_input(embed, token, true)?;+ let rows_ms = tick.elapsed().as_secs_f64() * 1000.0;+ (hidden, embedded, gemma4::GatherTimes { rows_ms, bulk_ms: 0.0, matmul_ms: 0.0 })+ } Some(gather) => { let tick = Instant::now(); let hidden = embed.int4_row(@@ -596,7 +616,11 @@ fn prefill_app( let (hidden, embedded) = g::token_rows(embed, &fed).and_then(|h| Ok((h, g::layer_rows(embed, &fed)?)))?; times.rows += tick.elapsed().as_secs_f64() * 1000.0; let tick = Instant::now();- let per_layer = gather.at(width)?.infer_raw_many(&[&hidden, &embedded])?.into_iter().next().ok_or("no combine")?;+ let per_layer = if fused() {+ embedded+ } else {+ gather.at(width)?.infer_raw_many(&[&hidden, &embedded])?.into_iter().next().ok_or("no combine")?+ }; times.combine += tick.elapsed().as_secs_f64() * 1000.0; let tick = Instant::now(); if let Some(thread) = building {@@ -656,7 +680,7 @@ fn time_prefill( net.at(gemma4::Mode::Prefill { tokens: 256 }.at(TIER))?; net.at(gemma4::Mode::PrefillFresh { tokens: 256 }.at(TIER))?; net.at(gemma4::Mode::DecodeStep.at(TIER))?;- for width in [256, 1] {+ for width in [256, 1].into_iter().filter(|_| !fused()) { gather.at(width)?; } if let Some(head) = head_net.as_mut() {@@ -753,7 +777,7 @@ fn feed( if !batched { for (offset, &token) in tokens.iter().enumerate() { let position = start + offset as u32;- let (hidden, per_layer) = gemma4::gather(embed, token)?;+ let (hidden, per_layer) = gather_in(embed, token)?; let local = rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; let global = rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; let at = net.at(gemma4::Mode::Prefill { tokens: 1 }.at(TIER))?;@@ -769,7 +793,7 @@ fn feed( let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize]; for (column, &token) in tokens.iter().enumerate() { let column = column as u32;- let (h, p) = gemma4::gather(embed, token)?;+ let (h, p) = gather_in(embed, token)?; place(&mut hidden, &h, column, width); place(&mut per_layer, &p, column, width); place(&mut local, &rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, start + column)?, column, width);@@ -802,7 +826,7 @@ fn last_logits( token: u32, position: u32, ) -> Result<Vec<f32>, String> {- let (hidden, per_layer) = gemma4::gather(embed, token)?;+ let (hidden, per_layer) = gather_in(embed, token)?; let local = rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?; let global = rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?; let at = net.at(gemma4::Mode::DecodeStep.at(TIER))?;@@ -1014,7 +1038,7 @@ fn soft_check( &[gemma4::VOCAB, gemma4::D_MODEL], token, )?;- let per_layer = gemma4::gather_soft(&reader, &hidden, 0)?;+ let per_layer = gemma4::gather_soft_input(&reader, &hidden, 0, fused())?; rows.push((hidden, per_layer)); } let mut run = |batched: bool| -> Result<Vec<f32>, String> {@@ -1143,7 +1167,7 @@ fn run( if position >= gemma4::MAX_CONTEXT { return Err(format!("position {position} is past MAX_CONTEXT")); }- let (hidden_in, per_layer) = gemma4::gather(&reader, token)?;+ let (hidden_in, per_layer) = gather_in(&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)?;
library/ml/src/main/rust/examples/dump_dev_caches.rs
diff --git a/library/ml/src/main/rust/examples/dump_dev_caches.rs b/library/ml/src/main/rust/examples/dump_dev_caches.rsindex 076d6d01b1..c26feb2a22 100644--- a/library/ml/src/main/rust/examples/dump_dev_caches.rs+++ b/library/ml/src/main/rust/examples/dump_dev_caches.rs@@ -52,7 +52,7 @@ fn main() { let rotary = weights.reader(); for (step, &token) in TOKENS.iter().enumerate() { let position = step as u32;- let (hidden_in, per_layer) = gemma4::gather(&reader, token).unwrap();+ let (hidden_in, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap(); 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);
library/ml/src/main/rust/examples/dump_dev_layers.rs
diff --git a/library/ml/src/main/rust/examples/dump_dev_layers.rs b/library/ml/src/main/rust/examples/dump_dev_layers.rsindex 3b44ec1a52..ffd5a5f8f0 100644--- a/library/ml/src/main/rust/examples/dump_dev_layers.rs+++ b/library/ml/src/main/rust/examples/dump_dev_layers.rs@@ -62,7 +62,7 @@ fn main() { let want_all = dump_all(); for (step, &token) in TOKENS.iter().enumerate() { let position = step as u32;- let (hidden, per_layer) = gemma4::gather(&reader, token).unwrap();+ let (hidden, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap(); let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position); let angles_global =
library/ml/src/main/rust/examples/dump_gemma4_hidden.rs
diff --git a/library/ml/src/main/rust/examples/dump_gemma4_hidden.rs b/library/ml/src/main/rust/examples/dump_gemma4_hidden.rsindex 1357dee340..bbf7c66201 100644--- a/library/ml/src/main/rust/examples/dump_gemma4_hidden.rs+++ b/library/ml/src/main/rust/examples/dump_gemma4_hidden.rs@@ -58,7 +58,7 @@ fn main() { let mut hidden = Vec::new(); for (step, &token) in TOKENS.iter().enumerate() { let position = step as u32;- let (hidden_in, per_layer) = gemma4::gather(&reader, token).unwrap();+ let (hidden_in, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap(); 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);
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 365d3fdd9f..3c1a26f589 100644--- a/library/ml/src/main/rust/examples/probe_gemma4.rs+++ b/library/ml/src/main/rust/examples/probe_gemma4.rs@@ -187,7 +187,7 @@ fn main() { // `<bos>` is 2, and 105 is an ordinary piece. A placeholder is included because it takes the // masked path, which is the one a gather written from the shapes alone would get wrong. for token in [2u32, 105, gemma4::embed::PLACEHOLDERS[0]] {- match gemma4::gather(&reader, token) {+ match gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)) { Ok((hidden, per_layer)) => { let rms = |v: &[f32]| (v.iter().map(|x| x * x).sum::<f32>() / v.len() as f32).sqrt(); println!(
library/ml/src/main/rust/examples/probe_gemma4_nan.rs
diff --git a/library/ml/src/main/rust/examples/probe_gemma4_nan.rs b/library/ml/src/main/rust/examples/probe_gemma4_nan.rsindex acbeaea26e..25bd9d5a64 100644--- a/library/ml/src/main/rust/examples/probe_gemma4_nan.rs+++ b/library/ml/src/main/rust/examples/probe_gemma4_nan.rs@@ -70,7 +70,7 @@ fn main() { let rotary = weights.reader(); // Gather outputs for the last prompt token, as the parity harness feeds them.- let (hidden_in, per_layer) = gemma4::gather(&reader, *TOKENS.last().unwrap()).unwrap();+ let (hidden_in, per_layer) = gemma4::gather_input(&reader, *TOKENS.last().unwrap(), gemma4::combines_in_plan(&weights)).unwrap(); stats("gather hidden", &hidden_in); stats("gather per_layer", &per_layer); @@ -93,7 +93,7 @@ fn main() { let mut failed = None; for (step, &token) in TOKENS.iter().enumerate() { let position = step as u32;- let (hidden_in, per_layer) = gemma4::gather(&reader, token).unwrap();+ let (hidden_in, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)).unwrap(); let angles_local = rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position); let angles_global =
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 fa399a4958..605313abe8 100644--- a/library/ml/src/main/rust/examples/run_gemma4.rs+++ b/library/ml/src/main/rust/examples/run_gemma4.rs@@ -461,7 +461,7 @@ fn generate( for (offset, &token) in chunk.iter().enumerate() { let column = offset as u32; let position = base + column;- let (h, p) = gemma4::gather(&reader, token)?;+ let (h, p) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(weights))?; place(&mut hidden, &h, column, width); place(&mut per_layer, &p, column, width); let take = |table: &[f32], dim: u32| {@@ -498,7 +498,7 @@ fn generate( break; } let token = tokens[step];- let (hidden, per_layer) = gemma4::gather(&reader, token)?;+ let (hidden, per_layer) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(weights))?; let row = |table: &[f32], width: u32| { let from = (position * width) as usize; table[from..from + width as usize].to_vec()@@ -620,7 +620,7 @@ fn run_chat( for (offset, &token) in chunk.iter().enumerate() { let column = offset as u32; let position = base + column;- let Ok((h, p)) = gemma4::gather(&reader, token) else { return };+ let Ok((h, p)) = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(weights)) else { return }; place(&mut hidden, &h, column, width); place(&mut per_layer, &p, column, width); let from = (position * gemma4::HEAD_DIM) as usize;@@ -658,7 +658,7 @@ fn run_chat( for step in 0..limit { let position = (fed + step) as u32; let at_gather = Instant::now();- let Ok((hidden, per_layer)) = gemma4::gather(&reader, next) else { break };+ let Ok((hidden, per_layer)) = gemma4::gather_input(&reader, next, gemma4::combines_in_plan(weights)) else { break }; let from = (position * gemma4::HEAD_DIM) as usize; let al = local[from..from + gemma4::HEAD_DIM as usize].to_vec(); let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;
library/ml/src/main/rust/examples/trace_collapse.rs
diff --git a/library/ml/src/main/rust/examples/trace_collapse.rs b/library/ml/src/main/rust/examples/trace_collapse.rsindex 2cba509ec0..945ce470aa 100644--- a/library/ml/src/main/rust/examples/trace_collapse.rs+++ b/library/ml/src/main/rust/examples/trace_collapse.rs@@ -70,7 +70,7 @@ fn main() { let mut ok = true; for (step, &token) in TOKENS.iter().enumerate() { let position = step as u32;- let gathered = gemma4::gather(&reader, token);+ let gathered = gemma4::gather_input(&reader, token, gemma4::combines_in_plan(&weights)); let (hidden_in, per_layer) = match gathered { Ok(g) => g, Err(why) => {
library/ml/src/main/rust/src/bridge_part11.rs
diff --git a/library/ml/src/main/rust/src/bridge_part11.rs b/library/ml/src/main/rust/src/bridge_part11.rsindex 69f3d198c1..a4ecb633e3 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -220,7 +220,9 @@ fn build_gemma4<'l>( head.at(out)?; } }- let mut gather_net = gemma4_gather_plan(&embed);+ // A text file that carries the combine needs no gather net.+ let fused = weights.len() == gemma4::TENSORS_WITH_COMBINE;+ let mut gather_net = if fused { None } else { gemma4_gather_plan(&embed) }; if let Some(gather) = gather_net.as_mut() { gather.at(CHUNK)?; gather.at(1)?;
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 bb27ac88c0..010f858459 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -30,10 +30,18 @@ impl Gemma4Handle { embedded.extend(reader.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], per_layer_row)?); } drop(reader);+ if self.fused() {+ return Ok((hidden, embedded));+ } let per_layer = self.combine(&hidden, &embedded)?; Ok((hidden, per_layer)) } + /// Whether the text plans combine the raw per-layer rows themselves (`combines_in_plan`).+ fn fused(&self) -> bool {+ self.weights.len() == gemma4::TENSORS_WITH_COMBINE+ }+ /// The per-layer block for already-gathered rows: on `gather_net` when it built, else the /// host `combine_cached` (same projection + grouped norm + scaled add). fn combine(&mut self, hidden: &[f32], embedded: &[f32]) -> Result<Vec<f32>, String> {
library/ml/src/main/rust/src/bridge_part7.rs
diff --git a/library/ml/src/main/rust/src/bridge_part7.rs b/library/ml/src/main/rust/src/bridge_part7.rsindex 95e7decdd4..9b93aab8ef 100644--- a/library/ml/src/main/rust/src/bridge_part7.rs+++ b/library/ml/src/main/rust/src/bridge_part7.rs@@ -456,7 +456,8 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_benchmark } // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live. let handle = unsafe { &mut *(handle as *mut Gemma4Handle) };- let Ok((hidden, per_layer)) = gemma4::gather(&handle.embed.reader(), 2) else {+ let fused = handle.fused();+ let Ok((hidden, per_layer)) = gemma4::gather_input(&handle.embed.reader(), 2, fused) else { return -1; }; let local = handle.local[..gemma4::HEAD_DIM as usize].to_vec();
library/ml/src/main/rust/src/bridge_part9.rs
diff --git a/library/ml/src/main/rust/src/bridge_part9.rs b/library/ml/src/main/rust/src/bridge_part9.rsindex 36da7fb141..c500ea3fef 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -401,7 +401,7 @@ impl Gemma4Handle { let building = pending.map(|(plan, offsets)| std::thread::spawn(move || plan(&offsets, mode))); let (hidden, embedded) = rows(&self.embed.reader())?; let gathered = started.elapsed();- let per_layer = self.combine_block(&hidden, &embedded, width)?;+ let per_layer = if self.fused() { embedded } else { self.combine_block(&hidden, &embedded, width)? }; let combined = started.elapsed() - gathered; if let Some(thread) = building { let plan = thread.join().map_err(|_| "the plan thread panicked".to_string())?;
library/ml/src/main/rust/src/nets/gemma4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4.rs b/library/ml/src/main/rust/src/nets/gemma4.rsindex d35b2fcf3d..cbedd37d02 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -435,4 +435,5 @@ include!("gemma4_part4.rs"); include!("gemma4_part5.rs"); include!("gemma4_part6.rs"); include!("gemma4_part7.rs");-include!("gemma4_part8.rs");\ No newline at end of file+include!("gemma4_part8.rs");+include!("gemma4_part9.rs");\ No newline at end of file
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex ca8ee5a589..c6a2a382ff 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -173,11 +173,12 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { _ => 1, }; let mut x = b.input(Shape::new(D_MODEL, 1, width));- // Already combined by the host (see [`super::gather`]): the shared projection- // lives in the embed file, so the device never sees the two halves.- let per_layer_inputs = b.input(Shape::new(PER_LAYER * LAYERS as u32, 1, width));+ // Combined by the host, or raw rows this plan combines (see `combines_in_plan`).+ let per_layer_in = b.input(Shape::new(PER_LAYER * LAYERS as u32, 1, width)); let angles_local = b.input(Shape::new(HEAD_DIM, 1, width)); let angles_global = b.input(Shape::new(GLOBAL_HEAD_DIM, 1, width));+ let fused = combines_in_plan(weights);+ let per_layer_inputs = if fused { combine_in_plan(b, x, per_layer_in) } else { per_layer_in }; // The rotary tables. Read on the host, a row at a time, and handed back as the two angle // inputs above - the same arrangement as the embedding. b.host_tensor(ROTARY_LOCAL, &[MAX_CONTEXT, HEAD_DIM]);
library/ml/src/main/rust/src/nets/gemma4_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part9.rs b/library/ml/src/main/rust/src/nets/gemma4_part9.rsnew file mode 100644index 0000000000..895c2920c5--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_part9.rs@@ -0,0 +1,94 @@+// The per-layer combine inside the text plans, for text files that carry its weights.+//+// The converter appends a copy of the EMBED file's `SHARED_PROJ` triple and `SHARED_NORM` to+// the text file (`s10_to_maml.emit_combine`). A plan over such a file takes the raw per-layer+// rows as input 1 and combines them in the same submit, so a prompt skips the separate combine+// plan and its readback. Files without them keep the combined-on-the-side input.++/// The appended `SHARED_PROJ` triple: int8 `[LAYERS * PER_LAYER, D_MODEL, 1, 1]`, scale, bias.+pub const COMBINE_PROJ: usize = TENSORS;++/// The appended `SHARED_NORM`, `[PER_LAYER]`.+pub const COMBINE_NORM: usize = COMBINE_PROJ + PROJECTION_TENSORS;++/// Tensors a text file that carries the combine holds.+pub const TENSORS_WITH_COMBINE: usize = COMBINE_NORM + 1;++/// Whether plans over `weights` take raw per-layer rows and combine them themselves.+pub fn combines_in_plan(weights: &dyn WeightSource) -> bool {+ weights.count() == TENSORS_WITH_COMBINE+}++/// `(16 * rows + rms_norm(SHARED_PROJ @ hidden)) / sqrt(2)` per 256-wide group, exactly+/// `gemma4_gather::build_plan_at` over the text file's copy of its tensors.+fn combine_in_plan(b: &mut Builder, hidden: Id, rows: Id) -> Id {+ let wide = PER_LAYER * LAYERS as u32;+ let projected = b.conv_int8(hidden, COMBINE_PROJ, wide, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+ let normed = b.rms_norm_grouped(projected, COMBINE_NORM, EPSILON, LAYERS as u32);+ let scaled = b.affine(rows, super::gemma4_gather::GATHER_SCALE, 0.0);+ let summed = b.add(scaled, normed);+ b.affine(summed, std::f32::consts::FRAC_1_SQRT_2, 0.0)+}++/// One token's plan inputs 0 and 1 for a text file: the working row and either the raw+/// per-layer rows (`fused`, see [`combines_in_plan`]) or the host-combined block.+pub fn gather_input(+ embed: &crate::weights::Reader<'_>,+ token: u32,+ fused: bool,+) -> Result<(Vec<f32>, Vec<f32>), String> {+ if !fused {+ return gather(embed, token);+ }+ let tokens = [token];+ let hidden = super::gemma4_gather::token_rows(embed, &tokens)?;+ Ok((hidden, super::gemma4_gather::layer_rows(embed, &tokens)?))+}++/// [`gather_soft`]'s plan input 1 for a text file: raw row-`token` rows when `fused`.+pub fn gather_soft_input(+ embed: &crate::weights::Reader<'_>,+ hidden: &[f32],+ token: u32,+ fused: bool,+) -> Result<Vec<f32>, String> {+ if !fused {+ return gather_soft(embed, hidden, token);+ }+ let mut embedded = Vec::with_capacity((PER_LAYER as usize) * LAYERS);+ for i in 0..LAYERS {+ let at = embed::table(i);+ embedded.extend(embed.int4_row(at, at + 1, &[VOCAB, PER_LAYER], token)?);+ }+ Ok(embedded)+}++#[cfg(test)]+mod combine_in_plan_tests {+ use super::*;+ use crate::nets::tests::Shapes;++ const TEST_CONTEXT: u32 = CONTEXT_TIERS[0];++ #[test]+ fn a_text_file_with_the_combine_reads_it_in_every_mode() {+ let source = Shapes::new(TENSORS_WITH_COMBINE);+ assert!(combines_in_plan(&source));+ assert!(!combines_in_plan(&Shapes::new(TENSORS)));+ for mode in [+ Mode::DecodeStep,+ Mode::Prefill { tokens: 8 },+ Mode::PrefillFresh { tokens: 8 },+ Mode::Trace { layers: 0 },+ Mode::TraceTail,+ ] {+ let fused = build(&source, mode.at(TEST_CONTEXT)).expect("builds with the combine");+ let plain = build(&Shapes::new(TENSORS), mode.at(TEST_CONTEXT)).expect("builds without");+ assert_eq!(fused.inputs.len(), plain.inputs.len(), "{mode:?}");+ assert_eq!(fused.inputs[1].shape, plain.inputs[1].shape, "{mode:?}");+ // conv + grouped norm + up to two affines and an add (the add may fold).+ let extra = fused.ops.len() - plain.ops.len();+ assert!((3..=5).contains(&extra), "{mode:?} added {extra} ops");+ }+ }+}
scripts/ml/s10_to_maml.py
diff --git a/scripts/ml/s10_to_maml.py b/scripts/ml/s10_to_maml.pyindex 42c6cb86e0..1e9340cbf7 100644--- a/scripts/ml/s10_to_maml.py+++ b/scripts/ml/s10_to_maml.py@@ -13,7 +13,7 @@ different checkpoint's arrangement); the tied head reads it raw-scale Usage: GEMMA4_EMBED_DUMP=analysis/maml-rebuild/embed_s2_fp32.bin \ python scripts/ml/s10_to_maml.py -o build/gemma4-s10 --print-digest-+ (--text-only writes gemma4_text.maml alone and needs no dump.) Then: cargo run --offline --release -p modelrunner --example check_gemma4_parity -- \ build/gemma4-s10/gemma4_text.maml build/gemma4-s10/gemma4_embed.maml \@@ -357,14 +357,28 @@ def collect_text(rdr): layers.append(mc.Layer(len(layers), 'MulScalar', f'transformer.layer_{index}.skip.scale', 'MulScalar s=[1]', len(tensors) - 1, 1))+ # The per-layer combine's projection + norm, byte-identical to the embed+ # file's tensors 3-6, appended so the text plans combine in their own+ # submit (nets::gemma4::COMBINE_PROJ). Last, so every other index holds.+ emit_combine(fid, layers, tensors, rdr) fid.report(mc.MIN_INT4_COSINE) return layers, tensors +def emit_combine(fid, layers, tensors, rdr):+ """S10 t312 (int8 [8960,1536], 1 scale/row) + norm gamma t305 (256)."""+ emit8(fid, layers, tensors, 'transformer.embedder.per_layer_model_projection.w',+ rdr.dequant8(312, 8960, 1536))+ emit_vec(layers, tensors, 'transformer.embedder.per_layer_projection_norm.scale',+ rdr.f32(305))++ def main(): ap = argparse.ArgumentParser() ap.add_argument('-o', '--outdir', required=True) ap.add_argument('--print-digest', action='store_true')+ ap.add_argument('--text-only', action='store_true',+ help='write gemma4_text.maml only (no embed dump needed)') args = ap.parse_args() os.makedirs(args.outdir, exist_ok=True) rdr = S10Reader(S10)@@ -377,6 +391,8 @@ def main(): out = os.path.join(args.outdir, 'gemma4_text.maml') open(out, 'wb').write(blob) print(f'wrote {out} ({len(blob)} bytes)')+ if args.text_only:+ return elayers, etensors = collect_embed(rdr) edigest = mc.layer_table_digest(elayers) print(f's10_embed: {len(elayers)} layers, {len(etensors)} tensors, digest {edigest}')@@ -450,10 +466,7 @@ def collect_embed(rdr): art = lt.LitertlmReader(art_path) if s3rdr is None else None if s3rdr is None and art is None: raise SystemExit('collect_embed needs S3 (analysis/base-sections/...) or the artisan file')- emit8(fid, layers, tensors, 'transformer.embedder.per_layer_model_projection.w',- rdr.dequant8(312, 8960, 1536))- emit_vec(layers, tensors, 'transformer.embedder.per_layer_projection_norm.scale',- rdr.f32(305))+ emit_combine(fid, layers, tensors, rdr) for index in range(35): if s3rdr is not None: out = s3rdr.table(index)