Modern Apps git

← Modern-Apps.git

ml: device top-64 for gemma4 sampling, sampled head 92 -> 20 ms on Pixel

Commit
eef7952e0956c7df5315dc551ee7ecb3c3edf6be
Author
vayun-mathur <[email protected]>
When
2026-10-26 01:12 UTC (1 month ago)
Parents
8d90d08

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 17ae5292d1..4bad336bfe 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -26,6 +26,7 @@ use std::path::PathBuf; use std::sync::Arc;  use modelrunner::nets::gemma4;+use modelrunner::nets::gemma4_head::HeadOut; use modelrunner::vulkan::context; use modelrunner::vulkan::reshape::Reshaped; use modelrunner::vulkan::run::StepParams;@@ -74,8 +75,8 @@ fn gemma4_plan(offsets: &modelrunner::weights::Offsets, pass: gemma4::Pass) -> R     gemma4::build(offsets, pass) } -fn head_plan(offsets: &modelrunner::weights::Offsets, greedy: bool) -> Result<modelrunner::nets::Plan, String> {-    modelrunner::nets::gemma4_head::build_plan_standalone(offsets, greedy)+fn head_plan(offsets: &modelrunner::weights::Offsets, out: HeadOut) -> Result<modelrunner::nets::Plan, String> {+    modelrunner::nets::gemma4_head::build_plan_standalone(offsets, out) }  struct Args {@@ -84,6 +85,7 @@ struct Args {     time: Option<usize>,     prefill: Option<u32>,     sample: bool,+    topk: bool,     split: Option<u32>,     len: Option<u32>,     gather: bool,@@ -94,7 +96,7 @@ struct Args { /// 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, soft: false };+        Args { positional: Vec::new(), head: None, time: None, prefill: None, sample: false, topk: 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() {@@ -102,6 +104,7 @@ 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,+            "--topk" => args.topk = 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,@@ -124,7 +127,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] [--split K [--len N]]"+             [--head head.maml] [--time N [--sample] [--topk]] [--prefill N] [--split K [--len N]]"         );         return;     };@@ -158,7 +161,8 @@ 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, args.gather);+        let mode = if args.topk { HeadOut::TopK } else if args.sample { HeadOut::Logits } else { HeadOut::Greedy };+        time_decode(&context, &weights, &embed_weights, head_weights.as_ref(), &tokens, repeats, mode, args.gather);         return print_memory();     }     if args.soft {@@ -347,13 +351,13 @@ struct StepTimes { #[allow(clippy::too_many_arguments)] fn decode_one(     net: &mut Reshaped<gemma4::Pass>,-    head: Option<&mut Reshaped<bool>>,+    head: Option<&mut Reshaped<HeadOut>>,     gather: Option<&mut Reshaped<()>>,     embed: &modelrunner::weights::Reader<'_>,     rotary: &modelrunner::weights::Reader<'_>,     token: u32,     position: u32,-    sample: bool,+    mode: HeadOut,     times: &mut StepTimes, ) -> Result<Option<u32>, String> {     use std::time::Instant;@@ -397,8 +401,11 @@ fn decode_one(     let Some(head) = head else { return Ok(None) };     let hidden = out.into_iter().next().ok_or("the step returned nothing")?;     let tick = Instant::now();-    let out = head.at(!sample)?.infer_raw_many(&[&hidden])?;-    let id = if sample {+    let out = head.at(mode)?.infer_raw_many(&[&hidden])?;+    let id = if mode == HeadOut::TopK {+        let top = out.first().ok_or("the top-k head returned nothing")?;+        top[2] as u32 * 2048 + top[1] as u32+    } else if mode == HeadOut::Logits {         let logits = softcapped(&out)?;         let mut best = (f32::NEG_INFINITY, 0u32);         for (i, &v) in logits.iter().enumerate() {@@ -418,9 +425,9 @@ fn decode_one(     Ok(Some(id)) } -fn build_head(context: &Arc<context::Context>, head: Option<&Streamed>, greedy: bool) -> Result<Option<Reshaped<bool>>, String> {+fn build_head(context: &Arc<context::Context>, head: Option<&Streamed>, mode: HeadOut) -> Result<Option<Reshaped<HeadOut>>, String> {     match head {-        Some(file) => streamed_net(context, file, greedy, head_plan).map(Some),+        Some(file) => streamed_net(context, file, mode, head_plan).map(Some),         None => {             println!("no --head: timings exclude the head");             Ok(None)@@ -440,7 +447,7 @@ fn time_decode(     head: Option<&Streamed>,     tokens: &[u32],     repeats: usize,-    sample: bool,+    mode: HeadOut,     device_gather: bool, ) {     use std::time::Instant;@@ -458,7 +465,7 @@ fn time_decode(     } else {         None     };-    let mut head_net = match build_head(context, head, !sample) {+    let mut head_net = match build_head(context, head, mode) {         Ok(net) => net,         Err(why) => return println!("the head does not build: {why}"),     };@@ -475,7 +482,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(), gather_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, mode, &mut times) {                 Ok(id) => ids.extend(id),                 Err(why) => return println!("step {step} failed: {why}"),             }@@ -499,7 +506,7 @@ fn time_decode(         let mean = steady.iter().sum::<f64>() / n;         println!(             "steady-state ({}): {mean:.1} ms/token = {:.2} tok/s",-            if head_net.is_none() { "no head" } else if sample { "sampled head" } else { "greedy head" },+            if head_net.is_none() { "no head" } else { match mode { HeadOut::Logits => "sampled head", HeadOut::TopK => "top-k head", HeadOut::Greedy => "greedy head" } },             1000.0 / mean.max(1e-9)         );         println!(@@ -517,7 +524,7 @@ fn time_decode(             Err(why) => println!("timestamps unreadable: {why}"),         }         if let Some(head) = head_net.as_mut() {-            match head.at(!sample).and_then(|at| at.op_times()) {+            match head.at(mode).and_then(|at| at.op_times()) {                 Ok(report) => print_kinds("head", &report),                 Err(why) => println!("head timestamps unreadable: {why}"),             }@@ -548,7 +555,7 @@ fn time_prefill(         Ok(net) => net,         Err(why) => return println!("the net does not build: {why}"),     };-    let mut head_net = match build_head(context, head, true) {+    let mut head_net = match build_head(context, head, HeadOut::Greedy) {         Ok(net) => net,         Err(why) => return println!("the head does not build: {why}"),     };@@ -600,7 +607,7 @@ fn time_prefill(         }         let tick = Instant::now();         let mut times = StepTimes::default();-        let id = match decode_one(&mut net, head_net.as_mut(), None, &reader, &rotary, next, width, false, &mut times) {+        let id = match decode_one(&mut net, head_net.as_mut(), None, &reader, &rotary, next, width, HeadOut::Greedy, &mut times) {             Ok(id) => id,             Err(why) => return println!("the first decode step failed: {why}"),         };@@ -681,7 +688,7 @@ fn feed( #[allow(clippy::too_many_arguments)] fn last_logits(     net: &mut Reshaped<gemma4::Pass>,-    head: &mut Reshaped<bool>,+    head: &mut Reshaped<HeadOut>,     embed: &modelrunner::weights::Reader<'_>,     rotary: &modelrunner::weights::Reader<'_>,     token: u32,@@ -694,7 +701,7 @@ fn last_logits(     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])?)+    softcapped(&head.at(HeadOut::Logits)?.infer_raw_many(&[&state])?) }  fn top10(logits: &[f32]) -> Vec<u32> {@@ -722,7 +729,7 @@ fn split_check(     }     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 mut head_net = streamed_net(context, head, HeadOut::Logits, head_plan)?;     let reader = embed.reader();     let rotary = weights.reader();     let last = prompt[n - 1];@@ -842,7 +849,7 @@ fn soft_check(     }     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 mut head_net = streamed_net(context, head, HeadOut::Logits, head_plan)?;     let reader = embed.reader();     let rotary = weights.reader();     let mut rows = Vec::new();@@ -995,8 +1002,8 @@ fn gpu_logits(     hidden: &[f32], ) -> Result<Vec<f32>, String> {     let head = head.ok_or("no head file: pass --head gemma4_head.maml")?;-    let mut net = streamed_net(context, head, false, head_plan)?;-    softcapped(&net.at(false)?.infer_raw_many(&[hidden])?)+    let mut net = streamed_net(context, head, HeadOut::Logits, head_plan)?;+    softcapped(&net.at(HeadOut::Logits)?.infer_raw_many(&[hidden])?) }  /// The 16 head splits concatenated and softcapped, as the bridge does it.
library/ml/src/main/rust/shaders/topk.comp
diff --git a/library/ml/src/main/rust/shaders/topk.comp b/library/ml/src/main/rust/shaders/topk.compnew file mode 100644index 0000000000..92f95baa1b--- /dev/null+++ b/library/ml/src/main/rust/shaders/topk.comp@@ -0,0 +1,88 @@+#version 450+//! The 64 largest logits of a row, highest first, ties by lower index - in two stages like+//! `argmax.comp` / `argmax_fold.comp`, selected by the same 64 rounds in both.+//!+//! Round `r` takes the best `(value, index)` strictly below round `r - 1`'s winner in the order+//! "greater value, then lower index", so equal values are taken in index order and nothing is+//! taken twice without marking anything. Each lane scans its elements for its own best+//! qualifying key and a 64-entry shared reduction picks the round's winner.+//!+//! `p.kh == 0`, stage 1: workgroup `g` of `p.group` owns `[g * slice, min((g + 1) * slice,+//! p.count))` of the row at `p.in0` and writes its top 64 ids to `p.out_at + (g * 64 + r) * 2`+//! as `(lo = id % 2048, hi = id / 2048)`, both exact in fp16. Missing ranks (a slice under 64)+//! are `(2047, 2047)`, an id past any row.+//!+//! `p.kh == 1`, stage 2: one workgroup reads the `p.in_c` candidate ids at `p.in0`, re-reads each+//! one's logit from the row at `p.in1` (`p.in_w` long), and writes rank `r` as `(value, lo, hi)`+//! at `p.out_at + r * 3`. The values are the row's own fp16 values, so nothing is rounded twice.+#include "common.glsl"+#define K 64u+#define NONE 0xFFFFFFFFu+shared float best_val[64];+shared uint best_idx[64];++bool better(float av, uint ai, float bv, uint bi) {+    return bi == NONE || (ai != NONE && (av > bv || (av == bv && ai < bi)));+}++void main() {+    uint lane = gl_LocalInvocationID.x;+    bool fold = p.kh != 0u;+    uint group = gl_WorkGroupID.x;+    uint groups = max(p.group, 1u);+    uint slice = (p.count + groups - 1u) / groups;+    uint first = fold ? 0u : group * slice;+    uint end = fold ? p.in_c : min(first + slice, p.count);+    float prev_val = 0.0;+    uint prev_idx = NONE;+    bool done = false;+    for (uint r = 0u; r < K; r++) {+        float mine_val = 0.0;+        uint mine_idx = NONE;+        for (uint e = first + lane; !done && e < end; e += 64u) {+            uint idx = e;+            if (fold) {+                idx = uint(float(arena[p.in0 + e * 2u])) + 2048u * uint(float(arena[p.in0 + e * 2u + 1u]));+                if (idx >= p.in_w) {+                    continue;+                }+            }+            float v = float(arena[(fold ? p.in1 : p.in0) + idx]);+            // Strictly after the previous winner in the order, so each key is taken once.+            bool after = prev_idx == NONE || v < prev_val || (v == prev_val && idx > prev_idx);+            if (after && better(v, idx, mine_val, mine_idx)) {+                mine_val = v;+                mine_idx = idx;+            }+        }+        best_val[lane] = mine_val;+        best_idx[lane] = mine_idx;+        barrier();+        for (uint stride = 32u; stride > 0u; stride >>= 1u) {+            if (lane < stride && better(best_val[lane + stride], best_idx[lane + stride], best_val[lane], best_idx[lane])) {+                best_val[lane] = best_val[lane + stride];+                best_idx[lane] = best_idx[lane + stride];+            }+            barrier();+        }+        float win_val = best_val[0];+        uint win_idx = best_idx[0];+        barrier();+        if (lane == 0u) {+            uint lo = win_idx == NONE ? 2047u : win_idx % 2048u;+            uint hi = win_idx == NONE ? 2047u : win_idx / 2048u;+            if (fold) {+                arena[p.out_at + r * 3u] = float16_t(win_idx == NONE ? -65504.0 : win_val);+                arena[p.out_at + r * 3u + 1u] = float16_t(float(lo));+                arena[p.out_at + r * 3u + 2u] = float16_t(float(hi));+            } else {+                arena[p.out_at + (group * K + r) * 2u] = float16_t(float(lo));+                arena[p.out_at + (group * K + r) * 2u + 1u] = float16_t(float(hi));+            }+        }+        // Uniform across the workgroup: every lane read the same winner.+        done = win_idx == NONE;+        prev_val = win_val;+        prev_idx = win_idx;+    }+}
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 e9a688fafc..4a234ffb4d 100644--- a/library/ml/src/main/rust/src/bridge_part11.rs+++ b/library/ml/src/main/rust/src/bridge_part11.rs@@ -36,9 +36,9 @@ fn gemma4_gather_plan(embed: &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>> {+/// int8 triples, ~385 MB): one upload, one recording per `HeadOut` (greedy id,+/// the 16 logit splits, the device top 64). `None` when the file does not match.+fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<crate::nets::gemma4_head::HeadOut>> {     let offsets = head.offsets();     if offsets.len() != crate::nets::gemma4_head::HEAD_FILE_TENSORS {         return None;@@ -47,8 +47,8 @@ fn gemma4_head_file_plan(head: &Streamed) -> Option<Reshaped<bool>> {         context::shared().ok()?,         offsets,         head,-        true,-        |offsets, greedy| crate::nets::gemma4_head::build_plan_standalone(offsets, greedy),+        crate::nets::gemma4_head::HeadOut::Greedy,+        |offsets, out| crate::nets::gemma4_head::build_plan_standalone(offsets, out),     )     .ok() }
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 a015e99354..078707781c 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -399,10 +399,10 @@ fn log(message: &str) { struct Gemma4Handle {     net: Reshaped<gemma4::Pass>,     /// 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)`+    /// plans: `at(Greedy)` is the device-argmax plan (one id back), `at(Logits)`     /// the 16 logit splits. `None` without a head file - the host head covers     /// that.-    head: Option<Reshaped<bool>>,+    head: Option<Reshaped<crate::nets::gemma4_head::HeadOut>>,     /// 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.
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 354e3fbc9d..d8a8961396 100644--- a/library/ml/src/main/rust/src/bridge_part6.rs+++ b/library/ml/src/main/rust/src/bridge_part6.rs@@ -160,8 +160,13 @@ impl Gemma4Handle {         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.+        let state = self.decode_state(hidden, per_layer)?;+        self.head_greedy(&state)+    }++    /// The transformer half of a decode step (DecodeStep, same params and cache discipline as+    /// the logits path): the normed hidden state the head reads.+    fn decode_state(&mut self, hidden: &[f32], per_layer: &[f32]) -> Result<Vec<f32>, String> {         if self.position >= self.context {             return Err(format!("the cache is full at {} positions", self.context));         }@@ -182,11 +187,11 @@ impl Gemma4Handle {         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));+        let state = out.into_iter().next().unwrap_or_default();+        if state.len() != gemma4::D_MODEL as usize {+            return Err(format!("hidden state of {} values, not {}", state.len(), gemma4::D_MODEL));         }-        self.head_greedy(hidden)+        Ok(state)     }      /// Logits for `hidden`, GPU head when the EMBED file carries chunks.@@ -199,7 +204,7 @@ impl Gemma4Handle {         let Some(head) = self.head.as_mut() else {             return self.tied_head_logits(hidden);         };-        let at = head.at(false)?;+        let at = head.at(crate::nets::gemma4_head::HeadOut::Logits)?;         let out = at.infer_raw_many(&[hidden])?;         if out.len() != crate::nets::gemma4_head::HEAD_CHUNKS {             return Err(format!(@@ -222,14 +227,14 @@ impl Gemma4Handle {      /// The greedy next token for `hidden`, reduced on the device.     ///-    /// `head.at(true)`: the splits concatenate and reduce on the device, so two values+    /// `head.at(Greedy)`: 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> {         let Some(head) = self.head.as_mut() else {             let logits = self.head_logits(hidden)?;             return Ok(argmax(&logits));         };-        let at = head.at(true)?;+        let at = head.at(crate::nets::gemma4_head::HeadOut::Greedy)?;         let out = at.infer_raw_many(&[hidden])?;         if out.len() != 1 {             return Err(format!("greedy head returned {} outputs, not 1", out.len()));
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 c5a6511d60..da36d8d177 100644--- a/library/ml/src/main/rust/src/bridge_part9.rs+++ b/library/ml/src/main/rust/src/bridge_part9.rs@@ -206,10 +206,7 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_topKGemma             log(&format!("gemma4 top-k was given token {token}, k {k}"));             return Ok(std::ptr::null_mut());         }-        let picked = handle-            .step(token, true)-            .and_then(|logits| logits.ok_or_else(|| "a decode step returned no logits".to_string()))-            .map(|logits| top_k_pairs(&logits, k));+        let picked = handle.step_top_k(token, k);         Ok(match picked {             Ok(pairs) => match new_float_array(env, &pairs) {                 Ok(array) => array,@@ -249,4 +246,32 @@ mod top_k_tests {         assert_eq!(super::top_k_pairs(&logits, 4), vec![2.0, 1.0, 2.0, 3.0, 1.5, 4.0, 0.5, 0.0]);         assert_eq!(super::top_k_pairs(&logits, 9).len(), 12, "k past the vocabulary keeps all");     }-}\ No newline at end of file+}+impl Gemma4Handle {+    /// One decode step whose head returns `[softcapped logit, id] x k`, highest first, ties by+    /// lower id. On the device (`HeadOut::TopK`, 192 values back) when the head file is loaded+    /// and `k` fits its 64; otherwise the full logits, selected on the host.+    fn step_top_k(&mut self, token: u32, k: usize) -> Result<Vec<f32>, String> {+        use crate::nets::gemma4_head::HeadOut;+        let device = k <= crate::nets::gemma4::TOP_K as usize && self.head.is_some();+        if !device {+            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 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")?;+        let mut pairs = Vec::with_capacity(k * 2);+        for triple in triples.chunks_exact(3).take(k) {+            let id = triple[2] as u32 * 2048 + triple[1] as u32;+            if id >= gemma4::VOCAB {+                break;+            }+            pairs.push(gemma4::LOGIT_CAP * (triple[0] / gemma4::LOGIT_CAP).tanh());+            pairs.push(id as f32);+        }+        Ok(pairs)+    }+}
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 66baa30094..d35b2fcf3d 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -434,4 +434,5 @@ include!("gemma4_part3.rs"); include!("gemma4_part4.rs"); include!("gemma4_part5.rs"); include!("gemma4_part6.rs");-include!("gemma4_part7.rs");\ No newline at end of file+include!("gemma4_part7.rs");+include!("gemma4_part8.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 9c52a493dd..66ee7733ba 100644--- a/library/ml/src/main/rust/src/nets/gemma4_head.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -200,14 +200,24 @@ fn build_plan_fp16(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, Str     builder.finish(&outs) } +/// What the standalone head hands back.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum HeadOut {+    /// The 16 logit splits.+    Logits,+    /// The device argmax id as `[lo, hi]`.+    Greedy,+    /// The 64 largest logits as `[value, lo, hi] x 64` (see `Builder::top_k`).+    TopK,+}+ /// The standalone head pass over the head file (`graph::GEMMA4_HEAD`). /// /// 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` 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> {+/// needed — `finish` sees every tensor read). `Greedy` and `TopK` reduce the+/// splits on the device, so a step reads back 2 or 192 values instead of 512 KB.+pub fn build_plan_standalone(weights: &dyn WeightSource, out: HeadOut) -> Result<Plan, String> {     let mut builder = Builder::new(weights);     let b = &mut builder;     let x = b.input(Shape::new(D_MODEL, 1, 1));@@ -215,12 +225,19 @@ pub fn build_plan_standalone(weights: &dyn WeightSource, greedy: bool) -> Result     for s in 0..HEAD_CHUNKS {         outs.push(point8(b, s * 3, x, CLASSES_PER_CHUNK));     }-    if greedy {-        let row = b.concat(&outs);-        let id = b.argmax(row);-        return builder.finish(&[id]);+    match out {+        HeadOut::Logits => builder.finish(&outs),+        HeadOut::Greedy => {+            let row = b.concat(&outs);+            let id = b.argmax(row);+            builder.finish(&[id])+        }+        HeadOut::TopK => {+            let row = b.concat(&outs);+            let top = b.top_k(row);+            builder.finish(&[top])+        }     }-    builder.finish(&outs) }  /// The shape of EMBED tensor `index`, derived from the layout constants.@@ -371,11 +388,13 @@ mod tests {     #[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");+        let plan = build_plan_standalone(&source, HeadOut::Greedy).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");+        let plan = build_plan_standalone(&source, HeadOut::Logits).expect("the logits head builds");         assert_eq!(plan.outputs.len(), HEAD_CHUNKS);+        let plan = build_plan_standalone(&source, HeadOut::TopK).expect("the top-k head builds");+        assert_eq!(plan.outputs[0].shape, Shape::new(192, 1, 1));     }      #[test]
library/ml/src/main/rust/src/nets/gemma4_part8.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part8.rs b/library/ml/src/main/rust/src/nets/gemma4_part8.rsnew file mode 100644index 0000000000..f2e21e7cb9--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_part8.rs@@ -0,0 +1,49 @@+// Device top-k over a logits row (`shaders/topk.comp`): Gemma's sampler draws from 64+// candidates, so 64 `(value, id)` triples come back instead of the 262,144-entry row.++/// Candidates per row. `topk.comp` hard-codes the same count as `K`.+pub const TOP_K: u32 = 64;++impl Builder<'_> {+    /// The [`TOP_K`] largest of `row` (any shape, read flat), highest first, ties by lower+    /// index, as `[value, lo, hi] x TOP_K` with `id = hi * 2048 + lo`. Ranks past the row's+    /// length have `lo = hi = 2047`.+    pub fn top_k(&mut self, row: Id) -> Id {+        let len = self.shape_of(row).len();+        let groups = super::argmax_groups(len).max(1);+        let partials = self.tensor(Shape::new(groups * TOP_K * 2, 1, 1));+        self.nodes.push(super::Node::TopK { input: row, row, out: partials, fold: false });+        let out = self.tensor(Shape::new(TOP_K * 3, 1, 1));+        self.nodes.push(super::Node::TopK { input: partials, row, out, fold: true });+        out+    }++    /// The emit arm for [`super::Node::TopK`]; every other node emits nothing here.+    pub(crate) fn emit_top_k(+        &self,+        node: &super::Node,+        at: &dyn Fn(Id) -> Result<u32, String>,+        shape: &dyn Fn(Id) -> Shape,+        ops: &mut Vec<super::Op>,+    ) -> Result<(), String> {+        let super::Node::TopK { input, row, out, fold } = node else { return Ok(()) };+        let (si, sr, so) = (shape(*input), shape(*row), shape(*out));+        let common = super::Push {+            in0: at(*input)?,+            out: at(*out)?,+            out_c: so.c,+            out_h: so.h,+            out_w: so.w,+            ..super::Push::default()+        };+        let (push, invocations) = if *fold {+            let push = super::Push { in1: at(*row)?, in_c: si.len() / 2, in_w: sr.len(), kh: 1, count: TOP_K, ..common };+            (push, 64)+        } else {+            let groups = super::argmax_groups(si.len()).max(1);+            (super::Push { in_c: si.len(), group: groups, count: si.len(), ..common }, groups * 64)+        };+        ops.push(super::Op::Dispatch { kind: super::Kind::TopK, push, invocations });+        Ok(())+    }+}
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 233770fe3f..d2f6189e02 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -150,22 +150,6 @@ pub enum Act {     Gelu, } -impl Act {-    pub(crate) fn code(self) -> u32 {-        match self {-            Act::None => 0,-            Act::Relu => 1,-            Act::HardSwish => 2,-            Act::Sigmoid => 3,-            Act::PRelu(_) => 4,-            Act::Clip01 => 5,-            Act::Swish => 6,-            Act::Relu6 => 7,-            Act::Gelu => 8,-        }-    }-}- /// Which compute pipeline an [`Op::Dispatch`] wants. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind {@@ -482,19 +466,15 @@ pub enum Kind {     Rotary, } -/// [`Push::res`] / [`Push::shift`] when no addend is folded into the store.-///-/// Arena offset 0 is a live tensor — the first input is pinned there — so "none" needs a value-/// no allocation can hold. [`Builder::finish`] writes real offsets only onto the ops it fuses;-/// everything else keeps this through the manual [`Push`] default below.-pub const NO_FUSE: u32 = u32::MAX;- include!("mod_part1.rs"); include!("mod_part2.rs");+include!("mod_part2b.rs"); include!("mod_part3.rs"); include!("mod_part4.rs");+include!("mod_part4b.rs"); include!("mod_part5.rs"); include!("mod_part6.rs");+include!("mod_part6b.rs"); include!("mod_part7.rs"); include!("mod_part8.rs"); include!("mod_part9.rs");@@ -502,4 +482,5 @@ include!("mod_part9b.rs"); include!("mod_part10.rs"); include!("mod_part11.rs"); include!("mod_part12.rs");-include!("mod_part13.rs");\ No newline at end of file+include!("mod_part13.rs");+include!("mod_part14.rs");\ No newline at end of file
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 75f04beb2b..8b068b3283 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -333,6 +333,7 @@ impl Kind {             | Kind::Quantize             | Kind::Argmax             | Kind::ArgmaxFold+            | Kind::TopK             | Kind::GatedActivate => {}             // A scalar (`mul_scalar`) or a low/high pair (`clamp`) at `act_weight`.             Kind::MulScalar | Kind::Clamp => {@@ -427,6 +428,9 @@ impl Kind {             // The candidate pairs plus the whole logits row, re-read at the candidates.             // `in_c` is the group count, `in_w` the row length.             Kind::ArgmaxFold => two((push.in0, push.in_c * 2), (push.in1, push.in_w)),+            // Stage 1 reads its row; stage 2 its candidate pairs and the row they index.+            Kind::TopK if push.kh == 0 => one(push.in0, push.count),+            Kind::TopK => two((push.in0, push.in_c * 2), (push.in1, push.in_w)),             // One row in. Not `dense`: `in_h` here is the cache's capacity, not a spatial extent.             Kind::CacheWrite => one(push.in0, push.count),             // Convolutions, whose store may also add a folded residual and a folded
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 9abd78dee1..cefe29b792 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -30,6 +30,7 @@ impl Node {             | Node::Softcap { out, .. } => *out,             | Node::Argmax { out, .. }             | Node::ArgmaxFold { out, .. } => *out,+            | Node::TopK { out, .. } => *out,             | Node::Quantize { out, .. } => *out,             | Node::Activate { out, .. }             | Node::GatedActivate { out, .. } => *out,@@ -73,6 +74,7 @@ impl Node {             | Node::SliceChannels { input, .. }             | Node::GlobalAvgPool { input, .. } => vec![*input],             Node::ArgmaxFold { input, row, .. } => vec![*input, *row],+            Node::TopK { input, row, .. } => vec![*input, *row],             Node::RmsNorm { input, res, .. } => {                 let mut reads = vec![*input];                 reads.extend(res.iter().copied());
library/ml/src/main/rust/src/nets/mod_part11.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part11.rs b/library/ml/src/main/rust/src/nets/mod_part11.rsindex a49bce5429..7c1d1f887d 100644--- a/library/ml/src/main/rust/src/nets/mod_part11.rs+++ b/library/ml/src/main/rust/src/nets/mod_part11.rs@@ -455,102 +455,5 @@ pub(crate) mod tests {         assert_eq!(fused[0].out_c, 4);     } -    /// An add whose convolution output has a second reader stays its own dispatch.-    ///-    /// Folding it would leave the other reader with no writer: the producer's old-    /// output tensor is never allocated once the fold moves the sum.-    #[test]-    fn a_shared_convolution_output_keeps_its_add() {-        let source = Shapes::new(5);-        let mut builder = Builder::new(&source);-        let x = builder.input(Shape::new(4, 1, 4));-        let narrowed = builder.conv_same(x, 0, 4, 1, 1, Act::None);-        let summed = builder.add(x, narrowed);-        // A second reader of the convolution's output: the folded store would orphan it.-        let mixed = builder.mul(summed, narrowed);-        // Tensors 2, 3 and 4 are the file's spares; see the residual test above.-        builder.host_tensor(2, &[1]);-        builder.host_tensor(3, &[1]);-        builder.host_tensor(4, &[1]);-        let plan = builder.finish(&[mixed]).expect("builds");-        assert_eq!(-            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),-            1,-            "the shared add must survive: {:?}",-            plan.ops-        );-    }--    /// An add held as a plan output stays its own dispatch.-    ///-    /// Nothing downstream reads it, but the host does — folding the sum into the-    /// convolution's store would leave the output binding pointing at an unwritten tensor.-    #[test]-    fn an_add_that_is_a_plan_output_keeps_its_dispatch() {-        let source = Shapes::new(5);-        let mut builder = Builder::new(&source);-        let x = builder.input(Shape::new(4, 1, 4));-        let narrowed = builder.conv_same(x, 0, 4, 1, 1, Act::None);-        let summed = builder.add(x, narrowed);-        // Both the convolution's output and the sum escape: neither may fold.-        // Tensors 2, 3 and 4 are the file's spares; see the residual test above.-        builder.host_tensor(2, &[1]);-        builder.host_tensor(3, &[1]);-        builder.host_tensor(4, &[1]);-        let plan = builder.finish(&[narrowed, summed]).expect("builds");-        assert_eq!(-            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),-            1,-            "the output add must survive: {:?}",-            plan.ops-        );-    }--    /// An FPN-style `add(earlier, later)` stays its own dispatch.-    ///-    /// The skip side is downstream of the producing convolution, so reading it from-    /// the producer's store would read an unwritten tensor. See `Builder::add`.-    #[test]-    fn an_add_of_a_downstream_tensor_does_not_fold() {-        let source = Shapes::new(7);-        let mut builder = Builder::new(&source);-        let x = builder.input(Shape::new(4, 1, 8));-        let early = builder.conv_same(x, 0, 4, 1, 1, Act::None);-        let later = builder.conv_same(early, 2, 4, 1, 1, Act::None);-        let grown = builder.resize_to(later, 1, 8);-        // `early` is upstream of the convolution that feeds `grown`'s side... but the-        // addend that matters is `grown` itself, produced after `early`: folding the-        // add into `early`'s store would read it before it is written.-        let merged = builder.add(early, grown);-        let out = builder.conv_same(merged, 4, 4, 1, 1, Act::None);-        // Tensor 6 is the file's spare; see the residual test above.-        builder.host_tensor(6, &[1]);-        let plan = builder.finish(&[out]).expect("builds");-        assert_eq!(-            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),-            1,-            "the FPN add must survive: {:?}",-            plan.ops-        );-    }--    /// A self-add never folds: the convolution would read the tensor it no longer writes.-    #[test]-    fn a_self_add_does_not_fold() {-        let source = Shapes::new(3);-        let mut builder = Builder::new(&source);-        let x = builder.input(Shape::new(4, 1, 4));-        let narrowed = builder.conv_same(x, 0, 4, 1, 1, Act::None);-        let doubled = builder.add(narrowed, narrowed);-        // Tensor 2 is the file's spare; see the residual test above.-        builder.host_tensor(2, &[1]);-        let plan = builder.finish(&[doubled]).expect("builds");-        assert_eq!(-            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),-            1,-            "the self-add must survive: {:?}",-            plan.ops-        );-    }-+    include!("mod_part11b.rs"); }\ No newline at end of file
library/ml/src/main/rust/src/nets/mod_part11b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part11b.rs b/library/ml/src/main/rust/src/nets/mod_part11b.rsnew file mode 100644index 0000000000..f01d5ac3be--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part11b.rs@@ -0,0 +1,97 @@+    /// An add whose convolution output has a second reader stays its own dispatch.+    ///+    /// Folding it would leave the other reader with no writer: the producer's old+    /// output tensor is never allocated once the fold moves the sum.+    #[test]+    fn a_shared_convolution_output_keeps_its_add() {+        let source = Shapes::new(5);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let narrowed = builder.conv_same(x, 0, 4, 1, 1, Act::None);+        let summed = builder.add(x, narrowed);+        // A second reader of the convolution's output: the folded store would orphan it.+        let mixed = builder.mul(summed, narrowed);+        // Tensors 2, 3 and 4 are the file's spares; see the residual test above.+        builder.host_tensor(2, &[1]);+        builder.host_tensor(3, &[1]);+        builder.host_tensor(4, &[1]);+        let plan = builder.finish(&[mixed]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),+            1,+            "the shared add must survive: {:?}",+            plan.ops+        );+    }++    /// An add held as a plan output stays its own dispatch.+    ///+    /// Nothing downstream reads it, but the host does — folding the sum into the+    /// convolution's store would leave the output binding pointing at an unwritten tensor.+    #[test]+    fn an_add_that_is_a_plan_output_keeps_its_dispatch() {+        let source = Shapes::new(5);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let narrowed = builder.conv_same(x, 0, 4, 1, 1, Act::None);+        let summed = builder.add(x, narrowed);+        // Both the convolution's output and the sum escape: neither may fold.+        // Tensors 2, 3 and 4 are the file's spares; see the residual test above.+        builder.host_tensor(2, &[1]);+        builder.host_tensor(3, &[1]);+        builder.host_tensor(4, &[1]);+        let plan = builder.finish(&[narrowed, summed]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),+            1,+            "the output add must survive: {:?}",+            plan.ops+        );+    }++    /// An FPN-style `add(earlier, later)` stays its own dispatch.+    ///+    /// The skip side is downstream of the producing convolution, so reading it from+    /// the producer's store would read an unwritten tensor. See `Builder::add`.+    #[test]+    fn an_add_of_a_downstream_tensor_does_not_fold() {+        let source = Shapes::new(7);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 8));+        let early = builder.conv_same(x, 0, 4, 1, 1, Act::None);+        let later = builder.conv_same(early, 2, 4, 1, 1, Act::None);+        let grown = builder.resize_to(later, 1, 8);+        // `early` is upstream of the convolution that feeds `grown`'s side... but the+        // addend that matters is `grown` itself, produced after `early`: folding the+        // add into `early`'s store would read it before it is written.+        let merged = builder.add(early, grown);+        let out = builder.conv_same(merged, 4, 4, 1, 1, Act::None);+        // Tensor 6 is the file's spare; see the residual test above.+        builder.host_tensor(6, &[1]);+        let plan = builder.finish(&[out]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),+            1,+            "the FPN add must survive: {:?}",+            plan.ops+        );+    }++    /// A self-add never folds: the convolution would read the tensor it no longer writes.+    #[test]+    fn a_self_add_does_not_fold() {+        let source = Shapes::new(3);+        let mut builder = Builder::new(&source);+        let x = builder.input(Shape::new(4, 1, 4));+        let narrowed = builder.conv_same(x, 0, 4, 1, 1, Act::None);+        let doubled = builder.add(narrowed, narrowed);+        // Tensor 2 is the file's spare; see the residual test above.+        builder.host_tensor(2, &[1]);+        let plan = builder.finish(&[doubled]).expect("builds");+        assert_eq!(+            plan.ops.iter().filter(|op| matches!(op, Op::Dispatch { kind: Kind::Add, .. })).count(),+            1,+            "the self-add must survive: {:?}",+            plan.ops+        );+    }
library/ml/src/main/rust/src/nets/mod_part14.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part14.rs b/library/ml/src/main/rust/src/nets/mod_part14.rsnew file mode 100644index 0000000000..7f6316c2c1--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part14.rs@@ -0,0 +1,22 @@+impl Act {+    pub(crate) fn code(self) -> u32 {+        match self {+            Act::None => 0,+            Act::Relu => 1,+            Act::HardSwish => 2,+            Act::Sigmoid => 3,+            Act::PRelu(_) => 4,+            Act::Clip01 => 5,+            Act::Swish => 6,+            Act::Relu6 => 7,+            Act::Gelu => 8,+        }+    }+}++/// [`Push::res`] / [`Push::shift`] when no addend is folded into the store.+///+/// Arena offset 0 is a live tensor — the first input is pinned there — so "none" needs a value+/// no allocation can hold. [`Builder::finish`] writes real offsets only onto the ops it fuses;+/// everything else keeps this through the manual [`Push`] default below.+pub const NO_FUSE: u32 = u32::MAX;
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 c83ffd0dd3..f81bff859d 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -478,27 +478,3 @@ pub(crate) enum Node {         band: u32,     }, }--/// Records a forward pass, then packs and resolves it.-pub struct Builder<'a> {-    weights: &'a dyn WeightSource,-    shapes: Vec<Shape>,-    nodes: Vec<Node>,-    /// Tensors that must keep a stable offset for the whole pass: the inputs and the-    /// outputs. Everything else is free to be reused once its last reader has run.-    pinned: Vec<Id>,-    error: Option<String>,-    inputs: Vec<Id>,-    /// One flag per tensor in the file, set when the pass reads it. See-    /// [`Builder::finish`], which insists every one was.-    read: Vec<bool>,-    /// Whether convolutions replicate their border rather than reading zeros.-    pad_edge: bool,-    /// Whether spatial convolutions lower to the register-blocked tiled path.-    /// See [`Builder::spatial_tiling`].-    spatial_tiled: bool,-}--/// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same-/// boundary `.maml` aligns its tensors to.-const ALIGN_ELEMS: u32 = 8;
library/ml/src/main/rust/src/nets/mod_part2b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2b.rs b/library/ml/src/main/rust/src/nets/mod_part2b.rsnew file mode 100644index 0000000000..39e2d14efa--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part2b.rs@@ -0,0 +1,23 @@+/// Records a forward pass, then packs and resolves it.+pub struct Builder<'a> {+    weights: &'a dyn WeightSource,+    shapes: Vec<Shape>,+    nodes: Vec<Node>,+    /// Tensors that must keep a stable offset for the whole pass: the inputs and the+    /// outputs. Everything else is free to be reused once its last reader has run.+    pinned: Vec<Id>,+    error: Option<String>,+    inputs: Vec<Id>,+    /// One flag per tensor in the file, set when the pass reads it. See+    /// [`Builder::finish`], which insists every one was.+    read: Vec<bool>,+    /// Whether convolutions replicate their border rather than reading zeros.+    pad_edge: bool,+    /// Whether spatial convolutions lower to the register-blocked tiled path.+    /// See [`Builder::spatial_tiling`].+    spatial_tiled: bool,+}++/// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same+/// boundary `.maml` aligns its tensors to.+const ALIGN_ELEMS: u32 = 8;
library/ml/src/main/rust/src/nets/mod_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part4.rs b/library/ml/src/main/rust/src/nets/mod_part4.rsindex 3f7620fa8d..1fd3eb3818 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -407,107 +407,4 @@ impl<'a> Builder<'a> {         });         out     }--    /// [`Builder::conv_int8`] with resolved weight offsets rather than table indices.-    ///-    /// As [`Builder::conv_raw`]: the section parser validated shapes, so lowering only-    /// translates addressing. `m` is the section's computed output channels.-    #[allow(clippy::too_many_arguments)]-    pub fn conv_int8_raw(-        &mut self,-        input: Id,-        weight: u32,-        scale: u32,-        bias: u32,-        m: u32,-        act: Act,-        kernel: (u32, u32),-        stride: (u32, u32),-        dilation: (u32, u32),-        pads: (u32, u32, u32, u32),-        group: u32,-        quant: Quant,-    ) -> Id {-        self.push_conv_int8(-            input, weight, scale, bias, m, kernel, stride, dilation, pads, group, act,-            quant,-        )-    }--    /// Resolve [`Act::PRelu`]'s slope tensor, which is `[channels, 1, 1]` in the ONNX-    /// exports this reads.-    fn act_weight(&mut self, act: Act, channels: u32) -> u32 {-        match act {-            Act::PRelu(index) => self.weight(index, &[channels, 1, 1]),-            _ => 0,-        }-    }--    /// The common case in both nets: `3x3` or `1x1`, stride 1, `pad == dilation`-    /// (which keeps the output size), one group.-    pub fn conv_same(-        &mut self,-        input: Id,-        weight_index: usize,-        m: u32,-        kernel: u32,-        dilation: u32,-        act: Act,-    ) -> Id {-        // `pad == dilation` holds the spatial size only for an odd kernel, which is-        // the only case either net uses it for.-        let pad = if kernel == 1 { 0 } else { dilation };-        self.conv(-            input,-            weight_index,-            m,-            (kernel, kernel),-            (1, 1),-            (dilation, dilation),-            (pad, pad, pad, pad),-            1,-            act,-        )-    }-    /// A transposed convolution: weights `[in_c, m/group, kh, kw]`, output-    /// `(in - 1) * stride + dilation * (k - 1) + 1 - pads`.-    #[allow(clippy::too_many_arguments)]-    pub fn conv_transpose(-        &mut self,-        input: Id,-        weight_index: usize,-        m: u32,-        kernel: (u32, u32),-        stride: (u32, u32),-        pads: (u32, u32, u32, u32),-        act: Act,-    ) -> Id {-        let in_shape = self.shape_of(input);-        let (kh, kw) = kernel;-        let weight = self.weight(weight_index, &[in_shape.c, m, kh, kw]);-        let bias = self.weight(weight_index + 1, &[m]);-        let (pad_t, pad_l, pad_b, pad_r) = pads;-        let out_h = deconv_out(in_shape.h, kh, stride.0, pad_t + pad_b);-        let out_w = deconv_out(in_shape.w, kw, stride.1, pad_l + pad_r);-        let out = self.tensor(Shape::new(m, out_h, out_w));-        let act_weight = self.act_weight(act, m);-        self.nodes.push(Node::Conv {-            input,-            out,-            weight,-            bias,-            kernel,-            stride,-            dilation: (1, 1),-            pad: (pad_t, pad_l),-            group: 1,-            act,-            act_weight,-            transpose: true,-            pad_edge: false,-            res: None,-            shift: None,-        });-        out-    } }\ No newline at end of file
library/ml/src/main/rust/src/nets/mod_part4b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part4b.rs b/library/ml/src/main/rust/src/nets/mod_part4b.rsnew file mode 100644index 0000000000..ca27696af6--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part4b.rs@@ -0,0 +1,104 @@+impl<'a> Builder<'a> {+    /// [`Builder::conv_int8`] with resolved weight offsets rather than table indices.+    ///+    /// As [`Builder::conv_raw`]: the section parser validated shapes, so lowering only+    /// translates addressing. `m` is the section's computed output channels.+    #[allow(clippy::too_many_arguments)]+    pub fn conv_int8_raw(+        &mut self,+        input: Id,+        weight: u32,+        scale: u32,+        bias: u32,+        m: u32,+        act: Act,+        kernel: (u32, u32),+        stride: (u32, u32),+        dilation: (u32, u32),+        pads: (u32, u32, u32, u32),+        group: u32,+        quant: Quant,+    ) -> Id {+        self.push_conv_int8(+            input, weight, scale, bias, m, kernel, stride, dilation, pads, group, act,+            quant,+        )+    }++    /// Resolve [`Act::PRelu`]'s slope tensor, which is `[channels, 1, 1]` in the ONNX+    /// exports this reads.+    fn act_weight(&mut self, act: Act, channels: u32) -> u32 {+        match act {+            Act::PRelu(index) => self.weight(index, &[channels, 1, 1]),+            _ => 0,+        }+    }++    /// The common case in both nets: `3x3` or `1x1`, stride 1, `pad == dilation`+    /// (which keeps the output size), one group.+    pub fn conv_same(+        &mut self,+        input: Id,+        weight_index: usize,+        m: u32,+        kernel: u32,+        dilation: u32,+        act: Act,+    ) -> Id {+        // `pad == dilation` holds the spatial size only for an odd kernel, which is+        // the only case either net uses it for.+        let pad = if kernel == 1 { 0 } else { dilation };+        self.conv(+            input,+            weight_index,+            m,+            (kernel, kernel),+            (1, 1),+            (dilation, dilation),+            (pad, pad, pad, pad),+            1,+            act,+        )+    }+    /// A transposed convolution: weights `[in_c, m/group, kh, kw]`, output+    /// `(in - 1) * stride + dilation * (k - 1) + 1 - pads`.+    #[allow(clippy::too_many_arguments)]+    pub fn conv_transpose(+        &mut self,+        input: Id,+        weight_index: usize,+        m: u32,+        kernel: (u32, u32),+        stride: (u32, u32),+        pads: (u32, u32, u32, u32),+        act: Act,+    ) -> Id {+        let in_shape = self.shape_of(input);+        let (kh, kw) = kernel;+        let weight = self.weight(weight_index, &[in_shape.c, m, kh, kw]);+        let bias = self.weight(weight_index + 1, &[m]);+        let (pad_t, pad_l, pad_b, pad_r) = pads;+        let out_h = deconv_out(in_shape.h, kh, stride.0, pad_t + pad_b);+        let out_w = deconv_out(in_shape.w, kw, stride.1, pad_l + pad_r);+        let out = self.tensor(Shape::new(m, out_h, out_w));+        let act_weight = self.act_weight(act, m);+        self.nodes.push(Node::Conv {+            input,+            out,+            weight,+            bias,+            kernel,+            stride,+            dilation: (1, 1),+            pad: (pad_t, pad_l),+            group: 1,+            act,+            act_weight,+            transpose: true,+            pad_edge: false,+            res: None,+            shift: None,+        });+        out+    }+}
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 77dcddc083..53022ea0b5 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -439,77 +439,4 @@ impl<'a> Builder<'a> {         self.nodes.push(Node::Rotary { input, angles, out, heads, axes });         out     }--    /// A learned tensor copied into the arena, so it can be an operand rather than a kernel.-    ///-    /// The only op that reads nothing from the arena. See [`Kind::Constant`] for why it exists-    /// at all; `shape` is what the `.maml` tensor holds, and its element count must match.-    pub fn constant(&mut self, weight_index: usize, shape: Shape) -> Id {-        let weight = self.weight(weight_index, &[shape.c, shape.h, shape.w]);-        let out = self.tensor(shape);-        self.nodes.push(Node::Constant { out, weight });-        out-    }--    /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor, or a-    /// `[2, 1, T]` one when the table has more than [`EMBED_LANE`] rows.-    ///-    /// `table` indexes a `[rows, channels]` tensor. A `sqrt(d_model)` scale applied after the-    /// lookup belongs in the table, folded by the converter, not here; see [`Kind::Embed`].-    pub fn embed(&mut self, ids: Id, table: usize, rows: u32, channels: u32) -> Id {-        let shape = self.shape_of(ids);-        let lanes = if rows > EMBED_LANE { 2 } else { 1 };-        if shape.c != lanes || shape.h != 1 {-            if lanes == 2 {-                // Refused rather than rounded: a single lane holds ids to 2048 exactly and-                // then starts landing on a neighbouring row, which reads as a plausible-                // wrong word rather than as a failure.-                self.fail(format!(-                    "embedding {shape:?}: {rows} rows is past {EMBED_LANE}, so the ids split \-                     across two lanes as a [2, 1, T] tensor"-                ));-            } else {-                self.fail(format!(-                    "embedding {shape:?}: ids are one per position, so a [1, 1, T] tensor"-                ));-            }-        }-        if rows == 0 || channels == 0 {-            self.fail(format!("an embedding table of {rows} x {channels}"));-        }-        let table = self.weight(table, &[rows, channels]);-        let out = self.tensor(Shape::new(channels, 1, shape.w));-        self.nodes.push(Node::Embed { ids, out, table, rows });-        out-    }--    /// [`Builder::attn_scores`] plus a relative-position term.-    ///-    /// `table` is a `[offsets, head_dim]` tensor of learned offsets, shared across heads.-    /// `offsets` must be odd: it is `2 * window + 1`, centred on zero displacement.-    pub fn attn_scores_relative(-        &mut self,-        q: Id,-        k: Id,-        heads: u32,-        table: usize,-        offsets: u32,-    ) -> Id {-        let (out, scale) = self.score_map(q, k, heads, heads);-        let shape = self.shape_of(q);-        // A relative offset is `key - query`, so the two sequences have to be the same one.-        // Only the cross-attention variants take differing lengths.-        if shape.w != self.shape_of(k).w {-            self.fail(format!(-                "a relative score map over q {shape:?} and k {:?}: an offset is `key - query`, \-                 so both are positions in the same sequence",-                self.shape_of(k)-            ));-        }-        let head_dim = shape.c.checked_div(heads.max(1)).unwrap_or(0);-        self.check_offsets(offsets);-        let table = self.weight(table, &[offsets, head_dim]);-        self.nodes.push(Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets });-        out-    } }
library/ml/src/main/rust/src/nets/mod_part6b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part6b.rs b/library/ml/src/main/rust/src/nets/mod_part6b.rsnew file mode 100644index 0000000000..661970f180--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mod_part6b.rs@@ -0,0 +1,74 @@+impl<'a> Builder<'a> {+    /// A learned tensor copied into the arena, so it can be an operand rather than a kernel.+    ///+    /// The only op that reads nothing from the arena. See [`Kind::Constant`] for why it exists+    /// at all; `shape` is what the `.maml` tensor holds, and its element count must match.+    pub fn constant(&mut self, weight_index: usize, shape: Shape) -> Id {+        let weight = self.weight(weight_index, &[shape.c, shape.h, shape.w]);+        let out = self.tensor(shape);+        self.nodes.push(Node::Constant { out, weight });+        out+    }++    /// An embedding lookup: `out[c][t] = table[id(t)][c]`, over a `[1, 1, T]` id tensor, or a+    /// `[2, 1, T]` one when the table has more than [`EMBED_LANE`] rows.+    ///+    /// `table` indexes a `[rows, channels]` tensor. A `sqrt(d_model)` scale applied after the+    /// lookup belongs in the table, folded by the converter, not here; see [`Kind::Embed`].+    pub fn embed(&mut self, ids: Id, table: usize, rows: u32, channels: u32) -> Id {+        let shape = self.shape_of(ids);+        let lanes = if rows > EMBED_LANE { 2 } else { 1 };+        if shape.c != lanes || shape.h != 1 {+            if lanes == 2 {+                // Refused rather than rounded: a single lane holds ids to 2048 exactly and+                // then starts landing on a neighbouring row, which reads as a plausible+                // wrong word rather than as a failure.+                self.fail(format!(+                    "embedding {shape:?}: {rows} rows is past {EMBED_LANE}, so the ids split \+                     across two lanes as a [2, 1, T] tensor"+                ));+            } else {+                self.fail(format!(+                    "embedding {shape:?}: ids are one per position, so a [1, 1, T] tensor"+                ));+            }+        }+        if rows == 0 || channels == 0 {+            self.fail(format!("an embedding table of {rows} x {channels}"));+        }+        let table = self.weight(table, &[rows, channels]);+        let out = self.tensor(Shape::new(channels, 1, shape.w));+        self.nodes.push(Node::Embed { ids, out, table, rows });+        out+    }++    /// [`Builder::attn_scores`] plus a relative-position term.+    ///+    /// `table` is a `[offsets, head_dim]` tensor of learned offsets, shared across heads.+    /// `offsets` must be odd: it is `2 * window + 1`, centred on zero displacement.+    pub fn attn_scores_relative(+        &mut self,+        q: Id,+        k: Id,+        heads: u32,+        table: usize,+        offsets: u32,+    ) -> Id {+        let (out, scale) = self.score_map(q, k, heads, heads);+        let shape = self.shape_of(q);+        // A relative offset is `key - query`, so the two sequences have to be the same one.+        // Only the cross-attention variants take differing lengths.+        if shape.w != self.shape_of(k).w {+            self.fail(format!(+                "a relative score map over q {shape:?} and k {:?}: an offset is `key - query`, \+                 so both are positions in the same sequence",+                self.shape_of(k)+            ));+        }+        let head_dim = shape.c.checked_div(heads.max(1)).unwrap_or(0);+        self.check_offsets(offsets);+        let table = self.weight(table, &[offsets, head_dim]);+        self.nodes.push(Node::AttnScoresRelative { q, k, out, heads, scale, table, offsets });+        out+    }+}
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 ad50ac9ef4..76d1ae14de 100644--- a/library/ml/src/main/rust/src/nets/mod_part9b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9b.rs@@ -502,7 +502,7 @@ impl<'a> Builder<'a> {                     invocations: so.len(),                 });             }-            _ => {}+            other => self.emit_top_k(other, at, shape, ops)?,         }         Ok(())     }
library/ml/src/main/rust/src/nets/nllb.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb.rs b/library/ml/src/main/rust/src/nets/nllb.rsindex 46b8597f26..39bdf0a77f 100644--- a/library/ml/src/main/rust/src/nets/nllb.rs+++ b/library/ml/src/main/rust/src/nets/nllb.rs@@ -443,68 +443,4 @@ pub(crate) fn split_of(id: u32) -> (usize, u32) {         (2 + (rest / CLASSES_PER_TAIL_SPLIT) as usize, rest % CLASSES_PER_TAIL_SPLIT)     } }--/// The embedded, scaled and positioned source for `ids`, in the channel-major layout the plan-/// wants.-///-/// The `[1024, 1, len]` fp16 input to [`Mode::Encode`], as f32 for the caller to upload. See the-/// module docs for why this is on the host and for the `+ 2` on the position.-///-/// `past` is how many positions precede these ids, which is 0 for the encoder and the step number-/// for the decoder — fairseq's `past_key_values_length`, and it lands in the same arithmetic.-pub fn embed_positions(-    weights: Reader<'_>,-    ids: &[u32],-    past: u32,-) -> Result<Vec<f32>, String> {-    let width = D_MODEL as usize;-    let mut out = vec![0.0f32; width * ids.len()];-    let scale = (D_MODEL as f32).sqrt();-    for (at, &id) in ids.iter().enumerate() {-        if id >= VOCAB {-            return Err(format!("token {id} is past the {VOCAB}-entry vocabulary"));-        }-        let (split, row) = split_of(id);-        let kernel = HEAD + split * 3;-        let embedding = weights.int8_row(-            kernel,-            kernel + 1,-            &[split_classes(split), D_MODEL, 1, 1],-            row,-        )?;-        let position = past + at as u32 + 1 + PADDING_IDX;-        // `make_weights(num_positions + padding_idx + 1, ...)`, so the table's last row is-        // `MAX_POSITIONS + PADDING_IDX`.-        if position > MAX_POSITIONS + PADDING_IDX {-            return Err(format!("position {position} is past the model's table"));-        }-        for (channel, value) in embedding.iter().enumerate() {-            // Channel-major: this runtime indexes `[c, h, w]`, and the export is `[w, c]`.-            let slot = out-                .get_mut(channel * ids.len() + at)-                .ok_or("an embedding row is wider than d_model")?;-            *slot = value * scale + sinusoid(position, channel);-        }-    }-    Ok(out)-}--/// fairseq's sinusoidal position, channel `channel` of position `position`.-///-/// Not the interleaved `sin, cos, sin, cos` of the original transformer paper: the halves are-/// **concatenated**, so channels `0..512` are all the sines and `512..1024` all the cosines. And-/// the frequency spacing divides `ln(10000)` by `half_dim - 1`, not by `half_dim`.-///-/// `padding_idx` is 1 and its row is zeroed upstream, which never matters here because-/// [`embed_positions`] never asks for it — the smallest position it can produce is 2.-pub(crate) fn sinusoid(position: u32, channel: usize) -> f32 {-    let half = D_MODEL as usize / 2;-    let index = channel % half;-    let spacing = (10_000.0f32).ln() / (half as f32 - 1.0);-    let angle = position as f32 * (-(index as f32) * spacing).exp();-    if channel < half {-        angle.sin()-    } else {-        angle.cos()-    }-}+include!("nllb_part1.rs");
library/ml/src/main/rust/src/nets/nllb_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra.rs b/library/ml/src/main/rust/src/nets/nllb_extra.rsindex c8752ab1df..8a388bf884 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra.rs@@ -428,107 +428,5 @@ mod tests {             assert_eq!(step + 1 + PADDING_IDX, step + 2);         }     }--    #[test]-    fn the_sinusoid_is_fairseqs_concatenated_halves() {-        // Position 0's sines are all zero and its cosines all one, which distinguishes the-        // concatenated layout from the interleaved one immediately: interleaved would alternate.-        let half = D_MODEL as usize / 2;-        for channel in 0..half {-            assert_eq!(sinusoid(0, channel), 0.0, "channel {channel}");-        }-        for channel in half..D_MODEL as usize {-            assert_eq!(sinusoid(0, channel), 1.0, "channel {channel}");-        }-        // The lowest frequency is 1, and the highest is `1 / 10000` — which needs the spacing to-        // divide by `half - 1`. Dividing by `half` puts the last channel at 10000^(-511/512).-        assert!((sinusoid(1, 0) - 1.0f32.sin()).abs() < 1e-6);-        let smallest = (1.0f32 / 10_000.0).sin();-        assert!((sinusoid(1, half - 1) - smallest).abs() < 1e-6, "{}", sinusoid(1, half - 1));-    }--    #[test]-    fn split_of_covers_the_whole_vocabulary_without_gaps() {-        // The uneven split is the one place an id could fall between two ranges or land in both.-        // Every id must map to exactly one (split, row), and the row must be inside that split.-        let mut seen = 0u32;-        for split in 0..HEAD_SPLITS {-            for row in 0..split_classes(split) {-                seen += 1;-                let _ = (split, row);-            }-        }-        assert_eq!(seen, VOCAB);-        // The boundaries: the last id of each split and the first of the next.-        assert_eq!(split_of(0), (0, 0));-        assert_eq!(split_of(64_051), (0, 64_051));-        assert_eq!(split_of(64_052), (1, 0));-        assert_eq!(split_of(128_103), (1, 64_051));-        assert_eq!(split_of(128_104), (2, 0));-        assert_eq!(split_of(192_154), (2, 64_050));-        assert_eq!(split_of(192_155), (3, 0));-        assert_eq!(split_of(256_205), (3, 64_050));-        // And the mapping is the identity in order: walking ids walks (split, row) contiguously.-        let mut next = 0u32;-        for split in 0..HEAD_SPLITS {-            let base = HEAD + split * 3;-            let _ = base;-            for row in 0..split_classes(split) {-                assert_eq!(split_of(next), (split, row), "id {next}");-                next += 1;-            }-        }-        assert_eq!(next, VOCAB);-    }--    #[test]-    fn a_pass_over_nothing_or_past_the_table_is_refused() {-        let source = Shapes::new(TENSORS);-        let error = build(&source, Mode::Encode { len: 0 }).expect_err("no tokens");-        assert!(error.contains("no tokens"), "{error}");-        let source = Shapes::new(TENSORS);-        let error =-            build(&source, Mode::Encode { len: MAX_POSITIONS + 1 }).expect_err("too long");-        assert!(error.contains("positions the model has"), "{error}");-    }--    #[test]-    fn every_tensor_shape_is_stated_the_same_way_twice() {-        // `dims_of` restates the table `maml_convert.collect_nllb` writes, and `Layers` walks-        // it. This checks the two agree for every index, which is what makes `host_tensor`'s shape-        // check meaningful rather than circular.-        let mut expected: Vec<Vec<u32>> = Vec::new();-        for split in 0..HEAD_SPLITS {-            let classes = split_classes(split);-            expected.push(vec![classes, D_MODEL, 1, 1]);-            expected.push(vec![classes]);-            expected.push(vec![classes]);-        }-        let projection = |out: u32, inputs: u32| {-            vec![vec![out, inputs, 1, 1], vec![out], vec![out]]-        };-        let norm = || vec![vec![D_MODEL], vec![D_MODEL]];-        for (layers, cross) in [(ENCODER_LAYERS, false), (DECODER_LAYERS, true)] {-            for _ in 0..layers {-                expected.extend(norm());-                for _ in 0..4 {-                    expected.extend(projection(D_MODEL, D_MODEL));-                }-                if cross {-                    expected.extend(norm());-                    for _ in 0..4 {-                        expected.extend(projection(D_MODEL, D_MODEL));-                    }-                }-                expected.extend(norm());-                expected.extend(projection(FFN, D_MODEL));-                expected.extend(projection(D_MODEL, FFN));-            }-            expected.extend(norm());-        }-        assert_eq!(expected.len(), TENSORS);-        for (index, want) in expected.iter().enumerate() {-            assert_eq!(&dims_of(index), want, "tensor {index}");-        }-    }+    include!("nllb_extra_part1.rs"); }
library/ml/src/main/rust/src/nets/nllb_extra_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra_part1.rs b/library/ml/src/main/rust/src/nets/nllb_extra_part1.rsnew file mode 100644index 0000000000..8d306b2840--- /dev/null+++ b/library/ml/src/main/rust/src/nets/nllb_extra_part1.rs@@ -0,0 +1,102 @@+    #[test]+    fn the_sinusoid_is_fairseqs_concatenated_halves() {+        // Position 0's sines are all zero and its cosines all one, which distinguishes the+        // concatenated layout from the interleaved one immediately: interleaved would alternate.+        let half = D_MODEL as usize / 2;+        for channel in 0..half {+            assert_eq!(sinusoid(0, channel), 0.0, "channel {channel}");+        }+        for channel in half..D_MODEL as usize {+            assert_eq!(sinusoid(0, channel), 1.0, "channel {channel}");+        }+        // The lowest frequency is 1, and the highest is `1 / 10000` — which needs the spacing to+        // divide by `half - 1`. Dividing by `half` puts the last channel at 10000^(-511/512).+        assert!((sinusoid(1, 0) - 1.0f32.sin()).abs() < 1e-6);+        let smallest = (1.0f32 / 10_000.0).sin();+        assert!((sinusoid(1, half - 1) - smallest).abs() < 1e-6, "{}", sinusoid(1, half - 1));+    }++    #[test]+    fn split_of_covers_the_whole_vocabulary_without_gaps() {+        // The uneven split is the one place an id could fall between two ranges or land in both.+        // Every id must map to exactly one (split, row), and the row must be inside that split.+        let mut seen = 0u32;+        for split in 0..HEAD_SPLITS {+            for row in 0..split_classes(split) {+                seen += 1;+                let _ = (split, row);+            }+        }+        assert_eq!(seen, VOCAB);+        // The boundaries: the last id of each split and the first of the next.+        assert_eq!(split_of(0), (0, 0));+        assert_eq!(split_of(64_051), (0, 64_051));+        assert_eq!(split_of(64_052), (1, 0));+        assert_eq!(split_of(128_103), (1, 64_051));+        assert_eq!(split_of(128_104), (2, 0));+        assert_eq!(split_of(192_154), (2, 64_050));+        assert_eq!(split_of(192_155), (3, 0));+        assert_eq!(split_of(256_205), (3, 64_050));+        // And the mapping is the identity in order: walking ids walks (split, row) contiguously.+        let mut next = 0u32;+        for split in 0..HEAD_SPLITS {+            let base = HEAD + split * 3;+            let _ = base;+            for row in 0..split_classes(split) {+                assert_eq!(split_of(next), (split, row), "id {next}");+                next += 1;+            }+        }+        assert_eq!(next, VOCAB);+    }++    #[test]+    fn a_pass_over_nothing_or_past_the_table_is_refused() {+        let source = Shapes::new(TENSORS);+        let error = build(&source, Mode::Encode { len: 0 }).expect_err("no tokens");+        assert!(error.contains("no tokens"), "{error}");+        let source = Shapes::new(TENSORS);+        let error =+            build(&source, Mode::Encode { len: MAX_POSITIONS + 1 }).expect_err("too long");+        assert!(error.contains("positions the model has"), "{error}");+    }++    #[test]+    fn every_tensor_shape_is_stated_the_same_way_twice() {+        // `dims_of` restates the table `maml_convert.collect_nllb` writes, and `Layers` walks+        // it. This checks the two agree for every index, which is what makes `host_tensor`'s shape+        // check meaningful rather than circular.+        let mut expected: Vec<Vec<u32>> = Vec::new();+        for split in 0..HEAD_SPLITS {+            let classes = split_classes(split);+            expected.push(vec![classes, D_MODEL, 1, 1]);+            expected.push(vec![classes]);+            expected.push(vec![classes]);+        }+        let projection = |out: u32, inputs: u32| {+            vec![vec![out, inputs, 1, 1], vec![out], vec![out]]+        };+        let norm = || vec![vec![D_MODEL], vec![D_MODEL]];+        for (layers, cross) in [(ENCODER_LAYERS, false), (DECODER_LAYERS, true)] {+            for _ in 0..layers {+                expected.extend(norm());+                for _ in 0..4 {+                    expected.extend(projection(D_MODEL, D_MODEL));+                }+                if cross {+                    expected.extend(norm());+                    for _ in 0..4 {+                        expected.extend(projection(D_MODEL, D_MODEL));+                    }+                }+                expected.extend(norm());+                expected.extend(projection(FFN, D_MODEL));+                expected.extend(projection(D_MODEL, FFN));+            }+            expected.extend(norm());+        }+        assert_eq!(expected.len(), TENSORS);+        for (index, want) in expected.iter().enumerate() {+            assert_eq!(&dims_of(index), want, "tensor {index}");+        }+    }
library/ml/src/main/rust/src/nets/nllb_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_part1.rs b/library/ml/src/main/rust/src/nets/nllb_part1.rsnew file mode 100644index 0000000000..1068c0620a--- /dev/null+++ b/library/ml/src/main/rust/src/nets/nllb_part1.rs@@ -0,0 +1,64 @@+/// The embedded, scaled and positioned source for `ids`, in the channel-major layout the plan+/// wants.+///+/// The `[1024, 1, len]` fp16 input to [`Mode::Encode`], as f32 for the caller to upload. See the+/// module docs for why this is on the host and for the `+ 2` on the position.+///+/// `past` is how many positions precede these ids, which is 0 for the encoder and the step number+/// for the decoder — fairseq's `past_key_values_length`, and it lands in the same arithmetic.+pub fn embed_positions(+    weights: Reader<'_>,+    ids: &[u32],+    past: u32,+) -> Result<Vec<f32>, String> {+    let width = D_MODEL as usize;+    let mut out = vec![0.0f32; width * ids.len()];+    let scale = (D_MODEL as f32).sqrt();+    for (at, &id) in ids.iter().enumerate() {+        if id >= VOCAB {+            return Err(format!("token {id} is past the {VOCAB}-entry vocabulary"));+        }+        let (split, row) = split_of(id);+        let kernel = HEAD + split * 3;+        let embedding = weights.int8_row(+            kernel,+            kernel + 1,+            &[split_classes(split), D_MODEL, 1, 1],+            row,+        )?;+        let position = past + at as u32 + 1 + PADDING_IDX;+        // `make_weights(num_positions + padding_idx + 1, ...)`, so the table's last row is+        // `MAX_POSITIONS + PADDING_IDX`.+        if position > MAX_POSITIONS + PADDING_IDX {+            return Err(format!("position {position} is past the model's table"));+        }+        for (channel, value) in embedding.iter().enumerate() {+            // Channel-major: this runtime indexes `[c, h, w]`, and the export is `[w, c]`.+            let slot = out+                .get_mut(channel * ids.len() + at)+                .ok_or("an embedding row is wider than d_model")?;+            *slot = value * scale + sinusoid(position, channel);+        }+    }+    Ok(out)+}++/// fairseq's sinusoidal position, channel `channel` of position `position`.+///+/// Not the interleaved `sin, cos, sin, cos` of the original transformer paper: the halves are+/// **concatenated**, so channels `0..512` are all the sines and `512..1024` all the cosines. And+/// the frequency spacing divides `ln(10000)` by `half_dim - 1`, not by `half_dim`.+///+/// `padding_idx` is 1 and its row is zeroed upstream, which never matters here because+/// [`embed_positions`] never asks for it — the smallest position it can produce is 2.+pub(crate) fn sinusoid(position: u32, channel: usize) -> f32 {+    let half = D_MODEL as usize / 2;+    let index = channel % half;+    let spacing = (10_000.0f32).ln() / (half as f32 - 1.0);+    let angle = position as f32 * (-(index as f32) * spacing).exp();+    if channel < half {+        angle.sin()+    } else {+        angle.cos()+    }+}
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 1d624b270b..f93df72355 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -168,6 +168,7 @@ pub struct Reference {  include!("reference_part1.rs"); include!("reference_part2.rs");+include!("reference_part13.rs"); include!("reference_part11.rs"); include!("reference_part3.rs"); include!("reference_part4.rs");
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 272893267c..8411bd11f8 100644--- a/library/ml/src/main/rust/src/nets/reference_part1.rs+++ b/library/ml/src/main/rust/src/nets/reference_part1.rs@@ -68,6 +68,7 @@ impl Reference {                     Kind::Softcap => self.softcap(push),                     Kind::Argmax => self.argmax(push),                     Kind::ArgmaxFold => self.argmax_fold(push),+                    Kind::TopK => self.top_k_stage(push),                     Kind::Quantize => self.quantize(push),                     Kind::Activate => self.activate(push),                     Kind::GatedActivate => self.gated_activate(push),
library/ml/src/main/rust/src/nets/reference_part12.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part12.rs b/library/ml/src/main/rust/src/nets/reference_part12.rsnew file mode 100644index 0000000000..af8c12eaa2--- /dev/null+++ b/library/ml/src/main/rust/src/nets/reference_part12.rs@@ -0,0 +1,44 @@+impl Reference {+    /// Mirrors `shaders/topk.comp`. Stage 1 (`kh == 0`): each of `p.group` slices of the row+    /// writes its 64 best ids as `(lo, hi)` pairs, highest value first, ties by lower id, with+    /// `(2047, 2047)` for missing ranks. Stage 2: the candidates' values re-read from the row at+    /// `p.in1`, the best 64 written as `(value, lo, hi)`.+    fn top_k_stage(&mut self, p: &Push) -> Result<(), String> {+        const K: u32 = 64;+        let order = |a: &(f32, u32), b: &(f32, u32)| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1));+        if p.kh == 0 {+            let groups = p.group.max(1);+            let slice = p.count.div_ceil(groups);+            for group in 0..groups {+                let mut keys = Vec::new();+                for i in group * slice..((group + 1) * slice).min(p.count) {+                    keys.push((self.load(p.in0, i)?, i));+                }+                keys.sort_by(order);+                for r in 0..K {+                    let (lo, hi) = keys.get(r as usize).map_or((2047, 2047), |&(_, i)| (i % 2048, i / 2048));+                    self.store(p.out, (group * K + r) * 2, lo as f32)?;+                    self.store(p.out, (group * K + r) * 2 + 1, hi as f32)?;+                }+            }+            return Ok(());+        }+        let mut keys = Vec::new();+        for c in 0..p.in_c {+            let index = self.load(p.in0, c * 2)? as u32 + 2048 * self.load(p.in0, c * 2 + 1)? as u32;+            if index < p.in_w {+                keys.push((self.load(p.in1, index)?, index));+            }+        }+        keys.sort_by(order);+        for r in 0..K {+            let (value, lo, hi) = keys+                .get(r as usize)+                .map_or((-65504.0, 2047, 2047), |&(v, i)| (v, i % 2048, i / 2048));+            self.store(p.out, r * 3, value)?;+            self.store(p.out, r * 3 + 1, lo as f32)?;+            self.store(p.out, r * 3 + 2, hi as f32)?;+        }+        Ok(())+    }+}
library/ml/src/main/rust/src/nets/reference_part13.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part13.rs b/library/ml/src/main/rust/src/nets/reference_part13.rsnew file mode 100644index 0000000000..616e034ad2--- /dev/null+++ b/library/ml/src/main/rust/src/nets/reference_part13.rs@@ -0,0 +1,114 @@+impl Reference {+    /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`.+    ///+    /// Q and K are `[d_model, 1, T]`; the output is `[heads, T, T]`. A head is a run of+    /// `in_c / group` consecutive channels, which is what makes the split free — there is+    /// no transpose anywhere in this, by construction.+    fn attn_scores(&mut self, p: &Push) -> Result<(), String> {+        let head_dim = heads(p, p.in_c)?;+        // Q and K carry their own lengths, which are the score map's height and width. For+        // self-attention those are equal.+        let (query_stride, key_stride) = (p.out_h, p.out_w);+        let scale = f32::from_bits(p.param0_bits);+        for head in 0..p.group {+            let query_base = head * head_dim * query_stride;+            // K is `kv_heads` wide, so several query heads share a key head. The identity when+            // the two counts match, which is every net that is not Gemma's.+            let key_base = Self::kv_head_of(p, head) * head_dim * key_stride;+            for query in 0..p.out_h {+                for key in 0..p.out_w {+                    let mut total = 0.0;+                    for d in 0..head_dim {+                        total += self.load(p.in0, query_base + d * query_stride + query)?+                            * self.load(p.in1, key_base + d * key_stride + key)?;+                    }+                    self.store(p.out, nchw(p, head, query, key), total * scale)?;+                }+            }+        }+        Ok(())+    }++    /// Softmax over the last axis, `count` contiguous rows of `out_w`.+    ///+    /// The row maximum is subtracted first, as `softmax.comp` does. That is not a+    /// refinement: without it a row containing a large score exponentiates to infinity in+    /// fp32 and every probability in it becomes a NaN.+    ///+    /// `causal` truncates each row at the diagonal, as `softmax_causal.comp` does: rows are+    /// head-major with `out_h` queries per head, so query `row % out_h` reads `query + 1` keys and+    /// the rest of its row is stored as zero.+    ///+    /// [`SoftmaxMode::Prefix`] instead normalises the leading `prefix + 1` entries and **leaves+    /// the rest of the row alone**, matching `softmax_prefix.comp`. Zeroing the tail would be+    /// wrong there rather than merely wasteful: the tail belongs to positions this step does not+    /// attend over but a later one will, and the corresponding apply stops at the same bound.+    fn softmax(&mut self, p: &Push, mode: SoftmaxMode) -> Result<(), String> {+        if p.out_w == 0 {+            return Err("a softmax over an empty axis".into());+        }+        if mode == SoftmaxMode::Causal && p.out_h == 0 {+            return Err("a causal softmax over no queries".into());+        }+        for row in 0..p.count {+            let at = row * p.out_w;+            let keys = match mode {+                // At query 0 this is 1, so the distribution is exactly `[1, 0, ...]` and the+                // denominator can never be empty.+                SoftmaxMode::Causal => ((row % p.out_h.max(1)) + 1).min(p.out_w),+                SoftmaxMode::Prefix => {+                    let (first, last) = self.attended_q(p, p.out_w, row % p.dil_h.max(1));+                    let mut peak = -65504.0f32;+                    for i in first..=last {+                        peak = peak.max(self.load(p.in0, at + i)?);+                    }+                    let mut total = 0.0;+                    for i in first..=last {+                        total += (self.load(p.in0, at + i)? - peak).exp();+                    }+                    let inverse = 1.0 / total;+                    for i in first..=last {+                        let value = (self.load(p.in0, at + i)? - peak).exp() * inverse;+                        self.store(p.out, at + i, value)?;+                    }+                    continue;+                }+                SoftmaxMode::Full => p.out_w,+            };+            // A sliding layer's causal row also drops everything more than `p.kh - 1` behind+            // the query. Zero is no window, which is the plain causal mask.+            let query = row % p.out_h.max(1);+            let first = if mode == SoftmaxMode::Causal && p.kh != 0 {+                (query + 1).saturating_sub(p.kh)+            } else {+                0+            };+            let mut peak = -65504.0f32;+            for i in first..keys {+                peak = peak.max(self.load(p.in0, at + i)?);+            }+            let mut total = 0.0;+            for i in first..keys {+                total += (self.load(p.in0, at + i)? - peak).exp();+            }+            // The peak's own term is `exp(0)`, so this is at least 1.+            let inverse = 1.0 / total;+            for i in 0..first {+                self.store(p.out, at + i, 0.0)?;+            }+            for i in first..keys {+                let value = (self.load(p.in0, at + i)? - peak).exp() * inverse;+                self.store(p.out, at + i, value)?;+            }+            if mode == SoftmaxMode::Causal {+                // Written rather than left alone: `attn_apply` multiplies the whole row, and the+                // arena is reused, so a stale masked value would contribute something+                // unpredictable.+                for i in keys..p.out_w {+                    self.store(p.out, at + i, 0.0)?;+                }+            }+        }+        Ok(())+    }+}
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 0001546a27..696ddfbda9 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -417,117 +417,4 @@ impl Reference {         let q = ((value / scale + 0.5).floor()).clamp(-128.0, 127.0);         Ok(q * scale)     }--    /// `S[h][i][j] = scale * sum_d Q[h][d][i] * K[h][d][j]`.-    ///-    /// Q and K are `[d_model, 1, T]`; the output is `[heads, T, T]`. A head is a run of-    /// `in_c / group` consecutive channels, which is what makes the split free — there is-    /// no transpose anywhere in this, by construction.-    fn attn_scores(&mut self, p: &Push) -> Result<(), String> {-        let head_dim = heads(p, p.in_c)?;-        // Q and K carry their own lengths, which are the score map's height and width. For-        // self-attention those are equal.-        let (query_stride, key_stride) = (p.out_h, p.out_w);-        let scale = f32::from_bits(p.param0_bits);-        for head in 0..p.group {-            let query_base = head * head_dim * query_stride;-            // K is `kv_heads` wide, so several query heads share a key head. The identity when-            // the two counts match, which is every net that is not Gemma's.-            let key_base = Self::kv_head_of(p, head) * head_dim * key_stride;-            for query in 0..p.out_h {-                for key in 0..p.out_w {-                    let mut total = 0.0;-                    for d in 0..head_dim {-                        total += self.load(p.in0, query_base + d * query_stride + query)?-                            * self.load(p.in1, key_base + d * key_stride + key)?;-                    }-                    self.store(p.out, nchw(p, head, query, key), total * scale)?;-                }-            }-        }-        Ok(())-    }--    /// Softmax over the last axis, `count` contiguous rows of `out_w`.-    ///-    /// The row maximum is subtracted first, as `softmax.comp` does. That is not a-    /// refinement: without it a row containing a large score exponentiates to infinity in-    /// fp32 and every probability in it becomes a NaN.-    ///-    /// `causal` truncates each row at the diagonal, as `softmax_causal.comp` does: rows are-    /// head-major with `out_h` queries per head, so query `row % out_h` reads `query + 1` keys and-    /// the rest of its row is stored as zero.-    ///-    /// [`SoftmaxMode::Prefix`] instead normalises the leading `prefix + 1` entries and **leaves-    /// the rest of the row alone**, matching `softmax_prefix.comp`. Zeroing the tail would be-    /// wrong there rather than merely wasteful: the tail belongs to positions this step does not-    /// attend over but a later one will, and the corresponding apply stops at the same bound.-    fn softmax(&mut self, p: &Push, mode: SoftmaxMode) -> Result<(), String> {-        if p.out_w == 0 {-            return Err("a softmax over an empty axis".into());-        }-        if mode == SoftmaxMode::Causal && p.out_h == 0 {-            return Err("a causal softmax over no queries".into());-        }-        for row in 0..p.count {-            let at = row * p.out_w;-            let keys = match mode {-                // At query 0 this is 1, so the distribution is exactly `[1, 0, ...]` and the-                // denominator can never be empty.-                SoftmaxMode::Causal => ((row % p.out_h.max(1)) + 1).min(p.out_w),-                SoftmaxMode::Prefix => {-                    let (first, last) = self.attended_q(p, p.out_w, row % p.dil_h.max(1));-                    let mut peak = -65504.0f32;-                    for i in first..=last {-                        peak = peak.max(self.load(p.in0, at + i)?);-                    }-                    let mut total = 0.0;-                    for i in first..=last {-                        total += (self.load(p.in0, at + i)? - peak).exp();-                    }-                    let inverse = 1.0 / total;-                    for i in first..=last {-                        let value = (self.load(p.in0, at + i)? - peak).exp() * inverse;-                        self.store(p.out, at + i, value)?;-                    }-                    continue;-                }-                SoftmaxMode::Full => p.out_w,-            };-            // A sliding layer's causal row also drops everything more than `p.kh - 1` behind-            // the query. Zero is no window, which is the plain causal mask.-            let query = row % p.out_h.max(1);-            let first = if mode == SoftmaxMode::Causal && p.kh != 0 {-                (query + 1).saturating_sub(p.kh)-            } else {-                0-            };-            let mut peak = -65504.0f32;-            for i in first..keys {-                peak = peak.max(self.load(p.in0, at + i)?);-            }-            let mut total = 0.0;-            for i in first..keys {-                total += (self.load(p.in0, at + i)? - peak).exp();-            }-            // The peak's own term is `exp(0)`, so this is at least 1.-            let inverse = 1.0 / total;-            for i in 0..first {-                self.store(p.out, at + i, 0.0)?;-            }-            for i in first..keys {-                let value = (self.load(p.in0, at + i)? - peak).exp() * inverse;-                self.store(p.out, at + i, value)?;-            }-            if mode == SoftmaxMode::Causal {-                // Written rather than left alone: `attn_apply` multiplies the whole row, and the-                // arena is reused, so a stale masked value would contribute something-                // unpredictable.-                for i in keys..p.out_w {-                    self.store(p.out, at + i, 0.0)?;-                }-            }-        }-        Ok(())-    } }
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 7eb95a3b8b..ed554f9f34 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -440,6 +440,7 @@ include!("parity_part1.rs"); include!("parity_part2.rs"); include!("parity_part3.rs"); include!("parity_part4.rs");+include!("parity_part9.rs"); include!("parity_part5.rs"); include!("parity_part6.rs"); include!("parity_part7.rs");
library/ml/src/main/rust/src/vulkan/parity_part4.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part4.rs b/library/ml/src/main/rust/src/vulkan/parity_part4.rsindex 4c2503cf09..44f30970d6 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part4.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part4.rs@@ -408,365 +408,3 @@ fn a_row_mode_softmax_agrees_with_the_reference() {     );     compare("a row-mode softmax", plan, source.into_data(), &[&x]); }--#[test]-#[ignore = "needs a Vulkan device"]-fn a_row_mode_prefix_softmax_agrees_with_the_reference() {-    // A decode plan built at 256 keys, run at several prefixes: the row is mostly stale, and only-    // the leading `prefix + 1` may be read or written. A prefix below and above the lane count, so-    // both the partly idle and the multi-pass cases run.-    let (heads, keys) = (4u32, 256u32);-    let x: Vec<f32> = spread((heads * keys) as usize, 0.7).iter().map(|v| v * 20.0).collect();-    for prefix in [0u32, 40, 200] {-        let source = Invented::new(0);-        let plan = row_mode_plan(-            &source,-            &[Shape::new(heads, 1, keys)],-            crate::nets::Kind::SoftmaxPrefix,-            |b, ids| b.softmax_prefix(ids[0], false),-        );-        let data = source.into_data();-        let host = crate::nets::reference::run_multi_at(&plan, &data, &[&x], prefix, 0)-            .expect("the interpreter runs the plan");-        let got = on_device_at(plan, data, &[&x], prefix);-        // Only the attended span is defined; the rest holds whatever the arena held.-        let live = (prefix + 1) as usize;-        let span = |all: &[Vec<f32>]| -> Vec<Vec<f32>> {-            vec![all[0]-                .chunks_exact(keys as usize)-                .flat_map(|row| row[..live].to_vec())-                .collect()]-        };-        matches(&format!("a row-mode prefix softmax at {prefix}"), &span(&host), &span(&got));-    }-}--#[test]-#[ignore = "needs a Vulkan device"]-fn a_two_lane_embedding_agrees_with_the_reference() {-    // Past 2048 rows an id does not survive a single fp16 lane, so it arrives as lo + 2048 * hi.-    // A shader that read only the low lane returns a real row of the table — the wrong one.-    let rows = 3000u32;-    let channels = 4u32;-    let ids = [7u32, 2048, 2999];-    let lanes = embed_lanes(&ids);-    let table = spread((rows * channels) as usize, 0.9);-    agrees(-        "a two-lane embedding",-        &[Shape::new(2, 1, ids.len() as u32)],-        &[&lanes],-        &[(vec![rows, channels], table)],-        |b, ids| b.embed(ids[0], 0, rows, channels),-    );-}--#[test]-#[ignore = "needs a Vulkan device"]-fn an_int8_convolution_agrees_with_the_reference() {-    // The only op whose weights are not fp16, so the only one where the shader and the interpreter-    // address the weights buffer differently: 32-bit words unpacked to bytes on one side, a byte-    // index into the undecoded blob on the other. Four output channels with four *different*-    // scales, because a shader that read `scale[0]` for every channel — which is what this op did-    // before the export turned out to be quantised per column — still returns the right shape and-    // three wrong channels.-    //-    // Deliberately a `1 x 3` rather than a `1 x 1`: an ungrouped `1 x 1` now lowers to-    // `Kind::ConvPointInt8` instead, so a pointwise fixture here would leave `conv_int8.comp`-    // untested on the device. The spatial kernel also puts its zero padding under test, which is-    // the one thing the tiled path has none of.-    let out_channels = 4u32;-    let in_channels = 3u32;-    let width = 5u32;-    let kernel: Vec<i8> = (0..(out_channels * in_channels * 3) as i32)-        .map(|i| ((i * 7) % 61 - 30) as i8)-        .collect();-    let scales: Vec<f32> = vec![0.25, 0.5, 0.0625, 1.0];-    let biases: Vec<f32> = vec![0.5, -0.25, 1.0, 0.0];-    let blob = write_mixed(-        graph::SUPERTONIC_VE,-        &[-            Fixture::I8(vec![out_channels, in_channels, 1, 3], kernel),-            Fixture::F16(vec![out_channels], scales),-            Fixture::F16(vec![out_channels], biases),-        ],-    );-    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");-    let input = spread((in_channels * width) as usize, 0.3);--    let mut builder = Builder::new(&weights);-    let first = builder.input(Shape::new(in_channels, 1, width));-    let last = builder.conv_int8(-        first,-        0,-        out_channels,-        (1, 3),-        (1, 1),-        (1, 1),-        (0, 1, 0, 1),-        1,-        Act::Relu,-    );-    let plan = builder.finish(&[last]).expect("the int8 fixture plan builds");-    compare("an int8 convolution", plan, weights.data().to_vec(), &[&input]);-}--#[test]-#[ignore = "needs a Vulkan device"]-fn a_tiled_int8_convolution_agrees_with_the_reference() {-    // `conv_point_int8.comp`, which every ungrouped 1x1 int8 convolution lowers to and which-    // Supertonic's sampler is 92% made of by parameter count.-    //-    // The shape is chosen so nothing about the tiling is exercised only at its happy path: 20-    // output channels and 21 positions are each more than one 16-wide tile and neither divides it,-    // so the four tiles include partial ones in both axes, and 24 input channels make the-    // accumulation loop take two staging steps of which the second is half out of range. A shader-    // that dropped the zero-fill on an out-of-range staging slot, or that mismatched its two-    // barriers, is wrong only on a fixture with all three of those properties.-    let out_channels = 20u32;-    let in_channels = 24u32;-    let width = 21u32;-    let kernel: Vec<i8> = (0..(out_channels * in_channels) as i32)-        .map(|i| ((i * 37) % 251 - 125) as i8)-        .collect();-    // Distinct per channel, as in the untiled fixture, and every one an exact multiple of a power-    // of two so the interpreter and the device read one number rather than two roundings of one.-    let scales: Vec<f32> = (0..out_channels).map(|c| 0.007_812_5 * (1.0 + c as f32)).collect();-    let biases: Vec<f32> = spread(out_channels as usize, 1.9);-    let blob = write_mixed(-        graph::SUPERTONIC_VE,-        &[-            Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),-            Fixture::F16(vec![out_channels], scales),-            Fixture::F16(vec![out_channels], biases),-        ],-    );-    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");-    let input = spread((in_channels * width) as usize, 0.7);--    let mut builder = Builder::new(&weights);-    let first = builder.input(Shape::new(in_channels, 1, width));-    // Gelu because that is what follows these convolutions in the sampler, and because it is the-    // activation whose input range the dequantisation scale decides.-    let last = builder.conv_int8(-        first,-        0,-        out_channels,-        (1, 1),-        (1, 1),-        (1, 1),-        (0, 0, 0, 0),-        1,-        Act::Gelu,-    );-    let plan = builder.finish(&[last]).expect("the tiled int8 fixture plan builds");-    compare("a tiled int8 convolution", plan, weights.data().to_vec(), &[&input]);-}--#[test]-#[ignore = "needs a Vulkan device"]-fn a_tiled_int8_convolution_agrees_across_many_tiles_and_both_loops() {-    // Several 32 x 32 workgroup tiles in both axes, each axis ending on a partial one, run once-    // through each of the shader's loops: sixteen-tap weights with quad activations-    // (`in_c % 16 == 0` and a width divisible by four), sixteen-tap weights with scalar-    // activations (ragged widths 75, 49 and 98, the sampler's frame count and its double), the-    // packed-word loop (`in_c % 4 == 0`) and the element-at-a-time one. A residual-free-    // projection with no activation, so a wrong tap shows directly in the numbers rather than-    // being squashed by a saturating activation.-    for (out_channels, in_channels, width) in-        [(70u32, 64u32, 76u32), (70, 64, 75), (70, 64, 49), (70, 64, 98), (45, 30, 40), (45, 36, 49)]-    {-        let kernel: Vec<i8> = (0..(out_channels * in_channels) as i32)-            .map(|i| ((i * 53) % 251 - 125) as i8)-            .collect();-        let scales: Vec<f32> = (0..out_channels).map(|c| 0.003_906_25 * (1.0 + (c % 7) as f32)).collect();-        let blob = write_mixed(-            graph::SUPERTONIC_VE,-            &[-                Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),-                Fixture::F16(vec![out_channels], scales),-                Fixture::F16(vec![out_channels], spread(out_channels as usize, 0.4)),-            ],-        );-        let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");-        let input = spread((in_channels * width) as usize, 0.2);-        let mut builder = Builder::new(&weights);-        let first = builder.input(Shape::new(in_channels, 1, width));-        let last = builder.conv_int8(-            first,-            0,-            out_channels,-            (1, 1),-            (1, 1),-            (1, 1),-            (0, 0, 0, 0),-            1,-            Act::None,-        );-        let plan = builder.finish(&[last]).expect("the fixture plan builds");-        let what = format!("a tiled int8 convolution {out_channels}x{in_channels} over {width}");-        compare(&what, plan, weights.data().to_vec(), &[&input]);-    }-}--#[test]-#[ignore = "needs a Vulkan device"]-fn report_the_tiled_int8_convolution_against_the_tiled_fp16_one() {-    // The measurement Phase 2 of the int8 plan is gated on, printed by-    // `cargo test -- --ignored --nocapture`. `conv_point_int8.comp` exists so that quantising-    // Supertonic's sampler does not move 92% of its parameters onto the untiled `conv_int8.comp`,-    // which was measured at 15.2 GFLOP/s against a device peak of order 1000. That is only worth-    // having if the int8 tiled path is close to the fp16 tiled one, because the alternative to-    // quantising is bundling 198 MB of fp16 rather than 105 MB of int8 — a size decision, not a-    // speed one, so a large slowdown here means take the size.-    //-    // Eight chained `512 -> 512` projections over 64 positions: the sampler's shape, deep enough-    // that the shader rather than the submit-and-read-back dominates.-    const CHANNELS: u32 = 512;-    const POSITIONS: u32 = 64;-    const LAYERS: usize = 8;-    const RUNS: usize = 20;--    // The two nets compute the same numbers, not merely the same shapes: the int8 weights are-    // exact small integers and the scale is an exact power of two, so dequantising is lossless-    // here. That is what lets the timings be compared against each other *and* the outputs-    // compared for equality, which is the only thing standing between a fast shader and a shader-    // that quietly wrote nothing.-    //-    // The divisor is what keeps eight chained layers inside fp16. A `512`-wide dot product of-    // weights spread over -3..3 has a gain of about `2 * sqrt(512) / DIVISOR`, so at 16 the chain-    // grows by ~2.8 a layer and reaches infinity by the eighth; at 64 it shrinks, which fp16-    // tolerates far better than it tolerates overflow.-    const DIVISOR: f32 = 64.0;-    let taps = (CHANNELS * CHANNELS) as usize;-    let int8_kernel: Vec<i8> = (0..taps).map(|i| (i % 7) as i8 - 3).collect();-    let fp16_kernel: Vec<f32> = int8_kernel.iter().map(|&w| f32::from(w) / DIVISOR).collect();-    let scales = vec![1.0 / DIVISOR; CHANNELS as usize];-    let biases = vec![0.0f32; CHANNELS as usize];--    let mut fp16_tensors = Vec::new();-    let mut int8_tensors = Vec::new();-    for _ in 0..LAYERS {-        let dims = vec![CHANNELS, CHANNELS, 1, 1];-        fp16_tensors.push(Fixture::F16(dims.clone(), fp16_kernel.clone()));-        fp16_tensors.push(Fixture::F16(vec![CHANNELS], biases.clone()));-        int8_tensors.push(Fixture::I8(dims, int8_kernel.clone()));-        int8_tensors.push(Fixture::F16(vec![CHANNELS], scales.clone()));-        int8_tensors.push(Fixture::F16(vec![CHANNELS], biases.clone()));-    }--    let input = spread((CHANNELS * POSITIONS) as usize, 0.5);-    let mut timings = Vec::new();-    let mut outputs = Vec::new();-    for (what, tensors, per_layer) in-        [("fp16", fp16_tensors, 2usize), ("int8", int8_tensors, 3usize)]-    {-        let blob = write_mixed(graph::SUPERTONIC_VE, &tensors);-        let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the blob parses");-        let mut builder = Builder::new(&weights);-        let mut x = builder.input(Shape::new(CHANNELS, 1, POSITIONS));-        for layer in 0..LAYERS {-            let at = layer * per_layer;-            x = if per_layer == 2 {-                builder.conv(x, at, CHANNELS, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::Gelu)-            } else {-                builder.conv_int8(-                    x,-                    at,-                    CHANNELS,-                    (1, 1),-                    (1, 1),-                    (1, 1),-                    (0, 0, 0, 0),-                    1,-                    Act::Gelu,-                )-            };-        }-        let plan = builder.finish(&[x]).expect("the benchmark plan builds");-        let mut net = Net::new(device(), plan, &weights, RESCALE_ONLY)-            .expect("the plan records into a command buffer");-        // One discarded run: the first submit pays for pipeline warm-up and for faulting the-        // weights into device memory, neither of which a steady-state utterance pays per step.-        let first = net.infer_raw(&input).expect("the benchmark submits and reads back");-        let start = std::time::Instant::now();-        for _ in 0..RUNS {-            net.infer_raw(&input).expect("the benchmark submits and reads back");-        }-        let each = start.elapsed().as_secs_f64() / RUNS as f64;-        // Two operations per multiply-accumulate, which is how the 15.2 GFLOP/s this shader-        // exists to escape was counted.-        let flops = 2.0 * f64::from(CHANNELS) * f64::from(CHANNELS) * f64::from(POSITIONS)-            * LAYERS as f64;-        println!("{what}: {:.3} ms per pass, {:.1} GFLOP/s", each * 1e3, flops / each / 1e9);-        timings.push(each);-        outputs.push(first);-    }--    match (timings.as_slice(), outputs.as_slice()) {-        ([fp16, int8], [from_fp16, from_int8]) => {-            println!("int8 / fp16 = {:.2}x", int8 / fp16);-            matches("the two benchmark nets", from_fp16, from_int8);-        }-        _ => panic!("two nets were timed"),-    }-}--#[test]-#[ignore = "needs a Vulkan device"]-fn a_net_uploaded_from_a_file_agrees_with_one_uploaded_from_memory() {-    // The bundled path end to end: the same plan, the same weights, uploaded once from a `Vec<u8>`-    // and once by streaming a file in chunks. The two must produce identical output, because a-    // wrong `dst_offset` on any chunk but the first gives a net whose early layers are right and-    // whose later ones read whatever the buffer was allocated with — plausible-looking audio, not-    // an error.-    //-    // The blob is deliberately larger than the chunk size the upload uses, so more than one copy is-    // issued. A single-chunk fixture exercises none of the arithmetic that can be wrong.-    const CHANNELS: u32 = 1024;-    const LAYERS: usize = 6;-    let taps = (CHANNELS * CHANNELS) as usize;-    let kernel: Vec<f32> = (0..taps).map(|i| ((i % 11) as f32 - 5.0) / 1024.0).collect();-    let bias = vec![0.0f32; CHANNELS as usize];-    let mut tensors = Vec::new();-    for _ in 0..LAYERS {-        tensors.push(Fixture::F16(vec![CHANNELS, CHANNELS, 1, 1], kernel.clone()));-        tensors.push(Fixture::F16(vec![CHANNELS], bias.clone()));-    }-    let blob = write_mixed(graph::SUPERTONIC_VE, &tensors);-    assert!(-        blob.len() as u64 > Net::CHUNK_BYTES,-        "{} bytes fits in one {}-byte chunk, so nothing is being tested",-        blob.len(),-        Net::CHUNK_BYTES,-    );--    let input = spread((CHANNELS * 8) as usize, 0.25);-    let plan_for = |source: &dyn WeightSource| -> Plan {-        let mut builder = Builder::new(source);-        let mut x = builder.input(Shape::new(CHANNELS, 1, 8));-        for layer in 0..LAYERS {-            x = builder.conv_same(x, layer * 2, CHANNELS, 1, 1, Act::Relu);-        }-        builder.finish(&[x]).expect("the upload fixture plan builds")-    };--    let parsed = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");-    let mut from_memory = Net::new(device(), plan_for(&parsed), &parsed, RESCALE_ONLY)-        .expect("the in-memory plan records");-    let want = from_memory.infer_raw(&input).expect("the in-memory net runs");--    // A leading pad, so the file's data section does not start where the file does — which is what-    // an asset inside an APK looks like, and the one thing an offset-free reader gets wrong.-    let path = std::env::temp_dir().join("modelrunner-upload-parity.maml");-    let mut staged = vec![0x5Au8; 8192];-    staged.extend_from_slice(&blob);-    std::fs::write(&path, &staged).expect("the fixture file writes");-    let file = std::fs::File::open(&path).expect("the fixture file reopens");-    let streamed = Streamed::open(file, 8192, blob.len() as u64, graph::SUPERTONIC_VE)-        .expect("the fixture file streams");-    let mut from_file = Net::new(device(), plan_for(&parsed), &streamed, RESCALE_ONLY)-        .expect("the streamed plan records");-    let got = from_file.infer_raw(&input).expect("the streamed net runs");--    matches("a net uploaded from a file", &want, &got);-}
library/ml/src/main/rust/src/vulkan/parity_part7.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part7.rs b/library/ml/src/main/rust/src/vulkan/parity_part7.rsindex 5e6b95dd18..a6afe2d94e 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part7.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part7.rs@@ -395,3 +395,47 @@ fn multi_query_cached_attention_equals_single_steps() {     // A short window, so every query's lower bound differs and most of them clip.     multi_query_fixture(7, 5, 256, 4); }++/// `[value, lo, hi] x 64` from a host sort: value descending, ties by lower id.+fn host_top_k(row: &[f32]) -> Vec<f32> {+    let mut ids: Vec<u32> = (0..row.len() as u32).collect();+    ids.sort_by(|&a, &b| row[b as usize].total_cmp(&row[a as usize]).then(a.cmp(&b)));+    (0..64)+        .flat_map(|r| match ids.get(r) {+            Some(&i) => [row[i as usize], (i % 2048) as f32, (i / 2048) as f32],+            None => [-65504.0, 2047.0, 2047.0],+        })+        .collect()+}++fn top_k_fixture(what: &str, row: &[f32]) {+    let source = Invented::new(0);+    let mut builder = Builder::new(&source);+    let input = builder.input(Shape::new(row.len() as u32, 1, 1));+    let out = builder.top_k(input);+    let plan = builder.finish(&[out]).expect("the top-k plan builds");+    crate::nets::tests::assert_no_aliasing(&plan);+    let data = source.into_data();+    let got = on_device(plan.clone(), data.clone(), &[row]);+    assert_eq!(got[0], host_top_k(row), "{what}: the device top 64 differs from a host sort");+    compare(what, plan, data, &[row]);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn device_top_k_equals_a_host_sort() {+    // Gemma's vocabulary. Multiples of 1/64 in [-8, 8) are exact in fp16, and only 1024 of them+    // over 262,144 entries means long runs of ties: the top 64 is decided by index alone.+    let vocab = 262_144usize;+    let ties: Vec<f32> = (0..vocab).map(|i| ((i * 7919 + i / 3) % 1024) as f32 / 64.0 - 8.0).collect();+    top_k_fixture("a tied 262144 row", &ties);+    // Eighty distinct peaks above the noise at scattered ids: the top 64 is decided by value.+    let mut peaks = ties.clone();+    for k in 0..80usize {+        peaks[(k * 104_729 + 17) % vocab] = 8.0 + k as f32 / 16.0;+    }+    top_k_fixture("a 262144 row with peaks", &peaks);+    // Shorter than 64: the missing ranks come back as (2047, 2047).+    let short: Vec<f32> = (0..40).map(|i| ((i * 13) % 7) as f32 - 3.0).collect();+    top_k_fixture("a 40-entry row", &short);+}
library/ml/src/main/rust/src/vulkan/parity_part9.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part9.rs b/library/ml/src/main/rust/src/vulkan/parity_part9.rsnew file mode 100644index 0000000000..748bb00660--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/parity_part9.rs@@ -0,0 +1,361 @@+#[test]+#[ignore = "needs a Vulkan device"]+fn a_row_mode_prefix_softmax_agrees_with_the_reference() {+    // A decode plan built at 256 keys, run at several prefixes: the row is mostly stale, and only+    // the leading `prefix + 1` may be read or written. A prefix below and above the lane count, so+    // both the partly idle and the multi-pass cases run.+    let (heads, keys) = (4u32, 256u32);+    let x: Vec<f32> = spread((heads * keys) as usize, 0.7).iter().map(|v| v * 20.0).collect();+    for prefix in [0u32, 40, 200] {+        let source = Invented::new(0);+        let plan = row_mode_plan(+            &source,+            &[Shape::new(heads, 1, keys)],+            crate::nets::Kind::SoftmaxPrefix,+            |b, ids| b.softmax_prefix(ids[0], false),+        );+        let data = source.into_data();+        let host = crate::nets::reference::run_multi_at(&plan, &data, &[&x], prefix, 0)+            .expect("the interpreter runs the plan");+        let got = on_device_at(plan, data, &[&x], prefix);+        // Only the attended span is defined; the rest holds whatever the arena held.+        let live = (prefix + 1) as usize;+        let span = |all: &[Vec<f32>]| -> Vec<Vec<f32>> {+            vec![all[0]+                .chunks_exact(keys as usize)+                .flat_map(|row| row[..live].to_vec())+                .collect()]+        };+        matches(&format!("a row-mode prefix softmax at {prefix}"), &span(&host), &span(&got));+    }+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_two_lane_embedding_agrees_with_the_reference() {+    // Past 2048 rows an id does not survive a single fp16 lane, so it arrives as lo + 2048 * hi.+    // A shader that read only the low lane returns a real row of the table — the wrong one.+    let rows = 3000u32;+    let channels = 4u32;+    let ids = [7u32, 2048, 2999];+    let lanes = embed_lanes(&ids);+    let table = spread((rows * channels) as usize, 0.9);+    agrees(+        "a two-lane embedding",+        &[Shape::new(2, 1, ids.len() as u32)],+        &[&lanes],+        &[(vec![rows, channels], table)],+        |b, ids| b.embed(ids[0], 0, rows, channels),+    );+}++#[test]+#[ignore = "needs a Vulkan device"]+fn an_int8_convolution_agrees_with_the_reference() {+    // The only op whose weights are not fp16, so the only one where the shader and the interpreter+    // address the weights buffer differently: 32-bit words unpacked to bytes on one side, a byte+    // index into the undecoded blob on the other. Four output channels with four *different*+    // scales, because a shader that read `scale[0]` for every channel — which is what this op did+    // before the export turned out to be quantised per column — still returns the right shape and+    // three wrong channels.+    //+    // Deliberately a `1 x 3` rather than a `1 x 1`: an ungrouped `1 x 1` now lowers to+    // `Kind::ConvPointInt8` instead, so a pointwise fixture here would leave `conv_int8.comp`+    // untested on the device. The spatial kernel also puts its zero padding under test, which is+    // the one thing the tiled path has none of.+    let out_channels = 4u32;+    let in_channels = 3u32;+    let width = 5u32;+    let kernel: Vec<i8> = (0..(out_channels * in_channels * 3) as i32)+        .map(|i| ((i * 7) % 61 - 30) as i8)+        .collect();+    let scales: Vec<f32> = vec![0.25, 0.5, 0.0625, 1.0];+    let biases: Vec<f32> = vec![0.5, -0.25, 1.0, 0.0];+    let blob = write_mixed(+        graph::SUPERTONIC_VE,+        &[+            Fixture::I8(vec![out_channels, in_channels, 1, 3], kernel),+            Fixture::F16(vec![out_channels], scales),+            Fixture::F16(vec![out_channels], biases),+        ],+    );+    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+    let input = spread((in_channels * width) as usize, 0.3);++    let mut builder = Builder::new(&weights);+    let first = builder.input(Shape::new(in_channels, 1, width));+    let last = builder.conv_int8(+        first,+        0,+        out_channels,+        (1, 3),+        (1, 1),+        (1, 1),+        (0, 1, 0, 1),+        1,+        Act::Relu,+    );+    let plan = builder.finish(&[last]).expect("the int8 fixture plan builds");+    compare("an int8 convolution", plan, weights.data().to_vec(), &[&input]);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_int8_convolution_agrees_with_the_reference() {+    // `conv_point_int8.comp`, which every ungrouped 1x1 int8 convolution lowers to and which+    // Supertonic's sampler is 92% made of by parameter count.+    //+    // The shape is chosen so nothing about the tiling is exercised only at its happy path: 20+    // output channels and 21 positions are each more than one 16-wide tile and neither divides it,+    // so the four tiles include partial ones in both axes, and 24 input channels make the+    // accumulation loop take two staging steps of which the second is half out of range. A shader+    // that dropped the zero-fill on an out-of-range staging slot, or that mismatched its two+    // barriers, is wrong only on a fixture with all three of those properties.+    let out_channels = 20u32;+    let in_channels = 24u32;+    let width = 21u32;+    let kernel: Vec<i8> = (0..(out_channels * in_channels) as i32)+        .map(|i| ((i * 37) % 251 - 125) as i8)+        .collect();+    // Distinct per channel, as in the untiled fixture, and every one an exact multiple of a power+    // of two so the interpreter and the device read one number rather than two roundings of one.+    let scales: Vec<f32> = (0..out_channels).map(|c| 0.007_812_5 * (1.0 + c as f32)).collect();+    let biases: Vec<f32> = spread(out_channels as usize, 1.9);+    let blob = write_mixed(+        graph::SUPERTONIC_VE,+        &[+            Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),+            Fixture::F16(vec![out_channels], scales),+            Fixture::F16(vec![out_channels], biases),+        ],+    );+    let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+    let input = spread((in_channels * width) as usize, 0.7);++    let mut builder = Builder::new(&weights);+    let first = builder.input(Shape::new(in_channels, 1, width));+    // Gelu because that is what follows these convolutions in the sampler, and because it is the+    // activation whose input range the dequantisation scale decides.+    let last = builder.conv_int8(+        first,+        0,+        out_channels,+        (1, 1),+        (1, 1),+        (1, 1),+        (0, 0, 0, 0),+        1,+        Act::Gelu,+    );+    let plan = builder.finish(&[last]).expect("the tiled int8 fixture plan builds");+    compare("a tiled int8 convolution", plan, weights.data().to_vec(), &[&input]);+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_tiled_int8_convolution_agrees_across_many_tiles_and_both_loops() {+    // Several 32 x 32 workgroup tiles in both axes, each axis ending on a partial one, run once+    // through each of the shader's loops: sixteen-tap weights with quad activations+    // (`in_c % 16 == 0` and a width divisible by four), sixteen-tap weights with scalar+    // activations (ragged widths 75, 49 and 98, the sampler's frame count and its double), the+    // packed-word loop (`in_c % 4 == 0`) and the element-at-a-time one. A residual-free+    // projection with no activation, so a wrong tap shows directly in the numbers rather than+    // being squashed by a saturating activation.+    for (out_channels, in_channels, width) in+        [(70u32, 64u32, 76u32), (70, 64, 75), (70, 64, 49), (70, 64, 98), (45, 30, 40), (45, 36, 49)]+    {+        let kernel: Vec<i8> = (0..(out_channels * in_channels) as i32)+            .map(|i| ((i * 53) % 251 - 125) as i8)+            .collect();+        let scales: Vec<f32> = (0..out_channels).map(|c| 0.003_906_25 * (1.0 + (c % 7) as f32)).collect();+        let blob = write_mixed(+            graph::SUPERTONIC_VE,+            &[+                Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),+                Fixture::F16(vec![out_channels], scales),+                Fixture::F16(vec![out_channels], spread(out_channels as usize, 0.4)),+            ],+        );+        let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+        let input = spread((in_channels * width) as usize, 0.2);+        let mut builder = Builder::new(&weights);+        let first = builder.input(Shape::new(in_channels, 1, width));+        let last = builder.conv_int8(+            first,+            0,+            out_channels,+            (1, 1),+            (1, 1),+            (1, 1),+            (0, 0, 0, 0),+            1,+            Act::None,+        );+        let plan = builder.finish(&[last]).expect("the fixture plan builds");+        let what = format!("a tiled int8 convolution {out_channels}x{in_channels} over {width}");+        compare(&what, plan, weights.data().to_vec(), &[&input]);+    }+}++#[test]+#[ignore = "needs a Vulkan device"]+fn report_the_tiled_int8_convolution_against_the_tiled_fp16_one() {+    // The measurement Phase 2 of the int8 plan is gated on, printed by+    // `cargo test -- --ignored --nocapture`. `conv_point_int8.comp` exists so that quantising+    // Supertonic's sampler does not move 92% of its parameters onto the untiled `conv_int8.comp`,+    // which was measured at 15.2 GFLOP/s against a device peak of order 1000. That is only worth+    // having if the int8 tiled path is close to the fp16 tiled one, because the alternative to+    // quantising is bundling 198 MB of fp16 rather than 105 MB of int8 — a size decision, not a+    // speed one, so a large slowdown here means take the size.+    //+    // Eight chained `512 -> 512` projections over 64 positions: the sampler's shape, deep enough+    // that the shader rather than the submit-and-read-back dominates.+    const CHANNELS: u32 = 512;+    const POSITIONS: u32 = 64;+    const LAYERS: usize = 8;+    const RUNS: usize = 20;++    // The two nets compute the same numbers, not merely the same shapes: the int8 weights are+    // exact small integers and the scale is an exact power of two, so dequantising is lossless+    // here. That is what lets the timings be compared against each other *and* the outputs+    // compared for equality, which is the only thing standing between a fast shader and a shader+    // that quietly wrote nothing.+    //+    // The divisor is what keeps eight chained layers inside fp16. A `512`-wide dot product of+    // weights spread over -3..3 has a gain of about `2 * sqrt(512) / DIVISOR`, so at 16 the chain+    // grows by ~2.8 a layer and reaches infinity by the eighth; at 64 it shrinks, which fp16+    // tolerates far better than it tolerates overflow.+    const DIVISOR: f32 = 64.0;+    let taps = (CHANNELS * CHANNELS) as usize;+    let int8_kernel: Vec<i8> = (0..taps).map(|i| (i % 7) as i8 - 3).collect();+    let fp16_kernel: Vec<f32> = int8_kernel.iter().map(|&w| f32::from(w) / DIVISOR).collect();+    let scales = vec![1.0 / DIVISOR; CHANNELS as usize];+    let biases = vec![0.0f32; CHANNELS as usize];++    let mut fp16_tensors = Vec::new();+    let mut int8_tensors = Vec::new();+    for _ in 0..LAYERS {+        let dims = vec![CHANNELS, CHANNELS, 1, 1];+        fp16_tensors.push(Fixture::F16(dims.clone(), fp16_kernel.clone()));+        fp16_tensors.push(Fixture::F16(vec![CHANNELS], biases.clone()));+        int8_tensors.push(Fixture::I8(dims, int8_kernel.clone()));+        int8_tensors.push(Fixture::F16(vec![CHANNELS], scales.clone()));+        int8_tensors.push(Fixture::F16(vec![CHANNELS], biases.clone()));+    }++    let input = spread((CHANNELS * POSITIONS) as usize, 0.5);+    let mut timings = Vec::new();+    let mut outputs = Vec::new();+    for (what, tensors, per_layer) in+        [("fp16", fp16_tensors, 2usize), ("int8", int8_tensors, 3usize)]+    {+        let blob = write_mixed(graph::SUPERTONIC_VE, &tensors);+        let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the blob parses");+        let mut builder = Builder::new(&weights);+        let mut x = builder.input(Shape::new(CHANNELS, 1, POSITIONS));+        for layer in 0..LAYERS {+            let at = layer * per_layer;+            x = if per_layer == 2 {+                builder.conv(x, at, CHANNELS, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::Gelu)+            } else {+                builder.conv_int8(+                    x,+                    at,+                    CHANNELS,+                    (1, 1),+                    (1, 1),+                    (1, 1),+                    (0, 0, 0, 0),+                    1,+                    Act::Gelu,+                )+            };+        }+        let plan = builder.finish(&[x]).expect("the benchmark plan builds");+        let mut net = Net::new(device(), plan, &weights, RESCALE_ONLY)+            .expect("the plan records into a command buffer");+        // One discarded run: the first submit pays for pipeline warm-up and for faulting the+        // weights into device memory, neither of which a steady-state utterance pays per step.+        let first = net.infer_raw(&input).expect("the benchmark submits and reads back");+        let start = std::time::Instant::now();+        for _ in 0..RUNS {+            net.infer_raw(&input).expect("the benchmark submits and reads back");+        }+        let each = start.elapsed().as_secs_f64() / RUNS as f64;+        // Two operations per multiply-accumulate, which is how the 15.2 GFLOP/s this shader+        // exists to escape was counted.+        let flops = 2.0 * f64::from(CHANNELS) * f64::from(CHANNELS) * f64::from(POSITIONS)+            * LAYERS as f64;+        println!("{what}: {:.3} ms per pass, {:.1} GFLOP/s", each * 1e3, flops / each / 1e9);+        timings.push(each);+        outputs.push(first);+    }++    match (timings.as_slice(), outputs.as_slice()) {+        ([fp16, int8], [from_fp16, from_int8]) => {+            println!("int8 / fp16 = {:.2}x", int8 / fp16);+            matches("the two benchmark nets", from_fp16, from_int8);+        }+        _ => panic!("two nets were timed"),+    }+}++#[test]+#[ignore = "needs a Vulkan device"]+fn a_net_uploaded_from_a_file_agrees_with_one_uploaded_from_memory() {+    // The bundled path end to end: the same plan, the same weights, uploaded once from a `Vec<u8>`+    // and once by streaming a file in chunks. The two must produce identical output, because a+    // wrong `dst_offset` on any chunk but the first gives a net whose early layers are right and+    // whose later ones read whatever the buffer was allocated with — plausible-looking audio, not+    // an error.+    //+    // The blob is deliberately larger than the chunk size the upload uses, so more than one copy is+    // issued. A single-chunk fixture exercises none of the arithmetic that can be wrong.+    const CHANNELS: u32 = 1024;+    const LAYERS: usize = 6;+    let taps = (CHANNELS * CHANNELS) as usize;+    let kernel: Vec<f32> = (0..taps).map(|i| ((i % 11) as f32 - 5.0) / 1024.0).collect();+    let bias = vec![0.0f32; CHANNELS as usize];+    let mut tensors = Vec::new();+    for _ in 0..LAYERS {+        tensors.push(Fixture::F16(vec![CHANNELS, CHANNELS, 1, 1], kernel.clone()));+        tensors.push(Fixture::F16(vec![CHANNELS], bias.clone()));+    }+    let blob = write_mixed(graph::SUPERTONIC_VE, &tensors);+    assert!(+        blob.len() as u64 > Net::CHUNK_BYTES,+        "{} bytes fits in one {}-byte chunk, so nothing is being tested",+        blob.len(),+        Net::CHUNK_BYTES,+    );++    let input = spread((CHANNELS * 8) as usize, 0.25);+    let plan_for = |source: &dyn WeightSource| -> Plan {+        let mut builder = Builder::new(source);+        let mut x = builder.input(Shape::new(CHAN

Diff truncated.