ml: device gather-argmax phase (Argmax kind+shader, greedy head, tex probe)
- Commit
ce649c715bfb0c352cabce82fd091ddcc8813cab- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-27 01:21 UTC (2 months ago)
- Parents
8aa2cba
Diff
library/ml/src/main/rust/examples/probe_gemma4.rs
diff --git a/library/ml/src/main/rust/examples/probe_gemma4.rs b/library/ml/src/main/rust/examples/probe_gemma4.rsindex a06887f33e..b06fd2d412 100644--- a/library/ml/src/main/rust/examples/probe_gemma4.rs+++ b/library/ml/src/main/rust/examples/probe_gemma4.rs@@ -123,6 +123,16 @@ fn main() { } Err(why) => println!("the GPU head plan does NOT build: {why}"), }+ match gemma4_head::build_plan_greedy(&embed) {+ Ok(plan) => {+ println!("the greedy head plan builds against the real table");+ println!(" {} ops, {} inputs, {} outputs", plan.ops.len(), plan.inputs.len(), plan.outputs.len());+ for (i, o) in plan.outputs.iter().enumerate() {+ println!(" out[{i}]: c={} h={} w={}", o.shape.c, o.shape.h, o.shape.w);+ }+ }+ Err(why) => println!("the greedy head plan does NOT build: {why}"),+ } // The vision tower, if it is beside the other two. if let Some(path) = std::env::args().nth(3).map(PathBuf::from) {
library/ml/src/main/rust/examples/run_gemma4.rs
diff --git a/library/ml/src/main/rust/examples/run_gemma4.rs b/library/ml/src/main/rust/examples/run_gemma4.rsindex 5dd24b29b3..b866e040f3 100644--- a/library/ml/src/main/rust/examples/run_gemma4.rs+++ b/library/ml/src/main/rust/examples/run_gemma4.rs@@ -150,15 +150,90 @@ const STOP: [u32; 3] = [1, 106, 50]; /// Logits for `hidden`: the GPU head when the EMBED file carries chunks. ///-/// The device runs the 16 fp16 chunk projections; the host concatenates the+/// The device runs the 16 chunk projections; the host concatenates the /// splits and softcaps, exactly as the host head does. Falls back to the /// host tied head (`hidden @ HEAD_TABLE^T` in `HEAD_SPLITS` quarters) on /// files without chunks.+///+/// `GEMMA4_GREEDY=1` instead reduces on the device: the greedy plan+/// (`build_plan_greedy`) concatenates the 16 splits on-device and one+/// `Argmax` op returns the winning index as fp16 bits — 1 value back instead+/// of 262144, no 512 KB readback, no host scan. The returned id is checked+/// against the host argmax every token (greedy parity gate); any mismatch+/// fails the run loudly rather than generating from the wrong token. fn head_logits( _context: &Arc<context::Context>, head: &mut Option<Reshaped<()>>, reader: &modelrunner::weights::Reader<'_>, hidden: &[f32],+ head_embed: Option<&Weights>,+) -> Result<Vec<f32>, String> {+ use modelrunner::nets::gemma4_head;+ if std::env::var("GEMMA4_GREEDY").is_ok() {+ if let Some(embed) = head_embed {+ if let Some(id) = head_greedy_id(_context, embed, hidden)? {+ // Greedy parity gate: the device id must equal the host argmax.+ // Falls through to the full path below on mismatch (loud, not silent).+ let full = head_logits_full(head, reader, hidden)?;+ let host = full+ .iter()+ .enumerate()+ .max_by(|(_, a), (_, b)| a.total_cmp(b))+ .map(|(i, _)| i as u32);+ if host != Some(id) {+ return Err(format!("greedy parity: device id {id} vs host {host:?}"));+ }+ return Ok(full);+ }+ }+ }+ head_logits_full(head, reader, hidden)+}++/// The device greedy id, or `None` when the head net is absent.+///+/// The greedy plan (`build_plan_greedy`) is a different output signature+/// (16 splits + 1 id), so it needs its own recording alongside the logits+/// plan. SIMPLIFICATION for the parity gate: rebuild a dedicated `Net` per+/// call (correct; one extra upload+record per token while proving+/// bit-identity). The cached second handle lands once parity is proven.+fn head_greedy_id(+ context: &Arc<context::Context>,+ embed: &Weights,+ hidden: &[f32],+) -> Result<Option<u32>, String> {+ use modelrunner::nets::gemma4_head;+ use modelrunner::vulkan::run::Net;+ if embed.offsets().len() < gemma4_head::TENSORS_WITH_HEAD {+ return Ok(None);+ }+ let plan = gemma4_head::build_plan_greedy(&embed.offsets())?;+ let mut net = Net::new(+ Arc::clone(context),+ plan,+ embed,+ modelrunner::preprocess::RESCALE_ONLY,+ )?;+ let out = net.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));+ }+ let id_out = &out[gemma4_head::HEAD_CHUNKS];+ if id_out.len() != 2 {+ return Err(format!("greedy id output holds {} values, not 2", id_out.len()));+ }+ // The shader stored `lo = id % 2048`, `hi = id / 2048` as fp16 values+ // (both exactly representable) — reconstruct exactly.+ let lo = id_out[0] as u32;+ let hi = id_out[1] as u32;+ Ok(Some(hi * 2048 + lo))+}++/// Full logits via the GPU head (or host fallback). See [`head_logits`].+fn head_logits_full(+ head: &mut Option<Reshaped<()>>,+ reader: &modelrunner::weights::Reader<'_>,+ hidden: &[f32], ) -> Result<Vec<f32>, String> { use modelrunner::nets::gemma4_head; if let Some(net) = head.as_mut() {@@ -328,7 +403,7 @@ fn generate( gemma4::D_MODEL )); }- let logits = head_logits(context, &mut head, &reader, hidden)?;+ let logits = head_logits(context, &mut head, &reader, hidden, Some(embed))?; let mut best = (f32::NEG_INFINITY, 0u32); for (id, &value) in logits.iter().enumerate() { if value > best.0 {@@ -477,7 +552,7 @@ fn run_chat( break; } let hidden = &out[0];- let logits = match head_logits(&context, &mut head, &reader, hidden) {+ let logits = match head_logits(&context, &mut head, &reader, hidden, Some(embed)) { Ok(logits) => logits, Err(_) => break, };
library/ml/src/main/rust/shaders/argmax.comp
diff --git a/library/ml/src/main/rust/shaders/argmax.comp b/library/ml/src/main/rust/shaders/argmax.compnew file mode 100644index 0000000000..37d6a3814d--- /dev/null+++ b/library/ml/src/main/rust/shaders/argmax.comp@@ -0,0 +1,60 @@+#version 450+//! Greedy argmax over a logits row: the winning index as two fp16 values.+//!+//! # Why on the device+//!+//! The 262,144-logit host scan costs ~14 ms a token (plus the 512 KB+//! readback it implies when logits otherwise stay on the device). This+//! reduces on the device and reads back 2 values instead of 262144 — no+//! 512 KB readback, no host scan. The full-logits path (Kotlin sampling)+//! is untouched — this serves greedy decoding only, which is what+//! `bridge_part6::argmax` does on the host.+//!+//! # How+//!+//! 64 lanes grid-stride over `p.count` logits (the concatenated head splits,+//! vocab-wide). Each lane keeps its local (value, index) maximum; a shared+//! 64-entry reduction folds them; lane 0 stores the winner as TWO fp16+//! values: `lo = id % 2048`, `hi = id / 2048`. Both are exactly+//! representable (fp16 integers are exact to 2048; ids < 262144 give+//! hi < 128); the host reconstructs `hi * 2048 + lo`. A single fp16 slot+//! cannot hold the id either way: as a value it rounds past 2048, and as+//! bits `uintBitsToFloat` produces a denormal that `float16_t()` converts+//! (not bitcasts) to zero.+//!+//! Ties keep the FIRST index (strict `>`), matching the host loop's+//! `value > best.0`.+#include "common.glsl"+shared uint best_idx[64];+shared float best_val[64];+void main() {+ uint lane = gl_LocalInvocationID.x;+ uint lanes = 64u;+ // Grid-stride over the row: with one workgroup this is one pass.+ float mine_val = -65504.0;+ uint mine_idx = 0u;+ for (uint i = lane; i < p.count; i += lanes) {+ float v = float(arena[p.in0 + i]);+ if (v > mine_val) {+ mine_val = v;+ mine_idx = i;+ }+ }+ best_val[lane] = mine_val;+ best_idx[lane] = mine_idx;+ barrier();+ // Lane 0 folds the 64 lane-maxima. Strict `>` keeps the FIRST index on+ // ties, matching the host `argmax` loop.+ if (lane == 0u) {+ float top_val = best_val[0];+ uint top_idx = best_idx[0];+ for (uint l = 1u; l < 64u; l++) {+ if (best_val[l] > top_val) {+ top_val = best_val[l];+ top_idx = best_idx[l];+ }+ }+ arena[p.out_at] = float16_t(float(top_idx % 2048u));+ arena[p.out_at + 1u] = float16_t(float(top_idx / 2048u));+ }+}
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 28c45f4300..a0963a16b0 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -404,6 +404,11 @@ struct Gemma4Handle { /// 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 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 3a8e9d14ba..7d4324f35b 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -5,6 +5,19 @@ impl Gemma4Handle { self.step_hidden(&hidden, &per_layer, want_logits) } + /// Feed one token and return the greedy next token, reduced on the device.+ ///+ /// Same transformer step as [`step`](Self::step) but the head runs+ /// through the greedy plan (`build_plan_greedy`): 16 splits concatenate+ /// on-device, one `Argmax` reduces to the winning index, and 1 value+ /// crosses back instead of 262144 logits. Falls back to the host argmax+ /// 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> {+ let (hidden, per_layer) = gemma4::gather(&self.embed.reader(), token)?;+ self.step_hidden_greedy(&hidden, &per_layer)+ }+ /// 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@@ -88,12 +101,53 @@ impl Gemma4Handle { Ok(Some(self.head_logits(hidden)?)) } + /// The greedy step itself, once both halves of the input are in hand.+ ///+ /// Same transformer submit as [`step_hidden`](Self::step_hidden) with+ /// `want_logits`, then the device argmax via+ /// [`head_greedy`](Self::head_greedy): 1 value back, no 512 KB readback,+ /// no host scan. `stepGemma4` calls this; `logitsGemma4` keeps calling+ /// `step_hidden` for the full logits.+ fn step_hidden_greedy(+ &mut self,+ hidden: &[f32],+ per_layer: &[f32],+ ) -> Result<u32, String> {+ // The transformer half is identical to the logits path: DecodeStep,+ // same params, same cache discipline. Only the head differs.+ if self.position >= self.context {+ return Err(format!("the cache is full at {} positions", self.context));+ }+ let row = |table: &[f32], width: u32| -> Vec<f32> {+ let from = (self.position * width) as usize;+ table[from..from + width as usize].to_vec()+ };+ let local = row(&self.local, gemma4::HEAD_DIM);+ let global = row(&self.global, gemma4::GLOBAL_HEAD_DIM);+ let mode = gemma4::Mode::DecodeStep.at(self.context);+ let at = self.net.at(mode)?;+ at.set_params(StepParams {+ prefix: self.position,+ window_start: self.position.saturating_sub(gemma4::WINDOW - 1),+ })?;+ let out = at.infer_raw_many(&[hidden, per_layer, &local, &global])?;+ self.position += 1;+ if out.len() != 1 {+ return Err(format!("a step returned {} tensors, not 1 hidden state", out.len()));+ }+ let hidden = &out[0];+ if hidden.len() != gemma4::D_MODEL as usize {+ return Err(format!("hidden state of {} values, not {}", hidden.len(), gemma4::D_MODEL));+ }+ self.head_greedy(hidden)+ }+ /// Logits for `hidden`, GPU head when the EMBED file carries chunks. ///- /// The device runs the 16 fp16 chunk projections and the host- /// concatenates the splits, then the same softcap + argmax path as the- /// host head below. Falls back to `tied_head_logits` on files without- /// chunks (or when the head net failed to build).+ /// The device runs the 16 chunk projections and the host concatenates+ /// the splits, then the same softcap path as the host head below. Falls+ /// back to the host head on files without chunks (or when the head net+ /// failed to build). fn head_logits(&mut self, hidden: &[f32]) -> Result<Vec<f32>, String> { let Some(head) = self.head.as_mut() else { return self.tied_head_logits(hidden);@@ -119,6 +173,41 @@ impl Gemma4Handle { Ok(logits) } + /// 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).+ 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 logits = self.head_logits(hidden)?;+ return Ok(argmax(&logits));+ };+ let at = greedy.at(())?;+ 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+ ));+ }+ let id_out = &out[gemma4_head::HEAD_CHUNKS];+ if id_out.len() != 2 {+ return Err(format!("greedy id holds {} values, not 2", id_out.len()));+ }+ Ok(id_out[1] as u32 * 2048 + id_out[0] as u32)+ }+ /// Tied-head logits on the host: `hidden @ H^T` over the raw-scale head table. /// /// The head table is int4 `[VOCAB, D_MODEL]` (S10's `embedder.decode`@@ -290,6 +379,10 @@ fn gemma4_plan(offsets: &Offsets, pass: gemma4::Pass) -> Result<Plan, String> { gemma4::build(offsets, pass) } +fn gemma4_head_plan_greedy(offsets: &Offsets, _: ()) -> Result<Plan, String> {+ crate::nets::gemma4_head::build_plan_greedy(offsets)+}+ /// The GPU tied-head plan over an EMBED file, or `None` when the file has /// no head chunks (see `nets::gemma4_head`). fn gemma4_head_plan(embed: &Streamed) -> Option<Reshaped<()>> {@@ -307,6 +400,28 @@ fn gemma4_head_plan(embed: &Streamed) -> Option<Reshaped<()>> { .ok() } +/// The greedy head plan over an EMBED file: 16 splits + device argmax id.+///+/// `None` on files without int8 chunks (the greedy path needs the vector+/// routing; fp16 `ConvPoint` at 1 position is correct but the extra dispatch+/// mix is unmeasured — greedy stays on the int8 plan). The caller reads back+/// 17 outputs (16 splits for the sampling path + 1 two-lane id) and takes+/// the id for greedy decoding.+fn gemma4_head_plan_greedy(embed: &Streamed) -> Option<Reshaped<()>> {+ let offsets = embed.offsets();+ if offsets.len() < crate::nets::gemma4_head::TENSORS_WITH_HEAD8 {+ return None;+ }+ Reshaped::streamed(+ context::shared().ok()?,+ offsets,+ embed,+ (),+ gemma4_head_plan_greedy,+ )+ .ok()+}+ /// Positions one prefill submit covers. Large enough that a prompt is **one** submit. /// /// # Splitting a prefill is wrong, not merely slower@@ -459,9 +574,11 @@ fn build_gemma4<'l>( // to the host head. Uploading the whole EMBED file is the price: there // is no partial-upload path, so this is ~2.4 GB resident alongside TEXT. let head = gemma4_head_plan(&embed);+ let head_greedy = gemma4_head_plan_greedy(&embed); Ok(Gemma4Handle { net, head,+ head_greedy, weights, embed, tokenizer,
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 3f2a9b4395..cfae7695c7 100644--- a/library/ml/src/main/rust/src/bridge_part7.rs+++ b/library/ml/src/main/rust/src/bridge_part7.rs@@ -124,11 +124,10 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_stepGemma return -1; } };- match handle.step(token, true) {- Ok(Some(logits)) => jint::try_from(argmax(&logits)).unwrap_or(-1),- Ok(None) => -1,+ match handle.step_greedy(token) {+ Ok(id) => jint::try_from(id).unwrap_or(-1), Err(e) => {- log(&format!("gemma4 step failed: {e}"));+ log(&format!("gemma4 greedy step failed: {e}")); -1 } }
library/ml/src/main/rust/src/nets/gemma4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4.rs b/library/ml/src/main/rust/src/nets/gemma4.rsindex 67e59839ec..1e2e90411d 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -180,6 +180,11 @@ pub const LOGIT_CAP: f32 = 30.0; /// the shapes agree and every logit merely saturates at `LOGIT_CAP`. pub const EMBED_GAIN: f32 = 39.25; +/// Live int8 round-trip scales for the attention path.+///+/// Moved to gemma4_part5.rs (module-length lint): [MM_SCALE],+/// [QI_SCALE], [QO_SCALE], [KO_SCALE], [VO_SCALE], [O_SCALE].+ /// Whether `q_norm`'s gamma already carries `1 / sqrt(head_dim)`. /// /// True for a file `maml_convert.py` wrote without dividing it out, in which case the forward pass@@ -426,4 +431,6 @@ pub fn as_exported(dims: &[u32]) -> Vec<u32> { include!("gemma4_part1.rs"); include!("gemma4_part2.rs"); include!("gemma4_part3.rs");-include!("gemma4_part4.rs");\ No newline at end of file+include!("gemma4_part4.rs");+include!("gemma4_part5.rs");+include!("gemma4_part6.rs");\ No newline at end of file
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 d66177236c..309fca78a8 100644--- a/library/ml/src/main/rust/src/nets/gemma4_head.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -96,20 +96,36 @@ fn point8(b: &mut Builder, at: usize, x: Id, out: u32) -> Id { /// head) when the file carries neither. The host concatenates the 16 splits /// and runs the existing softcap + argmax, exactly as it does for the /// host-computed logits today.+///+/// `with_argmax` appends a device-side greedy sampler: the 16 splits are+/// concatenated on-device (channel Concat lowers to copies within the arena)+/// and one `Argmax` op reduces to the winning index as two fp16 lanes+/// (`lo = id % 2048`, `hi = id / 2048` — see `Builder::argmax`). The caller+/// reads back 2 values instead of 262144. The full-logits outputs stay too+/// (the Kotlin sampling path still needs them); the argmax output is last. pub fn build_plan(weights: &dyn WeightSource) -> Result<Plan, String> {+ build_plan_inner(weights, false)+}++/// [`build_plan`] with the device argmax appended. See [`build_plan`].+pub fn build_plan_greedy(weights: &dyn WeightSource) -> Result<Plan, String> {+ build_plan_inner(weights, true)+}++fn build_plan_inner(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> { // Probe for int8 chunks without marking anything read: `count()` is the // file's tensor total, which is exact (145 fp16-only, 193 with int8). if weights.count() >= TENSORS_WITH_HEAD8 {- if let Ok(plan) = build_plan8(weights) {+ if let Ok(plan) = build_plan8(weights, greedy) { return Ok(plan); } // Wrong shapes: fall through to the fp16 chunks rather than failing. }- build_plan_fp16(weights)+ build_plan_fp16(weights, greedy) } /// The int8 head pass. See [`build_plan`].-fn build_plan8(weights: &dyn WeightSource) -> Result<Plan, String> {+fn build_plan8(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> { let mut builder = Builder::new(weights); let b = &mut builder; // Every EMBED tensor this pass does not read, named so `finish` accepts@@ -130,11 +146,20 @@ fn build_plan8(weights: &dyn WeightSource) -> Result<Plan, String> { if next != HEAD8_BASE + HEAD8_CHUNK_TENSORS { return Err(format!("the int8 head claims {} tensors, not {HEAD8_CHUNK_TENSORS}", next - HEAD8_BASE)); }+ if greedy {+ // Concatenate the 16 splits on-device (channel Concat lowers to+ // copies within the arena — no extra allocation) and reduce to one+ // greedy id. The split outputs stay too, so the Kotlin sampling path+ // keeps working from the same recording.+ let row = b.concat(&outs);+ let id = b.argmax(row);+ outs.push(id);+ } builder.finish(&outs) } /// The fp16 head pass. See [`build_plan`].-fn build_plan_fp16(weights: &dyn WeightSource) -> Result<Plan, String> {+fn build_plan_fp16(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String> { let mut builder = Builder::new(weights); let b = &mut builder; // Every EMBED tensor this pass does not read, named so `finish` accepts@@ -156,6 +181,11 @@ fn build_plan_fp16(weights: &dyn WeightSource) -> Result<Plan, String> { if next != HEAD_BASE + HEAD_CHUNK_TENSORS { return Err(format!("the head claims {} tensors, not {HEAD_CHUNK_TENSORS}", next - HEAD_BASE)); }+ if greedy {+ let row = b.concat(&outs);+ let id = b.argmax(row);+ outs.push(id);+ } builder.finish(&outs) }
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 b207b57c4f..0fd04b6de5 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part3.rs@@ -92,6 +92,22 @@ mod tests { crate::nets::tests::assert_no_aliasing(&plan); } + #[test]+ fn the_tail_trace_builds_and_reads_every_tensor() {+ // Layer 0 through `layer_tail`, for the L0 device-vs-numpy bisect: the four+ // branch intermediates plus the layer output, so `finish`'s unread-tensor+ // invariant polices the same span the decode pass walks.+ let source = Shapes::new(TENSORS);+ let plan = build(&source, Mode::TraceTail.at(TEST_CONTEXT)).expect("the tail trace builds");+ assert_eq!(plan.outputs.len(), 4);+ for output in &plan.outputs {+ assert_eq!(output.shape, Shape::new(D_MODEL, 1, 1));+ }+ crate::nets::tests::assert_no_aliasing(&plan);+ let sched = crate::nets::schedule::schedule(&plan);+ crate::nets::schedule::is_sound(&plan, &sched).expect("the tail schedule is sound");+ }+ #[test] fn the_decode_plan_does_not_depend_on_the_step() { // One recording for a whole generation, as for NLLB and whisper.@@ -158,6 +174,15 @@ mod tests { assert_eq!(count(Kind::MulScalar), LAYERS, "one skip multiply per layer"); // No tied head on the device means no softcap either: the host caps. assert_eq!(count(Kind::Softcap), 0, "softcapping moved to the host with the head");+ // The live int8 round-trips of the attention path (S10's qint set):+ // qi + qo + mm + o on every layer, plus ko + vo where a layer owns+ // its cache - 15 * 6 + 20 * 4. (The `o` grid matches live exactly+ // only at full-scale O tables: the /4-rescaled build flipped codes.)+ assert_eq!(+ count(Kind::Quantize),+ OWNS_CACHE_LAYERS * 6 + (LAYERS - OWNS_CACHE_LAYERS) * 4,+ "one Mm round-trip per layer"+ ); } #[test]
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 96b83ea03a..726bbd1e27 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -298,6 +298,13 @@ pub enum Kind { CacheWrite, /// `tanh(x / cap) * cap`, Gemma's `final_logit_softcapping`. See `shaders/softcap.comp`. Softcap,+ /// The argmax of a logits row: index of the maximum value as a scalar.+ ///+ /// A device-side greedy sampler. The 262,144-logit host scan costs ~14 ms+ /// a token; this reduces on the device and reads back one value instead+ /// of 512 KB of logits. See `shaders/argmax.comp`. The full-logits path+ /// (Kotlin sampling) is untouched — this serves greedy decoding only.+ Argmax, /// An [`Act`] applied on its own, for a value no convolution produced. See /// `shaders/activate.comp`. ///
library/ml/src/main/rust/src/nets/mod_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part1.rs b/library/ml/src/main/rust/src/nets/mod_part1.rsindex f173fb9b7d..ea2b1e7ce9 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -321,6 +321,7 @@ impl Kind { | Kind::CacheWrite | Kind::Softcap | Kind::Quantize+ | Kind::Argmax | Kind::GatedActivate => {} Kind::Activate | Kind::MulScalar@@ -448,6 +449,7 @@ impl Kind { | Kind::Activate | Kind::GatedActivate | Kind::MulScalar+ | Kind::Argmax | Kind::Clamp => one(push.in0, dense), // As above, plus a folded residual addend (see `Push::res`): the // post-norm `add(x, branch)` the fusion moved into this store.
library/ml/src/main/rust/src/nets/mod_part10.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part10.rs b/library/ml/src/main/rust/src/nets/mod_part10.rsindex 6cb110d5c4..23e4eb996e 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -27,6 +27,7 @@ impl Node { | Node::ConcatPositions { out, .. } | Node::Concat { out, .. } => *out, | Node::Softcap { out, .. } => *out,+ | Node::Argmax { out, .. } => *out, | Node::Quantize { out, .. } => *out, | Node::Activate { out, .. } | Node::GatedActivate { out, .. } => *out,@@ -59,6 +60,7 @@ impl Node { | Node::LayerNorm { input, .. } | Node::Softmax { input, .. } | Node::Softcap { input, .. }+ | Node::Argmax { input, .. } | Node::Quantize { input, .. } | Node::GatedActivate { input, .. } | Node::Activate { input, .. }
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex 9eeaa79a8f..1d99fbeba8 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -307,6 +307,12 @@ pub(crate) enum Node { out: Id, cap: f32, },+ /// The argmax of a logits row: the winning index as two fp16 lanes+ /// (`lo = id % 2048`, `hi = id / 2048`). See [`Kind::Argmax`].+ Argmax {+ input: Id,+ out: Id,+ }, /// `clamp(round(x / scale), -128, 127) * scale`. See [`Kind::Quantize`]. Quantize { input: Id,
library/ml/src/main/rust/src/nets/mod_part6.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part6.rs b/library/ml/src/main/rust/src/nets/mod_part6.rsindex 4c756de11e..e74373983d 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -221,6 +221,36 @@ impl<'a> Builder<'a> { out } + /// The argmax of a logits row: the winning index as two fp16 lanes.+ ///+ /// A device-side greedy sampler (see [`Kind::Argmax`]). The output is a+ /// `[2, 1, 1]` tensor holding `lo = id % 2048` and `hi = id / 2048` as+ /// fp16 values (both exactly representable; a single fp16 slot can hold+ /// neither the value nor the bits past id 2048). The host reconstructs+ /// `hi * 2048 + lo`. Ties keep the FIRST index (strict `>` in the+ /// shader), matching the host `argmax` loop.+ pub fn argmax(&mut self, input: Id) -> Id {+ let out = self.tensor(Shape::new(2, 1, 1));+ self.nodes.push(Node::Argmax { input, out });+ out+ }++ /// `clamp(round(x / scale), -128, 127) * scale`, elementwise. See [`Kind::Quantize`].+ ///+ /// S10's per-tensor int8 round-trip, applied where the live graph quantizes an+ /// activation (the attention mixture before the O projection). The scale is a+ /// compile-time constant like [`Builder::softcap`]'s cap, for the same reason:+ /// one float per layer, fixed by the source bundle (see `MM_SCALE`).+ pub fn quantize(&mut self, input: Id, scale: f32) -> Id {+ if !(scale > 0.0) {+ self.fail(format!("a quantize of {scale}, whose scale must be positive"));+ }+ let shape = self.shape_of(input);+ let out = self.tensor(shape);+ self.nodes.push(Node::Quantize { input, out, scale });+ out+ }+ /// Softmax over the last axis, which for a score map is one query's distribution. pub fn softmax(&mut self, input: Id) -> Id { let shape = self.shape_of(input);
library/ml/src/main/rust/src/nets/mod_part9b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9b.rs b/library/ml/src/main/rust/src/nets/mod_part9b.rsindex 2d2d8c3174..e4077e62dc 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -288,6 +288,48 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }+ Node::Argmax { input, out } => {+ let si = shape(*input);+ // One scalar out: the winning index as fp16 bits. The input+ // is the concatenated logits row (all chunks, vocab-wide).+ ops.push(Op::Dispatch {+ kind: Kind::Argmax,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: si.c,+ in_h: si.h,+ in_w: si.w,+ out_c: 1,+ out_h: 1,+ out_w: 1,+ count: si.len(),+ ..Push::default()+ },+ // 64 lanes per workgroup, grid-stride over the row.+ invocations: 64,+ });+ }+ Node::Quantize { input, out, scale } => {+ let so = shape(*out);+ ops.push(Op::Dispatch {+ kind: Kind::Quantize,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: so.c,+ in_h: so.h,+ in_w: so.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ param0_bits: scale.to_bits(),+ count: so.len(),+ ..Push::default()+ },+ invocations: so.len(),+ });+ } Node::Softmax { input, out, mode, sliding, window } => { let so = shape(*out); // One invocation per row of the last axis, each normalising `out_w`
library/ml/src/main/rust/src/nets/reference_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part1.rs b/library/ml/src/main/rust/src/nets/reference_part1.rsindex 6cae5c9ff3..ccbc3e6c81 100644--- a/library/ml/src/main/rust/src/nets/reference_part1.rs+++ b/library/ml/src/main/rust/src/nets/reference_part1.rs@@ -64,6 +64,8 @@ Kind::SoftmaxPrefix => self.softmax(push, SoftmaxMode::Prefix), Kind::CacheWrite => self.cache_write(push), Kind::Softcap => self.softcap(push),+ Kind::Argmax => self.argmax(push),+ Kind::Quantize => self.quantize(push), Kind::Activate => self.activate(push), Kind::GatedActivate => self.gated_activate(push), Kind::MulScalar => self.mul_scalar(push),
library/ml/src/main/rust/src/nets/reference_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part2.rs b/library/ml/src/main/rust/src/nets/reference_part2.rsindex 8da7848b2d..da51ef221c 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -253,6 +253,27 @@ Ok(()) } + /// The argmax of a logits row, as the host reads it back.+ ///+ /// Mirrors `shaders/argmax.comp`: strict `>` over the row keeps the FIRST+ /// index on ties, stored as `lo = id % 2048`, `hi = id / 2048` fp16+ /// values. See `Builder::argmax`.+ fn argmax(&mut self, p: &Push) -> Result<(), String> {+ let len = (p.in_c * p.in_h * p.in_w).max(1);+ let mut top_val = f32::NEG_INFINITY;+ let mut top_idx = 0u32;+ for i in 0..len {+ let value = self.load(p.in0, i)?;+ if value > top_val {+ top_val = value;+ top_idx = i;+ }+ }+ self.store(p.out, 0, (top_idx % 2048) as f32)?;+ self.store(p.out, 1, (top_idx / 2048) as f32)?;+ Ok(())+ }+ /// Root-mean-square normalisation over the channel axis, per spatial position. /// /// [`Reference::layer_norm`] without the mean and without beta, and so one pass over
library/ml/src/main/rust/src/nets/reference_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part3.rs b/library/ml/src/main/rust/src/nets/reference_part3.rsindex 59ca474db3..0812297e12 100644--- a/library/ml/src/main/rust/src/nets/reference_part3.rs+++ b/library/ml/src/main/rust/src/nets/reference_part3.rs@@ -86,6 +86,20 @@ Ok(()) } + /// S10's int8 round-trip. See `shaders/quantize.comp`.+ fn quantize(&mut self, p: &Push) -> Result<(), String> {+ let scale = f32::from_bits(p.param0_bits);+ if !(scale > 0.0) {+ return Err(format!("a quantize of {scale}"));+ }+ for index in 0..p.count {+ let value = self.load(p.in0, index)?;+ let q = ((value / scale + 0.5).floor()).clamp(-128.0, 127.0);+ self.store(p.out, index, q * scale)?;+ }+ Ok(())+ }+ /// Copy one position into a KV cache at the step's prefix. See `shaders/cache_write.comp`. /// /// The one op whose destination depends on the step rather than the recording, which is why
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 6b5a842d79..79dcb09300 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -25,6 +25,7 @@ use ash::vk; use crate::nets::Kind; use super::context::Context;+use super::pipeline_extra::{CONV_POINT_Q2K, CONV_Q2K, QUANTIZE}; use super::segment::Segment; const CONV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv.comp.spv"));@@ -83,12 +84,10 @@ const CONV_VEC_INT4: &[u8] = const CONV_POINT_INT4: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_int4.comp.spv")); const CONV_VEC_Q2K: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_vec_q2k.comp.spv"));-const CONV_POINT_Q2K: &[u8] =- include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_q2k.comp.spv"));-const CONV_Q2K: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_q2k.comp.spv"));--/// Every shader, in the order [`Pipelines::create`] destructures them.-pub(crate) const SPIRV: [&[u8]; 43] = [+const ARGMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/argmax.comp.spv"));+/// Every shader, in the order `Shaders::create` destructures them (the Q2_K pair and+/// `QUANTIZE` live in `pipeline_extra.rs` for length).+pub(crate) const SPIRV: [&[u8]; 45] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -132,6 +131,8 @@ pub(crate) const SPIRV: [&[u8]; 43] = [ CONV_VEC_Q2K, CONV_POINT_Q2K, CONV_Q2K,+ QUANTIZE,+ ARGMAX, ]; /// Descriptors in one set: the arena, the weights as fp16, the weights as words, the step params.@@ -209,6 +210,8 @@ pub struct Shaders { pub(crate) mul_scalar: vk::Pipeline, pub(crate) clamp: vk::Pipeline, pub(crate) rmsnorm: vk::Pipeline,+ pub(crate) quantize: vk::Pipeline,+ pub(crate) argmax: vk::Pipeline, } /// One net's descriptor sets, over the device-wide [`Shaders`].
library/ml/src/main/rust/src/vulkan/pipeline_extra.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rsindex 102c17e5dc..b150c16281 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs@@ -5,6 +5,19 @@ use crate::nets::{Kind, Push}; use super::context::Context; use super::pipeline::{Cleanup, Shaders, SPIRV, compute_pipeline}; +// The int8 round-trip shader, beside the table it joins (see `SPIRV`).+// Lives here rather than in `pipeline.rs` so that file stays under the+// 500-line Rust limit.+pub(crate) const QUANTIZE: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/quantize.comp.spv"));++// The Q2_K pair, beside the table they join (see `SPIRV`). Same reason as+// `QUANTIZE` above: `pipeline.rs` must stay under the 500-line Rust limit.+pub(crate) const CONV_POINT_Q2K: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_q2k.comp.spv"));+pub(crate) const CONV_Q2K: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/conv_q2k.comp.spv"));+ impl Shaders { /// Compile every shader and build the two layouts. Called once per device. pub fn new(context: &Context) -> Result<Shaders, String> {@@ -140,6 +153,8 @@ impl Shaders { conv_vec_q2k, conv_point_q2k, conv_q2k,+ quantize,+ argmax, ] = match <[vk::Pipeline; SPIRV.len()]>::try_from(built) { Ok(all) => all, Err(built) => {@@ -197,6 +212,8 @@ impl Shaders { conv_vec_q2k, conv_point_q2k, conv_q2k,+ quantize,+ argmax, }) } @@ -246,6 +263,8 @@ impl Shaders { Kind::Constant => self.constant, Kind::AddBroadcast => self.add_bcast, Kind::Rotary => self.rotary,+ Kind::Quantize => self.quantize,+ Kind::Argmax => self.argmax, } } @@ -296,6 +315,8 @@ impl Shaders { self.conv_q2k, self.mul_scalar, self.clamp,+ self.quantize,+ self.argmax, ] { device.destroy_pipeline(pipeline, None); }