Modern Apps git

← Modern-Apps.git

ml: gemma4 prefill past position 0 attends the cache; one head upload

Commit
915555161e764ddca65da85943aaca567bd69a77
Author
vayun-mathur <[email protected]>
When
2026-10-25 23:15 UTC (1 month ago)
Parents
82c1bc4

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 0ada1e0f39..44e2e3fe89 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -84,12 +84,15 @@ struct Args {     time: Option<usize>,     prefill: Option<u32>,     sample: bool,+    split: Option<u32>,+    len: Option<u32>, }  /// `--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 };+    let mut args =+        Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, split: None, len: None };     let mut it = std::env::args().skip(1);     while let Some(arg) = it.next() {         match arg.as_str() {@@ -97,6 +100,8 @@ fn parse_args() -> Args {             "--time" => args.time = it.next().and_then(|n| n.parse().ok()),             "--prefill" => args.prefill = it.next().and_then(|n| n.parse().ok()),             "--sample" => args.sample = true,+            "--split" => args.split = it.next().and_then(|n| n.parse().ok()),+            "--len" => args.len = it.next().and_then(|n| n.parse().ok()),             _ => args.positional.push(arg),         }     }@@ -115,7 +120,7 @@ fn main() {     ) else {         println!(             "usage: check_gemma4_parity <text.maml> <embed.maml> <golden.json> [trace] [tail] \-             [--head head.maml] [--time N [--sample]] [--prefill N]"+             [--head head.maml] [--time N [--sample]] [--prefill N] [--split K [--len N]]"         );         return;     };@@ -152,6 +157,14 @@ fn main() {         time_decode(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, repeats, args.sample);         return print_memory();     }+    if let Some(k) = args.split {+        let n = args.len.unwrap_or(tokens.len() as u32) as usize;+        let prompt: Vec<u32> = tokens.iter().copied().cycle().take(n).collect();+        if let Err(why) = split_check(&context, &weights, &embed_weights, head_weights.as_ref(), &prompt, k) {+            println!("the split check failed to run: {why}");+        }+        return print_memory();+    }     if let Some(width) = args.prefill {         time_prefill(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, width);         return print_memory();@@ -554,6 +567,154 @@ fn time_prefill(     } } +/// Feed `tokens` at positions `start..` without the head: one batched `Prefill` submit, or one+/// single-position pass each (the decode layer, which attends the cache).+fn feed(+    net: &mut Reshaped<gemma4::Pass>,+    embed: &modelrunner::weights::Reader<'_>,+    rotary: &modelrunner::weights::Reader<'_>,+    tokens: &[u32],+    start: u32,+    batched: bool,+) -> Result<(), String> {+    if tokens.is_empty() {+        return Ok(());+    }+    let params = |position: u32| StepParams {+        prefix: position,+        window_start: position.saturating_sub(gemma4::WINDOW - 1),+    };+    if !batched {+        for (offset, &token) in tokens.iter().enumerate() {+            let position = start + offset as u32;+            let (hidden, per_layer) = gemma4::gather(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))?;+            at.set_params(params(position))?;+            at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+        }+        return Ok(());+    }+    let width = tokens.len() as u32;+    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 tokens.iter().enumerate() {+        let column = column as u32;+        let (h, p) = gemma4::gather(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);+        place(+            &mut global,+            &rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, start + column)?,+            column,+            width,+        );+    }+    let at = net.at(gemma4::Mode::Prefill { tokens: width }.at(TIER))?;+    at.set_params(params(start))?;+    at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+    Ok(())+}++/// The last token as a decode step at `position`, then the logits head.+#[allow(clippy::too_many_arguments)]+fn last_logits(+    net: &mut Reshaped<gemma4::Pass>,+    head: &mut Reshaped<bool>,+    embed: &modelrunner::weights::Reader<'_>,+    rotary: &modelrunner::weights::Reader<'_>,+    token: u32,+    position: u32,+) -> Result<Vec<f32>, String> {+    let (hidden, per_layer) = gemma4::gather(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))?;+    at.set_params(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?;+    let out = at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+    let state = out.into_iter().next().ok_or("the step returned nothing")?;+    softcapped(&head.at(false)?.infer_raw_many(&[&state])?)+}++fn top10(logits: &[f32]) -> Vec<u32> {+    let mut order: Vec<u32> = (0..logits.len() as u32).collect();+    order.sort_by(|&a, &b| logits[b as usize].total_cmp(&logits[a as usize]));+    order.truncate(10);+    order+}++/// A prompt split `[0..k at 0][k..n-1 at k]` must give the next-token ranking the whole prompt+/// gives at 0. Variants: whole batched (reference), all sequential, the app's stopgap (batched+/// head + sequential tail), and a batched tail (correct only once prefill attends the cache).+fn split_check(+    context: &Arc<context::Context>,+    weights: &Streamed,+    embed: &Streamed,+    head: Option<&Streamed>,+    prompt: &[u32],+    k: u32,+) -> Result<(), String> {+    let n = prompt.len();+    let k = k as usize;+    if n < 3 || k == 0 || k + 1 >= n || n as u32 >= TIER {+        return Err(format!("need 0 < k < n - 1 and n < {TIER}; got k {k}, n {n}"));+    }+    let head = head.ok_or("the split check needs --head")?;+    let mut net = streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan)?;+    let mut head_net = streamed_net(context, head, false, head_plan)?;+    let reader = embed.reader();+    let rotary = weights.reader();+    let last = prompt[n - 1];+    let body = &prompt[..n - 1];+    let (front, tail) = body.split_at(k);+    let mut run = |label: &str, front_batched: bool, tail_batched: bool, whole: bool| -> Result<Vec<f32>, String> {+        let tick = std::time::Instant::now();+        let mut tail_ms = 0.0;+        if whole {+            feed(&mut net, &reader, &rotary, body, 0, front_batched)?;+        } else {+            feed(&mut net, &reader, &rotary, front, 0, front_batched)?;+            let tail_tick = std::time::Instant::now();+            feed(&mut net, &reader, &rotary, tail, k as u32, tail_batched)?;+            tail_ms = tail_tick.elapsed().as_secs_f64() * 1000.0;+        }+        let logits = last_logits(&mut net, &mut head_net, &reader, &rotary, last, (n - 1) as u32)?;+        println!(+            "  {label:<32} {:>7.0} ms (tail {tail_ms:.0} ms = {:.1} ms/token)  top10 {:?}",+            tick.elapsed().as_secs_f64() * 1000.0,+            tail_ms / tail.len().max(1) as f64,+            top10(&logits)+        );+        Ok(logits)+    };+    println!("split check: {n} tokens, split at {k}");+    // Widest batch first so the arena grows before anything it holds matters.+    let reference = run("whole batched at 0", true, true, true)?;+    let variants = [+        ("all sequential", run("all sequential", false, false, true)?),+        ("batched head + sequential tail", run("batched head + sequential tail", true, false, false)?),+        ("batched head + batched tail", run("batched head + batched tail", true, true, false)?),+    ];+    let want = top10(&reference);+    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);+        let verdict = if got == want {+            "SAME top10"+        } else if got[0] == want[0] {+            "same argmax, top10 reordered"+        } else {+            "ARGMAX DIFFERS"+        };+        println!("  {label:<32} {verdict}, max |logit diff| {max_diff:.4}");+    }+    Ok(())+}+ /// Per-kind GPU table for one submit, plus its ten hottest dispatches. fn print_kinds(title: &str, report: &[(String, f64, f64)]) {     let mut per_kind: Vec<(String, usize, f64)> = Vec::new();
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 34a4958b79..2a5beb8477 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -39,14 +39,10 @@ fn gemma4_gather_plan(embed: &Streamed) -> Option<Reshaped<()>> {     .ok() } -/// The standalone head plan over a head file (`graph::GEMMA4_HEAD`).-///-/// `None` when no head file was opened. The head file holds ONLY the 48-/// int8 triples (~402 MB), so this upload replaces the 3.6 GB EMBED upload-/// on memory-constrained devices (Pixel 8 OOM-reboot, twice, 2026-09-26:-/// TEXT 1.1 GB + EMBED 3.6 GB vs ~2.6 GB free). Preferred over-/// `gemma4_head_plan` whenever present — same numerics, one-ninth the bytes.-fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<()>> {+/// The head over the standalone head file (`graph::GEMMA4_HEAD`, the 48+/// int8 triples, ~385 MB): one upload, two recordings (`true` greedy id,+/// `false` the 16 logit splits). `None` when the file does not match.+fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<bool>> {     let offsets = head.offsets();     if offsets.len() != crate::nets::gemma4_head::HEAD_FILE_TENSORS {         return None;@@ -55,29 +51,11 @@ fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<()>> {         context::shared().ok()?,         offsets,         head,-        (),-        |offsets, ()| crate::nets::gemma4_head::build_plan_standalone(offsets, false),+        true,+        |offsets, greedy| crate::nets::gemma4_head::build_plan_standalone(offsets, greedy),     )     .ok() }--/// The greedy standalone head plan: 16 splits + device argmax id.-/// See `gemma4_head_file_plan` (file-size rationale) and `build_plan_greedy`.-fn gemma4_head_file_plan_greedy(head: &Streamed) -> Option<Reshaped<()>> {-    let offsets = head.offsets();-    if offsets.len() != crate::nets::gemma4_head::HEAD_FILE_TENSORS {-        return None;-    }-    Reshaped::streamed(-        context::shared().ok()?,-        offsets,-        head,-        (),-        |offsets, ()| crate::nets::gemma4_head::build_plan_standalone(offsets, true),-    )-    .ok()-}- /// Positions one prefill submit covers. Large enough that a prompt is **one** submit. /// /// # Splitting a prefill is wrong, not merely slower@@ -91,9 +69,8 @@ fn gemma4_head_file_plan_greedy(head: &Streamed) -> Option<Reshaped<()>> { /// single chunk agrees with it exactly at 100, 400, 900 and 1,907 positions. /// /// The real repair is to attend over the cache rather than the chunk, as decode does, which-/// makes any chunking correct. Until then the chunk must cover the prompt, and that is-/// affordable here because the fixed prefix arrives precomputed - a turn prefills only the new-/// tokens, not the 1,900 before them.+/// makes any chunking correct. Until then only the first chunk at position 0 is batched and+/// everything after it (later turns included) runs one position at a time. const CHUNK: u32 = 4096;  /// Write one position's `values` into column `column` of a `[C, 1, width]` block.@@ -254,15 +231,11 @@ fn build_gemma4<'l>(     // file, which on top of TEXT OOM-kills a Pixel 8. The head comes from the     // ~402 MB head file or the host; the combine stays on the host until     // uploads are windowed.-    let (head, head_greedy) = match &head_file {-        Some(file) => (gemma4_head_file_plan(file), gemma4_head_file_plan_greedy(file)),-        None => (None, None),-    };+    let head = head_file.as_ref().and_then(gemma4_head_file_plan);     let gather_net: Option<Reshaped<()>> = None;     Ok(Gemma4Handle {         net,         head,-        head_greedy,         gather_net,         weights,         embed,
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 e28da693f8..f3fc9f3f51 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -229,14 +229,17 @@ fn build_whisper<'l>(     // construction — when the UI can still report the recogniser as unavailable.     decoding.check(whisper::VOCAB)?; -    // Recorded on the encoder, which is what every transcription runs first.-    let net = Reshaped::streamed(+    // Recorded on the decode step first, then the encoder every transcription runs first: the+    // first recording of each kernel is the expensive one, and this keeps it out of the first+    // transcription's switch into decoding.+    let mut net = Reshaped::streamed(         context::shared()?,         weights.offsets(),         &weights,-        whisper::Mode::Encode,+        whisper::Mode::DecodeStep,         whisper_plan,     )?;+    net.at(whisper::Mode::Encode)?;     Ok(WhisperHandle { net, weights, decoding }) } @@ -395,14 +398,11 @@ fn log(message: &str) { /// [`Streamed`] and is gathered on the host, exactly as NLLB's tied embedding is. struct Gemma4Handle {     net: Reshaped<gemma4::Pass>,-    /// The GPU tied head over the EMBED file, upload-once at construction.-    /// `None` on files without head chunks — the host head covers those.-    head: Option<Reshaped<()>>,-    /// The greedy head over the EMBED file: 16 splits + device argmax id.-    /// `None` on files without int8 chunks — greedy falls back to the host-    /// argmax over `head`. Built alongside `head` (same upload-once cost-    /// class: one more recording over the same resident upload).-    head_greedy: Option<Reshaped<()>>,+    /// The GPU head over the standalone head file, one upload serving both+    /// plans: `at(true)` is the device-argmax plan (one id back), `at(false)`+    /// the 16 logit splits. `None` without a head file - the host head covers+    /// that.+    head: Option<Reshaped<bool>>,     /// The device combine over the EMBED file: host-gathered rows in,     /// combined per-layer block out. `None` always for now — the combine     /// plan is built and tested but not yet wired into the step path (see
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 a8182ab75b..0e416fe5ab 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -194,7 +194,7 @@ impl Gemma4Handle {         let Some(head) = self.head.as_mut() else {             return self.tied_head_logits(hidden);         };-        let at = head.at(())?;+        let at = head.at(false)?;         let out = at.infer_raw_many(&[hidden])?;         if out.len() != crate::nets::gemma4_head::HEAD_CHUNKS {             return Err(format!(@@ -217,33 +217,19 @@ impl Gemma4Handle {      /// The greedy next token for `hidden`, reduced on the device.     ///-    /// Same head submit through the greedy plan (`build_plan_greedy`): the 16-    /// splits concatenate on-device and one `Argmax` op reduces to a single-    /// scalar holding the winning index as fp16 bits. Reads back 1 value-    /// instead of 262144 — no 512 KB readback, no host scan. Falls back to-    /// the host argmax over [`head_logits`](Self::head_logits) when the head-    /// net is absent. The full-logits path (`logitsGemma4`) never calls this.-    ///-    /// NOTE: the greedy plan has a different output signature (16 splits + 1-    /// id) from the logits plan, so it runs on the dedicated `head_greedy`-    /// handle (same EMBED upload, separate recording). Falls back to the-    /// host argmax when that handle is absent (no int8 chunks in file).+    /// `head.at(true)`: the splits concatenate and reduce on the device, so two values+    /// ([lo, hi] of the id) come back instead of 262144 logits. Host argmax without a head file.     fn head_greedy(&mut self, hidden: &[f32]) -> Result<u32, String> {-        use crate::nets::gemma4_head;-        let Some(greedy) = self.head_greedy.as_mut() else {+        let Some(head) = self.head.as_mut() else {             let logits = self.head_logits(hidden)?;             return Ok(argmax(&logits));         };-        let at = greedy.at(())?;+        let at = head.at(true)?;         let out = at.infer_raw_many(&[hidden])?;-        if out.len() != gemma4_head::HEAD_CHUNKS + 1 {-            return Err(format!(-                "greedy head returned {} outputs, not {}",-                out.len(),-                gemma4_head::HEAD_CHUNKS + 1-            ));+        if out.len() != 1 {+            return Err(format!("greedy head returned {} outputs, not 1", out.len()));         }-        let id_out = &out[gemma4_head::HEAD_CHUNKS];+        let id_out = &out[0];         if id_out.len() != 2 {             return Err(format!("greedy id holds {} values, not 2", id_out.len()));         }@@ -372,7 +358,16 @@ impl Gemma4Handle {                 self.context             ));         }-        for chunk in tokens.chunks(CHUNK as usize) {+        // `prefill_layer` attends only within its own chunk, so a batch is correct only when+        // nothing precedes it. Past position 0 (later turns, text after an image, a second+        // chunk) each token goes through the single-position pass, which attends the cache.+        let (batched, sequential) = if self.position == 0 {+            tokens.split_at(tokens.len().min(CHUNK as usize))+        } else {+            (&[][..], tokens)+        };+        if !batched.is_empty() {+            let chunk = batched;             let width = chunk.len() as u32;             let gathering = std::time::Instant::now();             // Gathered per position and laid out `[C, 1, T]` - channel-major, which is what@@ -418,6 +413,19 @@ impl Gemma4Handle {             ));             self.position += width;         }+        if !sequential.is_empty() {+            let started = std::time::Instant::now();+            for &token in sequential {+                let (hidden, per_layer) = gemma4::gather(&self.embed.reader(), token)?;+                self.step_hidden(&hidden, &per_layer, false)?;+            }+            log(&format!(+                "gemma4 prefill {} positions sequentially, ending at {}: {:.0} ms",+                sequential.len(),+                self.position,+                started.elapsed().as_secs_f64() * 1000.0,+            ));+        }         Ok(())     } } // close impl Gemma4Handle: everything below is a free function.
library/ml/src/main/rust/src/nets/gemma4_head.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_head.rs b/library/ml/src/main/rust/src/nets/gemma4_head.rsindex 05e4625459..9c52a493dd 100644--- a/library/ml/src/main/rust/src/nets/gemma4_head.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -204,8 +204,9 @@ fn build_plan_fp16(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, Str /// /// Same 16 int8 triples as `build_plan8`, but the file holds NOTHING else: /// chunk `s` owns tensors `s * 3 .. s * 3 + 2` (no `host_tensor` companions-/// needed — `finish` sees every tensor read). `greedy` appends the same-/// on-device concat + argmax tail.+/// needed — `finish` sees every tensor read). `greedy` replaces the 16 split+/// outputs with the on-device argmax id alone, so a greedy step reads back+/// two values instead of 512 KB. pub fn build_plan_standalone(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> {     let mut builder = Builder::new(weights);     let b = &mut builder;@@ -215,7 +216,9 @@ pub fn build_plan_standalone(weights: &dyn WeightSource, greedy: bool) -> Result         outs.push(point8(b, s * 3, x, CLASSES_PER_CHUNK));     }     if greedy {-        finish_greedy(b, &mut outs);+        let row = b.concat(&outs);+        let id = b.argmax(row);+        return builder.finish(&[id]);     }     builder.finish(&outs) }@@ -365,6 +368,16 @@ mod tests {         crate::nets::schedule::is_sound(&plan, &sched).expect("the fp16 head schedule is sound");     } +    #[test]+    fn the_standalone_greedy_head_returns_only_the_id() {+        let source = Shapes::new(HEAD_FILE_TENSORS);+        let plan = build_plan_standalone(&source, true).expect("the greedy head builds");+        assert_eq!(plan.outputs.len(), 1);+        assert_eq!(plan.outputs[0].shape, Shape::new(2, 1, 1));+        let plan = build_plan_standalone(&source, false).expect("the logits head builds");+        assert_eq!(plan.outputs.len(), HEAD_CHUNKS);+    }+     #[test]     fn the_chunk_shapes_cover_the_vocabulary() {         // Chunk s owns classes [s * 16384, (s + 1) * 16384): contiguous and