ml: gemma4 prefill gathers a chunk at once, one device combine; TTFT 4.6 -> 2.8 s
- Commit
6f281ecf0b3a3c6c30e4946bb527868903ef4a5a- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 17:50 UTC (1 month ago)
- Parents
4662bd6
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 a26ac7fecb..c671e1a409 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -83,7 +83,7 @@ struct Args { positional: Vec<String>, head: Option<PathBuf>, time: Option<usize>,- prefill: Option<u32>,+ prefill: Option<Vec<u32>>, sample: bool, topk: bool, split: Option<u32>,@@ -102,7 +102,7 @@ fn parse_args() -> Args { match arg.as_str() { "--head" => args.head = it.next().map(PathBuf::from), "--time" => args.time = it.next().and_then(|n| n.parse().ok()),- "--prefill" => args.prefill = it.next().and_then(|n| n.parse().ok()),+ "--prefill" => args.prefill = it.next().map(|n| n.split(',').filter_map(|w| w.parse().ok()).collect()), "--sample" => args.sample = true, "--topk" => args.topk = true, "--split" => args.split = it.next().and_then(|n| n.parse().ok()),@@ -185,8 +185,8 @@ fn main() { } return print_memory(); }- if let Some(width) = args.prefill {- time_prefill(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, width);+ if let Some(widths) = args.prefill {+ time_prefill(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, &widths); return print_memory(); } match run(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens) {@@ -352,7 +352,7 @@ struct StepTimes { fn decode_one( net: &mut Reshaped<gemma4::Pass>, head: Option<&mut Reshaped<HeadOut>>,- gather: Option<&mut Reshaped<()>>,+ gather: Option<&mut Reshaped<u32>>, embed: &modelrunner::weights::Reader<'_>, rotary: &modelrunner::weights::Reader<'_>, token: u32,@@ -378,7 +378,7 @@ fn decode_one( } let rows_ms = tick.elapsed().as_secs_f64() * 1000.0; let tick = Instant::now();- let out = gather.at(())?.infer_raw_many(&[&hidden, &embedded])?;+ let out = gather.at(1)?.infer_raw_many(&[&hidden, &embedded])?; let per_layer = out.into_iter().next().ok_or("the gather net returned nothing")?; let matmul_ms = tick.elapsed().as_secs_f64() * 1000.0; (hidden, per_layer, gemma4::GatherTimes { rows_ms, bulk_ms: 0.0, matmul_ms })@@ -456,9 +456,7 @@ fn time_decode( Err(why) => return println!("the net does not build: {why}"), }; let mut gather_net = if device_gather {- match Reshaped::windowed(Arc::clone(context), embed.offsets(), embed, &[()], |offsets, ()| {- modelrunner::nets::gemma4_gather::build_plan(offsets)- }) {+ match gather_plan(context, embed) { Ok(net) => Some(net), Err(why) => return println!("the gather net does not build: {why}"), }@@ -544,16 +542,79 @@ fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) { } } -/// Prefill + TTFT probe: a `width`-token prompt (the golden's tokens cycled)-/// in one `Prefill` submit, as `bridge_part6::prefill` does it, then the first-/// decode step with the greedy head. Run twice: cold (records the plan) and warm.+/// The device combine over the EMBED file, uploading only the tensors it reads, keyed by width.+fn gather_plan(context: &Arc<context::Context>, embed: &Streamed) -> Result<Reshaped<u32>, String> {+ Reshaped::windowed(Arc::clone(context), embed.offsets(), embed, &[1], |offsets, width| {+ modelrunner::nets::gemma4_gather::build_plan_at(offsets, width)+ })+}++/// Positions one prefill submit covers. Mirrors the bridge's `CHUNK`.+const CHUNK: usize = 256;++/// Milliseconds per stage of one prompt, summed over its chunks.+#[derive(Default)]+struct PrefillTimes {+ rows: f64,+ combine: f64,+ rotary: f64,+ record: f64,+ 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.+fn prefill_app(+ net: &mut Reshaped<gemma4::Pass>,+ gather: &mut Reshaped<u32>,+ embed: &modelrunner::weights::Reader<'_>,+ rotary: &modelrunner::weights::Reader<'_>,+ prompt: &[u32],+) -> 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 tick = Instant::now();+ let hidden = g::token_rows(embed, chunk)?;+ let embedded = g::layer_rows(embed, chunk)?;+ 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")?;+ times.combine += tick.elapsed().as_secs_f64() * 1000.0;+ let tick = Instant::now();+ let mut local = vec![0f32; (gemma4::HEAD_DIM * width) as usize];+ let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];+ for column in 0..width {+ let position = start + column;+ place(&mut local, &rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?, column, width);+ 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))?;+ 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) })?;+ at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+ times.gpu += tick.elapsed().as_secs_f64() * 1000.0;+ }+ Ok(times)+}++/// TTFT as the app sees it: `prefill_app` for a prompt of each width (the golden's tokens cycled),+/// then the first greedy step (device combine, DecodeStep record, step, head). Each width runs+/// cold then warm, and the widths run back to back as consecutive prompts would. fn time_prefill( context: &Arc<context::Context>, weights: &Streamed, embed: &Streamed, head: Option<&Streamed>, tokens: &[u32],- width: u32,+ widths: &[u32], ) { use std::time::Instant; let mut net = match streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan) {@@ -564,66 +625,66 @@ fn time_prefill( Ok(net) => net, Err(why) => return println!("the head does not build: {why}"), };+ let mut gather = match gather_plan(context, embed) {+ Ok(net) => net,+ Err(why) => return println!("the gather net does not build: {why}"),+ };+ // 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::DecodeStep.at(TIER))?;+ gather.at(chunk)?;+ gather.at(1)?;+ Ok(())+ })();+ if let Err(why) = warmed {+ return println!("the warm-up failed: {why}");+ }+ println!("load-time warm-up {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0); let reader = embed.reader(); let rotary = weights.reader();- if width >= TIER {- return println!("a {width}-token prompt does not fit the {TIER}-position cache");- }- let prompt: Vec<u32> = tokens.iter().copied().cycle().take(width as usize).collect();- let next = tokens[width as usize % tokens.len()];- let mode = gemma4::Mode::PrefillFresh { tokens: width }.at(TIER); let stamps = modelrunner::knobs::is_set("timestamps"); let mut prefill_report = None;- for run in 0..2 {- let start = Instant::now();- let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];- let mut per_layer = vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * 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 (column, &token) in prompt.iter().enumerate() {- let column = column as u32;- let gathered = gemma4::gather(&reader, token)- .and_then(|(h, p)| Ok((h, p, rotary_row(&rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, column)?)))- .and_then(|(h, p, l)| Ok((h, p, l, rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, column)?)));- let Ok((h, p, l, g)) = gathered else { return println!("gather failed at {column}") };- place(&mut hidden, &h, column, width);- place(&mut per_layer, &p, column, width);- place(&mut local, &l, column, width);- place(&mut global, &g, column, width);- }- let gather_ms = start.elapsed().as_secs_f64() * 1000.0;- let tick = Instant::now();- let at = match net.at(mode) {- Ok(at) => at,- Err(why) => return println!("the prefill plan does not build: {why}"),- };- let record_ms = tick.elapsed().as_secs_f64() * 1000.0;- let tick = Instant::now();- let ran = at- .set_params(StepParams { prefix: 0, window_start: 0 })- .and_then(|()| at.infer_raw_many(&[&hidden, &per_layer, &local, &global]));- if let Err(why) = ran {- return println!("the prefill failed: {why}");+ for &width in widths {+ if width == 0 || width >= TIER {+ println!("a {width}-token prompt does not fit the {TIER}-position cache");+ continue; }- let gpu_ms = tick.elapsed().as_secs_f64() * 1000.0;- let prefill_ms = start.elapsed().as_secs_f64() * 1000.0;- if stamps && run == 1 {- prefill_report = at.op_times().ok();+ let prompt: Vec<u32> = tokens.iter().copied().cycle().take(width as usize).collect();+ 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) {+ 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 tick = Instant::now();+ if let Err(why) = net.at(gemma4::Mode::DecodeStep.at(TIER)) {+ return println!("the decode plan does not build: {why}");+ }+ let first_record = tick.elapsed().as_secs_f64() * 1000.0;+ let mut s = StepTimes::default();+ let id = match decode_one(&mut net, head_net.as_mut(), Some(&mut gather), &reader, &rotary, next, width, HeadOut::Greedy, &mut s) {+ Ok(id) => id,+ Err(why) => return println!("the first decode step failed: {why}"),+ };+ let first_ms = tick.elapsed().as_secs_f64() * 1000.0;+ println!(+ "{} prefill {width} tokens: rows {:.0} + combine {:.0} + rotary {:.0} + record {:.0} + gpu {:.0} = {prefill_ms:.0} ms; \+ first token {first_ms:.0} ms (record {first_record:.0}, gather {:.0}, step {:.0}, head {:.0}; id {id:?}); TTFT {:.0} ms",+ if run == 0 { "cold" } else { "warm" },+ p.rows, p.combine, p.rotary, p.record, p.gpu,+ s.rows + s.combine, s.infer, s.head,+ prefill_ms + first_ms,+ ); }- let tick = Instant::now();- let mut times = StepTimes::default();- let id = match decode_one(&mut net, head_net.as_mut(), None, &reader, &rotary, next, width, HeadOut::Greedy, &mut times) {- Ok(id) => id,- Err(why) => return println!("the first decode step failed: {why}"),- };- let first_ms = tick.elapsed().as_secs_f64() * 1000.0;- println!(- "{} prefill {width} tokens: gather {gather_ms:.0} ms, record {record_ms:.0} ms, gpu {gpu_ms:.0} ms \- = {prefill_ms:.0} ms ({:.1} tok/s); first token {first_ms:.0} ms (id {id:?}); TTFT {:.0} ms",- if run == 0 { "cold" } else { "warm" },- f64::from(width) * 1000.0 / prefill_ms,- prefill_ms + first_ms,- ); } if let Some(report) = prefill_report { print_kinds("prefill", &report);@@ -769,6 +830,16 @@ fn split_check( ("batched head + batched tail", run("batched head + batched tail", true, true, false)?), ]; let want = top10(&reference);+ let mut gather = gather_plan(context, embed)?;+ prefill_app(&mut net, &mut gather, &reader, &rotary, body)?;+ 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 variants = [+ variants[0].clone(),+ variants[1].clone(),+ variants[2].clone(),+ ("app path (rows + device combine)", app),+ ]; for (label, logits) in &variants { let got = top10(logits); let max_diff = logits.iter().zip(&reference).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);@@ -789,12 +860,11 @@ fn split_check( fn gather_check(context: &Arc<context::Context>, embed: &Streamed, tokens: &[u32]) -> Result<(), String> { use std::time::Instant; let tick = Instant::now();- let mut net = Reshaped::windowed(Arc::clone(context), embed.offsets(), embed, &[()], |offsets, ()| {- modelrunner::nets::gemma4_gather::build_plan(offsets)- })?;+ let mut net = gather_plan(context, embed)?; println!("gather net built in {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0); let reader = embed.reader(); let (mut host_ms, mut device_ms, mut worst) = (0.0, 0.0, 0f32);+ let mut device_cols = Vec::new(); let repeats = 4; for pass in 0..repeats { for &token in tokens {@@ -814,9 +884,12 @@ fn gather_check(context: &Arc<context::Context>, embed: &Streamed, tokens: &[u32 let host = gemma4::combine_cached(&reader, &hidden, &embedded)?; let host_t = tick.elapsed().as_secs_f64() * 1000.0; let tick = Instant::now();- let out = net.at(())?.infer_raw_many(&[&hidden, &embedded])?;+ let out = net.at(1)?.infer_raw_many(&[&hidden, &embedded])?; let device_t = tick.elapsed().as_secs_f64() * 1000.0; let device = out.into_iter().next().ok_or("the gather net returned nothing")?;+ if pass == 0 {+ device_cols.push(device.clone());+ } if device.len() != host.len() { return Err(format!("device {} values, host {}", device.len(), host.len())); }@@ -835,6 +908,31 @@ fn gather_check(context: &Arc<context::Context>, embed: &Streamed, tokens: &[u32 host_ms / n, device_ms / n );+ // The prefill's batched combine: every column at once, against the per-token device combine.+ use modelrunner::nets::gemma4_gather as g;+ let width = tokens.len();+ let tick = Instant::now();+ let hidden = g::token_rows(&reader, tokens)?;+ let embedded = g::layer_rows(&reader, tokens)?;+ let rows_ms = tick.elapsed().as_secs_f64() * 1000.0;+ let mut wide = Vec::new();+ let mut wide_ms = 0.0;+ for _ in 0..3 {+ let tick = Instant::now();+ wide = net.at(width as u32)?.infer_raw_many(&[&hidden, &embedded])?.into_iter().next().ok_or("no wide combine")?;+ wide_ms = tick.elapsed().as_secs_f64() * 1000.0;+ }+ let (mut identical, mut worst) = (0, 0f32);+ for (at, single) in device_cols.iter().enumerate() {+ let col = g::column(&wide, at, width);+ identical += usize::from(col == *single);+ let scale = single.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6);+ worst = worst.max(col.iter().zip(single).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max) / scale);+ }+ println!(+ "wide combine over {width} columns: rows {rows_ms:.1} ms, combine {wide_ms:.1} ms; \+ {identical}/{width} columns bit-identical to per-token, worst {worst:.5}"+ ); Ok(()) }
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 4a234ffb4d..3b4d245c96 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -24,13 +24,14 @@ fn gather_combine_host( /// The device combine plan over an EMBED file, uploading only the ~13 MB it reads /// (`Reshaped::windowed`), or `None` when the file predates the plan's tensors.-fn gemma4_gather_plan(embed: &Streamed) -> Option<Reshaped<()>> {+/// Keyed by column count: 1 for a decode step, the chunk width for a prefill.+fn gemma4_gather_plan(embed: &Streamed) -> Option<Reshaped<u32>> { Reshaped::windowed( context::shared().ok()?, embed.offsets(), embed,- &[()],- |offsets, ()| crate::nets::gemma4_gather::build_plan(offsets),+ &[1],+ |offsets, width| crate::nets::gemma4_gather::build_plan_at(offsets, width), ) .ok() }@@ -56,18 +57,15 @@ fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<crate::nets::gemma4 /// trades GEMM width against the `8 x CHUNK x context` score maps (4 MB each at 256 x 1024). const CHUNK: u32 = 256; -/// Write one position's `values` into column `column` of a `[C, 1, width]` block.-///-/// The layout is channel-major - channel `c` at `c * width + column` - which is the transpose of-/// how the values arrive. Getting this backwards is not a shape error and produces a prompt whose-/// tokens are scrambled across channels.-fn place(into: &mut [f32], values: &[f32], column: u32, width: u32) {- for (channel, &value) in values.iter().enumerate() {- let at = channel * width as usize + column as usize;- if let Some(slot) = into.get_mut(at) {- *slot = value;- }- }+/// 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.+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))?;+ net.at(gemma4::Mode::PrefillFresh { tokens: width }.at(context))?;+ net.at(gemma4::Mode::DecodeStep.at(context))?;+ Ok(()) } /// The most likely token, and nothing else.@@ -203,17 +201,22 @@ fn build_gemma4<'l>( (u64::from(cache) * u64::from(gemma4::BYTES_PER_POSITION)) / 1_000_000, budget / 1_000_000, ));- let net = Reshaped::streamed(+ let mut net = Reshaped::streamed( context::shared()?, weights.offsets(), &weights, gemma4::Mode::DecodeStep.at(gemma4::CONTEXT_TIERS[0]), gemma4_plan, )?;+ warm_gemma4(&mut net, gemma4::CONTEXT_TIERS[0])?; // Never `Reshaped::streamed` over EMBED: it uploads the whole 3.6 GB file, which on top of // TEXT OOM-kills a Pixel 8. The gather net is windowed to the tensors it reads. let head = head_file.as_ref().and_then(gemma4_head_file_plan);- let gather_net = gemma4_gather_plan(&embed);+ let mut gather_net = gemma4_gather_plan(&embed);+ if let Some(gather) = gather_net.as_mut() {+ gather.at(CHUNK)?;+ gather.at(1)?;+ } Ok(Gemma4Handle { net, head,
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 48d6f1225a..472c0cfe5f 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -407,7 +407,7 @@ struct Gemma4Handle { /// The device combine over the EMBED file, windowed to the ~13 MB it reads: /// host-gathered rows in, combined per-layer block out. `None` falls back to /// the host combine.- gather_net: Option<Reshaped<()>>,+ gather_net: Option<Reshaped<u32>>, /// 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 d8a8961396..f7a816a53d 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -34,32 +34,31 @@ impl Gemma4Handle { /// 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> {+ self.combine_block(hidden, embedded, 1)+ }++ /// The per-layer block for `width` gathered columns laid out `[C, 1, width]`: one+ /// `gather_net` submit for all of them, else the host `combine_cached` column by column.+ fn combine_block(&mut self, hidden: &[f32], embedded: &[f32], width: u32) -> Result<Vec<f32>, String> {+ let len = (gemma4::PER_LAYER as usize) * gemma4::LAYERS * width as usize; if let Some(net) = self.gather_net.as_mut() {- let out = net.at(())?.infer_raw_many(&[hidden, embedded])?;- if out.len() == 1 && out[0].len() == (gemma4::PER_LAYER as usize) * gemma4::LAYERS {+ let out = net.at(width)?.infer_raw_many(&[hidden, embedded])?;+ if out.len() == 1 && out[0].len() == len { return Ok(out.into_iter().next().unwrap_or_default()); } // Wrong shape: fall through to the host combine rather than failing. }- gather_combine_host(&self.embed, hidden, embedded)- }-- /// The per-layer block for a **soft token**: an encoder's output standing in for a token's- /// embedding. The table rows come from the pad token, which is what the reference does - it- /// rewrites the placeholder id to `pad_token_id` before gathering, then overwrites only the- /// hidden state with the encoder's row.- fn gather_soft(&mut self, hidden: &[f32]) -> Result<Vec<f32>, String> {- if hidden.len() != gemma4::D_MODEL as usize {- return Err(format!("a soft hidden state of {} values, not {}", hidden.len(), gemma4::D_MODEL));+ if width == 1 {+ return gather_combine_host(&self.embed, hidden, embedded); }- let reader = self.embed.reader();- 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], 0)?);+ let (wide, mut out) = (width as usize, vec![0f32; len]);+ for at in 0..wide {+ let h = crate::nets::gemma4_gather::column(hidden, at, wide);+ let e = crate::nets::gemma4_gather::column(embedded, at, wide);+ let combined = gather_combine_host(&self.embed, &h, &e)?;+ crate::nets::gemma4_gather::place(&mut out, &combined, at, wide); }- drop(reader);- self.combine(hidden, &embedded)+ Ok(out) } /// Feed one token and return the greedy next token, reduced on the device.@@ -327,6 +326,7 @@ impl Gemma4Handle { gemma4::Mode::DecodeStep.at(tier), gemma4_plan, )?;+ warm_gemma4(&mut rebuilt, tier)?; if let Some(bytes) = &carried { let at = rebuilt.at(gemma4::Mode::DecodeStep.at(tier))?; at.import_pinned(gemma4::CACHE_TENSORS, self.position, bytes)?;@@ -367,11 +367,17 @@ impl Gemma4Handle { )); } // Every chunk attends the whole cache (`attn_cached_multi`), so any split and any- // starting position is correct.+ // 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 rows = chunk.iter().map(|&token| self.gather(token)).collect::<Result<Vec<_>, _>>()?;- self.prefill_rows(&rows, gathering.elapsed())?;+ 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(()) }@@ -393,37 +399,42 @@ impl Gemma4Handle { } for chunk in values.chunks(width * CHUNK as usize) { let gathering = std::time::Instant::now();- let rows = chunk- .chunks_exact(width)- .map(|row| Ok((row.to_vec(), self.gather_soft(row)?)))- .collect::<Result<Vec<_>, String>>()?;- self.prefill_rows(&rows, gathering.elapsed())?;+ 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 `(hidden, per_layer)` rows at the current position.- fn prefill_rows(+ /// One batched `Prefill` submit over `[C, 1, width]` blocks at the current position.+ fn prefill_block( &mut self,- rows: &[(Vec<f32>, Vec<f32>)],- gathered: std::time::Duration,+ hidden: &[f32],+ per_layer: &[f32],+ width: u32,+ rows: std::time::Duration,+ combined: std::time::Duration, ) -> Result<(), String> {- let width = rows.len() as u32;- // Laid out `[C, 1, T]` - channel-major, which is what every op in the pass expects and- // what `cache_write` transposes on the way in.- let mut hidden = vec![0f32; (gemma4::D_MODEL * width) as usize];- let mut per_layer = vec![0f32; (gemma4::PER_LAYER * gemma4::LAYERS as u32 * width) as usize];+ 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 (offset, (h, p)) in rows.iter().enumerate() {- let column = offset as u32;- let position = self.position + column;- place(&mut hidden, h, column, width);- place(&mut per_layer, p, column, width);- let from = (position * gemma4::HEAD_DIM) as usize;- place(&mut local, &self.local[from..from + gemma4::HEAD_DIM as usize], column, width);- let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;- place(&mut global, &self.global[from..from + gemma4::GLOBAL_HEAD_DIM as usize], column, width);+ 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 {@@ -438,12 +449,13 @@ impl Gemma4Handle { window_start: self.position.saturating_sub(gemma4::WINDOW - 1), })?; let ran = std::time::Instant::now();- at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+ 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 gather, {:.0} ms record, {:.0} ms gpu",+ "gemma4 prefill {width} positions at {}: {:.0} ms rows, {:.0} ms combine, {:.0} ms record, {:.0} ms gpu", self.position,- gathered.as_secs_f64() * 1000.0,+ 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, ));
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 85c56d933d..a8f495479c 100644--- a/library/ml/src/main/rust/src/nets/gemma4_gather.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_gather.rs@@ -75,6 +75,12 @@ pub const GATHER_SCALE: f32 = 16.0; /// 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> {+ build_plan_at(weights, 1)+}++/// [`build_plan`] over `width` columns laid out `[C, 1, width]`, the prefill's input layout, so+/// a whole prompt chunk combines in one submit and the output feeds the prefill as it is.+pub fn build_plan_at(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> { use super::gemma4::embed; use super::gemma4::{D_MODEL, EPSILON}; @@ -93,8 +99,8 @@ pub fn build_plan(weights: &dyn WeightSource) -> Result<Plan, String> { 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));+ let hidden = b.input(Shape::new(D_MODEL, 1, width));+ let embedded = b.input(Shape::new(PER_LAYER * LAYERS as u32, 1, width)); // projected = W @ hidden, 8960-wide over the int8 triple. conv_int8 at // 1 position auto-routes to ConvVecInt8 (same as the per-layer@@ -125,6 +131,55 @@ pub fn build_plan(weights: &dyn WeightSource) -> Result<Plan, String> { builder.finish(&[combined]) } +/// 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) {+ *slot = value;+ }+}++/// Column `column` of a channel-major `[C, 1, width]` block.+pub fn column(block: &[f32], column: usize, width: usize) -> Vec<f32> {+ block.iter().skip(column).step_by(width.max(1)).copied().collect()+}++/// The working-table rows of `tokens`, channel-major `[D_MODEL, 1, tokens.len()]`.+pub fn token_rows(reader: &crate::weights::Reader<'_>, tokens: &[u32]) -> Result<Vec<f32>, String> {+ use super::gemma4::{embed, D_MODEL, VOCAB};+ let width = tokens.len();+ let mut block = vec![0f32; D_MODEL as usize * width];+ for (at, &token) in tokens.iter().enumerate() {+ if token >= VOCAB {+ return Err(format!("token {token} is past the {VOCAB}-entry vocabulary"));+ }+ let row = reader.int4_row(embed::TOKENS, embed::TOKENS + 1, &[VOCAB, D_MODEL], token)?;+ place(&mut block, &row, at, width);+ }+ Ok(block)+}++/// The 35 per-layer table rows of each token, concatenated per token and laid out channel-major+/// `[PER_LAYER * LAYERS, 1, tokens.len()]`. Placeholders read row 0, as the export masks them.+pub fn layer_rows(reader: &crate::weights::Reader<'_>, tokens: &[u32]) -> Result<Vec<f32>, String> {+ use super::gemma4::{embed, VOCAB};+ let width = tokens.len();+ let wide = PER_LAYER as usize;+ let mut block = vec![0f32; wide * LAYERS * width];+ for (at, &token) in tokens.iter().enumerate() {+ let row = if embed::PLACEHOLDERS.contains(&token) { 0 } else { token };+ for i in 0..LAYERS {+ let table = embed::table(i);+ let values = reader.int4_row(table, table + 1, &[VOCAB, PER_LAYER], row)?;+ let from = i * wide * width;+ let Some(slab) = block.get_mut(from..from + wide * width) else {+ return Err(format!("layer {i} past a {width}-column block"));+ };+ place(slab, &values, at, width);+ }+ }+ Ok(block)+}+ #[cfg(test)] mod tests { use super::*;@@ -158,4 +213,22 @@ mod tests { let sched = crate::nets::schedule::schedule(&plan); crate::nets::schedule::is_sound(&plan, &sched).expect("the combine schedule is sound"); }++ #[test]+ fn the_wide_combine_pass_keeps_the_prefill_layout() {+ let source = Shapes::new(super::super::gemma4::embed::TENSORS_WITH_HEAD8);+ let plan = build_plan_at(&source, 200).expect("the wide combine pass builds");+ assert_eq!(plan.inputs[0].shape, Shape::new(1536, 1, 200));+ assert_eq!(plan.inputs[1].shape, Shape::new(8960, 1, 200));+ assert_eq!(plan.outputs[0].shape, Shape::new(8960, 1, 200));+ assert_eq!(plan.ops.len(), 5);+ }++ #[test]+ fn place_and_column_round_trip() {+ let mut block = vec![0f32; 3 * 4];+ place(&mut block, &[1.0, 2.0, 3.0], 2, 4);+ assert_eq!(block, vec![0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 3.0, 0.0]);+ assert_eq!(column(&block, 2, 4), vec![1.0, 2.0, 3.0]);+ } }