ml: gemma4 pads prefill chunks to x8, plans off-thread; 163-token TTFT 5.1 -> 2.4 s
- Commit
ca07f52fde81234d165088fb74fc4c7621cf05e6- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 18:03 UTC (1 month ago)
- Parents
6f281ec
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 c671e1a409..5365b2f09b 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -562,24 +562,37 @@ struct PrefillTimes { gpu: f64, } -/// `prompt` at position 0 exactly as `Gemma4Handle::prefill` feeds it: per chunk, the host rows-/// straight into `[C, 1, T]`, one device combine, the rotary rows, then the Prefill record + submit.+/// `prompt` at position 0 exactly as `Gemma4Handle::prefill` feeds it: per chunk (padded to+/// `gemma4_gather::padded` when `pad`), the host rows straight into `[C, 1, T]` while an evicted+/// plan builds on another thread, one device combine, the rotary rows, then the Prefill submit. fn prefill_app( net: &mut Reshaped<gemma4::Pass>, gather: &mut Reshaped<u32>, embed: &modelrunner::weights::Reader<'_>, rotary: &modelrunner::weights::Reader<'_>, prompt: &[u32],+ pad: bool, ) -> Result<PrefillTimes, String> { use modelrunner::nets::gemma4_gather as g; use std::time::Instant; let mut times = PrefillTimes::default(); for (index, chunk) in prompt.chunks(CHUNK).enumerate() { let start = (index * CHUNK) as u32;- let width = chunk.len() as u32;+ let width = if pad { g::padded(chunk.len() as u32, TIER - start) } else { chunk.len() as u32 };+ let mut fed = chunk.to_vec();+ fed.resize(width as usize, 0);+ let mode = if start == 0 { gemma4::Mode::PrefillFresh { tokens: width } } else { gemma4::Mode::Prefill { tokens: width } }.at(TIER);+ let pending = (!net.holds(mode)).then(|| net.planner()); let tick = Instant::now();- let hidden = g::token_rows(embed, chunk)?;- let embedded = g::layer_rows(embed, chunk)?;+ let (rows, plan) = std::thread::scope(|scope| {+ let building = pending.map(|(plan, offsets)| scope.spawn(move || plan(&offsets, mode)));+ let rows = g::token_rows(embed, &fed).and_then(|h| Ok((h, g::layer_rows(embed, &fed)?)));+ (rows, building.map(|thread| thread.join().map_err(|_| "the plan thread panicked".to_string())))+ });+ let (hidden, embedded) = rows?;+ if let Some(plan) = plan {+ net.adopt(mode, plan??);+ } 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")?;@@ -593,9 +606,8 @@ fn prefill_app( place(&mut global, &rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?, column, width); } times.rotary += tick.elapsed().as_secs_f64() * 1000.0;- let mode = if start == 0 { gemma4::Mode::PrefillFresh { tokens: width } } else { gemma4::Mode::Prefill { tokens: width } }; let tick = Instant::now();- let at = net.at(mode.at(TIER))?;+ let at = net.at(mode)?; times.record += tick.elapsed().as_secs_f64() * 1000.0; let tick = Instant::now(); at.set_params(StepParams { prefix: start, window_start: start.saturating_sub(gemma4::WINDOW - 1) })?;@@ -631,13 +643,13 @@ fn time_prefill( }; // As `build_gemma4` warms at load: the arena at the widest chunk, then the decode step. let tick = Instant::now();- let chunk = CHUNK as u32; let warmed = (|| -> Result<(), String> {- net.at(gemma4::Mode::Prefill { tokens: chunk }.at(TIER))?;- net.at(gemma4::Mode::PrefillFresh { tokens: chunk }.at(TIER))?;+ 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))?;- gather.at(chunk)?;- gather.at(1)?;+ for width in [256, 1] {+ gather.at(width)?;+ } Ok(()) })(); if let Err(why) = warmed {@@ -657,13 +669,14 @@ fn time_prefill( let next = tokens[width as usize % tokens.len()]; for run in 0..2 { let start = Instant::now();- let p = match prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt) {+ let p = match prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt, true) { Ok(p) => p, Err(why) => return println!("the prefill failed: {why}"), }; let prefill_ms = start.elapsed().as_secs_f64() * 1000.0; if stamps && run == 1 {- prefill_report = net.at(gemma4::Mode::PrefillFresh { tokens: width.min(CHUNK as u32) }.at(TIER)).and_then(|at| at.op_times()).ok();+ let ran_at = modelrunner::nets::gemma4_gather::padded(width.min(CHUNK as u32), TIER);+ prefill_report = net.at(gemma4::Mode::PrefillFresh { tokens: ran_at }.at(TIER)).and_then(|at| at.op_times()).ok(); } let tick = Instant::now(); if let Err(why) = net.at(gemma4::Mode::DecodeStep.at(TIER)) {@@ -831,9 +844,14 @@ fn split_check( ]; let want = top10(&reference); let mut gather = gather_plan(context, embed)?;- prefill_app(&mut net, &mut gather, &reader, &rotary, body)?;+ prefill_app(&mut net, &mut gather, &reader, &rotary, body, false)?;+ let exact = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?;+ println!(" {:<32} top10 {:?}", "app path, unpadded", top10(&exact));+ prefill_app(&mut net, &mut gather, &reader, &rotary, body, true)?; let app = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?; println!(" {:<32} top10 {:?}", "app path (rows + device combine)", top10(&app));+ let pad_diff = app.iter().zip(&exact).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);+ println!(" padding {} -> {}: max |logit diff| vs unpadded {pad_diff:.4}", body.len(), body.len().div_ceil(8) * 8); let variants = [ variants[0].clone(), variants[1].clone(),
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 3b4d245c96..2a2e97cde5 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -59,7 +59,7 @@ const CHUNK: u32 = 256; /// Grow the arena to the widest prefill chunk, then record the decode step. An arena growth drops /// every kept recording, so without this the first prompt re-records the decode step for the-/// first token; after it a prompt only records its own width and the decode step stays warm.+/// first token. A new prompt width then only records its own plan, built while its rows gather. fn warm_gemma4(net: &mut Reshaped<gemma4::Pass>, context: u32) -> Result<(), String> { let width = CHUNK.min(context); net.at(gemma4::Mode::Prefill { tokens: width }.at(context))?;
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 f7a816a53d..cc75da483e 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -346,120 +346,4 @@ impl Gemma4Handle { Ok(tier) } - /// Feed many tokens in **one** submit, filling the caches and returning nothing.- ///- /// The prompt path, and the reason a conversation starts in under a second rather than in- /// tens of them. At one position a pass is bandwidth-bound: it reads 1.30 GB of weights to- /// produce a single 1536-wide vector, which measured 28.81 ms. At T positions it reads the- /// same 1.30 GB once and every projection becomes a GEMM over T columns, so the weights are- /// amortised T ways.- ///- /// Chunked because each chunk's score maps are eight heads of `T x context`.- fn prefill(&mut self, tokens: &[u32]) -> Result<(), String> {- if tokens.is_empty() {- return Ok(());- }- if self.position as usize + tokens.len() > self.context as usize {- return Err(format!(- "a prompt of {} positions past this device's {} cache",- self.position as usize + tokens.len(),- self.context- ));- }- // Every chunk attends the whole cache (`attn_cached_multi`), so any split and any- // starting position is correct. A chunk's rows gather on the host straight into the- // `[C, 1, T]` layout and combine in one submit, instead of a combine per token.- for chunk in tokens.chunks(CHUNK as usize) {- let gathering = std::time::Instant::now();- let reader = self.embed.reader();- let hidden = crate::nets::gemma4_gather::token_rows(&reader, chunk)?;- let embedded = crate::nets::gemma4_gather::layer_rows(&reader, chunk)?;- drop(reader);- let rows = gathering.elapsed();- let per_layer = self.combine_block(&hidden, &embedded, chunk.len() as u32)?;- self.prefill_block(&hidden, &per_layer, chunk.len() as u32, rows, gathering.elapsed() - rows)?;- }- Ok(())- }-- /// [`prefill`](Self::prefill) for **soft tokens** (`D_MODEL` values per row from the vision- /// or audio encoder), batched the same way instead of one decode-sized pass per row.- fn prefill_soft(&mut self, values: &[f32]) -> Result<(), String> {- let width = gemma4::D_MODEL as usize;- if values.is_empty() || !values.len().is_multiple_of(width) {- return Err(format!("{} values, which is not a whole number of {width}", values.len()));- }- let count = values.len() / width;- if self.position as usize + count > self.context as usize {- return Err(format!(- "{} soft tokens past this device's {} cache",- self.position as usize + count,- self.context- ));- }- for chunk in values.chunks(width * CHUNK as usize) {- let gathering = std::time::Instant::now();- let count = chunk.len() / width;- let mut hidden = vec![0f32; chunk.len()];- for (at, row) in chunk.chunks_exact(width).enumerate() {- crate::nets::gemma4_gather::place(&mut hidden, row, at, count);- }- // Soft rows take the pad token's per-layer rows: the reference rewrites the- // placeholder id to `pad_token_id` before gathering, then overwrites only the hidden.- let reader = self.embed.reader();- let embedded = crate::nets::gemma4_gather::layer_rows(&reader, &vec![0; count])?;- drop(reader);- let rows = gathering.elapsed();- let per_layer = self.combine_block(&hidden, &embedded, count as u32)?;- self.prefill_block(&hidden, &per_layer, count as u32, rows, gathering.elapsed() - rows)?;- }- Ok(())- }-- /// One batched `Prefill` submit over `[C, 1, width]` blocks at the current position.- fn prefill_block(- &mut self,- hidden: &[f32],- per_layer: &[f32],- width: u32,- rows: std::time::Duration,- combined: std::time::Duration,- ) -> Result<(), String> {- let wide = width as usize;- let mut local = vec![0f32; (gemma4::HEAD_DIM * width) as usize];- let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];- for at in 0..wide {- let position = self.position as usize + at;- let (l, g) = (gemma4::HEAD_DIM as usize, gemma4::GLOBAL_HEAD_DIM as usize);- let local_row = self.local.get(position * l..(position + 1) * l).ok_or("past the rotary table")?;- let global_row = self.global.get(position * g..(position + 1) * g).ok_or("past the rotary table")?;- crate::nets::gemma4_gather::place(&mut local, local_row, at, wide);- crate::nets::gemma4_gather::place(&mut global, global_row, at, wide);- }- let submitted = std::time::Instant::now();- let mode = if self.position == 0 {- gemma4::Mode::PrefillFresh { tokens: width }- } else {- gemma4::Mode::Prefill { tokens: width }- };- let at = self.net.at(mode.at(self.context))?;- let recorded = submitted.elapsed();- at.set_params(StepParams {- prefix: self.position,- window_start: self.position.saturating_sub(gemma4::WINDOW - 1),- })?;- let ran = std::time::Instant::now();- at.infer_raw_many(&[hidden, per_layer, &local, &global])?;- // `Reshaped` re-records whenever the width changes, so record time is logged apart.- log(&format!(- "gemma4 prefill {width} positions at {}: {:.0} ms rows, {:.0} ms combine, {:.0} ms record, {:.0} ms gpu",- self.position,- rows.as_secs_f64() * 1000.0,- combined.as_secs_f64() * 1000.0,- recorded.as_secs_f64() * 1000.0,- ran.elapsed().as_secs_f64() * 1000.0,- ));- self.position += width;- Ok(())- } } // close impl Gemma4Handle: everything below is a free function.
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 da36d8d177..b8835404ff 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -275,3 +275,125 @@ impl Gemma4Handle { Ok(pairs) } }++impl Gemma4Handle {+ /// Feed many tokens in **one** submit per chunk, filling the caches and returning nothing.+ ///+ /// At one position a pass reads 1.30 GB of weights for a single 1536-wide vector; at T+ /// positions it reads them once and every projection becomes a GEMM over T columns. Chunked+ /// because each chunk's score maps are eight heads of `T x context`. Every chunk attends the+ /// whole cache (`attn_cached_multi`), so any split and any starting position is correct.+ fn prefill(&mut self, tokens: &[u32]) -> Result<(), String> {+ if self.position as usize + tokens.len() > self.context as usize {+ return Err(format!(+ "a prompt of {} positions past this device's {} cache",+ self.position as usize + tokens.len(),+ self.context+ ));+ }+ for chunk in tokens.chunks(CHUNK as usize) {+ let real = chunk.len() as u32;+ let width = crate::nets::gemma4_gather::padded(real, self.context - self.position);+ // Pad columns feed the pad token; nothing real reads them (see `padded`).+ let mut fed = chunk.to_vec();+ fed.resize(width as usize, 0);+ self.prefill_chunk(real, width, |reader| {+ let hidden = crate::nets::gemma4_gather::token_rows(reader, &fed)?;+ Ok((hidden, crate::nets::gemma4_gather::layer_rows(reader, &fed)?))+ })?;+ }+ Ok(())+ }++ /// [`prefill`](Self::prefill) for **soft tokens** (`D_MODEL` values per row from the vision+ /// or audio encoder). Soft rows take the pad token's per-layer rows: the reference rewrites+ /// the placeholder id to `pad_token_id` before gathering, then overwrites only the hidden.+ fn prefill_soft(&mut self, values: &[f32]) -> Result<(), String> {+ let d = gemma4::D_MODEL as usize;+ if values.is_empty() || !values.len().is_multiple_of(d) {+ return Err(format!("{} values, which is not a whole number of {d}", values.len()));+ }+ if self.position as usize + values.len() / d > self.context as usize {+ return Err(format!(+ "{} soft tokens past this device's {} cache",+ self.position as usize + values.len() / d,+ self.context+ ));+ }+ for chunk in values.chunks(d * CHUNK as usize) {+ let real = (chunk.len() / d) as u32;+ let width = crate::nets::gemma4_gather::padded(real, self.context - self.position);+ self.prefill_chunk(real, width, |reader| {+ let mut hidden = vec![0f32; d * width as usize];+ for (at, row) in chunk.chunks_exact(d).enumerate() {+ crate::nets::gemma4_gather::place(&mut hidden, row, at, width as usize);+ }+ Ok((hidden, crate::nets::gemma4_gather::layer_rows(reader, &vec![0; width as usize])?))+ })?;+ }+ Ok(())+ }++ /// One chunk of `real` positions run at `width`: `rows` gathers the `[C, 1, width]` hidden+ /// and table blocks while the chunk's plan builds on another thread if it was evicted, then+ /// one combine submit and one Prefill submit.+ fn prefill_chunk(+ &mut self,+ real: u32,+ width: u32,+ rows: impl FnOnce(&crate::weights::Reader<'_>) -> Result<(Vec<f32>, Vec<f32>), String>,+ ) -> Result<(), String> {+ let started = std::time::Instant::now();+ let mode = if self.position == 0 {+ gemma4::Mode::PrefillFresh { tokens: width }+ } else {+ gemma4::Mode::Prefill { tokens: width }+ }+ .at(self.context);+ let pending = (!self.net.holds(mode)).then(|| self.net.planner());+ let embed = &self.embed;+ let (gathered, plan) = std::thread::scope(|scope| {+ let building = pending.map(|(plan, offsets)| scope.spawn(move || plan(&offsets, mode)));+ let gathered = rows(&embed.reader());+ let plan = building.map(|thread| thread.join().map_err(|_| "the plan thread panicked".to_string()));+ (gathered, plan)+ });+ let (hidden, embedded) = gathered?;+ if let Some(plan) = plan {+ self.net.adopt(mode, plan??);+ }+ let gathered = started.elapsed();+ let per_layer = self.combine_block(&hidden, &embedded, width)?;+ let combined = started.elapsed() - gathered;+ let wide = width as usize;+ let (l, g) = (gemma4::HEAD_DIM as usize, gemma4::GLOBAL_HEAD_DIM as usize);+ let (mut local, mut global) = (vec![0f32; l * wide], vec![0f32; g * wide]);+ for at in 0..wide {+ let position = self.position as usize + at;+ let local_row = self.local.get(position * l..(position + 1) * l).ok_or("past the rotary table")?;+ let global_row = self.global.get(position * g..(position + 1) * g).ok_or("past the rotary table")?;+ crate::nets::gemma4_gather::place(&mut local, local_row, at, wide);+ crate::nets::gemma4_gather::place(&mut global, global_row, at, wide);+ }+ let submitted = std::time::Instant::now();+ let at = self.net.at(mode)?;+ let recorded = submitted.elapsed();+ at.set_params(StepParams {+ prefix: self.position,+ window_start: self.position.saturating_sub(gemma4::WINDOW - 1),+ })?;+ let ran = std::time::Instant::now();+ at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+ log(&format!(+ "gemma4 prefill {real} positions (run at {width}) at {}: {:.0} ms rows, {:.0} ms combine, \+ {:.0} ms record, {:.0} ms gpu",+ self.position,+ gathered.as_secs_f64() * 1000.0,+ combined.as_secs_f64() * 1000.0,+ recorded.as_secs_f64() * 1000.0,+ ran.elapsed().as_secs_f64() * 1000.0,+ ));+ self.position += real;+ Ok(())+ }+}
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.rsindex a8f495479c..0cbb8b686e 100644--- a/library/ml/src/main/rust/src/nets/gemma4_gather.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_gather.rs@@ -131,6 +131,19 @@ pub fn build_plan_at(weights: &dyn WeightSource, width: u32) -> Result<Plan, Str builder.finish(&[combined]) } +/// Prefill chunks are padded up to a multiple of this many positions, where the int4 GEMM takes+/// its 16-byte activation path: on a Pixel 8 a 163-position chunk cost 4.7 s against 2.5 s at+/// 200. Coarser buckets (64) cost ~0.1 s of GPU on widths that were already aligned.+pub const PAD_TO: u32 = 8;++/// The width to run a `width`-position chunk at when `room` cache positions are free from its+/// start. Exact: queries attend causally, so no real position reads a pad, and the pads' cache+/// slots lie past the prompt, where the next position writes before anything reads.+pub fn padded(width: u32, room: u32) -> u32 {+ let up = width.div_ceil(PAD_TO) * PAD_TO;+ if up <= room { up } else { width }+}+ /// Write one position's `values` into column `column` of a channel-major `[C, 1, width]` block. pub fn place(into: &mut [f32], values: &[f32], column: usize, width: usize) { for (slot, &value) in into.iter_mut().skip(column).step_by(width.max(1)).zip(values) {@@ -224,6 +237,14 @@ mod tests { assert_eq!(plan.ops.len(), 5); } + #[test]+ fn padding_rounds_up_to_the_tile_when_the_cache_has_room() {+ assert_eq!(padded(163, 1024), 168);+ assert_eq!(padded(64, 1024), 64);+ assert_eq!(padded(1, 1024), 8);+ assert_eq!(padded(163, 165), 163);+ }+ #[test] fn place_and_column_round_trip() { let mut block = vec![0f32; 3 * 4];