Modern Apps git

← Modern-Apps.git

ml: gemma4 combine on GPU via windowed gather net, 222 -> 83 ms/token

Commit
5fccc62b33061c75bf63b15dc963caacc07fab22
Author
vayun-mathur <[email protected]>
When
2026-10-25 23:49 UTC (1 month ago)
Parents
fd9b5be

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 44e2e3fe89..05fbd253d7 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -86,13 +86,14 @@ struct Args {     sample: bool,     split: Option<u32>,     len: Option<u32>,+    gather: 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 };+        Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, split: None, len: None, gather: false };     let mut it = std::env::args().skip(1);     while let Some(arg) = it.next() {         match arg.as_str() {@@ -102,6 +103,7 @@ fn parse_args() -> Args {             "--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()),+            "--gather" => args.gather = true,             _ => args.positional.push(arg),         }     }@@ -154,7 +156,13 @@ fn main() {         Err(why) => return println!("no Vulkan device: {why}"),     };     if let Some(repeats) = args.time {-        time_decode(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, repeats, args.sample);+        time_decode(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, repeats, args.sample, args.gather);+        return print_memory();+    }+    if args.gather {+        if let Err(why) = gather_check(&context, &embed_weights, &tokens) {+            println!("the gather check failed: {why}");+        }         return print_memory();     }     if let Some(k) = args.split {@@ -332,6 +340,7 @@ struct StepTimes { fn decode_one(     net: &mut Reshaped<gemma4::Pass>,     head: Option<&mut Reshaped<bool>>,+    gather: Option<&mut Reshaped<()>>,     embed: &modelrunner::weights::Reader<'_>,     rotary: &modelrunner::weights::Reader<'_>,     token: u32,@@ -340,7 +349,30 @@ fn decode_one(     times: &mut StepTimes, ) -> Result<Option<u32>, String> {     use std::time::Instant;-    let (hidden_in, per_layer, gtimes) = gemma4::gather_timed(embed, token)?;+    let (hidden_in, per_layer, gtimes) = match gather {+        Some(gather) => {+            let tick = Instant::now();+            let hidden = embed.int4_row(+                gemma4::embed::TOKENS,+                gemma4::embed::TOKENS + 1,+                &[gemma4::VOCAB, gemma4::D_MODEL],+                token,+            )?;+            let row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token };+            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(embed.int4_row(at, at + 1, &[gemma4::VOCAB, gemma4::PER_LAYER], row)?);+            }+            let rows_ms = tick.elapsed().as_secs_f64() * 1000.0;+            let tick = Instant::now();+            let out = gather.at(())?.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 })+        }+        None => gemma4::gather_timed(embed, token)?,+    };     let rows_tick = Instant::now();     let angles_local = rotary_row(rotary, gemma4::ROTARY_LOCAL, gemma4::HEAD_DIM, position)?;     let angles_global = rotary_row(rotary, gemma4::ROTARY_GLOBAL, gemma4::GLOBAL_HEAD_DIM, position)?;@@ -401,12 +433,23 @@ fn time_decode(     tokens: &[u32],     repeats: usize,     sample: bool,+    device_gather: bool, ) {     use std::time::Instant;     let mut net = match streamed_net(context, weights, gemma4::Mode::DecodeStep.at(TIER), gemma4_plan) {         Ok(net) => net,         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)+        }) {+            Ok(net) => Some(net),+            Err(why) => return println!("the gather net does not build: {why}"),+        }+    } else {+        None+    };     let mut head_net = match build_head(context, head, !sample) {         Ok(net) => net,         Err(why) => return println!("the head does not build: {why}"),@@ -424,7 +467,7 @@ fn time_decode(         for (step, &token) in tokens.iter().enumerate() {             let tick = Instant::now();             let mut times = StepTimes::default();-            match decode_one(&mut net, head_net.as_mut(), &reader, &rotary, token, step as u32, sample, &mut times) {+            match decode_one(&mut net, head_net.as_mut(), gather_net.as_mut(), &reader, &rotary, token, step as u32, sample, &mut times) {                 Ok(id) => ids.extend(id),                 Err(why) => return println!("step {step} failed: {why}"),             }@@ -549,7 +592,7 @@ fn time_prefill(         }         let tick = Instant::now();         let mut times = StepTimes::default();-        let id = match decode_one(&mut net, head_net.as_mut(), &reader, &rotary, next, width, false, &mut times) {+        let id = match decode_one(&mut net, head_net.as_mut(), None, &reader, &rotary, next, width, false, &mut times) {             Ok(id) => id,             Err(why) => return println!("the first decode step failed: {why}"),         };@@ -715,6 +758,60 @@ fn split_check(     Ok(()) } +/// The device combine (`gemma4_gather`, uploaded through `Reshaped::windowed` so only the+/// tensors it reads leave the 3.6 GB file) against the host `combine_cached`, per token.+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)+    })?;+    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 repeats = 4;+    for pass in 0..repeats {+        for &token in tokens {+            let hidden = reader.int4_row(+                gemma4::embed::TOKENS,+                gemma4::embed::TOKENS + 1,+                &[gemma4::VOCAB, gemma4::D_MODEL],+                token,+            )?;+            let row = if gemma4::embed::PLACEHOLDERS.contains(&token) { 0 } else { token };+            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], row)?);+            }+            let tick = Instant::now();+            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 device_t = tick.elapsed().as_secs_f64() * 1000.0;+            let device = out.into_iter().next().ok_or("the gather net returned nothing")?;+            if device.len() != host.len() {+                return Err(format!("device {} values, host {}", device.len(), host.len()));+            }+            let scale = host.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-6);+            let diff = device.iter().zip(&host).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max) / scale;+            worst = worst.max(diff);+            if pass > 0 {+                host_ms += host_t;+                device_ms += device_t;+            }+        }+    }+    let n = (tokens.len() * (repeats - 1)) as f64;+    println!(+        "combine per token: host {:.2} ms, device {:.2} ms; worst max|diff|/max|host| {worst:.5}",+        host_ms / n,+        device_ms / n+    );+    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 2a5beb8477..7d9f5a90db 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -22,18 +22,14 @@ fn gather_combine_host(     crate::nets::gemma4::combine_cached(&embed.reader(), hidden, embedded) } -/// The device combine plan over an EMBED file, or `None` when the file-/// predates the plan's tensor expectations (see `nets::gemma4_gather`).-///-/// Unused until `Net::new` uploads only the tensors a plan reads: today this-/// uploads the whole 3.6 GB EMBED file.-#[allow(dead_code)]+/// 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<()>> {-    Reshaped::streamed(+    Reshaped::windowed(         context::shared().ok()?,         embed.offsets(),         embed,-        (),+        &[()],         |offsets, ()| crate::nets::gemma4_gather::build_plan(offsets),     )     .ok()@@ -227,12 +223,10 @@ fn build_gemma4<'l>(         gemma4::Mode::DecodeStep.at(gemma4::CONTEXT_TIERS[0]),         gemma4_plan,     )?;-    // Never a net over EMBED: `Reshaped::streamed` uploads the whole 3.6 GB-    // 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.+    // 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: Option<Reshaped<()>> = None;+    let gather_net = gemma4_gather_plan(&embed);     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 f3fc9f3f51..a015e99354 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -403,11 +403,9 @@ struct Gemma4Handle {     /// 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-    /// `gather_device` below); `gather` stays host-side until the parity-    /// gate below passes on host + P8.+    /// 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<()>>,     /// The text model, retained for the rotary tables which are also host-read.     weights: Streamed,
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 0e416fe5ab..95d9cb9b3f 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -5,13 +5,8 @@ impl Gemma4Handle {         self.step_hidden(&hidden, &per_layer, want_logits)     } -    /// One token's embedding and per-layer inputs, device-combined when available.-    ///-    /// The 36 int4 rows still gather on host (`int4_row` is mmap-cheap); the-    /// 13.8M-MAC `combine` SGEMV runs on-device via `gather_net` when the-    /// handle carries it, else on host via `gemma4::gather` (bit-parity gate-    /// between the two lives in `run_gemma4 --gather-parity`). `gather_net`-    /// is `None` until that gate passes โ€” today this is always the host path.+    /// One token's embedding and per-layer inputs. The 36 int4 rows gather on the host+    /// (`int4_row` is mmap-cheap); the combine runs on `gather_net` when it built, else on host.     fn gather(&mut self, token: u32) -> Result<(Vec<f32>, Vec<f32>), String> {         // Host rows (both paths need them โ€” see `gemma4_gather` module docs         // for why the row lookups did not move).@@ -378,7 +373,7 @@ impl Gemma4Handle {             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) = gemma4::gather(&self.embed.reader(), token)?;+                let (h, p) = self.gather(token)?;                 let column = offset as u32;                 let position = self.position + column;                 place(&mut hidden, &h, column, width);@@ -416,7 +411,7 @@ impl Gemma4Handle {         if !sequential.is_empty() {             let started = std::time::Instant::now();             for &token in sequential {-                let (hidden, per_layer) = gemma4::gather(&self.embed.reader(), token)?;+                let (hidden, per_layer) = self.gather(token)?;                 self.step_hidden(&hidden, &per_layer, false)?;             }             log(&format!(