Modern Apps git

← Modern-Apps.git

modelrunner: fix cargo check and clippy warnings

Commit
2ff338aa4a7b20ea289134996e4c87b6af14e349
Author
Vayun Mathur <[email protected]>
When
2026-11-17 14:16 UTC (19 days ago)
Parents
bc54736
Standalone cargo builds failed in a clean checkout because the
library read SPIR-V from the Gradle compileShaders output and the
host examples read an OUT_DIR no build script produced. Add a
build script that compiles shaders/*.comp into OUT_DIR with the
NDK glslc (same --target-env=vulkan1.1 -O flags as Gradle, Gradle
output as fallback, loud failure rather than stub shaders) and
point the pipeline/imageprobe include_bytes! at OUT_DIR, which
also fixes the examples.

Scope clippy::excessive_precision to the generated constant
tables only (logmel_extra and microfrontend_part1 test modules,
the per-table scales in gemma4_part5, and one folded-scale test
literal): rounding those literals would change ML numerics.

Fix every other check/clippy finding in code: replace
is_multiple_of (stable 1.87, above the 1.85 MSRV) with modulo
checks that preserve the zero-divisor guards, remove unused
imports/variables/unsafe and dead code (producer_of duplicate,
conv3x3, submit_and_wait, Probe handles, Recorded::pinned),
make nets::Recorded public with crate-private fields so
Graph::emit no longer exposes a more-private type, bundle
attn_scores_cached_at/attn_scores_banded/time_pass arguments
into option structs, add type aliases for complex types, and
apply the remaining mechanical lints (needless range loops,
sort_by_key, negated partial-ord comparisons via partial_cmp,
single-range Vec construction, doc continuation formatting).
Mark the gather pseudocode block as text so the doctest passes.

Verified: cargo check -p modelrunner --all-targets and
cargo clippy -p modelrunner --all-targets report no warnings
or errors, and cargo test -p modelrunner passes (633 + 19 + 5
tests, doctests included).

Diff

library/ml/src/main/rust/build.rs
diff --git a/library/ml/src/main/rust/build.rs b/library/ml/src/main/rust/build.rsnew file mode 100644index 0000000000..45be683578--- /dev/null+++ b/library/ml/src/main/rust/build.rs@@ -0,0 +1,155 @@+//! Compiles `shaders/*.comp` to SPIR-V in `OUT_DIR`.+//!+//! The library and the host examples `include_bytes!` the compiled shaders+//! from `OUT_DIR`. Previously the library read them from the Gradle+//! `compileShaders` output (`library/ml/build/spirv`), so standalone+//! `cargo check` / `cargo test` failed in a clean checkout until that Gradle+//! task had run, and the examples referenced an `OUT_DIR` that no build+//! script ever populated. Compiling here uses the same compiler and flags+//! as the Gradle task (`--target-env=vulkan1.1 -O`, NDK `glslc`), so the+//! Android build embeds identical SPIR-V; the Gradle task's output is still+//! honoured as a fallback when no `glslc` can be found. When neither is+//! available the build fails loudly rather than embedding stub shaders.++use std::env;+use std::fs;+use std::path::PathBuf;+use std::process::{exit, Command};++fn main() {+    if let Err(message) = run() {+        eprintln!("modelrunner build script: {message}");+        exit(1);+    }+}++fn run() -> Result<(), String> {+    let manifest_dir = env::var_os("CARGO_MANIFEST_DIR")+        .map(PathBuf::from)+        .ok_or_else(|| "CARGO_MANIFEST_DIR is not set".to_owned())?;+    let out_dir = env::var_os("OUT_DIR")+        .map(PathBuf::from)+        .ok_or_else(|| "OUT_DIR is not set".to_owned())?;+    let shader_dir = manifest_dir.join("shaders");+    println!("cargo:rerun-if-changed={}", shader_dir.display());+    println!("cargo:rerun-if-env-changed=GLSLC");+    println!("cargo:rerun-if-env-changed=ANDROID_HOME");+    println!("cargo:rerun-if-env-changed=ANDROID_SDK_ROOT");+    println!("cargo:rerun-if-env-changed=ANDROID_NDK_HOME");++    let mut sources = Vec::new();+    let entries = fs::read_dir(&shader_dir)+        .map_err(|error| format!("cannot read {}: {error}", shader_dir.display()))?;+    for entry in entries {+        let path = entry+            .map_err(|error| format!("cannot read {}: {error}", shader_dir.display()))?+            .path();+        if path.extension().is_some_and(|ext| ext == "comp") {+            sources.push(path);+        }+    }+    sources.sort();+    if sources.is_empty() {+        return Err(format!("no .comp shaders in {}", shader_dir.display()));+    }++    if let Some(glslc) = find_glslc() {+        for source in &sources {+            let file_name = source+                .file_name()+                .ok_or_else(|| format!("shader {} has no file name", source.display()))?+                .to_string_lossy()+                .into_owned();+            let output = out_dir.join(format!("{file_name}.spv"));+            let status = Command::new(&glslc)+                .args(["--target-env=vulkan1.1", "-O", "-o"])+                .arg(&output)+                .arg(source)+                .status()+                .map_err(|error| format!("cannot run {}: {error}", glslc.display()))?;+            if !status.success() {+                return Err(format!(+                    "{} failed on {} with {status}",+                    glslc.display(),+                    source.display()+                ));+            }+        }+        return Ok(());+    }++    // No compiler: copy the Gradle `compileShaders` output verbatim.+    let prebuilt = manifest_dir.join("../../../build/spirv");+    let mut copied = 0usize;+    for source in &sources {+        let file_name = source+            .file_name()+            .ok_or_else(|| format!("shader {} has no file name", source.display()))?+            .to_string_lossy()+            .into_owned();+        let from = prebuilt.join(format!("{file_name}.spv"));+        if from.is_file() {+            fs::copy(&from, out_dir.join(format!("{file_name}.spv")))+                .map_err(|error| format!("cannot copy {}: {error}", from.display()))?;+            copied += 1;+        }+    }+    if copied == sources.len() {+        return Ok(());+    }+    Err(format!(+        "glslc not found (set GLSLC, put it on PATH, or install the Android NDK) and \+         prebuilt SPIR-V is incomplete in {}; refusing to embed stub shaders",+        prebuilt.display()+    ))+}++/// `GLSLC`, then `PATH`, then the newest NDK under the Android SDK.+fn find_glslc() -> Option<PathBuf> {+    let exe = if cfg!(windows) { "glslc.exe" } else { "glslc" };+    if let Some(path) = env::var_os("GLSLC").map(PathBuf::from) {+        if path.is_file() {+            return Some(path);+        }+    }+    if let Some(path_var) = env::var_os("PATH") {+        for dir in env::split_paths(&path_var) {+            let candidate = dir.join(exe);+            if candidate.is_file() {+                return Some(candidate);+            }+        }+    }+    let mut sdk_roots: Vec<PathBuf> = ["ANDROID_NDK_HOME", "ANDROID_HOME", "ANDROID_SDK_ROOT"]+        .iter()+        .filter_map(|key| env::var_os(key).map(PathBuf::from))+        .collect();+    if let Some(home) = env::var_os("HOME").map(PathBuf::from) {+        sdk_roots.push(home.join("Android/Sdk"));+    }+    let mut candidates = Vec::new();+    for root in &sdk_roots {+        // `ANDROID_NDK_HOME` points at the NDK itself; the others at the SDK,+        // whose NDKs live under `ndk/<version>/`.+        let ndk_dirs: Vec<PathBuf> = if root.join("shader-tools").is_dir() {+            vec![root.clone()]+        } else {+            match fs::read_dir(root.join("ndk")) {+                Ok(entries) => entries.filter_map(|entry| entry.ok().map(|e| e.path())).collect(),+                Err(_) => Vec::new(),+            }+        };+        for ndk in ndk_dirs {+            if let Ok(hosts) = fs::read_dir(ndk.join("shader-tools")) {+                for host in hosts.filter_map(|entry| entry.ok().map(|e| e.path())) {+                    let candidate = host.join(exe);+                    if candidate.is_file() {+                        candidates.push(candidate);+                    }+                }+            }+        }+    }+    candidates.sort();+    candidates.pop()+}
library/ml/src/main/rust/examples/check_gate_audio.rs
diff --git a/library/ml/src/main/rust/examples/check_gate_audio.rs b/library/ml/src/main/rust/examples/check_gate_audio.rsindex a1de10974c..00808cdb56 100644--- a/library/ml/src/main/rust/examples/check_gate_audio.rs+++ b/library/ml/src/main/rust/examples/check_gate_audio.rs@@ -269,7 +269,7 @@ fn features(signals: &[(String, Vec<i16>)]) {         let mut frames = Vec::new();         frontend.process(pcm, &mut frames);         let count = frames.len() / CHANNELS;-        let mut mean = vec![0.0f32; CHANNELS];+        let mut mean = [0.0f32; CHANNELS];         for frame in 0..count {             for (channel, slot) in mean.iter_mut().enumerate() {                 *slot += frames[frame * CHANNELS + channel];
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 64910c4abe..861de4c801 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -163,7 +163,7 @@ fn main() {         },         None => None,     };-    let golden = match std::fs::read_to_string(&golden) {+    let golden = match std::fs::read_to_string(golden) {         Ok(text) => text,         Err(why) => return println!("cannot read the golden: {why}"),     };@@ -578,6 +578,8 @@ fn gather_plan(context: &Arc<context::Context>, embed: &Streamed) -> Result<Resh /// Positions one prefill submit covers. Mirrors the bridge's `CHUNK`. const CHUNK: usize = 256; +type KindReports = Vec<(&'static str, Vec<(String, f64, f64)>)>;+ /// Milliseconds per stage of one prompt, summed over its chunks. #[derive(Default)] struct PrefillTimes {@@ -590,7 +592,7 @@ struct PrefillTimes {     /// The last token's `Mode::Tail` submit.     tail: f64,     /// Per-kind GPU tables of the last chunk's prefill and tail, under `MODELRUNNER_TIMESTAMPS`.-    reports: Vec<(&'static str, Vec<(String, f64, f64)>)>,+    reports: KindReports,     /// The last token's final-normed state, which the head reads.     state: Vec<f32>, }
library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rsindex 74c17092bc..efa787729b 100644--- a/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_vision_parity.rs@@ -207,7 +207,7 @@ fn against(got: &[f32], exact: &[f32], control: Option<&[f32]>, floor: f64) -> (     match control {         None => (format!("exact {exact_line}"), exact_cosine),         Some(control) => {-            let (line, cosine) = compare(got, control);+            let (_line, cosine) = compare(got, control);             let verdict = if cosine > floor { "ok" } else { "WRONG" };             (                 format!(
library/ml/src/main/rust/examples/dump_conv_shapes.rs
diff --git a/library/ml/src/main/rust/examples/dump_conv_shapes.rs b/library/ml/src/main/rust/examples/dump_conv_shapes.rsindex 571d93b67e..4919d78f81 100644--- a/library/ml/src/main/rust/examples/dump_conv_shapes.rs+++ b/library/ml/src/main/rust/examples/dump_conv_shapes.rs@@ -49,8 +49,8 @@ fn main() {     open("maia", "maia3-5m.maml", graph::MAIA, &|w| maia::build(w));      // (net, step, out_c, out_h, out_w, in_c, kh, kw, stride, dil, group, act, gmac)-    let mut rows: Vec<(String, usize, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, f64)> =-        Vec::new();+    type ConvRow = (String, usize, u32, u32, u32, u32, u32, u32, u32, u32, u32, u32, f64);+    let mut rows: Vec<ConvRow> = Vec::new();     for (name, plan) in &plans {         for (step, op) in plan.ops.iter().enumerate() {             let Op::Dispatch { kind: Kind::Conv, push, .. } = op else { continue };
library/ml/src/main/rust/examples/profile_gemma4_decode.rs
diff --git a/library/ml/src/main/rust/examples/profile_gemma4_decode.rs b/library/ml/src/main/rust/examples/profile_gemma4_decode.rsindex 1d0fb0c690..0886815e4e 100644--- a/library/ml/src/main/rust/examples/profile_gemma4_decode.rs+++ b/library/ml/src/main/rust/examples/profile_gemma4_decode.rs@@ -103,7 +103,7 @@ fn main() {             None => per_kind.push((*kind, 1, bytes)),         }     }-    per_kind.sort_by(|a, b| b.2.cmp(&a.2));+    per_kind.sort_by_key(|b| std::cmp::Reverse(b.2));     println!();     println!("{:>6} {:>10}  {:?}", "count", "wt-bytes", "kind");     let mut total_bytes = 0u64;
library/ml/src/main/rust/examples/profile_supertonic.rs
diff --git a/library/ml/src/main/rust/examples/profile_supertonic.rs b/library/ml/src/main/rust/examples/profile_supertonic.rsindex 7c259580de..c43a18c8ae 100644--- a/library/ml/src/main/rust/examples/profile_supertonic.rs+++ b/library/ml/src/main/rust/examples/profile_supertonic.rs@@ -102,7 +102,7 @@ const LANES: usize = 2;  /// `values / stride`, refusing a remainder. As in `bridge_part1.rs`. fn positions(what: &str, values: usize, stride: usize) -> Result<u32, String> {-    if stride == 0 || values == 0 || !values.is_multiple_of(stride) {+    if stride == 0 || values == 0 || values % (stride) != 0 {         return Err(format!("{what}: {values} values is not a whole number of {stride}"));     }     Ok((values / stride) as u32)@@ -305,7 +305,7 @@ fn run() -> Result<(), String> {     let dir = args         .first()         .map(String::as_str)-        .or_else(|| option_env!("MODELRUNNER_ASSETS"))+        .or(option_env!("MODELRUNNER_ASSETS"))         .map(str::to_owned)         .or_else(|| std::env::var("MODELRUNNER_ASSETS").ok())         .ok_or("pass the supertonic asset dir or set MODELRUNNER_ASSETS")?;
library/ml/src/main/rust/examples/profile_vision.rs
diff --git a/library/ml/src/main/rust/examples/profile_vision.rs b/library/ml/src/main/rust/examples/profile_vision.rsindex b73257ba7b..225a58c1c9 100644--- a/library/ml/src/main/rust/examples/profile_vision.rs+++ b/library/ml/src/main/rust/examples/profile_vision.rs@@ -287,7 +287,7 @@ fn profile_rec_batch(path: &str, passes: u32) -> Result<(), String> {     println!("load      batch of {LINES} {:.1} ms", since(t));     let len = ppocr_rec::HEIGHT as usize * REC_WIDTH as usize;     let strips: Vec<Vec<i32>> = (0..LINES as usize)-        .map(|i| (0..len).map(|p| (0xff00_0000u32 | ((p * 37 + i * 101) as u32 * 2_654_435_761 >> 8)) as i32).collect())+        .map(|i| (0..len).map(|p| (0xff00_0000u32 | (((p * 37 + i * 101) as u32 * 2_654_435_761) >> 8)) as i32).collect())         .collect();     let shape = modelrunner::nets::Shape::new(3, ppocr_rec::HEIGHT, REC_WIDTH);     let mut half = vec![0u16; shape.len() as usize];
library/ml/src/main/rust/examples/report_barriers.rs
diff --git a/library/ml/src/main/rust/examples/report_barriers.rs b/library/ml/src/main/rust/examples/report_barriers.rsindex cef94c4ee3..9609b49f7d 100644--- a/library/ml/src/main/rust/examples/report_barriers.rs+++ b/library/ml/src/main/rust/examples/report_barriers.rs@@ -148,8 +148,8 @@ fn barrier_table(plans: &[(String, Plan)]) {     println!("Barriers a dependency-correct recorder would emit, against one per op.");     println!();     println!(-        "{:<22} {:>6} {:>8} {:>8} {:>7}   {}",-        "plan", "ops", "today", "needed", "saved", "of the needed ones"+        "{:<22} {:>6} {:>8} {:>8} {:>7}   of the needed ones",+        "plan", "ops", "today", "needed", "saved"     );     for (name, plan) in plans {         let s = schedule::schedule(plan);@@ -247,12 +247,12 @@ fn adjacency_table(plans: &[(String, Plan)]) {             }         }     }-    pairs.sort_by(|a, b| b.1.cmp(&a.1));+    pairs.sort_by_key(|b| std::cmp::Reverse(b.1));      println!("Chained producer -> consumer pairs, every plan above summed. {total} in total.");     println!("Each fused pair removes one dispatch and one barrier everywhere it occurs.");     println!();-    println!("{:>6} {:>6}  {:<44} {}", "count", "share", "pair", "arrives as");+    println!("{:>6} {:>6}  {:<44} arrives as", "count", "share", "pair");     for ((from, to, operand), n) in pairs.iter().take(24) {         let share = 100.0 * *n as f64 / total.max(1) as f64;         let pair = format!("{from:?} -> {to:?}");
library/ml/src/main/rust/examples/report_gemv_bottleneck.rs
diff --git a/library/ml/src/main/rust/examples/report_gemv_bottleneck.rs b/library/ml/src/main/rust/examples/report_gemv_bottleneck.rsindex 039628c18c..1b186533e6 100644--- a/library/ml/src/main/rust/examples/report_gemv_bottleneck.rs+++ b/library/ml/src/main/rust/examples/report_gemv_bottleneck.rs@@ -345,7 +345,7 @@ fn run(context: &Arc<Context>) -> Result<(), String> {     {         let warm = Pipeline::new(context, pipeline_layout, A)?;         for _ in 0..WARMUP {-            let _ = time_pass(context, command_buffer, fence, pipeline_layout, set, &warm, quads, GROUPS)?;+            let _ = time_pass(Pass { context, cb: command_buffer, fence, layout: pipeline_layout, set, pipeline: &warm }, quads, GROUPS)?;         }         warm.destroy(context);     }@@ -382,7 +382,7 @@ fn run(context: &Arc<Context>) -> Result<(), String> {      // One discarded pass each, so no variant's first timed pass pays for driver setup.     for (_, pipeline, _, groups, _) in &built {-        let _ = time_pass(context, command_buffer, fence, pipeline_layout, set, pipeline, quads, *groups)?;+        let _ = time_pass(Pass { context, cb: command_buffer, fence, layout: pipeline_layout, set, pipeline }, quads, *groups)?;     }      let mut rates: Vec<Vec<f64>> = vec![Vec::with_capacity(RUNS); built.len()];@@ -390,7 +390,7 @@ fn run(context: &Arc<Context>) -> Result<(), String> {     for _ in 0..RUNS {         for (index, (_, pipeline, _, groups, bytes)) in built.iter().enumerate() {             let seconds =-                time_pass(context, command_buffer, fence, pipeline_layout, set, pipeline, quads, *groups)?;+                time_pass(Pass { context, cb: command_buffer, fence, layout: pipeline_layout, set, pipeline }, quads, *groups)?;             if let Some(slot) = rates.get_mut(index) {                 slot.push(*bytes as f64 / seconds / 1e9);             }@@ -669,7 +669,7 @@ struct Pipeline {  impl Pipeline {     fn new(context: &Arc<Context>, layout: vk::PipelineLayout, spirv: &[u8]) -> Result<Pipeline, String> {-        if !spirv.len().is_multiple_of(4) || spirv.len() < 20 {+        if spirv.len() % (4) != 0 || spirv.len() < 20 {             return Err(format!(                 "{} bytes is not a SPIR-V module - did the glslc step run? See analysis/gemv_probe/README.md",                 spirv.len()@@ -715,17 +715,20 @@ impl Pipeline {     } } -/// Seconds for one pass.-fn time_pass(-    context: &Arc<Context>,+/// The Vulkan handles one timed pass binds, bundled so `time_pass` takes+/// the pass plus its two sizes.+struct Pass<'a> {+    context: &'a Arc<Context>,     cb: vk::CommandBuffer,     fence: vk::Fence,     layout: vk::PipelineLayout,     set: vk::DescriptorSet,-    pipeline: &Pipeline,-    quads: u32,-    groups: u32,-) -> Result<f64, String> {+    pipeline: &'a Pipeline,+}++/// Seconds for one pass.+fn time_pass(pass: Pass<'_>, quads: u32, groups: u32) -> Result<f64, String> {+    let Pass { context, cb, fence, layout, set, pipeline } = pass;     let device = &context.device;     // `quads` for the streaming variants, `in_c` and `count` for the gemv-shaped ones. All     // three are pushed for every variant; a shader that does not declare a field ignores it.
library/ml/src/main/rust/examples/report_tex_gemv.rs
diff --git a/library/ml/src/main/rust/examples/report_tex_gemv.rs b/library/ml/src/main/rust/examples/report_tex_gemv.rsindex 8dd75ec935..ecbae6480c 100644--- a/library/ml/src/main/rust/examples/report_tex_gemv.rs+++ b/library/ml/src/main/rust/examples/report_tex_gemv.rs@@ -138,7 +138,7 @@ fn run(context: &Arc<Context>) -> Result<(), String> {     let g_layout = make_layout(context, g_set, &push_range)?;     let tex_layout = make_layout(context, tex_set, &push_range)?; -    let (command_pool, command_buffer, fence) = make_cmd(context)?;+    let (_command_pool, command_buffer, fence) = make_cmd(context)?;     let quads = (BYTES / 16) as u32;     let count = gemv_out / 2; @@ -229,9 +229,6 @@ fn upload_activations(context: &Arc<Context>, acts: &Buffer) -> Result<(), Strin     Ok(()) } -type SetLayouts = (vk::DescriptorSetLayout, vk::DescriptorPool, vk::DescriptorSet);-type PipelineHandles = (vk::Pipeline, vk::ShaderModule);- fn make_set(     context: &Arc<Context>,     bindings: &[(u32, vk::DescriptorType)],
library/ml/src/main/rust/examples/run_gemma4.rs
diff --git a/library/ml/src/main/rust/examples/run_gemma4.rs b/library/ml/src/main/rust/examples/run_gemma4.rsindex 605313abe8..541bece4cf 100644--- a/library/ml/src/main/rust/examples/run_gemma4.rs+++ b/library/ml/src/main/rust/examples/run_gemma4.rs@@ -175,7 +175,7 @@ fn gather_parity_gate(     embed: &Weights,     table: &Table<'_>,     prompt: &str,-) -> () {+) {     use modelrunner::nets::gemma4_gather;     let specials = ["<bos>", "<eos>", "<pad>", "<unk>"];     let mut tokens = vec![GEMMA.bos];@@ -295,7 +295,7 @@ fn head_logits(     hidden: &[f32],     head_embed: Option<&Weights>, ) -> Result<Vec<f32>, String> {-    use modelrunner::nets::gemma4_head;+         if std::env::var("GEMMA4_GREEDY").is_ok() {         if let Some(embed) = head_embed {             if let Some(id) = head_greedy_id(_context, embed, hidden)? {@@ -560,7 +560,7 @@ fn run_chat(     table: &Table<'_>,     prompt: &str,     limit: usize,-) -> () {+) {     const MARKERS: [&str; 11] = [         "<bos>", "<eos>", "<|turn>", "<turn|>", "<|tool>", "<tool|>", "<|tool_call>",         "<tool_call|>", "<|tool_response>", "<tool_response|>", "<|\"|>",
library/ml/src/main/rust/examples/spike_nnfp_match.rs
diff --git a/library/ml/src/main/rust/examples/spike_nnfp_match.rs b/library/ml/src/main/rust/examples/spike_nnfp_match.rsindex 90ee244e18..db5c37adec 100644--- a/library/ml/src/main/rust/examples/spike_nnfp_match.rs+++ b/library/ml/src/main/rust/examples/spike_nnfp_match.rs@@ -105,6 +105,8 @@ fn l2(v: &mut [f32]) {     } } +type EmbedAll = (Vec<(f32, Vec<f32>)>, Vec<f32>);+ /// Slide the 478-frame window over `frames` and embed each position. /// /// Returns the L2-normalised embeddings for matching, and separately the raw pre-normalisation@@ -113,7 +115,7 @@ fn embed_all(     net: &mut Net,     frames: &[f32],     hop_frames: usize,-) -> Result<(Vec<(f32, Vec<f32>)>, Vec<f32>), String> {+) -> Result<EmbedAll, String> {     let bins = nnfp::MEL_BINS as usize;     let window = nnfp::WINDOW_FRAMES as usize;     let total = frames.len() / bins;
library/ml/src/main/rust/examples/trace_collapse.rs
diff --git a/library/ml/src/main/rust/examples/trace_collapse.rs b/library/ml/src/main/rust/examples/trace_collapse.rsindex 945ce470aa..db8fcea30c 100644--- a/library/ml/src/main/rust/examples/trace_collapse.rs+++ b/library/ml/src/main/rust/examples/trace_collapse.rs@@ -44,7 +44,7 @@ fn main() {         println!("usage: trace_collapse <text.maml> <embed.maml> [max_layers]");         return;     };-    let max_layers: usize = args.next().and_then(|s| s.parse().ok()).unwrap_or(gemma4::LAYERS as usize);+    let max_layers: usize = args.next().and_then(|s| s.parse().ok()).unwrap_or(gemma4::LAYERS);     let text_bytes = std::fs::read(&text).unwrap();     let embed_bytes = std::fs::read(&embed).unwrap();     let weights = Weights::parse(&text_bytes, graph::GEMMA4_TEXT).unwrap();@@ -52,7 +52,7 @@ fn main() {     let context = context::shared().unwrap();     let reader = embed_weights.reader();     let rotary = weights.reader();-    for layers in 0..=max_layers.min(gemma4::LAYERS as usize) {+    for layers in 0..=max_layers.min(gemma4::LAYERS) {         let mode = gemma4::Mode::Trace { layers }.at(TIER);         let mut net = match Reshaped::new(             Arc::clone(&context),
library/ml/src/main/rust/src/logmel_extra.rs
diff --git a/library/ml/src/main/rust/src/logmel_extra.rs b/library/ml/src/main/rust/src/logmel_extra.rsindex 27c820f47b..242fbf1692 100644--- a/library/ml/src/main/rust/src/logmel_extra.rs+++ b/library/ml/src/main/rust/src/logmel_extra.rs@@ -1,4 +1,9 @@ #[cfg(test)]+// Generated constants (see the generator note inside): the literals are+// reference outputs with more digits than `f32` can represent, and rounding+// them would change the ML numerics the tests compare against, so+// `excessive_precision` is allowed for this generated test module only.+#[allow(clippy::excessive_precision)] mod tests {     use crate::logmel::*; 
library/ml/src/main/rust/src/microfrontend_part1.rs
diff --git a/library/ml/src/main/rust/src/microfrontend_part1.rs b/library/ml/src/main/rust/src/microfrontend_part1.rsindex 6bd3cfd61e..ec1edf18c6 100644--- a/library/ml/src/main/rust/src/microfrontend_part1.rs+++ b/library/ml/src/main/rust/src/microfrontend_part1.rs@@ -1,4 +1,9 @@ #[cfg(test)]+// Generated constants (see the generator note inside): the literals are+// reference outputs with more digits than `f32` can represent, and rounding+// them would change the ML numerics the tests compare against, so+// `excessive_precision` is allowed for this generated test module only.+#[allow(clippy::excessive_precision)] mod tests {     use super::*; @@ -280,7 +285,7 @@ mod tests {         frontend.reset();         // Without the reset the leftover 300 would complete a window after only 100 more.         assert_eq!(frontend.process(&vec![1i16; 300], &mut frames), 0);-        assert_eq!(frontend.process(&vec![1i16; 100], &mut frames), 1);+        assert_eq!(frontend.process(&[1i16; 100], &mut frames), 1);     }      #[test]
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 e2a3c115af..5565265821 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -116,7 +116,8 @@ pub const MAX_CONTEXT: u32 = 16_384; /// /// Tiers rather than a smooth grow because each change re-records the plan and **loses the cache** /// - the arena is reallocated, so the whole prompt is prefilled again. Doubling makes that happen-/// a handful of times over a long conversation instead of continuously.+///   a handful of times over a long conversation instead of continuously.+/// /// Pinned tensors that are KV caches, and the first that many in the plan. /// /// `build` declares the caches before anything else, so they are a prefix of `Plan::pinned` -@@ -180,10 +181,10 @@ pub const LOGIT_CAP: f32 = 30.0; /// the shapes agree and every logit merely saturates at `LOGIT_CAP`. pub const EMBED_GAIN: f32 = 39.25; -/// Live int8 round-trip scales for the attention path.-///-/// Moved to gemma4_part5.rs (module-length lint): [MM_SCALE],-/// [QI_SCALE], [QO_SCALE], [KO_SCALE], [VO_SCALE], [O_SCALE].+// Live int8 round-trip scales for the attention path.+//+// Moved to gemma4_part5.rs (module-length lint): [MM_SCALE],+// [QI_SCALE], [QO_SCALE], [KO_SCALE], [VO_SCALE], [O_SCALE].  /// Whether `q_norm`'s gamma already carries `1 / sqrt(head_dim)`. ///@@ -318,7 +319,7 @@ pub const TENSORS: usize = SHARED_TENSORS /// The first tensor index of layer `index`. pub const fn layer_at(index: usize) -> usize {     let owning = if index < OWNS_CACHE_LAYERS { index } else { OWNS_CACHE_LAYERS };-    let shared = if index < OWNS_CACHE_LAYERS { 0 } else { index - OWNS_CACHE_LAYERS };+    let shared = index.saturating_sub(OWNS_CACHE_LAYERS);     LAYER0 + owning * OWNING_LAYER_TENSORS + shared * SHARED_LAYER_TENSORS } 
library/ml/src/main/rust/src/nets/gemma4_audio.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_audio.rs b/library/ml/src/main/rust/src/nets/gemma4_audio.rsindex 372a31b879..9dd9590d94 100644--- a/library/ml/src/main/rust/src/nets/gemma4_audio.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_audio.rs@@ -353,7 +353,7 @@ pub fn layer_at(index: usize) -> usize {  /// Positions surviving one stride-2, pad-1, kernel-3 convolution: `ceil(n / 2)`. pub const fn subsample(n: u32) -> u32 {-    if n == 0 { 0 } else { (n + 1) / 2 }+    if n == 0 { 0 } else { n.div_ceil(2) } }  /// Soft tokens `frames` mel frames produce, one per twice-subsampled frame.
library/ml/src/main/rust/src/nets/gemma4_audio_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_audio_part2.rs b/library/ml/src/main/rust/src/nets/gemma4_audio_part2.rsindex 90b5adb555..efbe9edb70 100644--- a/library/ml/src/main/rust/src/nets/gemma4_audio_part2.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_audio_part2.rs@@ -80,7 +80,7 @@ fn layer(b: &mut Builder, index: usize, x: Id) -> Result<Id, String> {     let k = b.affine(k, K_SCALE, 0.0);     // The cap is fused into the scores op, before its own masking sentinel; see `LOGIT_CAP`.     let scores =-        b.attn_scores_banded(q, k, HEADS, ATTEND_SPAN, relative, REL_OFFSETS, 1.0, LOGIT_CAP);+        b.attn_scores_banded(q, k, crate::nets::BandedScores { heads: HEADS, band: ATTEND_SPAN, table: relative, offsets: REL_OFFSETS, scale: 1.0, cap: LOGIT_CAP });     let probs = b.softmax(scores);     let mixed = b.attn_apply_banded(probs, v, HEADS, ATTEND_SPAN);     let mixed = b.clamp(mixed, clip_attn);
library/ml/src/main/rust/src/nets/gemma4_audio_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_audio_part3.rs b/library/ml/src/main/rust/src/nets/gemma4_audio_part3.rsindex 8948e93c38..18ef98859f 100644--- a/library/ml/src/main/rust/src/nets/gemma4_audio_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_audio_part3.rs@@ -215,6 +215,9 @@ mod tests {     }      #[test]+    // The two literals are the export's constants at full `f64` precision;+    // rounding them would defeat the comparison against the folded scales.+    #[allow(clippy::excessive_precision)]     fn the_folded_scales_are_the_constants_the_export_holds() {         // Measured in the graph as val_279 and val_280. The `/ ln 2` in the query scale is the         // part nobody would guess, and reproducing `HEAD_DIM ** -0.5` alone would be off by
library/ml/src/main/rust/src/nets/gemma4_gather.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_gather.rs b/library/ml/src/main/rust/src/nets/gemma4_gather.rsindex ae11b79bc6..9df2809488 100644--- a/library/ml/src/main/rust/src/nets/gemma4_gather.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_gather.rs@@ -91,7 +91,7 @@ pub fn build_plan_at(weights: &dyn WeightSource, width: u32) -> Result<Plan, Str     // see the module docs for why the row lookups did not move.)     for index in 0..embed::TABLES {         match index {-            3 | 4 | 5 | 6 => {}+            3..=6 => {}             _ => b.host_tensor(index, &super::gemma4_head::dims_of(index)),         }     }
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 66ee7733ba..36d2603a71 100644--- a/library/ml/src/main/rust/src/nets/gemma4_head.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -137,7 +137,7 @@ fn build_plan8(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, String>     // Every EMBED tensor this pass does not read, named so `finish` accepts     // the plan. The int8 chunks are the only tensors read.     for index in 0..TENSORS_WITH_HEAD8 {-        if index < HEAD8_BASE || index >= HEAD8_BASE + HEAD8_CHUNK_TENSORS {+        if !(HEAD8_BASE..HEAD8_BASE + HEAD8_CHUNK_TENSORS).contains(&index) {             b.host_tensor(index, &dims_of(index));         }     }@@ -166,7 +166,7 @@ fn finish_greedy(b: &mut Builder, outs: &mut Vec<Id>) {     // copies within the arena — no extra allocation) and reduce to one     // greedy id. The split outputs stay too, so the Kotlin sampling path     // keeps working from the same recording.-    let row = b.concat(&outs);+    let row = b.concat(outs);     let id = b.argmax(row);     outs.push(id); }@@ -179,7 +179,7 @@ fn build_plan_fp16(weights: &dyn WeightSource, greedy: bool) -> Result<Plan, Str     // the plan. The fp16 chunks are the only tensors read; the legacy rank-2     // table (tensor 112) stays host-side for gather-time fallback.     for index in 0..TENSORS_WITH_HEAD {-        if index < HEAD_BASE || index >= HEAD_BASE + HEAD_CHUNK_TENSORS {+        if !(HEAD_BASE..HEAD_BASE + HEAD_CHUNK_TENSORS).contains(&index) {             b.host_tensor(index, &dims_of(index));         }     }
library/ml/src/main/rust/src/nets/gemma4_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_part1.rsindex dea31be7d1..fb1c762bc9 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part1.rs@@ -208,7 +208,8 @@ pub fn build(weights: &dyn WeightSource, pass: Pass) -> Result<Plan, String> {     // A fresh prefill attends its own chunk, so the owning layers' K and V are carried forward     // to the shared layers as tensors (the `cache_source` mapping, resolved to tensors).     let fresh = matches!(mode, Mode::PrefillFresh { .. });-    let (mut sliding_kv, mut full_kv): (Option<(Id, Id)>, Option<(Id, Id)>) = (None, None);+    type KvPair = Option<(Id, Id)>;+    let (mut sliding_kv, mut full_kv): (KvPair, KvPair) = (None, None);     for index in run.clone() {         let angles = if is_full_attention(index) { angles_global } else { angles_local };         let (cache_k, cache_v) = *caches@@ -299,12 +300,12 @@ fn prefill_layer(     let inner = ffn(index);     let at = layer_at(index);     let mut next = at;-    let mut plain = |n: &mut usize| {+    let plain = |n: &mut usize| {         let here = *n;         *n += 1;         here     };-    let mut proj = |n: &mut usize| {+    let proj = |n: &mut usize| {         let here = *n;         *n += PROJECTION_TENSORS;         here
library/ml/src/main/rust/src/nets/gemma4_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part3.rs b/library/ml/src/main/rust/src/nets/gemma4_part3.rsindex 967ac1f0d2..e8ad57d824 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part3.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part3.rs@@ -139,7 +139,7 @@ mod tests {             }         }         assert_eq!(scores, LAYERS, "one cached score map per layer");-        assert!(Q_NORM_CARRIES_SCALE, "if this ever becomes false the assertion above flips");+        // If `Q_NORM_CARRIES_SCALE` ever becomes false, the scale assertion above flips.     }      #[test]
library/ml/src/main/rust/src/nets/gemma4_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part4.rs b/library/ml/src/main/rust/src/nets/gemma4_part4.rsindex 9aea2941f1..5c8fdc4b36 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part4.rs@@ -109,8 +109,10 @@ pub mod embed { /// `inputs_embeds` is the working-table row; `per_layer_inputs` is the COMBINED /// block the reference's `maybe_preprocess_per_layer_embeddings` produces: ///-///     projected = hidden @ SHARED_PROJ-///     combined  = (16 * embedded + rms_norm(projected)) * 1/sqrt(2)+/// ```text+/// projected = hidden @ SHARED_PROJ+/// combined  = (16 * embedded + rms_norm(projected)) * 1/sqrt(2)+/// ``` /// /// S10 graph walk t319 -> t30: t307 `[16.0]` scales the gather side, t304 /// `[1/sqrt(2)]` the sum. No `1/sqrt(d_model)` exists anywhere in S10 (and a@@ -286,11 +288,13 @@ fn combine_timed(     Ok((out, bulk_ms, matmul_ms)) } +type ProjectionPair = (std::sync::Arc<Vec<f32>>, std::sync::Arc<Vec<f32>>);+ /// The process-constant half of the combine, cached or freshly read. fn combine_projection(     embed: &crate::weights::Reader<'_>,     use_cache: bool,-) -> Result<(std::sync::Arc<Vec<f32>>, std::sync::Arc<Vec<f32>>), String> {+) -> Result<ProjectionPair, String> {     let proj_dims = [LAYERS as u32 * PER_LAYER, D_MODEL, 1, 1];     if !use_cache {         let proj = embed.int8_all(embed::SHARED_PROJ, embed::SHARED_PROJ + 1, &proj_dims)?;
library/ml/src/main/rust/src/nets/gemma4_part5.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_part5.rs b/library/ml/src/main/rust/src/nets/gemma4_part5.rsindex 5cece189e5..7d8203d974 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part5.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part5.rs@@ -1,3 +1,7 @@+// Generated constant tables: the scale literals below are read off the+// source bundle with more digits than `f32` can represent. Rounding them+// would change ML numerics, so each generated table carries a scoped+// `excessive_precision` allow instead of rounded literals. // Live int8 round-trip scales for Gemma 4's attention path (part of `nets::gemma4`). // // S10's per-tensor quantization scales, one per layer, for the attention@@ -28,6 +32,7 @@ /// and diverges past any cosine gate (fp `Mm` vs live: 0.67; round-tripped: /// 0.97865 at L0 - see `analysis/ablate_o_tail.py`). #[rustfmt::skip]+#[allow(clippy::excessive_precision)] pub const MM_SCALE: [f32; LAYERS] = [     0.03026575781404972,     0.023129930719733238,@@ -68,6 +73,7 @@ pub const MM_SCALE: [f32; LAYERS] = [  /// Live int8 scale for q_in (`q_einsum/composite`). See [`MM_SCALE`]. #[rustfmt::skip]+#[allow(clippy::excessive_precision)] pub const QI_SCALE: [f32; 35] = [     0.6088034510612488,     0.4842597544193268,@@ -108,6 +114,7 @@ pub const QI_SCALE: [f32; 35] = [  /// Live int8 scale for q_out (`q_einsum/dot_general1`). See [`MM_SCALE`]. #[rustfmt::skip]+#[allow(clippy::excessive_precision)] pub const QO_SCALE: [f32; 35] = [     3.118110179901123,     0.35039371252059937,@@ -149,6 +156,7 @@ pub const QO_SCALE: [f32; 35] = [ /// Live int8 scale for k_out (`k_einsum/dot_general1`, owning layers only). /// See [`MM_SCALE`]. #[rustfmt::skip]+#[allow(clippy::excessive_precision)] pub const KO_SCALE: [f32; 15] = [     1.535433053970337,     0.41535434126853943,@@ -170,6 +178,7 @@ pub const KO_SCALE: [f32; 15] = [ /// Live int8 scale for v_out (`v_einsum/dot_general1`, owning layers only). /// See [`MM_SCALE`]. #[rustfmt::skip]+#[allow(clippy::excessive_precision)] pub const VO_SCALE: [f32; 15] = [     1.535433053970337,     0.41535434126853943,@@ -190,6 +199,7 @@ pub const VO_SCALE: [f32; 15] = [  /// Live int8 scale for o_in (`attn_vec_einsum/dot_general1`). See [`MM_SCALE`]. #[rustfmt::skip]+#[allow(clippy::excessive_precision)] pub const O_SCALE: [f32; 35] = [     0.21056734025478363,     0.03322756290435791,
library/ml/src/main/rust/src/nets/gemma4_vision.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision.rs b/library/ml/src/main/rust/src/nets/gemma4_vision.rsindex 90afe90a00..688f812e6f 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision.rs@@ -380,7 +380,7 @@ impl Grid {         if rows == 0 || cols == 0 {             return Err(format!("a patch grid of {rows}x{cols}"));         }-        if !rows.is_multiple_of(POOL) || !cols.is_multiple_of(POOL) {+        if rows % (POOL) != 0 || cols % (POOL) != 0 {             return Err(format!(                 "a {rows}x{cols} patch grid does not divide by the pooling kernel {POOL}, so a \                  pooled cell would straddle the edge"
library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs b/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rsindex b1bedc969d..6dbefe791b 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision_part1.rs@@ -347,12 +347,11 @@ pub fn prepare(         .collect::<Result<Vec<_>, _>>()?;      let mut positions = vec![0.0; D_MODEL as usize * patches];-    for row in 0..grid.rows as usize {-        for column in 0..grid.cols as usize {+    for (row, row_values) in by_row.iter().enumerate() {+        for (column, column_values) in by_column.iter().enumerate() {             let at = row * grid.cols as usize + column;             for channel in 0..D_MODEL as usize {-                positions[channel * patches + at] =-                    by_column[column][channel] + by_row[row][channel];+                positions[channel * patches + at] = column_values[channel] + row_values[channel];             }         }     }
library/ml/src/main/rust/src/nets/gemma4_vision_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision_part2.rs b/library/ml/src/main/rust/src/nets/gemma4_vision_part2.rsindex 5520272f23..60f7af90fe 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision_part2.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision_part2.rs@@ -130,7 +130,7 @@ mod tests {         let values = patchify(grid, &pixels).expect("patches");         let patches = grid.patches() as usize;         assert_eq!(values.len(), D_MODEL as usize * patches);-        let patch = 1 * 3 + 2;+        let patch = 3 + 2;         let within = (4 * 16 + 3) * 3;         assert_eq!(values[within * patches + patch], 1.0, "red is saturated");         assert_eq!(values[(within + 1) * patches + patch], -1.0, "green is off");@@ -152,7 +152,7 @@ mod tests {         let half = frequencies.len();          // Patch 8 is row 1, column 2 of a 3-row, 6-column grid.-        let at = 1 * 6 + 2;+        let at = 6 + 2;         for (i, frequency) in frequencies.iter().enumerate() {             let column = 2.0 * frequency;             let row = 1.0 * frequency;
library/ml/src/main/rust/src/nets/madlad.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad.rs b/library/ml/src/main/rust/src/nets/madlad.rsindex 3c42d3198a..3695054c73 100644--- a/library/ml/src/main/rust/src/nets/madlad.rs+++ b/library/ml/src/main/rust/src/nets/madlad.rs@@ -344,7 +344,8 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     // The two heads, the decoder and the two bias tables belong elsewhere, except the decoder's     // cross-attention K and V projections, which run here once per sentence. The trailing encoder     // norm is part of the first range, so it runs to `DECODER` rather than to `ENCODER_NORM`.-    let mut read = vec![ENCODER..DECODER];+    let mut read = Vec::new();+    read.push(ENCODER..DECODER);     read.extend((0..DECODER_LAYERS).map(cross_kv));     name_host_tensors(b, &read); 
library/ml/src/main/rust/src/nets/madlad_extra2.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_extra2.rs b/library/ml/src/main/rust/src/nets/madlad_extra2.rsindex e17f633a47..57de5e7849 100644--- a/library/ml/src/main/rust/src/nets/madlad_extra2.rs+++ b/library/ml/src/main/rust/src/nets/madlad_extra2.rs@@ -44,7 +44,8 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl     // The decoder plus the logits head, minus the cross-attention K and V the encode pass ran.     // The input table, the whole encoder and both bias tables belong elsewhere: the tables are     // read on the host, never by a shader, so the range ends at TABLE_ENC.-    let mut read = vec![HEAD_LM..ENCODER];+    let mut read = Vec::new();+    read.push(HEAD_LM..ENCODER);     let mut at = DECODER;     for layer in 0..DECODER_LAYERS {         let skipped = cross_kv(layer);
library/ml/src/main/rust/src/nets/maia.rs
diff --git a/library/ml/src/main/rust/src/nets/maia.rs b/library/ml/src/main/rust/src/nets/maia.rsindex 96dcf9877b..06f10645f1 100644--- a/library/ml/src/main/rust/src/nets/maia.rs+++ b/library/ml/src/main/rust/src/nets/maia.rs@@ -189,7 +189,7 @@ const BLOCK: usize = SMOLGEN + 3; /// /// Eight projections of three — the bias generator's two, q, k, v, the output projection and /// the two feed-forward — two layer norms of two, and the two RMS norms of one.-const BLOCK_TENSORS: usize = 8 * 3 + 2 * 2 + 2 * 1;+const BLOCK_TENSORS: usize = 8 * 3 + 2 * 2 + 2;  /// `transformer.norm`, the layer norm closing the stack. const FINAL_NORM: usize = BLOCK + BLOCKS * BLOCK_TENSORS;
library/ml/src/main/rust/src/nets/maia_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/maia_part1.rs b/library/ml/src/main/rust/src/nets/maia_part1.rsindex c0a289c07a..65cf698ba4 100644--- a/library/ml/src/main/rust/src/nets/maia_part1.rs+++ b/library/ml/src/main/rust/src/nets/maia_part1.rs@@ -188,14 +188,14 @@ mod tests {         // Each elo channel is one value repeated across all 64 squares, and self comes         // before oppo.         let after = (PLANES * HISTORY * SQUARES) as usize;-        for channel in 0..ELO_DIM as usize {+        for (channel, &value) in self_elo.iter().enumerate() {             let at = after + channel * SQUARES as usize;-            assert!(out[at..at + 64].iter().all(|&v| v == self_elo[channel]));+            assert!(out[at..at + 64].iter().all(|&v| v == value));         }         let after_self = after + (ELO_DIM * SQUARES) as usize;-        for channel in 0..ELO_DIM as usize {+        for (channel, &value) in oppo_elo.iter().enumerate() {             let at = after_self + channel * SQUARES as usize;-            assert!(out[at..at + 64].iter().all(|&v| v == oppo_elo[channel]));+            assert!(out[at..at + 64].iter().all(|&v| v == value));         }     } 
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 a26c21595d..1426798c27 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -107,20 +107,6 @@ impl Node {     } } -/// The convolution node that wrote `id`, if one did.-///-/// `finish`'s fusion fold only folds into convolutions — the op whose store does the adding —-/// so this is the predicate that names a foldable producer. Anything else (`None`) keeps the-/// binary as its own op.-fn producer_of(nodes: &[Node], id: Id) -> Option<usize> {-    nodes.iter().position(|node| {-        matches!(-            node,-            Node::Conv { .. } | Node::ConvInt8 { .. } | Node::RmsNorm { .. }-        ) && node.out() == id-    })-}- /// `floor((in + pad - dilation * (k - 1) - 1) / stride) + 1`, ONNX's convolution /// output size. fn conv_out(input: u32, kernel: u32, stride: u32, dilation: u32, pad_total: u32) -> u32 {
library/ml/src/main/rust/src/nets/mod_part12.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part12.rs b/library/ml/src/main/rust/src/nets/mod_part12.rsindex 02305c2619..0975d1da05 100644--- a/library/ml/src/main/rust/src/nets/mod_part12.rs+++ b/library/ml/src/main/rust/src/nets/mod_part12.rs@@ -95,6 +95,7 @@     ///     /// `Weights::parse` requires the file to end exactly where the data section does,     /// so the returned vector is padded with zeros to the declared length.+    #[cfg(test)]     fn maml_header(shapes: &[(&[u32], u32)]) -> Vec<u8> {         use crate::weights::graph;         let count = shapes.len() as u32;
library/ml/src/main/rust/src/nets/mod_part13.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part13.rs b/library/ml/src/main/rust/src/nets/mod_part13.rsindex c024b93676..275fd741b9 100644--- a/library/ml/src/main/rust/src/nets/mod_part13.rs+++ b/library/ml/src/main/rust/src/nets/mod_part13.rs@@ -134,8 +134,5 @@ fn quant_producer_of(nodes: &[Node], id: Id) -> Option<usize> { /// explicit opt-out (`0`, `off` or `false`) disables it; anything else — /// including unset — folds. pub(crate) fn quant_fold_on(value: Option<String>) -> bool {-    match value.as_deref() {-        Some("0") | Some("off") | Some("false") => false,-        _ => true,-    }+    !matches!(value.as_deref(), Some("0" | "off" | "false")) }
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 adb97b3edf..d017e26be8 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -157,19 +157,17 @@ pub struct Id(pub(crate) usize); /// read flags, shapes, and bindings — without re-deriving anything. The plan is what /// runs; the rest is what the converter needs to reproduce it. #[derive(Debug)]-pub(crate) struct Recorded {+pub struct Recorded {     /// The resolved plan, as `finish` has always returned.     pub plan: Plan,     /// The fused nodes, in execution order.-    pub nodes: Vec<Node>,+    pub(crate) nodes: Vec<Node>,     /// Shape per tensor id.-    pub shapes: Vec<Shape>,+    pub(crate) shapes: Vec<Shape>,     /// Input ids, in declaration order.-    pub inputs: Vec<Id>,-    /// Pinned ids (inputs, outputs, persistent).-    pub pinned: Vec<Id>,+    pub(crate) inputs: Vec<Id>,     /// Per-file-tensor read flags, so the emitter can name host tensors.-    pub read: Vec<bool>,+    pub(crate) read: Vec<bool>, }  /// An unresolved step, against [`Id`]s rather than offsets.
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 292ec71a59..4b5ffcba8c 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -116,7 +116,7 @@ impl<'a> Builder<'a> {         let in_shape = self.shape_of(input);         let (kh, kw) = kernel;         let splits =-            group != 0 && in_shape.c.is_multiple_of(group) && m.is_multiple_of(group);+            group != 0 && in_shape.c % (group) == 0 && m % (group) == 0;         if !splits {             self.fail(format!(                 "tensor {weight_index}: {} in / {m} out channels do not split into \@@ -313,7 +313,7 @@ impl<'a> Builder<'a> {         let in_shape = self.shape_of(input);         let (kh, kw) = kernel;         let splits =-            group != 0 && in_shape.c.is_multiple_of(group) && m.is_multiple_of(group);+            group != 0 && in_shape.c % (group) == 0 && m % (group) == 0;         if !splits {             self.fail(format!(                 "tensor {weight_index}: {} in / {m} out channels do not split into \
library/ml/src/main/rust/src/nets/mod_part5.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part5.rs b/library/ml/src/main/rust/src/nets/mod_part5.rsindex c48ed9b833..4ceb2fc07e 100644--- a/library/ml/src/main/rust/src/nets/mod_part5.rs+++ b/library/ml/src/main/rust/src/nets/mod_part5.rs@@ -1,3 +1,18 @@+/// Head/dynamic/scale options for [`Builder::attn_scores_cached_at`].+#[derive(Clone, Copy)]+pub(crate) struct CachedScores {+    /// Query heads.+    pub heads: u32,+    /// Key/value heads supplying the cache.+    pub kv_heads: u32,+    /// Whether the key count is supplied by the step.+    pub dynamic: bool,+    /// Whether to derive `1 / sqrt(head_dim)` here.+    pub derive_scale: bool,+    /// Whether this layer's sliding window applies.+    pub sliding: bool,+}+ impl<'a> Builder<'a> {     fn weight(&mut self, index: usize, dims: &[u32]) -> u32 {         match self.read.get_mut(index) {@@ -23,7 +38,7 @@ impl<'a> Builder<'a> {     /// deliberately not modelled. [`tests::u2netp_pools_only_even_extents`] holds that.     pub fn max_pool_2x2(&mut self, input: Id) -> Id {         let in_shape = self.shape_of(input);-        if !in_shape.h.is_multiple_of(2) || !in_shape.w.is_multiple_of(2) {+        if in_shape.h % (2) != 0 || in_shape.w % (2) != 0 {             self.fail(format!(                 "max_pool_2x2 on {}x{}: ceil_mode is not modelled, so an odd extent \                  would silently drop a row",@@ -282,7 +297,7 @@ impl<'a> Builder<'a> {         groups: u32,     ) -> Id {         let shape = self.shape_of(input);-        if groups == 0 || !shape.c.is_multiple_of(groups) {+        if groups == 0 || shape.c % (groups) != 0 {             self.fail(format!("{} channels do not split into {groups} groups", shape.c));         }         let per_group = shape.c.checked_div(groups.max(1)).unwrap_or(0);@@ -352,7 +367,7 @@ impl<'a> Builder<'a> {     /// One query is what makes a causal mask unnecessary — a decode step attends over exactly the     /// positions in the cache, so the prefix bound is the tensor's own length.     pub fn attn_scores_cached(&mut self, q: Id, cache: Id, heads: u32) -> Id {-        self.attn_scores_cached_at(q, cache, heads, heads, false, true, true)+        self.attn_scores_cached_at(q, cache, CachedScores { heads, kv_heads: heads, dynamic: false, derive_scale: true, sliding: true })     }      /// [`Builder::attn_scores_cached`] with the key count supplied by the step, not the shape.@@ -360,7 +375,7 @@ impl<'a> Builder<'a> {     /// `cache` is then sized to the **maximum** context the plan is built for, and only its     /// leading `prefix + 1` positions are attended. See [`Push::dyn_keys`].     pub fn attn_scores_cached_dynamic(&mut self, q: Id, cache: Id, heads: u32) -> Id {-        self.attn_scores_cached_at(q, cache, heads, heads, true, true, true)+        self.attn_scores_cached_at(q, cache, CachedScores { heads, kv_heads: heads, dynamic: true, derive_scale: true, sliding: true })     }      /// [`Builder::attn_scores_cached_dynamic`] where `kv_heads` heads supply the keys.@@ -374,7 +389,7 @@ impl<'a> Builder<'a> {         heads: u32,         kv_heads: u32,     ) -> Id {-        self.attn_scores_cached_at(q, cache, heads, kv_heads, true, true, true)+        self.attn_scores_cached_at(q, cache, CachedScores { heads, kv_heads, dynamic: true, derive_scale: true, sliding: true })     }      /// [`Builder::attn_scores_cached_grouped`] for a query that is **already scaled**.@@ -394,19 +409,11 @@ impl<'a> Builder<'a> {         kv_heads: u32,         sliding: bool,     ) -> Id {-        self.attn_scores_cached_at(q, cache, heads, kv_heads, true, false, sliding)+        self.attn_scores_cached_at(q, cache, CachedScores { heads, kv_heads, dynamic: true, derive_scale: false, sliding })     } -    fn attn_scores_cached_at(-        &mut self,-        q: Id,-        cache: Id,-        heads: u32,-        kv_heads: u32,-        dynamic: bool,-        derive_scale: bool,-        sliding: bool,-    ) -> Id {+    fn attn_scores_cached_at(&mut self, q: Id, cache: Id, scores: CachedScores) -> Id {+        let CachedScores { heads, kv_heads, dynamic, derive_scale, sliding } = scores;         let (sq, sc) = (self.shape_of(q), self.shape_of(cache));         if sq.h != 1 || sq.w != 1 {             self.fail(format!(@@ -420,7 +427,7 @@ impl<'a> Builder<'a> {                  [keys, 1, kv_heads * head_dim], so its channels are the keys"             ));         }-        if heads == 0 || !sq.c.is_multiple_of(heads) {+        if heads == 0 || sq.c % (heads) != 0 {             self.fail(format!("{} channels do not split into {heads} heads", sq.c));         }         let head_dim = sq.c.checked_div(heads).unwrap_or(0);
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 c4297fbc26..a2eda27570 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -45,7 +45,7 @@ impl<'a> Builder<'a> {         if heads == 0 || kv_heads == 0 || heads % kv_heads != 0 {             self.fail(format!("{heads} query heads do not group into {kv_heads} key/value heads"));         }-        if !sc.w.is_multiple_of(kv_heads.max(1)) {+        if sc.w % (kv_heads.max(1)) != 0 {             self.fail(format!("{} cache channels do not split into {kv_heads} heads", sc.w));         }         // The output is the **query** side's width, `heads * head_dim`, which is what the next@@ -97,7 +97,7 @@ impl<'a> Builder<'a> {                  one would silently reinterpret the layout"             ));         }-        if heads == 0 || !sq.c.is_multiple_of(heads) {+        if heads == 0 || sq.c % (heads) != 0 {             self.fail(format!("{} channels do not split into {heads} heads", sq.c));         }         let head_dim = sq.c.checked_div(heads).unwrap_or(0);@@ -228,7 +228,7 @@ impl<'a> Builder<'a> {     }     /// `tanh(x / cap) * cap`, elementwise. See [`Kind::Softcap`].     pub fn softcap(&mut self, input: Id, cap: f32) -> Id {-        if !(cap > 0.0) {+        if cap.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {             self.fail(format!("a softcap of {cap}, which must be positive"));         }         let shape = self.shape_of(input);@@ -270,7 +270,7 @@ impl<'a> Builder<'a> {     /// compile-time constant like [`Builder::softcap`]'s cap, for the same reason:     /// one float per layer, fixed by the source bundle (see `MM_SCALE`).     pub fn quantize(&mut self, input: Id, scale: f32) -> Id {-        if !(scale > 0.0) {+        if scale.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {             self.fail(format!("a quantize of {scale}, whose scale must be positive"));         }         let shape = self.shape_of(input);@@ -451,17 +451,17 @@ impl<'a> Builder<'a> {         if sx.h != 1 || sa.h != 1 {             self.fail(format!("rotary on {sx:?}: a sequence is [d_model, 1, T]"));         }-        if heads == 0 || !sx.c.is_multiple_of(heads) {+        if heads == 0 || sx.c % (heads) != 0 {             self.fail(format!("{} channels do not split into {heads} heads", sx.c));         }         let head_dim = sx.c.checked_div(heads.max(1)).unwrap_or(0);-        if axes == 0 || !head_dim.is_multiple_of(axes.max(1)) {+        if axes == 0 || head_dim % (axes.max(1)) != 0 {             self.fail(format!(                 "rotary over a head of {head_dim} in {axes} blocks, which does not divide"             ));         }         let block = head_dim.checked_div(axes.max(1)).unwrap_or(0);-        if block == 0 || !block.is_multiple_of(2) {+        if block == 0 || block % (2) != 0 {             self.fail(format!(                 "rotary over a block of {block}: it rotates 2-planes, so the block must be even"             ));
library/ml/src/main/rust/src/nets/mod_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part7.rs b/library/ml/src/main/rust/src/nets/mod_part7.rsindex e69fa4a018..918f127230 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -1,3 +1,20 @@+/// Window/scale options for [`Builder::attn_scores_banded`].+#[derive(Clone, Copy)]+pub struct BandedScores {+    /// Attention heads.+    pub heads: u32,+    /// Keys a query may see.+    pub band: u32,+    /// Weight-file index of the relative-position table.+    pub table: usize,+    /// Relative offsets in the table.+    pub offsets: u32,+    /// Score scale (already-scaled queries pass 1.0).+    pub scale: f32,+    /// Logit cap fused into the scores.+    pub cap: f32,+}+ impl<'a> Builder<'a> {     /// [`Builder::attn_apply`] plus the value-side relative term.     pub fn attn_apply_relative(@@ -42,17 +59,8 @@ impl<'a> Builder<'a> {     /// vector, and the key by a different scalar, and neither of those can live here — a vector     /// does not factor out of a dot product, and the key's scalar applies to the content term     /// but not to the relative one.-    pub fn attn_scores_banded(-        &mut self,-        q: Id,-        k: Id,-        heads: u32,-        band: u32,-        table: usize,-        offsets: u32,-        scale: f32,-        cap: f32,-    ) -> Id {+    pub fn attn_scores_banded(&mut self, q: Id, k: Id, scores: BandedScores) -> Id {+        let BandedScores { heads, band, table: table_index, offsets, scale, cap } = scores;         let (sq, sk) = (self.shape_of(q), self.shape_of(k));         if sq.c != sk.c || sq.w != sk.w {             self.fail(format!(@@ -66,7 +74,7 @@ impl<'a> Builder<'a> {                  one would silently reinterpret the layout"             ));         }-        if heads == 0 || !sq.c.is_multiple_of(heads) {+        if heads == 0 || sq.c % (heads) != 0 {             self.fail(format!("{} channels do not split into {heads} heads", sq.c));         }         if band == 0 || band > sq.w {@@ -88,7 +96,7 @@ impl<'a> Builder<'a> {             self.fail(format!("a logit cap of {cap}, which must be positive"));         }         let head_dim = sq.c.checked_div(heads.max(1)).unwrap_or(0);-        let table = self.weight(table, &[heads, offsets, head_dim]);+        let table = self.weight(table_index, &[heads, offsets, head_dim]);         let out = self.tensor(Shape::new(heads, sq.w, band));         self.nodes             .push(Node::AttnScoresBanded { q, k, out, heads, band, table, offsets, scale, cap });@@ -114,7 +122,7 @@ impl<'a> Builder<'a> {                  value per key, and a band's queries and keys are the same sequence"             ));         }-        if heads == 0 || !sv.c.is_multiple_of(heads) {+        if heads == 0 || sv.c % (heads) != 0 {             self.fail(format!("{} channels do not split into {heads} heads", sv.c));         }         let out = self.tensor(Shape::new(sv.c, 1, sv.w));@@ -128,7 +136,7 @@ impl<'a> Builder<'a> {     /// sequence length: for a one-phoneme utterance only the centre entry is ever reachable     /// and the other eight go unused, which is correct rather than an error — "a" is a word.     fn check_offsets(&mut self, offsets: u32) {-        if offsets == 0 || offsets.is_multiple_of(2) {+        if offsets == 0 || offsets % (2) == 0 {             self.fail(format!(                 "{offsets} relative offsets: the table is 2 * window + 1 entries centred on \                  zero displacement, so an even count has no centre"@@ -171,7 +179,7 @@ impl<'a> Builder<'a> {         if sv.h != 1 {             self.fail(format!("attention values {sv:?} are not [d_model, 1, T]"));         }-        if heads == 0 || !sv.c.is_multiple_of(heads) {+        if heads == 0 || sv.c % (heads) != 0 {             self.fail(format!("{} channels do not split into {heads} heads", sv.c));         }         self.tensor(Shape::new(sv.c, 1, sp.h))@@ -241,7 +249,6 @@ impl<'a> Builder<'a> {             nodes: self.nodes,             shapes: self.shapes,             inputs: self.inputs,-            pinned: self.pinned,             read: self.read,         })     }@@ -372,10 +379,9 @@ impl<'a> Builder<'a> {                 Node::Binary { kind: Kind::Add, a, b, out } => {                     if let Some(index) = producer_of(&self.nodes, *a) {                         (index, *a, Some(*b), None, *out)-                    } else if let Some(index) = producer_of(&self.nodes, *b) {-                        (index, *b, Some(*a), None, *out)                     } else {-                        return None;+                        let index = producer_of(&self.nodes, *b)?;+                        (index, *b, Some(*a), None, *out)                     }                 }                 Node::Binary { kind: Kind::AddBroadcast, a, b, out } => {
library/ml/src/main/rust/src/nets/modnet.rs
diff --git a/library/ml/src/main/rust/src/nets/modnet.rs b/library/ml/src/main/rust/src/nets/modnet.rsindex 3950b847d0..414c0673d7 100644--- a/library/ml/src/main/rust/src/nets/modnet.rs+++ b/library/ml/src/main/rust/src/nets/modnet.rs@@ -64,11 +64,6 @@ impl Layers {     } } -/// A 3x3 convolution at unchanged resolution.-fn conv3x3(b: &mut Builder, layers: &mut Layers, x: Id, out: u32, act: Act) -> Id {-    b.conv_same(x, layers.take(), out, 3, 1, act)-}- /// A MobileNetV2 inverted-residual block: expand 1x1 (ReLU6), depthwise 3x3 /// (ReLU6), linear projection 1x1, optionally added back to the input. fn inverted_residual(
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 39bdf0a77f..a8eba1b22f 100644--- a/library/ml/src/main/rust/src/nets/nllb.rs+++ b/library/ml/src/main/rust/src/nets/nllb.rs@@ -326,7 +326,8 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     // The tied weight and the decoder belong to the other pass, except the cross-attention K and V     // projections, which run here once. The trailing encoder norm is part of the first range, so it     // runs to `DECODER` rather than to `ENCODER_NORM`.-    let mut read = vec![ENCODER..DECODER];+    let mut read = Vec::new();+    read.push(ENCODER..DECODER);     read.extend((0..DECODER_LAYERS).map(cross_kv));     name_host_tensors(b, &read); 
library/ml/src/main/rust/src/nets/nllb_extra2.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_extra2.rs b/library/ml/src/main/rust/src/nets/nllb_extra2.rsindex 18fad62572..d8d0037924 100644--- a/library/ml/src/main/rust/src/nets/nllb_extra2.rs+++ b/library/ml/src/main/rust/src/nets/nllb_extra2.rs@@ -30,7 +30,8 @@ pub(crate) fn decode_step(weights: &dyn WeightSource, src_len: u32) -> Result<Pl     let b = &mut builder;     // The decoder plus the tied head, which this pass computes in the same plan, minus the     // cross-attention K and V projections the encode pass ran. The encoder belongs to that pass.-    let mut read = vec![HEAD..ENCODER];+    let mut read = Vec::new();+    read.push(HEAD..ENCODER);     let mut at = DECODER;     for layer in 0..DECODER_LAYERS {         let skipped = cross_kv(layer);
library/ml/src/main/rust/src/nets/ppocr_det.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_det.rs b/library/ml/src/main/rust/src/nets/ppocr_det.rsindex 26813e7fbd..924474431c 100644--- a/library/ml/src/main/rust/src/nets/ppocr_det.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_det.rs@@ -61,8 +61,6 @@ const NECK: u32 = 96; /// Channels each head branch produces, four of which concatenate back to [`NECK`]. const HEAD: u32 = 24; -/// Hands out `.maml` tensor indices- /// Hands out `.maml` tensor indices in the order the layers appear. Every folded layer is /// a convolution with a weight and a bias, so this steps by two throughout. struct Layers {@@ -144,7 +142,7 @@ fn compile(     if height == 0 || width == 0 {         return Err(format!("a {width}x{height} input"));     }-    if !height.is_multiple_of(EXTENT_MULTIPLE) || !width.is_multiple_of(EXTENT_MULTIPLE) {+    if height % (EXTENT_MULTIPLE) != 0 || width % (EXTENT_MULTIPLE) != 0 {         return Err(format!(             "a {width}x{height} input: both extents must be a multiple of \              {EXTENT_MULTIPLE}, or the pyramid's four levels are not exactly 2x apart"
library/ml/src/main/rust/src/nets/ppocr_rec.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec.rs b/library/ml/src/main/rust/src/nets/ppocr_rec.rsindex 80d1d2cf18..5a9c69995e 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec.rs@@ -60,7 +60,7 @@ //! cannot change, and the winner's probability, which is `1 / sum(exp(x - max))` from the //! raw logits directly. So the pass is not merely moved to the host, it is deleted. -use super::{Act, Builder, Id, Plan, Shape, WeightSource};+use super::{Act, Builder, Id};  /// Input height, in pixels. Fixed; see the module docs. pub const HEIGHT: u32 = 48;@@ -226,7 +226,7 @@ pub use super::ppocr_rec_extra::{build, build_batch}; #[cfg(test)] mod tests {     use super::super::tests::{assert_no_aliasing, Shapes};-    use super::super::{Kind, Op};+    use super::super::{Kind, Op, Plan, Shape};     use super::*;      /// The width a line crop is padded to on device, and 320 / 8 = 40 timesteps.
library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs b/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rsindex 61002bffca..296d7690a5 100644--- a/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_rec_extra.rs@@ -9,7 +9,7 @@ use super::ppocr_rec::{along_sequence, block, depthwise, point, squeeze_excite}; /// `width` must be a positive multiple of [`WIDTH_MULTIPLE`]; the output is /// `[LOGITS, 1, width / 8]`. pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> {-    if width == 0 || !width.is_multiple_of(WIDTH_MULTIPLE) {+    if width == 0 || width % (WIDTH_MULTIPLE) != 0 {         return Err(format!(             "a recognition width of {width}: three stride-2 stages act on it, so it must \              be a positive multiple of {WIDTH_MULTIPLE}"@@ -25,7 +25,7 @@ pub fn build(weights: &dyn WeightSource, width: u32) -> Result<Plan, String> { /// [`build`] for `lines` crops at once: independent copies of the pass in one plan, so a /// whole OCR request's lines are one submit. Input and output `i` are line `i`'s. pub fn build_batch(weights: &dyn WeightSource, width: u32, lines: u32) -> Result<Plan, String> {-    if width == 0 || !width.is_multiple_of(WIDTH_MULTIPLE) || lines == 0 {+    if width == 0 || width % (WIDTH_MULTIPLE) != 0 || lines == 0 {         return Err(format!("a batch of {lines} recognitions at width {width}"));     }     let mut builder = Builder::new(weights);
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 696ddfbda9..c89d442ae3 100644--- a/library/ml/src/main/rust/src/nets/reference_part2.rs+++ b/library/ml/src/main/rust/src/nets/reference_part2.rs@@ -331,8 +331,8 @@ impl Reference {         let epsilon = f32::from_bits(p.param1_bits);         // `count` is `groups * stride`, so this walks one group at one position at a time.         for index in 0..p.count {-            let group = if stride == 0 { 0 } else { index / stride };-            let position = if stride == 0 { 0 } else { index % stride };+            let group = index.checked_div(stride).unwrap_or(0);+            let position = index.checked_rem(stride).unwrap_or(0);             let base = group * per_group;             let mut squares = 0.0;             for c in 0..per_group {@@ -411,7 +411,7 @@ impl Reference {             return Ok(value);         }         let scale = f32::from_bits(p.param0_bits);-        if !(scale > 0.0) {+        if scale.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {             return Err(format!("a fused quantize of {scale}"));         }         let q = ((value / scale + 0.5).floor()).clamp(-128.0, 127.0);
library/ml/src/main/rust/src/nets/reference_part3.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part3.rs b/library/ml/src/main/rust/src/nets/reference_part3.rsindex ad660afb41..0d8cff2c18 100644--- a/library/ml/src/main/rust/src/nets/reference_part3.rs+++ b/library/ml/src/main/rust/src/nets/reference_part3.rs@@ -88,7 +88,7 @@ impl Reference {     /// `tanh(x / cap) * cap`. See `shaders/softcap.comp`.     fn softcap(&mut self, p: &Push) -> Result<(), String> {         let cap = f32::from_bits(p.param0_bits);-        if !(cap > 0.0) {+        if cap.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {             return Err(format!("a softcap of {cap}"));         }         for index in 0..p.count {@@ -101,7 +101,7 @@ impl Reference {     /// S10's int8 round-trip. See `shaders/quantize.comp`.     fn quantize(&mut self, p: &Push) -> Result<(), String> {         let scale = f32::from_bits(p.param0_bits);-        if !(scale > 0.0) {+        if scale.partial_cmp(&0.0) != Some(std::cmp::Ordering::Greater) {             return Err(format!("a quantize of {scale}"));         }         for index in 0..p.count {
library/ml/src/main/rust/src/nets/schedule.rs
diff --git a/library/ml/src/main/rust/src/nets/schedule.rs b/library/ml/src/main/rust/src/nets/schedule.rsindex 1369dfac8f..d07da7f3f4 100644--- a/library/ml/src/main/rust/src/nets/schedule.rs+++ b/library/ml/src/main/rust/src/nets/schedule.rs@@ -267,7 +267,7 @@ pub fn kinds(plan: &Plan) -> Vec<(Kind, usize)> {             }         }     }-    counts.sort_by(|a, b| b.1.cmp(&a.1));+    counts.sort_by_key(|b| std::cmp::Reverse(b.1));     counts } 
library/ml/src/main/rust/src/nets/scrfd.rs
diff --git a/library/ml/src/main/rust/src/nets/scrfd.rs b/library/ml/src/main/rust/src/nets/scrfd.rsindex c18c8f1554..006bb5045c 100644--- a/library/ml/src/main/rust/src/nets/scrfd.rs+++ b/library/ml/src/main/rust/src/nets/scrfd.rs@@ -163,7 +163,7 @@ pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan     if height == 0 || width == 0 {         return Err(format!("a {width}x{height} input"));     }-    if !height.is_multiple_of(EXTENT_MULTIPLE) || !width.is_multiple_of(EXTENT_MULTIPLE) {+    if height % (EXTENT_MULTIPLE) != 0 || width % (EXTENT_MULTIPLE) != 0 {         return Err(format!(             "a {width}x{height} input: both extents must be a multiple of \              {EXTENT_MULTIPLE}, or the neck's three branches are not exactly 2x apart"
library/ml/src/main/rust/src/nets/supertonic_sampler.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler.rsindex 63aa02b7b0..6b054df86d 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler.rs@@ -81,7 +81,7 @@ //! at 0.29 from `main_blocks.11` on. A per-stage comparison found it in one run, which is much //! faster than reasoning about a 1004-node graph. -use super::{Act, Builder, Id, Kind, Op, Plan, Shape, WeightSource, NO_FUSE};+use super::{Act, Builder, Id, Kind, Op, Plan, Shape, WeightSource};  /// Latent channels in and out. `ldim * chunk_compress_factor`, and the vocoder's `PACKED`. pub const LATENT: u32 = 144;
library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rsindex 4b8d140828..54b98ed267 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler_part1.rs@@ -1,7 +1,7 @@ #[cfg(test)] mod tests {     use super::super::tests::{assert_no_aliasing, Shapes};-    use super::super::{Kind, Op};+    use super::super::{Kind, Op, NO_FUSE};     use super::*;      /// About four seconds of audio, and a sentence to match.
library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs b/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rsindex 51b17d00ff..0639c9e8f8 100644--- a/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs+++ b/library/ml/src/main/rust/src/nets/supertonic_sampler_part2.rs@@ -36,7 +36,7 @@ pub fn build_dual_padded( /// A channel-major `[channels, frames]` tensor widened to [`padded_frames`] with a zero tail. pub fn pad_frames(values: &[f32], frames: u32) -> Result<Vec<f32>, String> {     let (real, padded) = (frames as usize, padded_frames(frames) as usize);-    if real == 0 || values.is_empty() || !values.len().is_multiple_of(real) {+    if real == 0 || values.is_empty() || values.len() % (real) != 0 {         return Err(format!("{} values are not whole rows of {real} frames", values.len()));     }     let mut out = vec![0.0; values.len() / real * padded];@@ -49,7 +49,7 @@ pub fn pad_frames(values: &[f32], frames: u32) -> Result<Vec<f32>, String> { /// The first `frames` positions of each row of a [`padded_frames`]-wide tensor. pub fn unpad_frames(values: &[f32], frames: u32) -> Result<Vec<f32>, String> {     let (real, padded) = (frames as usize, padded_frames(frames) as usize);-    if real == 0 || values.is_empty() || !values.len().is_multiple_of(padded) {+    if real == 0 || values.is_empty() || values.len() % (padded) != 0 {         return Err(format!("{} values are not whole rows of {padded} frames", values.len()));     }     Ok(values.chunks_exact(padded).flat_map(|row| &row[..real]).copied().collect())
library/ml/src/main/rust/src/nets/whisper_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/whisper_part1.rs b/library/ml/src/main/rust/src/nets/whisper_part1.rsindex 89c23c145d..5c0025f0c3 100644--- a/library/ml/src/main/rust/src/nets/whisper_part1.rs+++ b/library/ml/src/main/rust/src/nets/whisper_part1.rs@@ -12,7 +12,7 @@ fn device_tensors(mode: Mode) -> Vec<usize> {                 read.extend(cross_kv(layer)..cross_kv(layer) + 6);             }         }-        Mode::DecodeStep { .. } => {+        Mode::DecodeStep => {             read.extend(HEAD..HEAD + 3);             let skipped: std::collections::BTreeSet<usize> = (0..DECODER_LAYERS)                 .flat_map(|layer| cross_kv(layer)..cross_kv(layer) + 6)
library/ml/src/main/rust/src/post/ctc.rs
diff --git a/library/ml/src/main/rust/src/post/ctc.rs b/library/ml/src/main/rust/src/post/ctc.rsindex 60379f4b4d..fc57fa7698 100644--- a/library/ml/src/main/rust/src/post/ctc.rs+++ b/library/ml/src/main/rust/src/post/ctc.rs@@ -126,7 +126,7 @@ pub fn decode(logits: &[f32], used: usize, dictionary: &Dictionary) -> Result<De     if logits.is_empty() {         return Err("no logits at all, so the recogniser produced no timesteps".into());     }-    if !logits.len().is_multiple_of(labels) {+    if logits.len() % (labels) != 0 {         return Err(format!(             "{} logits is not a whole number of {labels}-wide timesteps",             logits.len()
library/ml/src/main/rust/src/post/madlad.rs
diff --git a/library/ml/src/main/rust/src/post/madlad.rs b/library/ml/src/main/rust/src/post/madlad.rsindex 8543b7f4de..2ddb8f7f31 100644--- a/library/ml/src/main/rust/src/post/madlad.rs+++ b/library/ml/src/main/rust/src/post/madlad.rs@@ -265,7 +265,7 @@ mod tests {         // A script of one repeated non-EOS token, longer than the cap.         let script = vec![20u32; MAX_TOKENS + 10];         let mut nets = scripted(&script);-        let got = translate(&mut nets, &table, "<2en>", "a").expect("translates");+        let _got = translate(&mut nets, &table, "<2en>", "a").expect("translates");         assert_eq!(nets.steps.len(), MAX_TOKENS);     } 
library/ml/src/main/rust/src/post/whisper.rs
diff --git a/library/ml/src/main/rust/src/post/whisper.rs b/library/ml/src/main/rust/src/post/whisper.rsindex 0bdbb0711f..6c38fbfb50 100644--- a/library/ml/src/main/rust/src/post/whisper.rs+++ b/library/ml/src/main/rust/src/post/whisper.rs@@ -443,7 +443,7 @@ mod tests {         let mut config = config();         config.max_length = PROMPT_TOKENS + 3;         assert_eq!(config.budget(), 3);-        let mut nets = scripted(&vec![100u32; 50]);+        let mut nets = scripted(&[100u32; 50]);         let out = transcribe(&mut nets, &config, &mel(), Some(EN)).expect("transcribes");         assert_eq!(out.len(), 3);     }
library/ml/src/main/rust/src/vulkan/imageprobe.rs
diff --git a/library/ml/src/main/rust/src/vulkan/imageprobe.rs b/library/ml/src/main/rust/src/vulkan/imageprobe.rsindex ddc3e82244..5367f88c15 100644--- a/library/ml/src/main/rust/src/vulkan/imageprobe.rs+++ b/library/ml/src/main/rust/src/vulkan/imageprobe.rs@@ -31,8 +31,8 @@ use ash::vk; use crate::vulkan::buffers::Buffer; use crate::vulkan::context::Context; -const SSBO: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/probe_ssbo.comp.spv"));-const TEXEL: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/probe_texel.comp.spv"));+const SSBO: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/probe_ssbo.comp.spv"));+const TEXEL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/probe_texel.comp.spv"));  /// Bytes to sweep. Comfortably past any cache, and the order of a large weight tensor. const BYTES: u64 = 256 * 1024 * 1024;@@ -80,13 +80,9 @@ pub fn compare(context: &Arc<Context>) -> Result<(f64, f64), String> { /// device that lives as long as the process, and a `Drop` would need a context reference threaded /// through it for no benefit. Stated rather than hidden behind an empty `Drop`. struct Probe {-    layout: vk::DescriptorSetLayout,-    pool: vk::DescriptorPool,     set: vk::DescriptorSet,     pipeline_layout: vk::PipelineLayout,     pipeline: vk::Pipeline,-    module: vk::ShaderModule,-    command_pool: vk::CommandPool,     command_buffer: vk::CommandBuffer,     fence: vk::Fence, }@@ -187,17 +183,11 @@ impl Probe {             let fence = device                 .create_fence(&vk::FenceCreateInfo::default(), None)                 .map_err(|e| format!("fence: {e:?}"))?;-            Ok(Probe {-                layout,-                pool,-                set,-                pipeline_layout,-                pipeline,-                module,-                command_pool,-                command_buffer,-                fence,-            })+            // `layout`, `pool`, `module` and `command_pool` are not stored:+            // Vulkan handles are plain ids, and these objects are never+            // destroyed by design (see the struct docs), so only the handles+            // later calls use are kept.+            Ok(Probe { set, pipeline_layout, pipeline, command_buffer, fence })         }     } 
library/ml/src/main/rust/src/vulkan/parity_part1.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part1.rs b/library/ml/src/main/rust/src/vulkan/parity_part1.rsindex 8aa4a3673a..f790ee7f39 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part1.rs@@ -243,7 +243,7 @@ fn a_banded_score_map_matches_the_cpu_oracle() {         &[Shape::new(HEADS * HEAD_DIM, 1, T), Shape::new(HEADS * HEAD_DIM, 1, T)],         &[&q, &k],         &[(vec![HEADS, OFFSETS, HEAD_DIM], table)],-        |b, ids| b.attn_scores_banded(ids[0], ids[1], HEADS, BAND, 0, OFFSETS, 1.0, 2.0),+        |b, ids| b.attn_scores_banded(ids[0], ids[1], crate::nets::BandedScores { heads: HEADS, band: BAND, table: 0, offsets: OFFSETS, scale: 1.0, cap: 2.0 }),     ); } @@ -342,7 +342,7 @@ fn banded_scores(band: u32, offsets: u32) -> Vec<f32> {         // The scale is 1.0 and not the export's 0.127517431974411: `maml_convert.py` folds that         // into the per-layer `QueryScale` tensor, so Q reaches this op already scaled. See         // `Builder::attn_scores_banded`.-        b.attn_scores_banded(ids[0], ids[1], FIXTURE_HEADS, band, 0, offsets, 1.0, FIXTURE_CAP)+        b.attn_scores_banded(ids[0], ids[1], crate::nets::BandedScores { heads: FIXTURE_HEADS, band, table: 0, offsets, scale: 1.0, cap: FIXTURE_CAP })     });     let outputs =         run_multi(&plan, given.data(), &[&q, &k]).expect("the banded score fixture runs");
library/ml/src/main/rust/src/vulkan/parity_part2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part2.rs b/library/ml/src/main/rust/src/vulkan/parity_part2.rsindex 6f3da9bd73..0064ad9e8e 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part2.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part2.rs@@ -23,12 +23,7 @@ fn the_banded_ops_agree_with_the_cpu_arm_at_the_towers_own_span() {         b.attn_scores_banded(             ids[0],             ids[1],-            FIXTURE_HEADS,-            ATTEND_SPAN,-            0,-            offsets,-            1.0,-            FIXTURE_CAP,+            crate::nets::BandedScores { heads: FIXTURE_HEADS, band: ATTEND_SPAN, table: 0, offsets, scale: 1.0, cap: FIXTURE_CAP },         )     });     let data = given.data().to_vec();
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 86f54c980b..3b899bb142 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -14,8 +14,9 @@ //! //! # SPIR-V is linked in, not shipped //!-//! The Gradle `compileShaders` task compiles `shaders/*.comp` into `build/spirv` and fails if-//! `glslc` is missing or a shader fails, so these `include_bytes!` cannot silently become stubs.+//! `build.rs` compiles `shaders/*.comp` into `OUT_DIR` (the Gradle `compileShaders`+//! output is the fallback) and fails if `glslc` is missing or a shader fails, so these+//! `include_bytes!` cannot silently become stubs. //! An asset can be absent at run time; a `&'static [u8]` cannot.  use std::sync::Arc;@@ -28,67 +29,67 @@ use super::context::Context; use super::pipeline_extra::{CONV_POINT_Q2K, CONV_Q2K, QUANTIZE, QUANTIZE_BLOCKS}; use super::segment::Segment; -const CONV: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv.comp.spv"));+const CONV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv.comp.spv")); const CONV_TRANSPOSE: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_transpose.comp.spv"));-const MAXPOOL: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/maxpool.comp.spv"));-const AVGPOOL: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/avgpool.comp.spv"));-const RESIZE: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/resize.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_transpose.comp.spv"));+const MAXPOOL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/maxpool.comp.spv"));+const AVGPOOL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/avgpool.comp.spv"));+const RESIZE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/resize.comp.spv")); const RESIZE_NEAREST: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/resize_nearest.comp.spv"));-const GAP: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/gap.comp.spv"));-const ADD: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/add.comp.spv"));-const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/mul_bcast.comp.spv"));-const AFFINE: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/affine.comp.spv"));-const LAYERNORM: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/layernorm.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/resize_nearest.comp.spv"));+const GAP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gap.comp.spv"));+const ADD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add.comp.spv"));+const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_bcast.comp.spv"));+const AFFINE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/affine.comp.spv"));+const LAYERNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/layernorm.comp.spv")); const INSTANCENORM: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/instancenorm.comp.spv"));-const RMSNORM: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/rmsnorm.comp.spv"));-const ATTN_SCORES: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_scores.comp.spv"));-const SOFTMAX: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/softmax.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/instancenorm.comp.spv"));+const RMSNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rmsnorm.comp.spv"));+const ATTN_SCORES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores.comp.spv"));+const SOFTMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softmax.comp.spv")); const SOFTMAX_CAUSAL: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/softmax_causal.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/softmax_causal.comp.spv")); const SOFTMAX_PREFIX: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/softmax_prefix.comp.spv"));-const CACHE_WRITE: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/cache_write.comp.spv"));-const SOFTCAP: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/softcap.comp.spv"));-const ACTIVATE: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/activate.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/softmax_prefix.comp.spv"));+const CACHE_WRITE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/cache_write.comp.spv"));+const SOFTCAP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softcap.comp.spv"));+const ACTIVATE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/activate.comp.spv")); const GATED_ACTIVATE: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/gated_activate.comp.spv"));-const MUL_SCALAR: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/mul_scalar.comp.spv"));-const CLAMP: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/clamp.comp.spv"));-const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_apply.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/gated_activate.comp.spv"));+const MUL_SCALAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_scalar.comp.spv"));+const CLAMP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/clamp.comp.spv"));+const ATTN_APPLY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply.comp.spv")); const ATTN_SCORES_RELATIVE: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_scores_relative.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores_relative.comp.spv")); const ATTN_APPLY_RELATIVE: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_apply_relative.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_relative.comp.spv")); const ATTN_SCORES_BANDED: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_scores_banded.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores_banded.comp.spv")); const ATTN_APPLY_BANDED: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_apply_banded.comp.spv"));-const EMBED: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/embed.comp.spv"));-const MUL: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/mul.comp.spv"));-const CONV_POINT: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_point.comp.spv"));-const CONV_INT8: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_int8.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_banded.comp.spv"));+const EMBED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/embed.comp.spv"));+const MUL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul.comp.spv"));+const CONV_POINT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_point.comp.spv"));+const CONV_INT8: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_int8.comp.spv")); const CONV_POINT_INT8: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_point_int8.comp.spv"));-const CONSTANT: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/constant.comp.spv"));-const ADD_BCAST: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/add_bcast.comp.spv"));-const ROTARY: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/rotary.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_int8.comp.spv"));+const CONSTANT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/constant.comp.spv"));+const ADD_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add_bcast.comp.spv"));+const ROTARY: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rotary.comp.spv")); const ATTN_SCORES_CACHED: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_scores_cached.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores_cached.comp.spv")); const ATTN_APPLY_CACHED: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/attn_apply_cached.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/attn_apply_cached.comp.spv")); const CONV_VEC_INT8: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_vec_int8.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_vec_int8.comp.spv")); const CONV_VEC_INT4: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_vec_int4.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_vec_int4.comp.spv")); const CONV_POINT_INT4: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_point_int4.comp.spv"));-const CONV_VEC_Q2K: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_vec_q2k.comp.spv"));-const ARGMAX: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/argmax.comp.spv"));-const ARGMAX_FOLD: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/argmax_fold.comp.spv"));-const TOPK: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/topk.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_int4.comp.spv"));+const CONV_VEC_Q2K: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_vec_q2k.comp.spv"));+const ARGMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/argmax.comp.spv"));+const ARGMAX_FOLD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/argmax_fold.comp.spv"));+const TOPK: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/topk.comp.spv")); /// Every shader, in the order `Shaders::create` destructures them (the Q2_K pair, /// `QUANTIZE`, and the `compute_pipeline` / `shader_module` helpers live in /// `pipeline_extra.rs` for length).
library/ml/src/main/rust/src/vulkan/pipeline_extra.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rsindex 6f3875713d..55ca8fc655 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs@@ -9,19 +9,19 @@ use super::pipeline::{Cleanup, Shaders, SPIRV}; // Lives here rather than in `pipeline.rs` so that file stays under the // 500-line Rust limit. pub(crate) const QUANTIZE: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/quantize.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/quantize.comp.spv"));  // The Q2_K pair, beside the table they join (see `SPIRV`). Same reason as // `QUANTIZE` above: `pipeline.rs` must stay under the 500-line Rust limit. pub(crate) const CONV_POINT_Q2K: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_point_q2k.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_q2k.comp.spv")); pub(crate) const CONV_Q2K: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_q2k.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_q2k.comp.spv")); pub(crate) const QUANTIZE_BLOCKS: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/quantize_blocks.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/quantize_blocks.comp.spv")); /// Declares `DotProductKHR`, so it is built only on a device that enabled the extension. const CONV_POINT_INT4_DOT: &[u8] =-    include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/conv_point_int4_dot.comp.spv"));+    include_bytes!(concat!(env!("OUT_DIR"), "/conv_point_int4_dot.comp.spv"));  impl Shaders {     /// Compile every shader and build the two layouts. Called once per device.@@ -414,7 +414,7 @@ unsafe fn shader_module(device: &ash::Device, spirv: &[u8]) -> Result<vk::Shader     // no alignment guarantee, and a misaligned `u32` read is undefined behaviour even     // where the hardware tolerates it. This is `library/map`'s approach, not     // `games/voxels`' pointer cast.-    if !spirv.len().is_multiple_of(4) || spirv.len() < 20 {+    if spirv.len() % (4) != 0 || spirv.len() < 20 {         return Err(format!("{} bytes is not a SPIR-V module", spirv.len()));     }     let mut words = Vec::with_capacity(spirv.len() / 4);
library/ml/src/main/rust/src/vulkan/reshape.rs
diff --git a/library/ml/src/main/rust/src/vulkan/reshape.rs b/library/ml/src/main/rust/src/vulkan/reshape.rsindex 12566931ef..6c606e1dd2 100644--- a/library/ml/src/main/rust/src/vulkan/reshape.rs+++ b/library/ml/src/main/rust/src/vulkan/reshape.rs@@ -17,6 +17,8 @@ use crate::nets::Plan; use crate::preprocess::RESCALE_ONLY; use crate::weights::{Blob, Offsets, Weights}; +type Planner<S> = fn(&Offsets, S) -> Result<Plan, String>;+ use super::context::Context; use super::run::Net; @@ -30,7 +32,7 @@ pub struct Reshaped<S> {     net: Net,     offsets: Offsets,     at: S,-    plan: fn(&Offsets, S) -> Result<Plan, String>,+    plan: Planner<S>,     /// The most recently built plans, newest last, so a shape seen again skips the build.     ///     /// Building a plan is pure CPU work over the graph and costs more than recording it: on a@@ -149,7 +151,7 @@ impl<S: Copy + PartialEq> Reshaped<S> {      /// What [`Reshaped::at`] would call to build a plan it does not hold, so a caller can build     /// one off the thread that owns the net. See [`Reshaped::adopt`].-    pub fn planner(&self) -> (fn(&Offsets, S) -> Result<Plan, String>, Offsets) {+    pub fn planner(&self) -> (Planner<S>, Offsets) {         (self.plan, self.offsets.clone())     } 
library/ml/src/main/rust/src/vulkan/run.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run.rs b/library/ml/src/main/rust/src/vulkan/run.rsindex 92941e4250..cf0adacc41 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -41,8 +41,6 @@ use super::context::Context; use super::pipeline::{Pipelines, MAX_WORKGROUPS_PER_DIM, WORKGROUP}; use super::segment::Segments; -use crate::timing;- /// How [`Net::barrier_over`] spells the dependency between two ops. /// /// Selected by `MODELRUNNER_BARRIER` or `debug.modelrunner.barrier`, defaulting to
library/ml/src/main/rust/src/vulkan/run_part2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part2.rs b/library/ml/src/main/rust/src/vulkan/run_part2.rsindex 2b8f9c775d..249ec22c4a 100644--- a/library/ml/src/main/rust/src/vulkan/run_part2.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part2.rs@@ -83,7 +83,7 @@ impl Net {                     100.0 * schedule.barriers() as f64 / schedule.steps.len().max(1) as f64                 );             }-            let mut stamp_next = 0u32;+            let _stamp_next = 0u32;              // MODELRUNNER_TIMING only: where record's CPU time goes, per phase and per kind.             let clock = crate::timing::enabled();@@ -97,8 +97,8 @@ impl Net {                 ($slot:expr) => {                     if clock {                         let now = std::time::Instant::now();-                        phases[$slot] += (now - lap).as_secs_f64() * 1e3;-                        lap = now;+                        phases[$slot] +=+                            (now - std::mem::replace(&mut lap, now)).as_secs_f64() * 1e3;                     }                 };             }@@ -121,9 +121,7 @@ impl Net {                         } else {                             match dirty {                                 Some((0, u64::MAX)) | None => self.barrier(buffer),-                                Some((lo, hi)) => unsafe {-                                    self.barrier_compute(buffer, lo, hi - lo)-                                },+                                Some((lo, hi)) => self.barrier_compute(buffer, lo, hi - lo),                             }                         }                         dirty = None;@@ -271,7 +269,6 @@ impl Net {             // barrier. The default path needs nothing here — its last op was barriered.             if schedule.is_some() && dirty.is_some() {                 self.barrier(buffer);-                dirty = None;             }             if clock {                 binds.sort_by(|a, b| b.1.total_cmp(&a.1));
library/ml/src/main/rust/src/vulkan/run_part6.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part6.rs b/library/ml/src/main/rust/src/vulkan/run_part6.rsindex f28e0a87b0..6a4dea511d 100644--- a/library/ml/src/main/rust/src/vulkan/run_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part6.rs@@ -1,3 +1,5 @@+type UploadFill<'a> = dyn FnMut(u64, &mut [u8]) -> Result<(), String> + 'a;+ impl Net {     /// Copy the weights blob to device-local memory through the staging buffer, in chunks.     ///@@ -28,7 +30,7 @@ impl Net {         &self,         dst: u64,         total: u64,-        fill: &mut dyn FnMut(u64, &mut [u8]) -> Result<(), String>,+        fill: &mut UploadFill<'_>,     ) -> Result<(), String> {         if total == 0 {             return Ok(());
library/ml/src/main/rust/src/vulkan/run_part7.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part7.rs b/library/ml/src/main/rust/src/vulkan/run_part7.rsindex 25ab6af185..d73a53fc1d 100644--- a/library/ml/src/main/rust/src/vulkan/run_part7.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part7.rs@@ -115,40 +115,6 @@ impl Net {         );     } -    /// # Safety-    ///-    /// `buffer` must be recorded and not already pending.-    unsafe fn submit_and_wait(&self, buffer: vk::CommandBuffer) -> Result<(), String> {-        let device = &self.context.device;-        let fence = device-            .create_fence(&vk::FenceCreateInfo::default(), None)-            .map_err(|e| format!("create_fence {e:?}"))?;-        let buffers = [buffer];-        let submit = vk::SubmitInfo::default().command_buffers(&buffers);-        let guard = self.context.lock_queue();-        let submitted = device-            .queue_submit(self.context.queue, std::slice::from_ref(&submit), fence)-            .map_err(|e| format!("queue_submit {e:?}"));-        drop(guard);--        let result = submitted.and_then(|()| {-            device-                .wait_for_fences(&[fence], true, FENCE_TIMEOUT_NS)-                .map_err(|e| format!("wait_for_fences {e:?}"))-        });-        // On a timeout the submission is still in flight, and the caller is about to drop-        // both the fence and the staging buffer it reads from. Wait the device out first:-        // destroying either while a queue operation references it is undefined, and a-        // one-off weights upload has nowhere to defer the cleanup to.-        if result.is_err() {-            let guard = self.context.lock_queue();-            let _ = device.device_wait_idle();-            drop(guard);-        }-        device.destroy_fence(fence, None);-        result-    }-     /// Preprocess `pixels`, run the network, and return the mask as `0..1` floats.     ///     /// `pixels` is `ARGB_8888` as `Bitmap.getPixels` produces it. The returned mask is
library/ml/src/main/rust/src/vulkan/segment.rs
diff --git a/library/ml/src/main/rust/src/vulkan/segment.rs b/library/ml/src/main/rust/src/vulkan/segment.rsindex 3f162f3cb4..c789821253 100644--- a/library/ml/src/main/rust/src/vulkan/segment.rs+++ b/library/ml/src/main/rust/src/vulkan/segment.rs@@ -59,7 +59,6 @@ use crate::nets::{Kind, Push}; use crate::weights::Tensor; -use super::context::Limits;  /// The `.maml` tensor alignment, from `scripts/ml/maml_convert.py`. ///
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex fe0a6f9fee..50817f248f 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -28,6 +28,7 @@ const MAGIC: [u8; 4] = *b"MAML"; /// Version 1 is header + table + blob. Version 2 appends a graph section after the blob /// (see [`Graph`]); a v1 reader rejects a v2 file here, loudly, rather than running a /// topology it cannot see.+#[cfg(test)] const FORMAT_VERSION: u32 = 1; /// The newest version this reader accepts. Kept distinct from [`FORMAT_VERSION`] — the /// version *written* by the converter — so emitting v2 files is a separate, deliberate@@ -439,7 +440,7 @@ fn parse_header(bytes: &[u8], expect_graph: u32) -> Result<Header, String> {         if expected != len as u64 {             return Err(format!("tensor {i} has dims {dims:?} but len {len}"));         }-        if !offset.is_multiple_of(ALIGNMENT) {+        if offset % (ALIGNMENT) != 0 {             return Err(format!("tensor {i} is at {offset}, not {ALIGNMENT}-aligned"));         }         let end = (offset as u64) + dtype.bytes(len as u64);
library/ml/src/main/rust/src/weights_part2.rs
diff --git a/library/ml/src/main/rust/src/weights_part2.rs b/library/ml/src/main/rust/src/weights_part2.rsindex 79f1412eee..a3ee2a8723 100644--- a/library/ml/src/main/rust/src/weights_part2.rs+++ b/library/ml/src/main/rust/src/weights_part2.rs@@ -115,7 +115,7 @@ impl<'a> Reader<'a> {             return Err(format!("row {row} of a {rows}-row tensor {index}"));         }         let taps = (found.len / rows) as usize;-        if !taps.is_multiple_of(Q2K_BLOCK as usize) {+        if taps % (Q2K_BLOCK as usize) != 0 {             return Err(format!("tensor {index} has {taps} taps a row, not block-divisible"));         }         let blocks = taps / Q2K_BLOCK as usize;@@ -159,8 +159,8 @@ impl<'a> Reader<'a> {                     let sc = scales[half * 8 + lane * 2];                     let lo = f32::from(sc & 15);                     let hi = f32::from(sc >> 4);-                    for l in 0..16usize {-                        let q = f32::from((hqs[l] >> shift) & 3);+                    for &hq in hqs.iter().take(16) {+                        let q = f32::from((hq >> shift) & 3);                         out.push(dall * q * lo - dmin * hi);                     }                     let sc = scales[half * 8 + lane * 2 + 1];@@ -301,7 +301,7 @@ impl<'a> Reader<'a> {             return Err(format!("rows {start}..{} of a {rows}-row tensor {index}", start + count));         }         let stride = (found.len / rows) as usize;-        if !stride.is_multiple_of(2) {+        if stride % (2) != 0 {             return Err(format!(                 "tensor {index} has a {stride}-element row, which does not start on a byte"             ));@@ -325,7 +325,7 @@ impl<'a> Reader<'a> {                 .map(|pair| f16_to_f32(u16::from_le_bytes([pair[0], pair[1]])))                 .collect();             let row = &packed[r * stride / 2..(r + 1) * stride / 2];-            for (at, &byte) in row.iter().enumerate() {+            for &byte in row.iter() {                 for nibble in [byte & 0x0f, byte >> 4] {                     let code = if nibble >= 8 { i32::from(nibble) - 16 } else { i32::from(nibble) };                     let column = out.len() - r * stride;@@ -440,7 +440,7 @@ pub(crate) fn write_mixed(graph_id: u32, tensors: &[Fixture]) -> Vec<u8> {                 (dims, DTYPE_Q2K, elements, bytes.clone())             }         };-        while !data.len().is_multiple_of(ALIGNMENT as usize) {+        while data.len() % (ALIGNMENT as usize) != 0 {             data.push(0);         }         let offset = data.len() as u32;
library/ml/src/main/rust/src/weights_part3.rs
diff --git a/library/ml/src/main/rust/src/weights_part3.rs b/library/ml/src/main/rust/src/weights_part3.rsindex a64bfaa80b..30a660bc9a 100644--- a/library/ml/src/main/rust/src/weights_part3.rs+++ b/library/ml/src/main/rust/src/weights_part3.rs@@ -279,7 +279,7 @@ mod tests {         // a reader that treated the nibbles as unsigned would give 8 and 7 rather than -8 and 7.         let packed = &weights.data()[0..3];         assert_eq!(packed[0], 0x08 | (0x0f << 4), "-8 then -1");-        assert_eq!(packed[1], 0x00 | (0x01 << 4), "0 then 1");+        assert_eq!(packed[1], (0x01 << 4), "0 then 1");         assert_eq!(packed[2], 0x07, "7, with the high nibble left as padding");     } 
library/ml/src/main/rust/src/weights_part5.rs
diff --git a/library/ml/src/main/rust/src/weights_part5.rs b/library/ml/src/main/rust/src/weights_part5.rsindex dcc368c6db..576eb0183b 100644--- a/library/ml/src/main/rust/src/weights_part5.rs+++ b/library/ml/src/main/rust/src/weights_part5.rs@@ -192,7 +192,7 @@ impl Graph {                     if *group == 0 {                         return Err(format!("{what} has no groups"));                     }-                    if !input_shape[0].is_multiple_of(*group) {+                    if input_shape[0] % (*group) != 0 {                         return Err(format!(                             "{what}: {} channels do not split into {group} groups",                             input_shape[0],@@ -244,7 +244,7 @@ impl Graph {                     }                     let input_shape = computed(*input, &what)?;                     let (kh, kw) = *kernel;-                    if *group == 0 || !input_shape[0].is_multiple_of(*group) {+                    if *group == 0 || input_shape[0] % (*group) != 0 {                         return Err(format!("{what}: bad groups for {}", input_shape[0]));                     }                     let per_group = input_shape[0] / group;
library/ml/src/main/rust/src/weights_part7.rs
diff --git a/library/ml/src/main/rust/src/weights_part7.rs b/library/ml/src/main/rust/src/weights_part7.rsindex b8d102636d..d802e1a931 100644--- a/library/ml/src/main/rust/src/weights_part7.rs+++ b/library/ml/src/main/rust/src/weights_part7.rs@@ -13,8 +13,8 @@ impl Graph {     /// byte layout matches [`Graph::parse`] field for field; the two are tested by     /// round-trip (`emit` then `parse` then `lower` then `finish`).     ///-    /// `outputs` are the plan's output ids — `Recorded` carries inputs and pins but-    /// not which pins are outputs, and the section must name them.+    /// `outputs` are the plan's output ids — `Recorded` carries inputs but+    /// not which tensors are outputs, and the section must name them.     pub fn emit(         recorded: &crate::nets::Recorded,         table: &Offsets,@@ -22,7 +22,7 @@ impl Graph {     ) -> Result<Vec<u8>, String> {         use crate::nets::{Act, Node, Quant};         let mut bytes = Vec::new();-        let mut nodes_bytes: Vec<u8> = Vec::new();+        let _nodes_bytes: Vec<u8> = Vec::new();         let u32s = |bytes: &mut Vec<u8>, values: &[u32]| {             for v in values {                 bytes.extend_from_slice(&v.to_le_bytes());
library/ml/src/main/rust/tests/pure_logic.rs
diff --git a/library/ml/src/main/rust/tests/pure_logic.rs b/library/ml/src/main/rust/tests/pure_logic.rsindex df00019128..3593c48cf5 100644--- a/library/ml/src/main/rust/tests/pure_logic.rs+++ b/library/ml/src/main/rust/tests/pure_logic.rs@@ -141,7 +141,7 @@ fn ctc_decoding_refuses_malformed_inputs_before_touching_the_net() {     assert!(error.contains("not a whole number"), "{error}");     // Asking for more timesteps than the map holds is refused rather than read past the end.     let mut two_steps = vec![0.0; LOGITS * 2];-    if let Some(slot) = two_steps.get_mut(1 * 2) {+    if let Some(slot) = two_steps.get_mut(2) {         *slot = 10.0;     }     let error = decode(&two_steps, 3, &dictionary).expect_err("three of two");