Modern Apps git

← Modern-Apps.git

ml: add modelrunner Rust tests and fix tokenizer edges

Commit
694920a11c800bbc6dea5be9fda9bd766ff34bf1
Author
Vayun Mathur <[email protected]>
When
2026-11-17 22:00 UTC (18 days ago)
Parents
e0c053c
34 new tests targeting the least-covered pure-logic files: Gemma vision plan builder, SentencePiece BPE/Unigram, Supertonic text normalization, Madlad relative-position buckets, weight-file dequantizers, reference max-pool/instance-norm. Fixes found by the tests: unigram encoding of an empty string emitted a spurious prefix token, and the space-before-punctuation normalization only stripped one space of a run. Line coverage 70.8% -> 72.0% (the remainder is mostly Vulkan device code and ignored shipped-net fixtures). cargo test -p modelrunner green.

Diff

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 688f812e6f..9bca7c15c8 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision.rs@@ -443,4 +443,8 @@ impl Mode { }  include!("gemma4_vision_part1.rs");-include!("gemma4_vision_part2.rs");\ No newline at end of file+include!("gemma4_vision_part2.rs");++#[cfg(test)]+#[path = "gemma4_vision_tests.rs"]+mod gemma4_vision_tests;\ No newline at end of file
library/ml/src/main/rust/src/nets/gemma4_vision_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_vision_tests.rs b/library/ml/src/main/rust/src/nets/gemma4_vision_tests.rsnew file mode 100644index 0000000000..1e4cf2a4b4--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_vision_tests.rs@@ -0,0 +1,72 @@+//! Host tests for the Gemma 4 vision plan builder (`gemma4_vision_part1.rs`).+//!+//! The builder was the least-covered non-generated logic in the crate: the+//! existing tests pin the grid arithmetic and the host inputs, but nothing+//! built a plan. These tests build both modes against the shape-only+//! `WeightSource` stub and pin the plan's interface — input/output shapes,+//! the padded sequence length and the trace contract — plus the error paths+//! a bad trace request must take.++use super::*;+use crate::nets::tests::Shapes;++#[test]+fn padded_positions_rounds_up_to_a_multiple_of_eight() {+    assert_eq!(padded_positions(0), 0);+    assert_eq!(padded_positions(1), 8);+    assert_eq!(padded_positions(8), 8);+    assert_eq!(padded_positions(9), 16);+    assert_eq!(padded_positions(36), 40);+    assert_eq!(padded_positions(64), 64);+}++#[test]+fn an_image_plan_pads_its_inputs_and_pools_to_one_soft_token() {+    // A 3x3 grid is 9 patches, padded to 16; pooling 3x3 gives one soft token.+    let grid = Grid::new(3, 3).expect("a grid");+    let source = Shapes::new(TENSORS);+    let plan = build(&source, Mode::Image(grid)).expect("the image plan builds");+    assert_eq!(plan.inputs.len(), INPUTS);+    for input in &plan.inputs[..2] {+        assert_eq!(input.shape, Shape::new(D_MODEL, 1, 16));+    }+    assert_eq!(plan.inputs[2].shape, Shape::new(HEAD_DIM, 1, 16));+    let output = plan.output().expect("one output");+    assert_eq!(output.shape, Shape::new(OUT_DIM, 1, 1));+    assert!(!plan.ops.is_empty(), "a plan with no ops runs nothing");+    assert!(plan.arena_elems > 0);+}++#[test]+fn an_image_plan_at_a_multiple_of_eight_needs_no_padding() {+    // 6x12 patches is 72, already a multiple of eight.+    let grid = Grid::new(6, 12).expect("a grid");+    let source = Shapes::new(TENSORS);+    let plan = build(&source, Mode::Image(grid)).expect("the image plan builds");+    assert_eq!(plan.inputs[0].shape, Shape::new(D_MODEL, 1, 72));+    // (6/3) x (12/3) pooled cells.+    assert_eq!(plan.output().expect("one output").shape, Shape::new(OUT_DIM, 1, 8));+}++#[test]+fn a_trace_stops_where_asked_and_reports_both_sides_of_the_pooling() {+    let grid = Grid::new(6, 12).expect("a grid");+    let source = Shapes::new(TENSORS);+    let plan = build(&source, Mode::Trace { grid, layers: 0 }).expect("a zero-layer trace");+    assert_eq!(plan.outputs.len(), 2, "hidden state and its pooling");+    assert_eq!(plan.outputs[0].shape, Shape::new(D_MODEL, 1, 72));+    assert_eq!(plan.outputs[1].shape, Shape::new(D_MODEL, 1, 8));+    // A full-depth trace is the whole tower, still with both outputs.+    let source = Shapes::new(TENSORS);+    let plan = build(&source, Mode::Trace { grid, layers: LAYERS }).expect("a full trace");+    assert_eq!(plan.outputs.len(), 2);+}++#[test]+fn a_trace_past_the_tower_is_refused() {+    let grid = Grid::new(6, 12).expect("a grid");+    let source = Shapes::new(TENSORS);+    let error = build(&source, Mode::Trace { grid, layers: LAYERS + 1 })+        .expect_err("a trace deeper than the tower");+    assert!(error.contains("layers"), "unexpected error: {error}");+}
library/ml/src/main/rust/src/nets/madlad_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_part1.rs b/library/ml/src/main/rust/src/nets/madlad_part1.rsindex 383f29d1ec..eaa1fc7c8a 100644--- a/library/ml/src/main/rust/src/nets/madlad_part1.rs+++ b/library/ml/src/main/rust/src/nets/madlad_part1.rs@@ -127,3 +127,7 @@ pub fn relative_bias(     }     Ok(out) }++#[cfg(test)]+#[path = "madlad_part1_tests.rs"]+mod madlad_part1_tests;
library/ml/src/main/rust/src/nets/madlad_part1_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/madlad_part1_tests.rs b/library/ml/src/main/rust/src/nets/madlad_part1_tests.rsnew file mode 100644index 0000000000..aeba892d70--- /dev/null+++ b/library/ml/src/main/rust/src/nets/madlad_part1_tests.rs@@ -0,0 +1,118 @@+//! Host tests for MADLAD's host helpers (`madlad_part1.rs`): the T5+//! relative-position bucket, the class-split arithmetic and the relative+//! bias gather. Bucket expectations are hand-computed from transformers'+//! `modeling_t5.py` bucketing, not from this implementation.++use super::*;+use crate::preprocess::f32_to_f16;+use crate::weights::{Blob, Dtype, Offsets, Reader, Tensor};++#[test]+fn tokens_split_evenly_across_the_four_class_shards() {+    assert_eq!(split_of(0), (0, 0));+    assert_eq!(split_of(63_999), (0, 63_999));+    assert_eq!(split_of(64_000), (1, 0));+    assert_eq!(split_of(255_999), (3, 63_999));+}++#[test]+fn bidirectional_buckets_spend_half_the_range_on_keys_ahead() {+    // Same position, and keys behind the query: exact low buckets.+    assert_eq!(relative_bucket(0, true), 0);+    assert_eq!(relative_bucket(-1, true), 1);+    assert_eq!(relative_bucket(-7, true), 7);+    // Keys ahead get the upper half (16..32 with 32 buckets).+    assert_eq!(relative_bucket(1, true), 17);+    assert_eq!(relative_bucket(7, true), 23);+    // The logarithmic region: 8 is the first inexact bucket, and anything at+    // or past max_distance saturates the half-range.+    assert_eq!(relative_bucket(-8, true), 8);+    assert_eq!(relative_bucket(-128, true), 15);+    assert_eq!(relative_bucket(-10_000, true), 15);+    assert_eq!(relative_bucket(128, true), 31);+    assert_eq!(relative_bucket(10_000, true), 31);+}++#[test]+fn causal_buckets_clamp_keys_ahead_to_zero() {+    assert_eq!(relative_bucket(5, false), 0, "a key ahead, clamped");+    assert_eq!(relative_bucket(0, false), 0);+    assert_eq!(relative_bucket(-1, false), 1);+    assert_eq!(relative_bucket(-15, false), 15);+    // 32 buckets, 16 exact: the rest are logarithmic up to 128.+    assert_eq!(relative_bucket(-128, false), 31);+    assert_eq!(relative_bucket(-10_000, false), 31);+}++/// A `Blob` over owned bytes, for building a `Reader` in tests.+struct Bytes {+    bytes: Vec<u8>,+    tensors: Vec<Tensor>,+}++impl Blob for Bytes {+    fn data_len(&self) -> u64 {+        self.bytes.len() as u64+    }+    fn tensors(&self) -> &[Tensor] {+        &self.tensors+    }+    fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {+        let start = offset as usize;+        let end = start + into.len();+        let source = self+            .bytes+            .get(start..end)+            .ok_or_else(|| format!("read of {start}..{end} past {}", self.bytes.len()))?;+        into.copy_from_slice(source);+        Ok(())+    }+}++/// A table whose only real tensor is the encoder relative-bias table, with+/// value `bucket * 16 + head` in every cell (exact in fp16).+fn bias_reader() -> (Offsets, Bytes) {+    let mut tensors = vec![+        Tensor { rank: 1, dims: [1, 0, 0, 0], offset: 0, len: 1, dtype: Dtype::F16 };+        TABLE_ENC + 1+    ];+    tensors[TABLE_ENC] = Tensor {+        rank: 2,+        dims: [BUCKETS, HEADS, 0, 0],+        offset: 0,+        len: BUCKETS * HEADS,+        dtype: Dtype::F16,+    };+    let mut bytes = Vec::new();+    for bucket in 0..BUCKETS {+        for head in 0..HEADS {+            bytes.extend_from_slice(&f32_to_f16((bucket * HEADS + head) as f32).to_le_bytes());+        }+    }+    let blob = Bytes { bytes, tensors: tensors.clone() };+    (Offsets::from_test(tensors), blob)+}++#[test]+fn the_bias_gather_lays_heads_out_as_channels() {+    let (offsets, blob) = bias_reader();+    let reader = Reader::new(&offsets, &blob);+    let out = relative_bias(reader, TABLE_ENC, &[0, 1], &[0, 1, 2], true).expect("bias");+    assert_eq!(out.len(), HEADS as usize * 2 * 3);+    // Buckets by hand: (q0,k0)=0, (q0,k1)=17, (q0,k2)=18, (q1,k0)=1.+    let at = |head: usize, qi: usize, ki: usize| out[head * 6 + qi * 3 + ki];+    assert_eq!(at(0, 0, 0), 0.0);+    assert_eq!(at(0, 0, 1), (17 * HEADS) as f32);+    assert_eq!(at(3, 0, 2), (18 * HEADS + 3) as f32);+    assert_eq!(at(2, 1, 0), (HEADS + 2) as f32);+    assert!(relative_bias(reader, TABLE_ENC + 5, &[0], &[0], true).is_err(), "not a table");+}++#[test]+fn embedding_refuses_a_token_past_the_vocabulary_before_reading() {+    let offsets = Offsets::empty();+    let blob = Bytes { bytes: Vec::new(), tensors: Vec::new() };+    let reader = Reader::new(&offsets, &blob);+    assert!(embed_positions(reader, &[256_000], 0).is_err(), "past the vocabulary");+    assert!(embed_positions(reader, &[u32::MAX], 0).is_err());+}
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex d071be54dd..9ebebc4c98 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -187,3 +187,7 @@ include!("reference_part8.rs"); include!("reference_part9.rs"); include!("reference_part10.rs"); }++#[cfg(test)]+#[path = "reference_tests.rs"]+mod reference_tests;
library/ml/src/main/rust/src/nets/reference_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_tests.rs b/library/ml/src/main/rust/src/nets/reference_tests.rsnew file mode 100644index 0000000000..d924e29009--- /dev/null+++ b/library/ml/src/main/rust/src/nets/reference_tests.rs@@ -0,0 +1,67 @@+//! Host tests for the CPU reference interpreter's weightless ops+//! (`reference_part11.rs`): max pooling and instance normalisation, run+//! end to end through `Builder` + `reference::run` against hand-computed+//! values. These ops had no direct coverage; a wrong window or a biased/+//! unbiased variance mix-up would only have shown up as a worse mask.++use super::*;+use crate::nets::tests::Shapes;+use crate::nets::{Builder, Shape};++#[test]+fn max_pool_takes_the_largest_of_each_2x2_window() {+    let source = Shapes::new(0);+    let mut builder = Builder::new(&source);+    let input = builder.input(Shape::new(1, 4, 4));+    let pooled = builder.max_pool_2x2(input);+    let plan = builder.finish(&[pooled]).expect("the plan builds");+    assert_eq!(plan.output().expect("one output").shape, Shape::new(1, 2, 2));+    let values: Vec<f32> = (0..16).map(|v| v as f32).collect();+    let out = run(&plan, &[], &values).expect("the reference runs");+    // Windows over rows/cols (0..2, 2..4): maxes are the bottom-right corners.+    assert_eq!(out, vec![5.0, 7.0, 13.0, 15.0]);+}++#[test]+fn max_pool_is_per_channel() {+    let source = Shapes::new(0);+    let mut builder = Builder::new(&source);+    let input = builder.input(Shape::new(2, 2, 2));+    let pooled = builder.max_pool_2x2(input);+    let plan = builder.finish(&[pooled]).expect("the plan builds");+    // Channel 0 peaks at 9, channel 1 (negatives) at -1.+    let out = run(&plan, &[], &[1.0, 9.0, 3.0, 4.0, -5.0, -1.0, -9.0, -2.0]).expect("runs");+    assert_eq!(out, vec![9.0, -1.0]);+}++#[test]+fn instance_norm_centres_and_scales_each_channel_independently() {+    let source = Shapes::new(0);+    let mut builder = Builder::new(&source);+    let input = builder.input(Shape::new(2, 2, 2));+    let normed = builder.instance_norm(input, 0.0);+    let plan = builder.finish(&[normed]).expect("the plan builds");+    // Channel 0: [1,2,3,4], mean 2.5, biased variance 1.25.+    // Channel 1: [10,10,20,20], mean 15, biased variance 25.+    let out = run(&plan, &[], &[1.0, 2.0, 3.0, 4.0, 10.0, 10.0, 20.0, 20.0]).expect("runs");+    let want0: Vec<f32> = [1.0, 2.0, 3.0, 4.0]+        .iter()+        .map(|v| (v - 2.5) / 1.25f32.sqrt())+        .collect();+    for (got, want) in out[..4].iter().zip(&want0) {+        assert!((got - want).abs() < 1e-3, "channel 0: {got} vs {want}");+    }+    // Channel 1 normalises to exactly -1, -1, +1, +1 (through fp16, so near).+    for (got, want) in out[4..].iter().zip([-1.0, -1.0, 1.0, 1.0]) {+        assert!((got - want).abs() < 1e-3, "channel 1: {got} vs {want}");+    }+    // A constant channel has zero variance; with epsilon 0 the reference+    // divides by zero and stores inf/NaN — so use a live epsilon there.+    let source = Shapes::new(0);+    let mut builder = Builder::new(&source);+    let input = builder.input(Shape::new(1, 1, 2));+    let normed = builder.instance_norm(input, 1.0);+    let plan = builder.finish(&[normed]).expect("the plan builds");+    let out = run(&plan, &[], &[7.0, 7.0]).expect("runs");+    assert_eq!(out, vec![0.0, 0.0], "centred zeros stay zero at any epsilon");+}
library/ml/src/main/rust/src/post/sentencepiece.rs
diff --git a/library/ml/src/main/rust/src/post/sentencepiece.rs b/library/ml/src/main/rust/src/post/sentencepiece.rsindex 29a6f95c0a..741f6bacae 100644--- a/library/ml/src/main/rust/src/post/sentencepiece.rs+++ b/library/ml/src/main/rust/src/post/sentencepiece.rs@@ -371,3 +371,7 @@ impl<'a> Table<'a> {         String::from_utf8_lossy(&out).replace(METASPACE, " ").trim().to_string()     } }++#[cfg(test)]+#[path = "sentencepiece_tests.rs"]+mod sentencepiece_tests;
library/ml/src/main/rust/src/post/sentencepiece_tests.rs
diff --git a/library/ml/src/main/rust/src/post/sentencepiece_tests.rs b/library/ml/src/main/rust/src/post/sentencepiece_tests.rsnew file mode 100644index 0000000000..d56b468ba3--- /dev/null+++ b/library/ml/src/main/rust/src/post/sentencepiece_tests.rs@@ -0,0 +1,206 @@+//! Host tests for the SentencePiece table (`sentencepiece.rs` ++//! `sentencepiece_unigram.rs` + `sentencepiece_extra.rs`).+//!+//! Every table here is built in memory in the converter's `SPM1` layout, so+//! the parser, both encoders and the decoder are exercised end to end with+//! hand-computed expectations: BPE merge ranking, byte fallback, special+//! tokens, Viterbi segmentation and the malformed-table errors.++use super::*;+use crate::post::sentencepiece_flavours::{FAIRSEQ, GEMMA};++/// One `SPM1` blob for `pieces` as `(text, score)` in id order.+fn blob(pieces: &[(&str, i32)]) -> Vec<u8> {+    let mut out = Vec::new();+    out.extend_from_slice(b"SPM1");+    out.extend_from_slice(&(pieces.len() as u32).to_le_bytes());+    for (text, score) in pieces {+        out.extend_from_slice(&score.to_le_bytes());+        out.extend_from_slice(&(text.len() as u16).to_le_bytes());+        out.extend_from_slice(text.as_bytes());+    }+    out+}++/// The fairseq specials plus a small Latin vocabulary.+///+/// Ids: 0 `<s>`, 1 `<pad>`, 2 `</s>`, 3 `<unk>`, 4 `▁`, 5 `a`, 6 `b`,+/// 7 `▁a`, 8 `▁b`, 9 `ab`. Merge scores rise with merge priority.+fn latin() -> Vec<u8> {+    blob(&[+        ("<s>", 0),+        ("<pad>", 0),+        ("</s>", 0),+        ("<unk>", 0),+        ("\u{2581}", -40),+        ("a", -41),+        ("b", -42),+        ("\u{2581}a", -1),+        ("\u{2581}b", -2),+        ("ab", -3),+    ])+}++/// The latin table plus all 256 byte-fallback pieces (ids 10..266).+fn latin_with_bytes() -> Vec<u8> {+    let mut pieces: Vec<(String, i32)> = vec![+        ("<s>".into(), 0),+        ("<pad>".into(), 0),+        ("</s>".into(), 0),+        ("<unk>".into(), 0),+        ("\u{2581}".into(), -40),+        ("a".into(), -41),+        ("b".into(), -42),+        ("\u{2581}a".into(), -1),+        ("\u{2581}b".into(), -2),+        ("ab".into(), -3),+    ];+    for byte in 0..=255u32 {+        pieces.push((format!("<0x{byte:02X}>"), -100));+    }+    let refs: Vec<(&str, i32)> = pieces.iter().map(|(t, s)| (t.as_str(), *s)).collect();+    blob(&refs)+}++#[test]+fn a_table_parses_and_answers_lookups() {+    let bytes = latin();+    let table = Table::parse(&bytes).expect("the table parses");+    assert_eq!(table.len(), 10);+    assert!(!table.is_empty());+    assert_eq!(table.specials(), FAIRSEQ);+    assert!(!table.has_byte_fallback(), "no byte pieces in this table");+    assert_eq!(table.piece(7), Some("\u{2581}a".as_bytes()));+    assert_eq!(table.piece(10), None, "one past the end");+    assert_eq!(table.id_of("ab"), Some(9));+    assert_eq!(table.id_of("zz"), None);+}++#[test]+fn malformed_tables_are_refused_with_the_reason() {+    assert!(Table::parse(b"SPM").is_err(), "shorter than the header");+    assert!(Table::parse(b"XXXX........").is_err(), "bad magic");+    // Truncated inside the second piece's header.+    let bytes = latin();+    assert!(Table::parse(&bytes[..12]).is_err(), "ends inside a piece");+    // One trailing byte the piece count does not account for.+    let mut padded = latin();+    padded.push(0);+    assert!(Table::parse(&padded).is_err(), "trailing bytes");+    // The reserved ids must spell what the flavour expects.+    let wrong = blob(&[("<pad>", 0), ("<s>", 0), ("</s>", 0), ("<unk>", 0)]);+    assert!(Table::parse(&wrong).is_err(), "id 0 is not <s>");+}++#[test]+fn bpe_merges_the_highest_ranked_pair_first_leftmost_on_a_tie() {+    let bytes = latin();+    let table = Table::parse(&bytes).expect("the table parses");+    // "a b" prepares to "▁a▁b"; both word pieces outrank their parts.+    assert_eq!(table.encode("a b"), vec![7, 8]);+    // Whitespace runs collapse and the ends trim (fairseq tidying).+    assert_eq!(table.encode("  a   b  "), vec![7, 8]);+    assert_eq!(table.encode(""), Vec::<u32>::new());+    assert_eq!(table.encode("   "), Vec::<u32>::new());+    // Inside one word, "ab" (rank -3) merges after neither ▁ piece applies.+    assert_eq!(table.encode("ab"), vec![7, 6], "▁a then a lone b: no ▁ab piece");+}++#[test]+fn an_uncovered_character_is_unk_without_byte_fallback() {+    let bytes = latin();+    let table = Table::parse(&bytes).expect("the table parses");+    // 'z' has no piece: one unk for the whole symbol, the rest still encodes.+    assert_eq!(table.encode("az"), vec![7, FAIRSEQ.unk]);+}++#[test]+fn byte_fallback_spells_every_byte_and_decode_fuses_them_back() {+    let bytes = latin_with_bytes();+    let table = Table::parse(&bytes).expect("the table parses");+    assert!(table.has_byte_fallback());+    // 'é' is U+00E9, UTF-8 C3 A9: two byte pieces, ids 10 + byte.+    let ids = table.encode("a\u{e9}");+    assert_eq!(ids, vec![7, 10 + 0xC3, 10 + 0xA9]);+    // Decoding fuses the byte run into the character again, and the leading+    // metaspace becomes a space that the trim then removes.+    assert_eq!(table.decode(&ids), "a\u{e9}");+    assert_eq!(table.decode(&[7, 8]), "a b");+    // Ids past the table are skipped, not fatal.+    assert_eq!(table.decode(&[7, 9999, 8]), "a b");+}++#[test]+fn gemma_flavour_keeps_space_runs_significant() {+    let bytes = blob(&[+        ("<pad>", 0),+        ("<eos>", 0),+        ("<bos>", 0),+        ("<unk>", 0),+        ("\u{2581}", -40),+        ("a", -41),+        ("\u{2581}a", -1),+        ("\u{2581}\u{2581}a", -2),+    ]);+    let table = Table::parse_with(&bytes, GEMMA).expect("the table parses");+    assert_eq!(table.specials().bos, 2);+    // No tidying: two spaces stay two metaspaces and merge as one piece.+    assert_eq!(table.encode("a  a"), vec![5, 7]);+}++#[test]+fn specials_are_matched_literally_and_never_merged_into() {+    let bytes = latin();+    let table = Table::parse(&bytes).expect("the table parses");+    // "<s>" as text would BPE into pieces; as a special it is id 0.+    assert_eq!(table.encode_with_specials("<s>a", &["<s>"]), vec![0, 7]);+    // Unknown specials are skipped, and ordinary text still encodes.+    assert_eq!(table.encode_with_specials("a", &["<nope>"]), vec![7]);+    assert_eq!(table.encode_with_specials("", &["<s>"]), Vec::<u32>::new());+}++#[test]+fn the_unigram_viterbi_prefers_the_better_scoring_segmentation() {+    // Scores are log-probability-like: -1 beats -2 + -2, so the long piece wins.+    let bytes = blob(&[+        ("<s>", 0),+        ("<pad>", 0),+        ("</s>", 0),+        ("<unk>", 0),+        ("\u{2581}", -3_000_000),+        ("a", -3_000_000),+        ("b", -3_000_000),+        ("\u{2581}a", -2_000_000),+        ("ab", -1_000_000),+        ("\u{2581}ab", -1_000_000),+    ]);+    let table = Table::parse(&bytes).expect("the table parses");+    assert_eq!(table.encode_unigram("ab"), vec![9], "one long piece");+    // With the long piece dearer than its parts, Viterbi splits it.+    let bytes = blob(&[+        ("<s>", 0),+        ("<pad>", 0),+        ("</s>", 0),+        ("<unk>", 0),+        ("\u{2581}", -3_000_000),+        ("a", -1_000_000),+        ("b", -1_000_000),+        ("\u{2581}a", -1_000_000),+        ("\u{2581}ab", -9_000_000),+    ]);+    let table = Table::parse(&bytes).expect("the table parses");+    assert_eq!(table.encode_unigram("ab"), vec![7, 6]);+    assert_eq!(table.encode_unigram(""), Vec::<u32>::new());+}++#[test]+fn byte_piece_spelling_is_strict() {+    use crate::post::sentencepiece_extra::byte_piece;+    assert_eq!(byte_piece(b"<0x00>"), Some(0));+    assert_eq!(byte_piece(b"<0xFF>"), Some(255));+    assert_eq!(byte_piece(b"<0xff>"), Some(255), "lowercase hex is accepted");+    assert_eq!(byte_piece(b"<0x0G>"), None);+    assert_eq!(byte_piece(b"<0x0>"), None, "too short");+    assert_eq!(byte_piece(b"a"), None);+    assert_eq!(byte_piece(b""), None);+}
library/ml/src/main/rust/src/post/sentencepiece_unigram.rs
diff --git a/library/ml/src/main/rust/src/post/sentencepiece_unigram.rs b/library/ml/src/main/rust/src/post/sentencepiece_unigram.rsindex 3e50bfbf23..e53c8c9f07 100644--- a/library/ml/src/main/rust/src/post/sentencepiece_unigram.rs+++ b/library/ml/src/main/rust/src/post/sentencepiece_unigram.rs@@ -23,6 +23,13 @@ impl<'a> Table<'a> {     ///     /// [`EOS`]: super::sentencepiece::EOS     pub fn encode_unigram(&self, text: &str) -> Vec<u32> {+        // Empty text encodes to no tokens: the dummy prefix `prepare_unigram`+        // adds is a word-start marker for real text, not a token of its own,+        // so it must not survive on its own (the `prepared.is_empty()` check+        // below can never fire, since the prefix alone is non-empty).+        if text.is_empty() {+            return Vec::new();+        }         let prepared = self.prepare_unigram(text);         if prepared.is_empty() {             return Vec::new();
library/ml/src/main/rust/src/post/supertonic.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic.rs b/library/ml/src/main/rust/src/post/supertonic.rsindex 43bcaaa4d5..8133cc4085 100644--- a/library/ml/src/main/rust/src/post/supertonic.rs+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -219,9 +219,13 @@ pub fn normalise(text: &str) -> String {     }      // Expansions, then the spacing fixes that a stray space before punctuation would leave.+    // Repeated until none remains: a run of spaces before a mark would otherwise+    // lose only its last space and keep the rest.     out = out.replace('@', " at ").replace("e.g.,", "for example, ").replace("i.e.,", "that is, ");     for mark in [',', '.', '!', '?', ';', ':', '\''] {-        out = out.replace(&format!(" {mark}"), &mark.to_string());+        while out.contains(&format!(" {mark}")) {+            out = out.replace(&format!(" {mark}"), &mark.to_string());+        }     }      // Runs of one quote character collapse to a single one; `` ` `` is already an apostrophe.@@ -447,4 +451,7 @@ pub struct Voice { }  include!("supertonic_part1.rs");-include!("supertonic_part2.rs");\ No newline at end of file+include!("supertonic_part2.rs");+#[cfg(test)]+#[path = "supertonic_tests.rs"]+mod supertonic_tests;
library/ml/src/main/rust/src/post/supertonic_tests.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic_tests.rs b/library/ml/src/main/rust/src/post/supertonic_tests.rsnew file mode 100644index 0000000000..6480062fd8--- /dev/null+++ b/library/ml/src/main/rust/src/post/supertonic_tests.rs@@ -0,0 +1,99 @@+//! Host tests for Supertonic's text front end (`post/supertonic.rs`):+//! `normalise`, `to_ids` and the small host tensors. All expectations are+//! hand-derived from the SDK behaviour the module documents.++use super::*;+use crate::nets::supertonic_sampler as sampler;++/// An indexer with only `<`, `>`, `/`, `e`, `n`, `a`, `.` and space mapped.+fn indexer() -> Vec<u8> {+    let mut bytes = vec![0xffu8; INDEXER_ENTRIES * 2];+    let mut set = |c: char, token: i16| {+        let at = c as usize * 2;+        bytes[at..at + 2].copy_from_slice(&token.to_le_bytes());+    };+    set('<', 0);+    set('>', 1);+    set('e', 2);+    set('n', 3);+    set('/', 4);+    set('a', 5);+    set('.', 6);+    set(' ', 7);+    bytes+}++#[test]+fn normalise_strips_emoji_and_unifies_punctuation() {+    assert_eq!(normalise("hi \u{1F600} there"), "hi there");+    assert_eq!(normalise("\u{201C}hi\u{201D}"), "\"hi\"");+    assert_eq!(normalise("a\u{2014}b"), "a-b");+    assert_eq!(normalise("one @ two"), "one at two");+    assert_eq!(normalise("x, e.g., y"), "x, for example, y");+    assert_eq!(normalise("a  ,  b"), "a, b", "space before punctuation goes");+    assert_eq!(normalise("say \"\"hi\"\""), "say \"hi\"", "quote runs collapse");+    assert_eq!(normalise("  spaced   out  "), "spaced out");+    // No trailing period here: `to_ids` owns that decision.+    assert_eq!(normalise("no end mark"), "no end mark");+}++#[test]+fn to_ids_wraps_the_text_in_its_language_tag_and_ends_the_sentence() {+    let table = indexer();+    // "<en>" = 0,2,3,1; "a" = 5; added "." = 6; "</en>" = 0,4,2,3,1.+    assert_eq!(+        to_ids(&table, "a", "en").expect("ids"),+        vec![0, 2, 3, 1, 5, 6, 0, 4, 2, 3, 1]+    );+    // A sentence already ending in terminal punctuation gets no extra period.+    assert_eq!(+        to_ids(&table, "a.", "en").expect("ids"),+        vec![0, 2, 3, 1, 5, 6, 0, 4, 2, 3, 1]+    );+    // Unmapped characters are dropped, not substituted.+    assert_eq!(+        to_ids(&table, "aza", "en").expect("ids"),+        vec![0, 2, 3, 1, 5, 5, 6, 0, 4, 2, 3, 1]+    );+}++#[test]+fn to_ids_refuses_unreadable_text_and_bad_arguments() {+    let table = indexer();+    assert!(to_ids(&table, "\u{1F600}", "en").is_err(), "nothing maps");+    assert!(to_ids(&table[..100], "a", "en").is_err(), "short indexer");+    assert!(to_ids(&table, "a", "EN").is_err(), "uppercase language");+    assert!(to_ids(&table, "a", "e").is_err(), "one-letter language");+    assert!(to_ids(&table, "a", "e1").is_err(), "non-letter language");+}++#[test]+fn rotary_angles_are_normalised_by_the_sequence_length() {+    let theta = vec![0.0f32; sampler::FREQUENCIES as usize];+    let table = rotary_angles(&theta, 4).expect("a table");+    assert_eq!(table.len(), 2 * sampler::FREQUENCIES as usize * 4);+    assert!(table.iter().take(32 * 4).all(|&v| v == 1.0), "cos(0) everywhere");+    assert!(table.iter().skip(32 * 4).all(|&v| v == 0.0), "sin(0) everywhere");++    let mut theta = vec![0.0f32; sampler::FREQUENCIES as usize];+    theta[0] = std::f32::consts::PI;+    let table = rotary_angles(&theta, 4).expect("a table");+    // Frequency 0, position 2 of 4: angle = (2/4) * PI = PI/2.+    assert!((table[2] - 0.0).abs() < 1e-6, "cos(pi/2), got {}", table[2]);+    assert!((table[32 * 4 + 2] - 1.0).abs() < 1e-6, "sin(pi/2)");++    assert!(rotary_angles(&theta, 0).is_err(), "no positions");+    assert!(rotary_angles(&theta[..4], 4).is_err(), "wrong frequency count");+}++#[test]+fn unconditional_text_broadcasts_the_token_and_rejects_bad_shapes() {+    let token: Vec<f32> = (0..sampler::TEXT).map(|i| i as f32).collect();+    let out = unconditional_text(&token, 3).expect("broadcast");+    assert_eq!(out.len(), sampler::TEXT as usize * 3);+    // Channel-major: channel c repeats at every position before c + 1 starts.+    assert_eq!(&out[..3], &[0.0, 0.0, 0.0]);+    assert_eq!(&out[3..6], &[1.0, 1.0, 1.0]);+    assert!(unconditional_text(&token, 0).is_err(), "no characters");+    assert!(unconditional_text(&token[..4], 3).is_err(), "short token");+}
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 50817f248f..055ae2984b 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -481,6 +481,10 @@ pub struct Offsets {     tensors: Vec<Tensor>, } +#[cfg(test)]+#[path = "weights_tests.rs"]+mod weights_tests;+ include!("weights_part1.rs"); include!("weights_part2.rs"); include!("weights_part3.rs");
library/ml/src/main/rust/src/weights_tests.rs
diff --git a/library/ml/src/main/rust/src/weights_tests.rs b/library/ml/src/main/rust/src/weights_tests.rsnew file mode 100644index 0000000000..f65da235d9--- /dev/null+++ b/library/ml/src/main/rust/src/weights_tests.rs@@ -0,0 +1,188 @@+//! Host tests for the `.maml` reader's format arithmetic (`weights.rs`):+//! dtype byte counts and the header parser's refusals, with hand-built+//! files. A parser that accepts a malformed asset fails later as a driver+//! reset, so every refusal branch gets a case.++use super::*;+use crate::preprocess::f32_to_f16;++/// A minimal valid v1 file: one fp16 tensor `[2, 2]` holding 1..4, for+/// `graph::SELFIE`.+fn valid_file() -> Vec<u8> {+    let mut out = vec![0u8; HEADER_BYTES];+    out[0..4].copy_from_slice(&MAGIC);+    out[4..8].copy_from_slice(&1u32.to_le_bytes());+    out[8..12].copy_from_slice(&graph::SELFIE.to_le_bytes());+    out[12..16].copy_from_slice(&1u32.to_le_bytes());+    // data_offset = 64 + 32, data_len = 4 elements * 2 bytes.+    out[48..52].copy_from_slice(&96u32.to_le_bytes());+    out[52..56].copy_from_slice(&8u32.to_le_bytes());+    // Tensor entry at 64: rank 2, dims [2, 2], dtype f16, offset 0, len 4.+    out.extend_from_slice(&2u32.to_le_bytes());+    out.extend_from_slice(&2u32.to_le_bytes());+    out.extend_from_slice(&2u32.to_le_bytes());+    out.extend_from_slice(&0u32.to_le_bytes());+    out.extend_from_slice(&0u32.to_le_bytes());+    out.extend_from_slice(&0u32.to_le_bytes()); // dtype+    out.extend_from_slice(&0u32.to_le_bytes()); // offset+    out.extend_from_slice(&4u32.to_le_bytes()); // len+    for value in [1.0f32, 2.0, 3.0, 4.0] {+        out.extend_from_slice(&f32_to_f16(value).to_le_bytes());+    }+    out+}++#[test]+fn dtype_byte_counts_match_the_format() {+    assert_eq!(Dtype::F16.bytes(4), 8);+    assert_eq!(Dtype::I8.bytes(4), 4);+    assert_eq!(Dtype::I4.bytes(4), 2);+    assert_eq!(Dtype::I4.bytes(5), 3, "an odd tap count pads the last nibble");+    assert_eq!(Dtype::Q2K.bytes(256), 84);+    assert_eq!(Dtype::Q2K.bytes(257), 168, "a short block still costs a superblock");+    assert_eq!(Dtype::Q2K.bytes(0), 0);+    assert!(!Dtype::F16.is_quantised());+    assert!(Dtype::I8.is_quantised() && Dtype::I4.is_quantised() && Dtype::Q2K.is_quantised());+}++#[test]+fn a_minimal_file_parses_and_reads_back() {+    let bytes = valid_file();+    let weights = Weights::parse(&bytes, graph::SELFIE).expect("the file parses");+    assert_eq!(weights.graph_id, graph::SELFIE);+    assert_eq!(weights.data().len(), 8);+    let reader = weights.reader();+    assert_eq!(reader.fp16(0, &[2, 2]).expect("the tensor"), vec![1.0, 2.0, 3.0, 4.0]);+    assert!(reader.fp16(0, &[4]).is_err(), "wrong shape is refused");+    assert!(reader.fp16(1, &[1]).is_err(), "past the table is refused");+}++#[test]+fn malformed_files_are_refused_at_the_header() {+    let good = valid_file();+    assert!(Weights::parse(&good[..32], graph::SELFIE).is_err(), "short header");+    let mut bad = good.clone();+    bad[0] = b'X';+    assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "bad magic");+    assert!(Weights::parse(&good, graph::U2NETP).is_err(), "wrong graph");+    let mut bad = good.clone();+    bad[4..8].copy_from_slice(&99u32.to_le_bytes());+    assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "future version");+    let mut bad = good.clone();+    bad[4..8].copy_from_slice(&0u32.to_le_bytes());+    assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "version zero");+    // Trailing bytes: the whole slice must end where the sections end.+    let mut padded = good.clone();+    padded.push(0);+    assert!(Weights::parse(&padded, graph::SELFIE).is_err(), "trailing bytes");+    // Truncated data section.+    assert!(Weights::parse(&good[..good.len() - 2], graph::SELFIE).is_err());+}++#[test]+fn malformed_tensor_entries_are_refused() {+    let good = valid_file();+    let entry = HEADER_BYTES;+    // Rank 0 and rank 5 are both outside 1..=4.+    for rank in [0u32, 5] {+        let mut bad = good.clone();+        bad[entry..entry + 4].copy_from_slice(&rank.to_le_bytes());+        assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "rank {rank}");+    }+    // An unknown dtype.+    let mut bad = good.clone();+    bad[entry + 20..entry + 24].copy_from_slice(&7u32.to_le_bytes());+    assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "dtype 7");+    // Length that disagrees with the dims ([2,2] is 4, not 5).+    let mut bad = good.clone();+    bad[entry + 28..entry + 32].copy_from_slice(&5u32.to_le_bytes());+    assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "len vs dims");+    // An offset off the 16-byte alignment.+    let mut bad = good.clone();+    bad[entry + 24..entry + 28].copy_from_slice(&2u32.to_le_bytes());+    assert!(Weights::parse(&bad, graph::SELFIE).is_err(), "unaligned offset");+}++#[test]+fn offsets_answer_shape_checks_without_a_file() {+    let empty = Offsets::empty();+    assert!(empty.is_empty());+    assert_eq!(empty.len(), 0);+    assert!(empty.tensor(0).is_err());+    let table = Offsets::from_test(vec![Tensor {+        rank: 2,+        dims: [2, 2, 0, 0],+        offset: 0,+        len: 4,+        dtype: Dtype::F16,+    }]);+    assert_eq!(table.shaped(0, &[2, 2]).expect("the tensor").len, 4);+    assert!(table.shaped(0, &[4]).is_err(), "shape mismatch names the tensor");+    assert!(table.shaped(1, &[1]).is_err(), "out of range");+}++/// A hand-built file with four tensors: an int8 `[2, 4]` at offset 0, its+/// fp16 per-row scale `[2]` at 16, an int4 `[1, 32]` at 32 (16 packed bytes)+/// and its fp16 block scale `[1, 1]` at 48. The data section is 50 bytes.+fn quantised_file() -> Vec<u8> {+    let mut out = vec![0u8; HEADER_BYTES];+    out[0..4].copy_from_slice(&MAGIC);+    out[4..8].copy_from_slice(&1u32.to_le_bytes());+    out[8..12].copy_from_slice(&graph::SELFIE.to_le_bytes());+    out[12..16].copy_from_slice(&4u32.to_le_bytes());+    out[48..52].copy_from_slice(&((HEADER_BYTES + 4 * 32) as u32).to_le_bytes());+    out[52..56].copy_from_slice(&50u32.to_le_bytes());+    let mut entry = |rank: u32, dims: [u32; 4], dtype: u32, offset: u32, len: u32, out: &mut Vec<u8>| {+        out.extend_from_slice(&rank.to_le_bytes());+        for d in dims { out.extend_from_slice(&d.to_le_bytes()); }+        out.extend_from_slice(&dtype.to_le_bytes());+        out.extend_from_slice(&offset.to_le_bytes());+        out.extend_from_slice(&len.to_le_bytes());+    };+    entry(2, [2, 4, 0, 0], 1, 0, 8, &mut out);+    entry(1, [2, 0, 0, 0], 0, 16, 2, &mut out);+    entry(2, [1, 32, 0, 0], 2, 32, 32, &mut out);+    entry(2, [1, 1, 0, 0], 0, 48, 1, &mut out);+    let mut data = vec![0u8; 50];+    data[0..8].copy_from_slice(&[1, -2, 3, -4, 10, 20, -30, 40].map(|v| v as u8));+    for (at, v) in [(16usize, 0.5f32), (18, 2.0), (48, 0.25)] {+        data[at..at + 2].copy_from_slice(&f32_to_f16(v).to_le_bytes());+    }+    // Nibbles low-first: codes [1, -2, 7, -8] as bytes 0x? — low=1, high=-2 (14).+    data[32] = 1 | (14 << 4);+    data[33] = 7 | (8 << 4);+    out.extend_from_slice(&data);+    out+}++#[test]+fn reader_dequantises_int8_and_int4_rows() {+    let bytes = quantised_file();+    let weights = Weights::parse(&bytes, graph::SELFIE).expect("the file parses");+    let reader = weights.reader();+    assert_eq!(+        reader.int8_row(0, 1, &[2, 4], 1).expect("row 1"),+        vec![20.0, 40.0, -60.0, 80.0],+        "int8 values times the row scale of 2"+    );+    assert_eq!(+        reader.int8_row(0, 1, &[2, 4], 0).expect("row 0"),+        vec![0.5, -1.0, 1.5, -2.0]+    );+    assert!(reader.int8_row(0, 1, &[2, 4], 2).is_err(), "row past the table");+    assert!(reader.int8_row(1, 1, &[2], 0).is_err(), "an fp16 tensor is not int8");+    // int4: first four codes are 1, -2, 7, -8, scaled by 0.25; the rest are 0.+    let row = reader.int4_row(2, 3, &[1, 32], 0).expect("the int4 row");+    assert_eq!(&row[..4], &[0.25, -0.5, 1.75, -2.0]);+    assert!(row[4..].iter().all(|&v| v == 0.0));+    assert!(reader.int4_row(0, 1, &[2, 4], 0).is_err(), "an int8 tensor is not int4");+}++#[test]+fn reader_reads_blocks_of_fp16_rows() {+    let bytes = valid_file();+    let weights = Weights::parse(&bytes, graph::SELFIE).expect("the file parses");+    let reader = weights.reader();+    assert_eq!(reader.fp16_rows(0, &[2, 2], 1, 1).expect("row 1"), vec![3.0, 4.0]);+    assert!(reader.fp16_rows(0, &[2, 2], 1, 2).is_err(), "past the last row");+}