Modern Apps git

← Modern-Apps.git

ml: gemma4 soft tokens prefill in one batched pass per chunk

Commit
fc8c9612ab0e7063057d15db93c8c483ac255fe7
Author
vayun-mathur <[email protected]>
When
2026-10-26 00:17 UTC (1 month ago)
Parents
a9c0659

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 05fbd253d7..5d56105b85 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -87,13 +87,14 @@ struct Args {     split: Option<u32>,     len: Option<u32>,     gather: bool,+    soft: 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, split: None, len: None, gather: false };+        Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, split: None, len: None, gather: false, soft: false };     let mut it = std::env::args().skip(1);     while let Some(arg) = it.next() {         match arg.as_str() {@@ -104,6 +105,7 @@ fn parse_args() -> Args {             "--split" => args.split = it.next().and_then(|n| n.parse().ok()),             "--len" => args.len = it.next().and_then(|n| n.parse().ok()),             "--gather" => args.gather = true,+            "--soft" => args.soft = true,             _ => args.positional.push(arg),         }     }@@ -159,6 +161,12 @@ fn main() {         time_decode(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, repeats, args.sample, args.gather);         return print_memory();     }+    if args.soft {+        if let Err(why) = soft_check(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens) {+            println!("the soft check failed to run: {why}");+        }+        return print_memory();+    }     if args.gather {         if let Err(why) = gather_check(&context, &embed_weights, &tokens) {             println!("the gather check failed: {why}");@@ -812,6 +820,78 @@ fn gather_check(context: &Arc<context::Context>, embed: &Streamed, tokens: &[u32     Ok(()) } +/// Soft tokens after text: `prompt[..2]` batched at 0, then `prompt[2..n-1]` as soft rows+/// (embedding row + pad-token per-layer inputs, as `pushSoftGemma4` builds them) batched at 2+/// versus one pass each, then the last token. The two next-token rankings must agree.+fn soft_check(+    context: &Arc<context::Context>,+    weights: &Streamed,+    embed: &Streamed,+    head: Option<&Streamed>,+    prompt: &[u32],+) -> Result<(), String> {+    let n = prompt.len();+    if n < 4 {+        return Err("the soft check needs at least 4 tokens".into());+    }+    let head = head.ok_or("the soft 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 mut rows = Vec::new();+    for &token in &prompt[2..n - 1] {+        let hidden = reader.int4_row(+            gemma4::embed::TOKENS,+            gemma4::embed::TOKENS + 1,+            &[gemma4::VOCAB, gemma4::D_MODEL],+            token,+        )?;+        let per_layer = gemma4::gather_soft(&reader, &hidden, 0)?;+        rows.push((hidden, per_layer));+    }+    let mut run = |batched: bool| -> Result<Vec<f32>, String> {+        feed(&mut net, &reader, &rotary, &prompt[..2], 0, true)?;+        if batched {+            let width = rows.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, (h, p)) in rows.iter().enumerate() {+                let column = column as u32;+                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, 2 + column)?, column, width);+                place(&mut global, &rotary_row(&rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, 2 + column)?, column, width);+            }+            let at = net.at(gemma4::Mode::Prefill { tokens: width }.at(TIER))?;+            at.set_params(StepParams { prefix: 2, window_start: 0 })?;+            at.infer_raw_many(&[&hidden, &per_layer, &local, &global])?;+        } else {+            for (offset, (h, p)) in rows.iter().enumerate() {+                let position = 2 + offset as u32;+                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(StepParams { prefix: position, window_start: position.saturating_sub(gemma4::WINDOW - 1) })?;+                at.infer_raw_many(&[h, p, &local, &global])?;+            }+        }+        last_logits(&mut net, &mut head_net, &reader, &rotary, prompt[n - 1], (n - 1) as u32)+    };+    let batched = run(true)?;+    let sequential = run(false)?;+    let max_diff = batched.iter().zip(&sequential).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);+    println!("soft rows batched    top10 {:?}", top10(&batched));+    println!("soft rows sequential top10 {:?}", top10(&sequential));+    println!(+        "soft check: {}, max |logit diff| {max_diff:.4}",+        if top10(&batched) == top10(&sequential) { "SAME top10" } else if top10(&batched)[0] == top10(&sequential)[0] { "same argmax, top10 reordered" } else { "ARGMAX DIFFERS" }+    );+    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_part6.rs
diff --git a/library/ml/src/main/rust/src/bridge_part6.rs b/library/ml/src/main/rust/src/bridge_part6.rsindex b36a93f776..2ee7025e9d 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -27,29 +27,39 @@ impl Gemma4Handle {             embedded.extend(reader.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], per_layer_row)?);         }         drop(reader);+        let per_layer = self.combine(&hidden, &embedded)?;+        Ok((hidden, per_layer))+    }++    /// 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> {         if let Some(net) = self.gather_net.as_mut() {-            let at = net.at(())?;-            let out = at.infer_raw_many(&[&hidden, &embedded])?;+            let out = net.at(())?.infer_raw_many(&[hidden, embedded])?;             if out.len() == 1 && out[0].len() == (gemma4::PER_LAYER as usize) * gemma4::LAYERS {-                return Ok((hidden, out.into_iter().next().unwrap_or_default()));+                return Ok(out.into_iter().next().unwrap_or_default());             }             // Wrong shape: fall through to the host combine rather than failing.         }-        // Host combine: the same projection + grouped-norm + scaled add that-        // `gemma4_gather::build_plan` runs on-device, via the shared cached-        // implementation (`gemma4::combine_cached`) over the already-gathered-        // rows. The `--gather-parity` gate enforces exact agreement.-        Ok((hidden.clone(), gather_combine_host(&self.embed, &hidden, &embedded)?))+        gather_combine_host(&self.embed, hidden, embedded)     } -    /// Feed one **soft token**: an encoder's output standing in for a token's embedding.-    ///-    /// The per-layer inputs come from the pad token, which is what the reference does - it+    /// 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 step_soft(&mut self, hidden: &[f32], want_logits: bool) -> Result<Option<Vec<f32>>, String> {-        let per_layer = gemma4::gather_soft(&self.embed.reader(), hidden, 0)?;-        self.step_hidden(hidden, &per_layer, want_logits)+    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));+        }+        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)?);+        }+        drop(reader);+        self.combine(hidden, &embedded)     }      /// Feed one token and return the greedy next token, reduced on the device.@@ -354,51 +364,80 @@ impl Gemma4Handle {         // Every chunk attends the whole cache (`attn_cached_multi`), so any split and any         // starting position is correct.         for chunk in tokens.chunks(CHUNK as usize) {-            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-            // 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 mut local = vec![0f32; (gemma4::HEAD_DIM * width) as usize];-            let mut global = vec![0f32; (gemma4::GLOBAL_HEAD_DIM * width) as usize];-            for (offset, &token) in chunk.iter().enumerate() {-                let (h, p) = self.gather(token)?;-                let column = offset as u32;-                let position = self.position + column;-                place(&mut hidden, &h, column, width);-                place(&mut per_layer, &p, column, width);-                // Written out rather than closed over: a closure returning a borrow of its own-                // argument needs a named lifetime, and two call sites do not justify one.-                let from = (position * gemma4::HEAD_DIM) as usize;-                let row = &self.local[from..from + gemma4::HEAD_DIM as usize];-                place(&mut local, row, column, width);-                let from = (position * gemma4::GLOBAL_HEAD_DIM) as usize;-                let row = &self.global[from..from + gemma4::GLOBAL_HEAD_DIM as usize];-                place(&mut global, row, column, width);-            }-            let gathered = gathering.elapsed();-            let submitted = std::time::Instant::now();-            let at = self.net.at(gemma4::Mode::Prefill { tokens: width }.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])?;-            // Timed on the device because nothing about a desktop GPU predicts a phone's. The-            // record time is called out separately: `Reshaped` re-records whenever the mode or-            // the width changes, and a prompt whose last chunk is short pays it twice.-            log(&format!(-                "gemma4 prefill {width} positions: {:.0} ms gather, {:.0} ms record, {:.0} ms gpu",-                gathered.as_secs_f64() * 1000.0,-                recorded.as_secs_f64() * 1000.0,-                ran.elapsed().as_secs_f64() * 1000.0,+            let rows = chunk.iter().map(|&token| self.gather(token)).collect::<Result<Vec<_>, _>>()?;+            self.prefill_rows(&rows, gathering.elapsed())?;+        }+        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             ));-            self.position += width;         }+        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())?;+        }+        Ok(())+    }++    /// One batched `Prefill` submit over `(hidden, per_layer)` rows at the current position.+    fn prefill_rows(+        &mut self,+        rows: &[(Vec<f32>, Vec<f32>)],+        gathered: 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 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);+        }+        let submitted = std::time::Instant::now();+        let at = self.net.at(gemma4::Mode::Prefill { tokens: width }.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 gather, {:.0} ms record, {:.0} ms gpu",+            self.position,+            gathered.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_part8.rs
diff --git a/library/ml/src/main/rust/src/bridge_part8.rs b/library/ml/src/main/rust/src/bridge_part8.rsindex 88f77cc777..ee466471a5 100644--- a/library/ml/src/main/rust/src/bridge_part8.rs+++ b/library/ml/src/main/rust/src/bridge_part8.rs@@ -214,7 +214,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyGe /// /// This is the seam the vision tower attaches to. The decoder is text-only and gathers a row of /// the embedding table per token; an image has no token to gather, so its rows arrive here-/// instead. See `Gemma4Handle::step_soft` for why the per-layer half still comes from the table.+/// instead. See `Gemma4Handle::gather_soft` for why the per-layer half still comes from the table. /// /// # Safety ///@@ -234,14 +234,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| {-            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()));-            }-            for row in values.chunks_exact(width) {-                handle.step_soft(row, false)?;-            }-            Ok((values.len() / width) as jint)+            handle.prefill_soft(&values)?;+            Ok((values.len() / gemma4::D_MODEL as usize) as jint)         });         Ok(match fed {             Ok(count) => count,