ml: gemma4 runs a step's token with the pending prompt, no first decode step
- Commit
1a924eb9991e98daf7184404b5a2bd450fde883f- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 18:28 UTC (1 month ago)
- Parents
d5e989d
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 5365b2f09b..5b5a465c84 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -90,13 +90,14 @@ struct Args { len: Option<u32>, gather: bool, soft: bool,+ spread: bool, } /// `--head <path>`, `--time <repeats>`, `--prefill <tokens>`, `--sample`; the /// rest are positional: text embed golden [trace] [tail] [head]. fn parse_args() -> Args { let mut args =- Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, topk: false, split: None, len: None, gather: false, soft: false };+ Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, topk: false, split: None, len: None, gather: false, soft: false, spread: false }; let mut it = std::env::args().skip(1); while let Some(arg) = it.next() { match arg.as_str() {@@ -109,6 +110,7 @@ fn parse_args() -> Args { "--len" => args.len = it.next().and_then(|n| n.parse().ok()), "--gather" => args.gather = true, "--soft" => args.soft = true,+ "--spread" => args.spread = true, _ => args.positional.push(arg), } }@@ -186,7 +188,10 @@ fn main() { return print_memory(); } if let Some(widths) = args.prefill {- time_prefill(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, &widths);+ // `--spread`: a prompt of distinct ids, where no row read repeats (the golden cycles 6).+ let spread: Vec<u32> = (0..TIER).map(|i| (i * 7919 + 1000) % 250_000).collect();+ let prompt = if args.spread { &spread } else { &tokens };+ time_prefill(&context, &weights, &embed_weights, head_weights.as_ref(), prompt, &widths); return print_memory(); } match run(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens) {@@ -560,6 +565,8 @@ struct PrefillTimes { rotary: f64, record: f64, gpu: f64,+ /// The last token's final-normed state, which the head reads.+ state: Vec<f32>, } /// `prompt` at position 0 exactly as `Gemma4Handle::prefill` feeds it: per chunk (padded to@@ -611,8 +618,10 @@ fn prefill_app( 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])?;+ let out = at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?; times.gpu += tick.elapsed().as_secs_f64() * 1000.0;+ let states = out.first().ok_or("a prefill returned nothing")?;+ times.state = g::column(states, chunk.len() - 1, width as usize); } Ok(times) }@@ -667,37 +676,52 @@ fn time_prefill( } let prompt: Vec<u32> = tokens.iter().copied().cycle().take(width as usize).collect(); let next = tokens[width as usize % tokens.len()];+ // The app's flow: Kotlin pushes the prompt, then steps its last token; native runs them as+ // one prefill and the head reads the last column (`Gemma4Handle::fold_pending`).+ let folded: Vec<u32> = prompt.iter().copied().chain([next]).collect(); for run in 0..2 { let start = Instant::now();- let p = match prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt, true) {+ let p = match prefill_app(&mut net, &mut gather, &reader, &rotary, &folded, 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 {- let ran_at = modelrunner::nets::gemma4_gather::padded(width.min(CHUNK as u32), TIER);+ let ran_at = modelrunner::nets::gemma4_gather::padded((width + 1).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)) {- 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 id = match head_net.as_mut().map(|h| h.at(HeadOut::Greedy).and_then(|at| at.infer_raw_many(&[&p.state]))) {+ Some(Ok(out)) => out.last().filter(|id| id.len() == 2).map(|id| id[1] as u32 * 2048 + id[0] as u32),+ Some(Err(why)) => return println!("the head failed: {why}"),+ None => None, };- let first_ms = tick.elapsed().as_secs_f64() * 1000.0;+ let head_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",+ "{} prefill {width}+1 tokens: rows {:.0} + combine {:.0} + rotary {:.0} + record {:.0} + gpu {:.0} = {prefill_ms:.0} ms; \+ head {head_ms:.0} ms (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,+ prefill_ms + head_ms, ); }+ // The old flow once (prefill the prompt, then a decode step), for the token to match.+ let tick = Instant::now();+ let unfolded = prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt, true).and_then(|_| {+ let mut s = StepTimes::default();+ decode_one(&mut net, head_net.as_mut(), Some(&mut gather), &reader, &rotary, next, width, HeadOut::Greedy, &mut s)+ });+ println!(" decode-step flow: id {unfolded:?}, {:.0} ms", tick.elapsed().as_secs_f64() * 1000.0);+ let margins = (|| -> Result<String, String> {+ let head = head_net.as_mut().ok_or("no head")?;+ let p = prefill_app(&mut net, &mut gather, &reader, &rotary, &folded, true)?;+ let a = softcapped(&head.at(HeadOut::Logits)?.infer_raw_many(&[&p.state])?)?;+ prefill_app(&mut net, &mut gather, &reader, &rotary, &prompt, true)?;+ let b = last_logits(&mut net, head, &reader, &rotary, next, width)?;+ let top3 = |l: &[f32]| top10(l).into_iter().take(3).map(|i| (i, l[i as usize])).collect::<Vec<_>>();+ Ok(format!("folded {:?} / decode-step {:?}", top3(&a), top3(&b)))+ })();+ println!(" top3 {margins:?}"); } if let Some(report) = prefill_report { print_kinds("prefill", &report);@@ -852,11 +876,15 @@ fn split_check( 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 folded = prefill_app(&mut net, &mut gather, &reader, &rotary, prompt, true)?;+ let folded = softcapped(&head_net.at(HeadOut::Logits)?.infer_raw_many(&[&folded.state])?)?;+ println!(" {:<32} top10 {:?}", "app path, last token folded", top10(&folded)); let variants = [ variants[0].clone(), variants[1].clone(), variants[2].clone(), ("app path (rows + device combine)", app),+ ("app path, last token folded", folded), ]; for (label, logits) in &variants { let got = top10(logits);
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 2a2e97cde5..22dae55ae0 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -234,6 +234,7 @@ fn build_gemma4<'l>( // something else was killed. context: gemma4::CONTEXT_TIERS[0], position: 0,+ pending: Vec::new(), }) }
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 472c0cfe5f..0a0dbcf29c 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -444,6 +444,9 @@ struct Gemma4Handle { /// `[window_start, prefix]`, so rows past the new prefix are never looked at again and /// overwriting them lazily is free. position: u32,+ /// Pushed tokens not yet in the cache: held so the next step runs them and its own token as+ /// one prefill and reads its logits off the last column, with no decode step of its own.+ pending: Vec<u32>, } fn gemma4_plan(offsets: &Offsets, pass: gemma4::Pass) -> Result<Plan, String> {
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 cc75da483e..bb27ac88c0 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -1,6 +1,9 @@ impl Gemma4Handle { /// Feed one token and return its logits, or `None` while only filling the cache. fn step(&mut self, token: u32, want_logits: bool) -> Result<Option<Vec<f32>>, String> {+ if let Some(state) = self.fold_pending(token)? {+ return if want_logits { self.head_logits(&state).map(Some) } else { Ok(None) };+ } let (hidden, per_layer) = self.gather(token)?; self.step_hidden(&hidden, &per_layer, want_logits) }@@ -70,6 +73,9 @@ impl Gemma4Handle { /// when the head net is absent. The sampling path (`logitsGemma4`) never /// calls this — it needs the full logits. fn step_greedy(&mut self, token: u32) -> Result<u32, String> {+ if let Some(state) = self.fold_pending(token)? {+ return self.head_greedy(&state);+ } let (hidden, per_layer) = self.gather(token)?; self.step_hidden_greedy(&hidden, &per_layer) }
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 2085596396..95e7decdd4 100644--- a/library/ml/src/main/rust/src/bridge_part7.rs+++ b/library/ml/src/main/rust/src/bridge_part7.rs@@ -94,8 +94,8 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_pushGemma .map_err(|_| format!("token {token} is not in the vocabulary"))?, ); }- handle.prefill(&owned)?;- Ok(handle.position)+ handle.push(&owned)?;+ Ok(handle.fed()) }); Ok(match pushed { Ok(position) => jint::try_from(position).unwrap_or(-1),@@ -207,7 +207,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_positionG } // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live. let handle = unsafe { &*(handle as *const Gemma4Handle) };- jint::try_from(handle.position).unwrap_or(-1)+ jint::try_from(handle.fed()).unwrap_or(-1) } /// A weight source for the scaling probe: every tensor at offset zero.@@ -489,5 +489,6 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_benchmark log(&format!("gemma4 benchmark {label}: {best:.0} ms")); } handle.position = 0;+ handle.pending.clear(); -1 }
library/ml/src/main/rust/src/bridge_part8.rs
diff --git a/library/ml/src/main/rust/src/bridge_part8.rs b/library/ml/src/main/rust/src/bridge_part8.rsindex ee466471a5..9808c5840e 100644--- a/library/ml/src/main/rust/src/bridge_part8.rs+++ b/library/ml/src/main/rust/src/bridge_part8.rs@@ -48,6 +48,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_loadPrefi let at = handle.net.at(gemma4::Mode::DecodeStep.at(handle.context))?; at.import_pinned(gemma4::CACHE_TENSORS, positions, &bytes)?; handle.position = positions;+ handle.pending.clear(); Ok(positions) }); Ok(match loaded {@@ -154,6 +155,12 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_seekGemma match u32::try_from(position) { Ok(position) if position <= handle.position => { handle.position = position;+ handle.pending.clear();+ jint::try_from(position).unwrap_or(-1)+ }+ // Inside what was pushed but not yet run: keep that much of it.+ Ok(position) if position <= handle.fed() => {+ handle.pending.truncate((position - handle.position) as usize); jint::try_from(position).unwrap_or(-1) } // Forward is refused: those rows were never written, so attending over them would read@@ -186,6 +193,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_resetGemm // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live. let handle = unsafe { &mut *(handle as *mut Gemma4Handle) }; handle.position = 0;+ handle.pending.clear(); } /// Release the handle. Idempotent from Kotlin's side, which zeroes its field first.@@ -234,6 +242,8 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_pushSoftG // that no other call on it overlaps this one. let handle = unsafe { &mut *(handle as *mut Gemma4Handle) }; let fed = read_float_array(env, &embeddings).and_then(|values| {+ // Soft tokens follow whatever was pushed before them, so that goes in first.+ handle.flush()?; handle.prefill_soft(&values)?; Ok((values.len() / gemma4::D_MODEL as usize) as jint) });
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 b8835404ff..4cbeb0f667 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -258,8 +258,13 @@ impl Gemma4Handle { let logits = self.step(token, true)?.ok_or("a decode step returned no logits")?; return Ok(top_k_pairs(&logits, k)); }- let (hidden, per_layer) = self.gather(token)?;- let state = self.decode_state(&hidden, &per_layer)?;+ let state = match self.fold_pending(token)? {+ Some(state) => state,+ None => {+ let (hidden, per_layer) = self.gather(token)?;+ self.decode_state(&hidden, &per_layer)?+ }+ }; let Some(head) = self.head.as_mut() else { return Err("the head disappeared".into()) }; let out = head.at(HeadOut::TopK)?.infer_raw_many(&[&state])?; let triples = out.first().ok_or("the top-k head returned nothing")?;@@ -277,13 +282,53 @@ impl Gemma4Handle { } impl Gemma4Handle {- /// Feed many tokens in **one** submit per chunk, filling the caches and returning nothing.+ /// Take pushed tokens into `pending`, refusing what the cache cannot hold. They run with the+ /// next step's token (see [`fold_pending`](Self::fold_pending)), or at the next [`flush`](Self::flush).+ fn push(&mut self, tokens: &[u32]) -> Result<(), String> {+ let total = self.position as usize + self.pending.len() + tokens.len();+ if total > self.context as usize {+ return Err(format!("a prompt of {total} positions past this device's {} cache", self.context));+ }+ if let Some(bad) = tokens.iter().find(|&&t| t >= gemma4::VOCAB) {+ return Err(format!("token {bad} is past the {}-entry vocabulary", gemma4::VOCAB));+ }+ self.pending.extend_from_slice(tokens);+ Ok(())+ }++ /// Positions the cache holds once `pending` is in it: what Kotlin counts.+ fn fed(&self) -> u32 {+ self.position + self.pending.len() as u32+ }++ /// Prefill `pending` now, for any call that needs the cache to hold it.+ fn flush(&mut self) -> Result<(), String> {+ let tokens = std::mem::take(&mut self.pending);+ if !tokens.is_empty() {+ self.prefill(&tokens)?;+ }+ Ok(())+ }++ /// `pending` and `token` as one prefill, returning `token`'s normed state for the head, or+ /// `None` when nothing is pending and the step runs as a decode step.+ fn fold_pending(&mut self, token: u32) -> Result<Option<Vec<f32>>, String> {+ if self.pending.is_empty() {+ return Ok(None);+ }+ let mut tokens = std::mem::take(&mut self.pending);+ tokens.push(token);+ self.prefill(&tokens).map(Some)+ }++ /// Feed many tokens in **one** submit per chunk, filling the caches. Returns the last token's+ /// final-normed state, which the head reads when that token is a step's. /// /// 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> {+ fn prefill(&mut self, tokens: &[u32]) -> Result<Vec<f32>, String> { if self.position as usize + tokens.len() > self.context as usize { return Err(format!( "a prompt of {} positions past this device's {} cache",@@ -291,18 +336,19 @@ impl Gemma4Handle { self.context )); }+ let mut state = Vec::new(); 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| {+ state = 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(())+ Ok(state) } /// [`prefill`](Self::prefill) for **soft tokens** (`D_MODEL` values per row from the vision@@ -336,13 +382,13 @@ impl Gemma4Handle { /// 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.+ /// one combine submit and one Prefill submit. Returns the last real column's normed state. fn prefill_chunk( &mut self, real: u32, width: u32, rows: impl FnOnce(&crate::weights::Reader<'_>) -> Result<(Vec<f32>, Vec<f32>), String>,- ) -> Result<(), String> {+ ) -> Result<Vec<f32>, String> { let started = std::time::Instant::now(); let mode = if self.position == 0 { gemma4::Mode::PrefillFresh { tokens: width }@@ -383,7 +429,7 @@ 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])?;+ let out = 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",@@ -394,6 +440,7 @@ impl Gemma4Handle { ran.elapsed().as_secs_f64() * 1000.0, )); self.position += real;- Ok(())+ let states = out.first().ok_or("a prefill returned nothing")?;+ Ok(crate::nets::gemma4_gather::column(states, real.saturating_sub(1) as usize, wide)) } }
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 ed335caf2e..ca8ee5a589 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -247,15 +247,12 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> { } if let Mode::Prefill { .. } | Mode::PrefillFresh { .. } = mode {- // Prefill runs every layer - the point is the caches those layers fill - and then stops.- // The head and the final norm are named rather than evaluated, exactly as a trace names- // the layers it stops short of.- name_head(b);- // `finish` needs an output and the hidden state is the only thing left. A prefill's real- // product is the thirty caches, which are `persistent` and so are not outputs at all;- // returning `x` costs nothing, since it is already in the arena, and gives the host- // something to sanity-check a pass against.- return builder.finish(&[x]);+ // Prefill runs every layer - the point is the caches those layers fill - and then the+ // final norm, so the host can run the head on the last column: a prompt's final token+ // rides its prefill instead of costing a decode step of its own. The other columns'+ // states are read back and ignored.+ let state = b.rms_norm(x, FINAL_NORM, EPSILON);+ return builder.finish(&[state]); } let state = b.rms_norm(x, FINAL_NORM, EPSILON);
library/ml/src/main/rust/src/nets/gemma4_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part3.rs b/library/ml/src/main/rust/src/nets/gemma4_part3.rsindex 72c0687036..4a41b5e52c 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part3.rs@@ -186,23 +186,15 @@ mod tests { } #[test]- fn a_prefill_plan_drops_the_final_norm() {- // The head is tied and lives on the host, so a decode step ends at the final- // norm - and a prefill, which only fills caches, stops one op earlier.- //- // Asserted as a DIFFERENCE against `DecodeStep` rather than an absolute count, so it- // survives the rest of the net changing under it.+ fn a_prefill_plan_ends_at_the_final_norm_like_decode() {+ // A prefill skips nothing a decode step runs: the head lives in its own file, and the+ // final norm stays so the host can run the head on a prefill's last column. let decode = build(&Shapes::new(TENSORS), Mode::DecodeStep.at(TEST_CONTEXT)).expect("decode builds"); let prefill = build(&Shapes::new(TENSORS), Mode::Prefill { tokens: 1 }.at(TEST_CONTEXT)).expect("prefill builds");- assert!(- prefill.ops.len() < decode.ops.len(),- "prefill {} ops against decode {}",- prefill.ops.len(),- decode.ops.len()- );- // Exactly the final RMS norm.- assert_eq!(decode.ops.len() - prefill.ops.len(), 1, "prefill skips only the norm");+ assert_eq!(decode.ops.len(), prefill.ops.len(), "prefill {} ops against decode {}", prefill.ops.len(), decode.ops.len());+ assert_eq!(prefill.outputs.len(), 1);+ assert_eq!(prefill.outputs[0].shape, decode.outputs[0].shape, "the normed state, one per column"); // The caches are the point of a prefill, so it must still write all of them. let writes = |plan: &Plan| { plan.ops