ml: add modelrunner and share Rust tests, fix three defects
- Commit
fac0585530300afa65dafb16863638a40574cfbd- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-18 16:27 UTC (17 days ago)
- Parents
a938e56
share_nearby: 74.4% to 80.45% line coverage. modelrunner: 72.0% to 78.5% (865 lib tests passing); the remaining gap is Vulkan device code, generated SPIR-V/shader tables, and ignored shipped-asset test bodies that cannot run on this host. Production fixes: parse_file_list_json mangled filenames containing quotes/backslashes (escape-aware parser, JSON section moved to lib_part3.rs); the presence parser looped forever on truncated-but-header-valid adverts (both parse loops now stop at the first error); Builder::copy_into accepted plan inputs as persistent destinations (persistent tensors now tracked separately). Verified with cargo test -p modelrunner (865 passed), cargo test -p share_nearby (119 passed), and cargo llvm-cov per crate.
Diff
library/ml/src/main/rust/src/gate.rs
diff --git a/library/ml/src/main/rust/src/gate.rs b/library/ml/src/main/rust/src/gate.rsindex 33f9ab5b6e..d1b084343b 100644--- a/library/ml/src/main/rust/src/gate.rs+++ b/library/ml/src/main/rust/src/gate.rs@@ -436,4 +436,7 @@ pub struct Latch { active: bool, } -include!("gate_part1.rs");\ No newline at end of file+include!("gate_part1.rs");+#[cfg(test)]+#[path = "gate_tests.rs"]+mod gate_tests;
library/ml/src/main/rust/src/gate_tests.rs
diff --git a/library/ml/src/main/rust/src/gate_tests.rs b/library/ml/src/main/rust/src/gate_tests.rsnew file mode 100644index 0000000000..138f3a5656--- /dev/null+++ b/library/ml/src/main/rust/src/gate_tests.rs@@ -0,0 +1,112 @@+//! Gate tests: the channel-count refusal, the probability mapping,+//! and the gate over real PCM (silence in, bounded probabilities out).++use super::{probability, Gate, Hysteresis, Latch, MusicGate};+use crate::microfrontend::{Config, NOW_PLAYING};++#[test]+fn the_probability_mapping_is_bounded_and_monotonic() {+ let lo = probability(i16::MIN);+ let mid = probability(0);+ let hi = probability(i16::MAX);+ assert!((0.0..=1.0).contains(&lo), "lo {lo}");+ assert!((0.0..=1.0).contains(&hi), "hi {hi}");+ assert!(lo <= mid && mid <= hi, "monotonic: {lo} {mid} {hi}");+ assert!(lo < hi, "the extremes differ");+}++#[test]+fn a_gate_with_the_wrong_channel_count_is_refused() {+ let config = Config { channels: NOW_PLAYING.channels + 1, ..NOW_PLAYING };+ let err = match MusicGate::with_config(config) {+ Ok(_) => panic!("wrong channels must refuse"),+ Err(e) => e,+ };+ assert!(err.contains("mel channels"), "{err}");+}++#[test]+fn silence_flows_through_the_gate_and_reset_clears_it() {+ let mut gate = MusicGate::new().expect("the gate builds");+ // Two seconds of silence: many hops, each completing a frame.+ let pcm = vec![0i16; 32_000];+ let mut out = Vec::new();+ gate.push(&pcm, &mut out);+ assert!(gate.frames() > 0, "frames were produced");+ for p in &out {+ assert!((0.0..=1.0).contains(p), "probability {p} in range");+ }+ // The latest-score accessor agrees with the pushed stream (both+ // may be silent during warm-up; scores must be probabilities).+ if let Some(score) = gate.score(&pcm) {+ assert!((0.0..=1.0).contains(&score), "score {score} in range");+ }+ gate.reset();+ assert_eq!(gate.frames(), 0, "reset discards the context");+ let _ = Gate::new();+}++#[test]+fn the_defaults_are_the_shipped_parameters() {+ assert_eq!(Gate::default().frames(), 0);+ let shipped = Hysteresis::default();+ assert_eq!(shipped.positive_threshold, Hysteresis::SHIPPED.positive_threshold);+ assert_eq!(shipped.negative_threshold, Hysteresis::SHIPPED.negative_threshold);+ assert_eq!(shipped.window_frames, Hysteresis::SHIPPED.window_frames);+}++#[test]+fn the_latch_fires_after_the_positive_run_and_releases_on_negatives() {+ // SHIPPED wants five positive frames before the event. A maximal+ // score smoothes to probability ~1 from the first frame (the+ // window mean is over the frames fed so far).+ let mut latch = Latch::new(Hysteresis::SHIPPED);+ for frame in 1..5 {+ let verdict = latch.push(i16::MAX);+ assert!(!verdict.positive_event, "frame {frame} is too early");+ assert!(!verdict.active);+ }+ let verdict = latch.push(i16::MAX);+ assert!(verdict.positive_event, "the fifth positive frame fires");+ assert!(verdict.active);+ assert!(verdict.smoothed > 0.99);+ // Negative scores drain the window; the state releases, but the+ // shipped parameters generate no negative event.+ let mut verdict = latch.push(i16::MIN);+ for _ in 0..4 {+ verdict = latch.push(i16::MIN);+ }+ assert!(!verdict.active, "the state released: {verdict:?}");+ assert!(!verdict.negative_event, "shipped parameters suppress it");+}++#[test]+fn squelch_suppresses_events_but_not_the_state_and_negative_events_fire_when_enabled() {+ // Squelched for the whole run: the state still latches, silently.+ let squelched = Hysteresis { initial_squelch_frames: 100, ..Hysteresis::SHIPPED };+ let mut latch = Latch::new(squelched);+ let mut verdict = latch.push(i16::MAX);+ for _ in 0..5 {+ verdict = latch.push(i16::MAX);+ }+ assert!(verdict.active);+ assert!(!verdict.positive_event, "squelched");++ // With negative events enabled and no squelch, release fires one.+ let audible = Hysteresis { generate_negative_events: true, ..Hysteresis::SHIPPED };+ let mut latch = Latch::new(audible);+ for _ in 0..5 {+ latch.push(i16::MAX);+ }+ // The event is on the release frame itself, not after it.+ let mut fired = false;+ let mut verdict = latch.push(i16::MIN);+ for _ in 0..5 {+ verdict = latch.push(i16::MIN);+ fired |= verdict.negative_event;+ }+ assert!(!verdict.active);+ assert!(fired, "the release event fired");+ latch.reset();+ assert!(!latch.push(i16::MIN).active);+}
library/ml/src/main/rust/src/knobs.rs
diff --git a/library/ml/src/main/rust/src/knobs.rs b/library/ml/src/main/rust/src/knobs.rsindex 61fa78ad7e..6455e5b2d4 100644--- a/library/ml/src/main/rust/src/knobs.rs+++ b/library/ml/src/main/rust/src/knobs.rs@@ -59,3 +59,7 @@ fn property(name: &str) -> Option<String> { fn property(_name: &str) -> Option<String> { None }++#[cfg(test)]+#[path = "knobs_tests.rs"]+mod knobs_tests;
library/ml/src/main/rust/src/knobs_tests.rs
diff --git a/library/ml/src/main/rust/src/knobs_tests.rs b/library/ml/src/main/rust/src/knobs_tests.rsnew file mode 100644index 0000000000..7e97c7129e--- /dev/null+++ b/library/ml/src/main/rust/src/knobs_tests.rs@@ -0,0 +1,16 @@+//! Knob lookup tests: the environment source, on a name no other+//! test in the process consults.++use super::{get, is_set};++#[test]+fn a_knob_reads_its_environment_variable_and_reports_absence() {+ std::env::remove_var("MODELRUNNER_COVERAGEPROBE");+ assert_eq!(get("coverageprobe"), None);+ assert!(!is_set("coverageprobe"));+ std::env::set_var("MODELRUNNER_COVERAGEPROBE", "yes");+ assert_eq!(get("coverageprobe"), Some("yes".to_string()));+ assert!(is_set("coverageprobe"));+ std::env::remove_var("MODELRUNNER_COVERAGEPROBE");+ assert_eq!(get("coverageprobe"), None);+}
library/ml/src/main/rust/src/logmel.rs
diff --git a/library/ml/src/main/rust/src/logmel.rs b/library/ml/src/main/rust/src/logmel.rsindex d0444aa6a0..a017dec55d 100644--- a/library/ml/src/main/rust/src/logmel.rs+++ b/library/ml/src/main/rust/src/logmel.rs@@ -231,3 +231,7 @@ impl LogMel { } } ++#[cfg(test)]+#[path = "logmel_tests.rs"]+mod logmel_tests;
library/ml/src/main/rust/src/logmel_tests.rs
diff --git a/library/ml/src/main/rust/src/logmel_tests.rs b/library/ml/src/main/rust/src/logmel_tests.rsnew file mode 100644index 0000000000..953c76e2ec--- /dev/null+++ b/library/ml/src/main/rust/src/logmel_tests.rs@@ -0,0 +1,22 @@+//! LogMel tests: the default construction, the (initially zero)+//! magnitude spectrum, and silence in -> finite log-mel out.++use super::{frame_count, LogMel, BINS, MELS};++#[test]+fn a_default_logmel_starts_with_a_zero_magnitude() {+ let logmel = LogMel::default();+ assert_eq!(logmel.magnitude().len(), BINS);+ assert!(logmel.magnitude().iter().all(|&v| v == 0.0));+}++#[test]+fn silence_produces_finite_frames() {+ let mut logmel = LogMel::new();+ let samples = vec![0.0f32; 16_000];+ let mut out = Vec::new();+ let frames = logmel.spectrogram(&samples, &mut out);+ assert_eq!(frames, frame_count(samples.len()));+ assert_eq!(out.len(), frames * MELS);+ assert!(out.iter().all(|v| v.is_finite()), "silence must not produce NaN");+}
library/ml/src/main/rust/src/microfrontend.rs
diff --git a/library/ml/src/main/rust/src/microfrontend.rs b/library/ml/src/main/rust/src/microfrontend.rsindex 627b715849..ed1a107cad 100644--- a/library/ml/src/main/rust/src/microfrontend.rs+++ b/library/ml/src/main/rust/src/microfrontend.rs@@ -433,4 +433,7 @@ pub(crate) fn fft(data: &mut [[f32; 2]], twiddles: &[[f32; 2]], reversed: &[u32] } } -include!("microfrontend_part1.rs");\ No newline at end of file+include!("microfrontend_part1.rs");+#[cfg(test)]+#[path = "microfrontend_tests.rs"]+mod microfrontend_tests;
library/ml/src/main/rust/src/microfrontend_tests.rs
diff --git a/library/ml/src/main/rust/src/microfrontend_tests.rs b/library/ml/src/main/rust/src/microfrontend_tests.rsnew file mode 100644index 0000000000..d5d7be51dd--- /dev/null+++ b/library/ml/src/main/rust/src/microfrontend_tests.rs@@ -0,0 +1,58 @@+//! Microfrontend tests for the configuration refusals in the filter+//! bank and the front end constructor.++use super::{mel_breakpoints, Config, Frontend};++fn config() -> Config {+ Config {+ sample_rate: 16_000,+ window_samples: 400,+ hop_samples: 160,+ fft_size: 512,+ channels: 40,+ lower_band_limit: 125.0,+ upper_band_limit: 7_500.0,+ window_bits: 12,+ fft_gain: 1.0,+ log_correction_bits: 0,+ ceiling: f32::INFINITY,+ }+}++#[test]+fn the_filter_bank_refuses_degenerate_configs() {+ let mut bad = config();+ bad.fft_size = 0;+ assert!(mel_breakpoints(&bad).is_err(), "zero FFT");+ let mut bad = config();+ bad.channels = 0;+ assert!(mel_breakpoints(&bad).is_err(), "zero channels");+ // An empty mel band: upper at or below the lower edge.+ let mut bad = config();+ bad.upper_band_limit = bad.lower_band_limit;+ assert!(mel_breakpoints(&bad).is_err(), "empty band");+ // A band no FFT bin falls into: both edges above Nyquist's first bin.+ let mut bad = config();+ bad.lower_band_limit = 7_990.0;+ bad.upper_band_limit = 7_999.0;+ assert!(mel_breakpoints(&bad).is_err(), "no bin in band");+}++#[test]+fn the_frontend_refuses_bad_window_geometry_and_reports_its_channels() {+ let mut bad = config();+ bad.hop_samples = 0;+ assert!(Frontend::new(bad).is_err(), "zero hop");+ let mut bad = config();+ bad.window_samples = 0;+ assert!(Frontend::new(bad).is_err(), "zero window");+ let mut bad = config();+ bad.fft_size = 256; // power of two, but smaller than the 400-sample window+ assert!(Frontend::new(bad).is_err(), "FFT smaller than window");+ let mut bad = config();+ bad.fft_size = 500; // not a power of two+ bad.window_samples = 400;+ assert!(Frontend::new(bad).is_err(), "FFT not a power of two");+ let frontend = Frontend::new(config()).expect("a sane config builds");+ assert_eq!(frontend.channels(), 40);+}
library/ml/src/main/rust/src/nets/builder_validation_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/builder_validation_tests.rs b/library/ml/src/main/rust/src/nets/builder_validation_tests.rsnew file mode 100644index 0000000000..6bda5d5e73--- /dev/null+++ b/library/ml/src/main/rust/src/nets/builder_validation_tests.rs@@ -0,0 +1,451 @@+//! Builder validation tests: every `fail` path in the phase-1 builder+//! methods, exercised with shapes that violate exactly one rule, plus+//! the raw-offset conv entry point the graph lowerer uses. A builder+//! that accepted any of these would emit a plan whose pushes disagree+//! with its shapes, so each case asserts `finish` refuses.++use super::tests::Shapes;+use super::{Act, Builder, Id, Shape};+use crate::weights::{graph, write_mixed, Fixture, Weights};++/// Run `record` on a fresh builder over one input of `shape`; return+/// the error `finish` reports.+fn fails(shape: Shape, record: impl FnOnce(&mut Builder, Id) -> Id) -> String {+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let input = builder.input(shape);+ let out = record(&mut builder, input);+ builder.finish(&[out]).expect_err("the builder must refuse")+}++#[test]+fn elementwise_validations_refuse_bad_parameters() {+ // A standalone PReLU has no slope binding.+ assert!(fails(Shape::new(1, 1, 2), |b, x| b.activate(x, Act::PRelu(0))).contains("PRelu"));+ // A gated activation needs paired channels, and is not a PReLU either.+ assert!(fails(Shape::new(3, 1, 1), |b, x| b.gated_activate(x, Act::Relu)).contains("pair"));+ assert!(fails(Shape::new(2, 1, 1), |b, x| b.gated_activate(x, Act::PRelu(0))).contains("PRelu"));+ // Softcap and quantize need a positive constant.+ assert!(fails(Shape::new(1, 1, 1), |b, x| b.softcap(x, 0.0)).contains("softcap"));+ assert!(fails(Shape::new(1, 1, 1), |b, x| b.softcap(x, -1.0)).contains("softcap"));+ assert!(fails(Shape::new(1, 1, 1), |b, x| b.quantize(x, 0.0)).contains("quantize"));+}++#[test]+fn softmax_and_position_validations_refuse_bad_shapes() {+ // Softmax over an empty last axis, in all three modes.+ assert!(fails(Shape::new(1, 1, 0), |b, x| b.softmax(x)).contains("empty"));+ assert!(fails(Shape::new(1, 0, 0), |b, x| b.softmax_causal(x)).contains("empty"));+ assert!(fails(Shape::new(1, 1, 0), |b, x| b.softmax_prefix(x, false)).contains("empty"));+ // A causal map must be square.+ assert!(fails(Shape::new(1, 2, 3), |b, x| b.softmax_causal(x)).contains("attend"));+ // A key-bounded softmax needs 1..=w keys.+ assert!(fails(Shape::new(1, 1, 3), |b, x| b.softmax_keys(x, 0)).contains("keys"));+ assert!(fails(Shape::new(1, 1, 3), |b, x| b.softmax_keys(x, 4)).contains("keys"));+ // Cropping to nothing or past the end; padding below the width.+ assert!(fails(Shape::new(1, 1, 3), |b, x| b.crop_positions(x, 0)).contains("first"));+ assert!(fails(Shape::new(1, 1, 3), |b, x| b.crop_positions(x, 4)).contains("first"));+ assert!(fails(Shape::new(1, 1, 3), |b, x| b.pad_positions(x, 2)).contains("padded"));+ // A channel slice must be a non-empty in-range range.+ assert!(fails(Shape::new(3, 1, 1), |b, x| b.slice_channels(x, 2, 2)).contains("channels"));+ assert!(fails(Shape::new(3, 1, 1), |b, x| b.slice_channels(x, 0, 0)).contains("channels"));+ // A reshape may not change the element count.+ assert!(fails(Shape::new(1, 2, 2), |b, x| b.reshaped(x, Shape::new(1, 1, 3))).contains("reshaping"));+ // Max pooling needs even extents.+ assert!(fails(Shape::new(1, 3, 4), |b, x| b.max_pool_2x2(x)).contains("odd"));+}++#[test]+fn binary_and_concat_validations_refuse_mismatched_operands() {+ // Add of two different shapes (built with two inputs).+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(1, 1, 2));+ let c = builder.input(Shape::new(1, 1, 3));+ let out = builder.add(a, c);+ assert!(builder.finish(&[out]).is_err());++ // mul_channel's gate must be Cx1x1.+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(2, 1, 2));+ let c = builder.input(Shape::new(2, 1, 2));+ let out = builder.mul_channel(a, c);+ assert!(builder.finish(&[out]).is_err());++ // Concatenating nothing, and concatenating mismatched planes.+ assert!(fails(Shape::new(1, 1, 1), |b, _x| b.concat(&[])).contains("nothing"));+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(1, 2, 2));+ let c = builder.input(Shape::new(1, 3, 2));+ let out = builder.concat(&[a, c]);+ assert!(builder.finish(&[out]).is_err());+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(1, 1, 1));+ let out = builder.concat_positions(&[]);+ let _ = a;+ assert!(builder.finish(&[out]).is_err());+}++#[test]+fn cache_and_copy_validations_refuse_bad_targets() {+ // The row is not a whole number of cache positions.+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let row = builder.input(Shape::new(3, 1, 1));+ let cache = builder.persistent(Shape::new(2, 1, 2));+ builder.cache_write(row, cache);+ assert!(builder.finish(&[cache]).is_err());+ // A cache must be [positions, 1, d_model].+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let row = builder.input(Shape::new(2, 1, 1));+ let cache = builder.persistent(Shape::new(2, 2, 2));+ builder.cache_write(row, cache);+ assert!(builder.finish(&[cache]).is_err());+ // Copying into a non-persistent tensor, or a mismatched one.+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(1, 1, 2));+ let dst = builder.input(Shape::new(1, 1, 2));+ builder.copy_into(a, dst);+ assert!(builder.finish(&[dst]).is_err());+}++#[test]+fn norm_and_attention_validations_refuse_bad_head_counts() {+ // Grouped rms norm needs the groups to divide the channels.+ assert!(fails(Shape::new(3, 1, 1), |b, x| b.rms_norm_grouped(x, 0, 0.0, 2)).contains("groups")+ || fails(Shape::new(3, 1, 1), |b, x| b.rms_norm_grouped(x, 0, 0.0, 2)).contains("split"));+ // Attention scores need the heads to divide the channels.+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let q = builder.input(Shape::new(3, 1, 2));+ let k = builder.input(Shape::new(3, 1, 2));+ let out = builder.attn_scores(q, k, 2);+ assert!(builder.finish(&[out]).is_err());+ // Rotary needs a [d_model, 1, T] input whose channels split into heads.+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let x = builder.input(Shape::new(3, 1, 2));+ let angles = builder.input(Shape::new(3, 1, 2));+ let out = builder.rotary(x, angles, 2);+ assert!(builder.finish(&[out]).is_err());+}++#[test]+fn conv_validations_refuse_bad_groups_and_prelu_quantisation() {+ // Groups must divide both channel counts.+ assert!(fails(Shape::new(4, 1, 1), |b, x| {+ b.conv(x, 0, 4, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 3, Act::None)+ })+ .contains("groups"));+ // A quantised conv cannot carry a PReLU.+ let err = fails(Shape::new(2, 1, 1), |b, x| {+ b.conv_int8(x, 0, 2, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::PRelu(0))+ });+ assert!(err.contains("PRelu"), "actual error: {err}");+}++#[test]+fn finish_refuses_a_pass_with_no_input_or_no_output() {+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let input = builder.input(Shape::new(1, 1, 1));+ let _ = input;+ assert!(builder.finish(&[]).is_err(), "no output");+ let source = Shapes::new(16);+ let builder = Builder::new(&source);+ assert!(builder.finish(&[Id(0)]).is_err(), "no input");+}++#[test]+fn the_fp32_int4_flag_keeps_an_int4_conv_buildable() {+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I4(vec![1, 2, 1, 1], vec![1, 1]),+ Fixture::F16(vec![1, 1], vec![1.0]),+ Fixture::F16(vec![1], vec![0.0]),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let mut builder = Builder::new(&weights);+ builder.fp32_int4();+ let input = builder.input(Shape::new(2, 1, 1));+ let out = builder.conv_int4(input, 0, 1, Act::None);+ let plan = builder.finish(&[out]).expect("the fp32 path builds");+ let got = crate::nets::reference::run(&plan, weights.data(), &[3.0, 4.0]).expect("runs");+ assert_eq!(got, vec![7.0]);+}++#[test]+fn conv_raw_takes_resolved_offsets_directly() {+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[Fixture::F16(vec![1, 1, 1, 1], vec![2.0]), Fixture::F16(vec![1], vec![0.5])],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let weight = weights.shaped(0, &[1, 1, 1, 1]).expect("kernel").elem_offset();+ let bias = weights.shaped(1, &[1]).expect("bias").elem_offset();+ let mut builder = Builder::new(&weights);+ let input = builder.input(Shape::new(1, 1, 1));+ let out = builder.conv_raw(input, weight, bias, u32::MAX, 1, Act::None, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, false);+ builder.host_tensor(0, &[1, 1, 1, 1]);+ builder.host_tensor(1, &[1]);+ let plan = builder.finish(&[out]).expect("builds");+ let got = crate::nets::reference::run(&plan, weights.data(), &[3.0]).expect("runs");+ assert_eq!(got, vec![6.5]);+}++/// Run `record` on a fresh builder over two inputs; return the error.+fn fails2(+ q: Shape,+ k: Shape,+ record: impl FnOnce(&mut Builder, Id, Id) -> Id,+) -> String {+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let a = builder.input(q);+ let b = builder.input(k);+ let out = record(&mut builder, a, b);+ builder.finish(&[out]).expect_err("the builder must refuse")+}++use super::BandedScores;++#[test]+fn banded_attention_validations_refuse_bad_windows() {+ let valid = BandedScores { heads: 1, band: 2, table: 0, offsets: 3, scale: 1.0, cap: 30.0 };+ // Same sequence on both sides.+ assert!(fails2(Shape::new(4, 1, 3), Shape::new(2, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, valid)+ }).contains("same"));+ assert!(fails2(Shape::new(4, 2, 3), Shape::new(4, 2, 3), |b, q, k| {+ b.attn_scores_banded(q, k, valid)+ }).contains("[d_model, 1, T]"));+ // Heads must divide the channels.+ assert!(fails2(Shape::new(5, 1, 3), Shape::new(5, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, BandedScores { heads: 2, ..valid })+ }).contains("heads"));+ // The band is between one and the whole sequence.+ assert!(fails2(Shape::new(4, 1, 3), Shape::new(4, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, BandedScores { band: 0, offsets: 1, ..valid })+ }).contains("band"));+ assert!(fails2(Shape::new(4, 1, 3), Shape::new(4, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, BandedScores { band: 4, offsets: 5, ..valid })+ }).contains("band"));+ // Column j reads offset j + 1, so offsets must exceed the band.+ assert!(fails2(Shape::new(4, 1, 3), Shape::new(4, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, BandedScores { offsets: 2, ..valid })+ }).contains("offset"));+ // The fused logit cap must be positive.+ assert!(fails2(Shape::new(4, 1, 3), Shape::new(4, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, BandedScores { cap: 0.0, ..valid })+ }).contains("cap"));+ assert!(fails2(Shape::new(4, 1, 3), Shape::new(4, 1, 3), |b, q, k| {+ b.attn_scores_banded(q, k, BandedScores { cap: -2.0, ..valid })+ }).contains("cap"));+}++#[test]+fn attention_apply_validations_refuse_bad_operands() {+ // The value mix needs one row per query over the same sequence.+ assert!(fails2(Shape::new(2, 3, 3), Shape::new(4, 1, 4), |b, p, v| {+ b.attn_apply(p, v, 2)+ }).contains("match"));+ assert!(fails2(Shape::new(1, 2, 2), Shape::new(2, 2, 2), |b, p, v| {+ b.attn_apply(p, v, 1)+ }).contains("[d_model, 1, T]"));+ assert!(fails2(Shape::new(2, 2, 2), Shape::new(3, 1, 2), |b, p, v| {+ b.attn_apply(p, v, 2)+ }).contains("heads"));+ // The banded value mix reads its geometry off the probs shape.+ assert!(fails2(Shape::new(2, 2, 3), Shape::new(4, 1, 2), |b, p, v| {+ b.attn_apply_banded(p, v, 2, 4)+ }).contains("band"));+ assert!(fails2(Shape::new(2, 2, 3), Shape::new(4, 2, 2), |b, p, v| {+ b.attn_apply_banded(p, v, 2, 3)+ }).contains("value mix"));+ assert!(fails2(Shape::new(2, 1, 1), Shape::new(3, 1, 1), |b, p, v| {+ b.attn_apply_banded(p, v, 2, 1)+ }).contains("heads"));+ // The relative value mix needs a square map and a centred table.+ assert!(fails2(Shape::new(1, 2, 3), Shape::new(4, 1, 3), |b, p, v| {+ b.attn_apply_relative(p, v, 1, 0, 3)+ }).contains("same sequence"));+ assert!(fails2(Shape::new(1, 3, 3), Shape::new(4, 1, 3), |b, p, v| {+ b.attn_apply_relative(p, v, 1, 0, 2)+ }).contains("centre"));+ assert!(fails2(Shape::new(1, 3, 3), Shape::new(4, 1, 3), |b, p, v| {+ b.attn_apply_relative(p, v, 1, 0, 0)+ }).contains("centre"));+}++#[test]+fn cached_attention_validations_refuse_bad_geometry() {+ // A decode step's query is exactly one position.+ assert!(fails2(Shape::new(4, 1, 2), Shape::new(8, 1, 2), |b, q, c| {+ b.attn_scores_cached_grouped(q, c, 2, 1)+ }).contains("one query"));+ // The cache is [keys, 1, kv_heads * head_dim].+ assert!(fails2(Shape::new(4, 1, 1), Shape::new(8, 2, 2), |b, q, c| {+ b.attn_scores_cached_grouped(q, c, 2, 1)+ }).contains("cache is"));+ assert!(fails2(Shape::new(5, 1, 1), Shape::new(8, 1, 2), |b, q, c| {+ b.attn_scores_cached_grouped(q, c, 2, 1)+ }).contains("heads"));+ assert!(fails2(Shape::new(4, 1, 1), Shape::new(8, 1, 2), |b, q, c| {+ b.attn_scores_cached_grouped(q, c, 2, 3)+ }).contains("group into"));+ assert!(fails2(Shape::new(4, 1, 1), Shape::new(8, 1, 3), |b, q, c| {+ b.attn_scores_cached_grouped(q, c, 2, 1)+ }).contains("width should be"));+}++#[test]+fn quantised_convs_refuse_an_fp16_only_source_and_unsplittable_groups() {+ // The fp16 fixture's word view refuses: both quantised conv+ // builders surface that refusal at finish.+ let given = crate::nets::reference::Given::new(&[(vec![32], vec![0.0; 32])]).expect("given");+ let mut builder = Builder::new(&given);+ let x = builder.input(Shape::new(32, 1, 1));+ let out = builder.conv_int8(x, 0, 1, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+ let err = builder.finish(&[out]).expect_err("int8 over fp16");+ assert!(err.contains("holds no int8"), "{err}");++ let given = crate::nets::reference::Given::new(&[(vec![256], vec![0.0; 256])]).expect("given");+ let mut builder = Builder::new(&given);+ let x = builder.input(Shape::new(256, 1, 1));+ let out = builder.conv_q2k(x, 0, 1, Act::None);+ let err = builder.finish(&[out]).expect_err("q2k over fp16");+ assert!(err.contains("holds no int8"), "{err}");++ // 32 channels in 3 groups does not split.+ let source = Shapes::new(16);+ let mut builder = Builder::new(&source);+ let x = builder.input(Shape::new(32, 1, 1));+ let out = builder.conv_int8(x, 0, 1, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 3, Act::None);+ let err = builder.finish(&[out]).expect_err("unsplittable groups");+ assert!(err.contains("do not split into 3 groups"), "{err}");+}++#[test]+fn single_binding_accessors_require_exactly_one_binding() {+ // One input used as the only output: both accessors succeed.+ let source = Shapes::new(0);+ let mut builder = Builder::new(&source);+ let only = builder.input(Shape::new(1, 1, 2));+ let plan = builder.finish(&[only]).expect("builds");+ assert_eq!(plan.input().expect("one input").shape, Shape::new(1, 1, 2));+ assert_eq!(plan.output().expect("one output").shape, Shape::new(1, 1, 2));++ // Two inputs and two outputs: both accessors name the real count.+ let source = Shapes::new(0);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(1, 1, 2));+ let b = builder.input(Shape::new(1, 1, 2));+ let sum = builder.add(a, b);+ let plan = builder.finish(&[sum, a]).expect("builds");+ assert!(plan.input().expect_err("two inputs").contains("2 inputs, not one"));+ assert!(plan.output().expect_err("two outputs").contains("2 outputs, not one"));+}++#[test]+fn cached_apply_and_grouped_score_validations_refuse_bad_geometry() {+ // Probs not [heads, 1, keys].+ assert!(fails2(Shape::new(2, 2, 2), Shape::new(2, 1, 2), |b, p, c| {+ b.attn_apply_cached_grouped(p, c, 2, 2, false)+ }).contains("cached attention over probs"));+ // Key counts differ (cache channels c != probs width w).+ assert!(fails2(Shape::new(2, 1, 3), Shape::new(4, 1, 8), |b, p, c| {+ b.attn_apply_cached_grouped(p, c, 2, 2, false)+ }).contains("key counts differ"));+ // Query heads do not group into the KV heads.+ assert!(fails2(Shape::new(3, 1, 2), Shape::new(2, 1, 4), |b, p, c| {+ b.attn_apply_cached_grouped(p, c, 3, 2, false)+ }).contains("do not group into"));+ // Cache channels do not split across the KV heads.+ assert!(fails2(Shape::new(2, 1, 2), Shape::new(2, 1, 3), |b, p, c| {+ b.attn_apply_cached_grouped(p, c, 2, 2, false)+ }).contains("do not split into"));+ // Grouped score map: head grouping and head-dim agreement.+ assert!(fails2(Shape::new(4, 1, 2), Shape::new(4, 1, 2), |b, q, k| {+ b.attn_scores_grouped_prescaled(q, k, 3, 2)+ }).contains("do not group into"));+ assert!(fails2(Shape::new(4, 1, 2), Shape::new(6, 1, 2), |b, q, k| {+ b.attn_scores_grouped_prescaled(q, k, 2, 1)+ }).contains("attention over q"));+}++#[test]+fn copy_into_and_rotary_validations_refuse_bad_targets() {+ // Copying between different shapes.+ let source = Shapes::new(0);+ let mut builder = Builder::new(&source);+ let src = builder.input(Shape::new(1, 1, 2));+ let dst = builder.persistent(Shape::new(1, 1, 3));+ builder.copy_into(src, dst);+ assert!(builder.finish(&[src]).expect_err("shape mismatch").contains("copying"));++ // Copying into a tensor that is not persistent.+ let source = Shapes::new(0);+ let mut builder = Builder::new(&source);+ let src = builder.input(Shape::new(1, 1, 2));+ let dst = builder.input(Shape::new(1, 1, 2));+ builder.copy_into(src, dst);+ assert!(builder.finish(&[src]).expect_err("not persistent").contains("not persistent"));++ // Rotary over a non-sequence, over an unsplittable axis count,+ // and with an angle table of the wrong head width.+ assert!(fails2(Shape::new(4, 2, 2), Shape::new(4, 1, 2), |b, x, a| {+ b.rotary_axes(x, a, 1, 2)+ }).contains("a sequence is"));+ assert!(fails2(Shape::new(4, 1, 2), Shape::new(4, 1, 2), |b, x, a| {+ b.rotary_axes(x, a, 1, 3)+ }).contains("does not divide"));+ assert!(fails2(Shape::new(4, 1, 2), Shape::new(2, 1, 2), |b, x, a| {+ b.rotary_axes(x, a, 1, 2)+ }).contains("the table is"));+}++#[test]+fn a_broadcast_shift_folds_into_an_int8_conv_but_not_into_a_norm() {+ // conv_int8 -> add_channel: the per-channel shift folds into the+ // convolution's store, leaving one dispatch with shift set.+ let source = Shapes::new(3);+ let mut builder = Builder::new(&source);+ let x = builder.input(Shape::new(32, 1, 2));+ let shift = builder.input(Shape::new(2, 1, 1));+ let conv = builder.conv_int8(x, 0, 2, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None);+ let out = builder.add_channel(conv, shift);+ let plan = builder.finish(&[out]).expect("builds");+ let dispatches: Vec<_> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ crate::nets::Op::Dispatch { kind, push, .. } => Some((kind, push)),+ _ => None,+ })+ .collect();+ assert_eq!(dispatches.len(), 1, "the shift folded: {:?}", plan.ops);+ assert_ne!(dispatches[0].1.shift, crate::nets::NO_FUSE, "the folded shift is addressed");++ // rms_norm -> add_channel: a norm has no shift slot, so the fold+ // is refused and both dispatches survive.+ let source = Shapes::new(1);+ let mut builder = Builder::new(&source);+ let x = builder.input(Shape::new(2, 1, 2));+ let shift = builder.input(Shape::new(2, 1, 1));+ let norm = builder.rms_norm(x, 0, 0.0);+ let out = builder.add_channel(norm, shift);+ let plan = builder.finish(&[out]).expect("builds");+ let count = plan+ .ops+ .iter()+ .filter(|op| matches!(op, crate::nets::Op::Dispatch { .. }))+ .count();+ assert_eq!(count, 2, "the norm keeps its separate add: {:?}", plan.ops);+}
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 5565265821..2018ad4707 100644--- a/library/ml/src/main/rust/src/nets/gemma4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4.rs@@ -438,4 +438,10 @@ include!("gemma4_part6.rs"); include!("gemma4_part7.rs"); include!("gemma4_part8.rs"); include!("gemma4_part9.rs");-include!("gemma4_part10.rs");\ No newline at end of file+include!("gemma4_part10.rs");++#[cfg(test)]+#[path = "gemma4_tier_tests.rs"]+mod gemma4_tier_tests;+#[cfg(test)] #[path = "gemma4_gather_host_tests.rs"] mod gemma4_gather_host_tests;+#[cfg(test)] #[path = "gemma4_build_tests.rs"] mod gemma4_build_tests;\ No newline at end of file
library/ml/src/main/rust/src/nets/gemma4_build_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_build_tests.rs b/library/ml/src/main/rust/src/nets/gemma4_build_tests.rsnew file mode 100644index 0000000000..21a1521832--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_build_tests.rs@@ -0,0 +1,34 @@+//! Gemma 4 pass-shape refusal tests: cache tiers, trace depth, and+//! prefill extents, all of which fire before a single tensor is read.++use super::{build, Mode, CONTEXT_TIERS, LAYERS};+use crate::nets::tests::Shapes;++#[test]+fn a_cache_length_that_is_no_tier_is_refused() {+ let err = build(&Shapes::new(0), Mode::DecodeStep.at(1000)).expect_err("not a tier");+ assert!(err.contains("a cache of 1000 positions"), "{err}");+ // Every real tier is admitted (the build then fails on the empty+ // source, which is a different refusal).+ for tier in CONTEXT_TIERS {+ let err = build(&Shapes::new(0), Mode::DecodeStep.at(tier)).expect_err("no tensors");+ assert!(!err.contains("not one of the tiers"), "tier {tier}: {err}");+ }+}++#[test]+fn trace_and_prefill_extents_are_refused() {+ let context = CONTEXT_TIERS[0];+ let err = build(&Shapes::new(0), Mode::Trace { layers: LAYERS + 1 }.at(context))+ .expect_err("trace too deep");+ assert!(err.contains("a trace of"), "{err}");+ let err = build(&Shapes::new(0), Mode::Prefill { tokens: 0 }.at(context))+ .expect_err("empty prefill");+ assert!(err.contains("a prefill of no positions"), "{err}");+ let err = build(&Shapes::new(0), Mode::Prefill { tokens: context + 1 }.at(context))+ .expect_err("prefill past the cache");+ assert!(err.contains("past a"), "{err}");+ let err = build(&Shapes::new(0), Mode::PrefillFresh { tokens: 0 }.at(context))+ .expect_err("empty fresh prefill");+ assert!(err.contains("a prefill of no positions"), "{err}");+}
library/ml/src/main/rust/src/nets/gemma4_gather_host_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_gather_host_tests.rs b/library/ml/src/main/rust/src/nets/gemma4_gather_host_tests.rsnew file mode 100644index 0000000000..02c4a84f1a--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_gather_host_tests.rs@@ -0,0 +1,94 @@+//! Gemma 4 host-gather refusal tests: the vocabulary bound and the+//! soft-hidden length check, both of which fire before any table+//! read, so an empty file is a valid fixture.++use super::{gather, gather_soft, D_MODEL, VOCAB};+use crate::weights::Weights;++#[test]+fn gather_refuses_a_token_past_the_vocabulary() {+ let weights = Weights::from_data(Vec::new());+ let err = gather(&weights.reader(), VOCAB).expect_err("past vocab");+ assert!(err.contains("past the"), "{err}");+ // The largest valid token still refuses here, but on the missing+ // table rather than the bound โ a different error entirely.+ let err = gather(&weights.reader(), VOCAB - 1).expect_err("no table");+ assert!(!err.contains("past the"), "{err}");+}++#[test]+fn gather_soft_refuses_a_hidden_state_of_the_wrong_width() {+ let weights = Weights::from_data(Vec::new());+ let err = gather_soft(&weights.reader(), &[1.0], 0).expect_err("wrong width");+ assert!(err.contains(&format!("not {D_MODEL}")), "{err}");+ let wide = vec![0.0f32; D_MODEL as usize + 1];+ assert!(gather_soft(&weights.reader(), &wide, 0).is_err(), "too wide is also refused");+}++#[test]+fn the_input_wrappers_delegate_to_the_same_refusals() {+ use super::{gather_input, gather_soft_input};+ let weights = Weights::from_data(Vec::new());+ // Unfused gather_input is gather itself: the vocabulary bound fires.+ let err = gather_input(&weights.reader(), VOCAB, false).expect_err("past vocab");+ assert!(err.contains("past the"), "{err}");+ // Unfused gather_soft_input checks the hidden width first.+ let err = gather_soft_input(&weights.reader(), &[1.0], 0, false).expect_err("wrong width");+ assert!(err.contains(&format!("not {D_MODEL}")), "{err}");+}++#[test]+fn row_gathering_admits_empty_and_zero_table_requests() {+ use crate::nets::gemma4_gather::{leading_layer_rows, token_rows};+ let weights = Weights::from_data(Vec::new());+ // No tokens: an empty block, and no table is ever consulted.+ assert!(token_rows(&weights.reader(), &[]).expect("empty").is_empty());+ // Zero tables requested: the block is allocated at full width+ // and left zeroed, again without a read.+ let block = leading_layer_rows(&weights.reader(), &[5, 5], 0).expect("zero tables");+ assert!(!block.is_empty());+ assert!(block.iter().all(|&v| v == 0.0));+}++#[test]+fn token_rows_refuses_a_token_past_the_vocabulary() {+ use crate::nets::gemma4_gather::{layer_rows, token_rows};+ let weights = Weights::from_data(Vec::new());+ let err = token_rows(&weights.reader(), &[VOCAB]).expect_err("past vocab");+ assert!(err.contains("past the"), "{err}");+ // No tokens at all: the per-layer gather is an empty block too.+ assert!(layer_rows(&weights.reader(), &[]).expect("empty").is_empty());+}++#[test]+fn leading_layer_rows_reads_only_the_tables_asked_for() {+ use super::embed;+ use crate::nets::gemma4_gather::leading_layer_rows;+ use crate::weights::{graph, write_mixed, Fixture, Weights};+ // Table 0 raw 1s at scale 1.0: token 3's row is all 1.0, placed+ // in the first table's slab; the other 34 slabs stay zero.+ let first = embed::table(0);+ let mut fixtures: Vec<Fixture> = Vec::new();+ for i in 0..=(first + 1) {+ if i == first {+ fixtures.push(Fixture::I4(+ vec![VOCAB, super::PER_LAYER],+ vec![1i8; (VOCAB * super::PER_LAYER) as usize],+ ));+ } else if i == first + 1 {+ fixtures.push(Fixture::F16(+ vec![VOCAB, super::PER_LAYER / 32],+ vec![1.0; (VOCAB * super::PER_LAYER / 32) as usize],+ ));+ } else {+ fixtures.push(Fixture::F16(vec![1], vec![0.0]));+ }+ }+ let blob = write_mixed(graph::GEMMA4_EMBED, &fixtures);+ let weights = Weights::parse(&blob, graph::GEMMA4_EMBED).expect("parses");+ let block = leading_layer_rows(&weights.reader(), &[3], 1).expect("one table");+ let wide = super::PER_LAYER as usize;+ assert_eq!(block.len(), wide * super::LAYERS);+ assert!(block[..wide].iter().all(|&v| (v - 1.0).abs() < 1e-3), "the read slab");+ assert!(block[wide..].iter().all(|&v| v == 0.0), "the unread slabs stay zero");+}
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 36d2603a71..28c99f55bf 100644--- a/library/ml/src/main/rust/src/nets/gemma4_head.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_head.rs@@ -301,6 +301,8 @@ pub fn dims_of(index: usize) -> Vec<u32> { } } +#[cfg(test)] #[path = "gemma4_head_tests.rs"] mod gemma4_head_tests;+ #[cfg(test)] mod tests { use super::*;
library/ml/src/main/rust/src/nets/gemma4_head_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_head_tests.rs b/library/ml/src/main/rust/src/nets/gemma4_head_tests.rsnew file mode 100644index 0000000000..7e2f6145ff--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_head_tests.rs@@ -0,0 +1,24 @@+//! Gemma 4 head-plan tests: the greedy variant appends the+//! on-device argmax to the sixteen chunk outputs, in both the+//! fp16 and int8 chunk passes.++use super::{build_plan, build_plan_greedy, HEAD_CHUNKS, TENSORS_WITH_HEAD, TENSORS_WITH_HEAD8};+use crate::nets::tests::Shapes;++#[test]+fn the_greedy_fp16_head_appends_one_argmax_output() {+ let plan = build_plan_greedy(&Shapes::new(TENSORS_WITH_HEAD)).expect("greedy builds");+ assert_eq!(plan.outputs.len(), HEAD_CHUNKS + 1, "chunks plus the winning id");+ let plain = build_plan(&Shapes::new(TENSORS_WITH_HEAD)).expect("builds");+ assert_eq!(plain.outputs.len(), HEAD_CHUNKS);+ // The greedy tail is a single extra output past the chunks.+ assert_eq!(plan.outputs[..HEAD_CHUNKS], plain.outputs[..]);+}++#[test]+fn the_greedy_int8_head_appends_one_argmax_output() {+ let plan = build_plan_greedy(&Shapes::new(TENSORS_WITH_HEAD8)).expect("greedy builds");+ assert_eq!(plan.outputs.len(), HEAD_CHUNKS + 1);+ let plain = build_plan(&Shapes::new(TENSORS_WITH_HEAD8)).expect("builds");+ assert_eq!(plain.outputs.len(), HEAD_CHUNKS);+}
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 5c8fdc4b36..d2988a9bf8 100644--- a/library/ml/src/main/rust/src/nets/gemma4_part4.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_part4.rs@@ -423,6 +423,44 @@ mod combine_cache_tests { assert!(embed::carries_combine(&reader)); } + #[test]+ fn the_cached_wrapper_agrees_with_the_reread_path() {+ // Same fixture shape as above; the wrapper under test is the+ // one the bridge calls, flag and all.+ const PROJ: usize = LAYERS * PER_LAYER as usize * D_MODEL as usize;+ let blob = crate::weights::write_mixed(+ crate::weights::graph::GEMMA4_EMBED,+ &[+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::I8(+ vec![LAYERS as u32 * PER_LAYER, D_MODEL, 1, 1],+ (0..PROJ).map(|i| (i % 15) as i8 - 7).collect(),+ ),+ crate::weights::Fixture::F16(+ vec![LAYERS as u32 * PER_LAYER],+ vec![1.0; LAYERS * PER_LAYER as usize],+ ),+ crate::weights::Fixture::F16(vec![1], vec![0.0]),+ crate::weights::Fixture::F16(vec![PER_LAYER], vec![1.0; PER_LAYER as usize]),+ ],+ );+ let weights = crate::weights::Weights::parse(&blob, crate::weights::graph::GEMMA4_EMBED)+ .expect("the combine fixture parses");+ let reader = weights.reader();+ let hidden: Vec<f32> = (0..D_MODEL as usize).map(|i| (i % 7) as f32 * 0.125).collect();+ let embedded: Vec<f32> =+ (0..LAYERS * PER_LAYER as usize).map(|i| (i % 11) as f32 * 0.0625).collect();+ let want = combine_timed(&reader, &hidden, &embedded, false).expect("reread").0;+ let got = combine_cached(&reader, &hidden, &embedded).expect("the wrapper runs");+ assert_eq!(got, want);+ // A second call through the wrapper serves the same bytes+ // (a cache hit whenever the flag is on, a re-read otherwise).+ let again = combine_cached(&reader, &hidden, &embedded).expect("the wrapper runs again");+ assert_eq!(again, want);+ }+ #[test] fn a_slim_embed_keeps_every_index_and_carries_neither_combine_nor_head() { assert_eq!(embed::SLIM_TENSORS, 112);
library/ml/src/main/rust/src/nets/gemma4_tier_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/gemma4_tier_tests.rs b/library/ml/src/main/rust/src/nets/gemma4_tier_tests.rsnew file mode 100644index 0000000000..32eb7e8328--- /dev/null+++ b/library/ml/src/main/rust/src/nets/gemma4_tier_tests.rs@@ -0,0 +1,32 @@+//! Tier arithmetic tests: which KV-cache context tier a byte budget+//! buys, and the ladder between tiers. Expectations restate+//! `CONTEXT_TIERS` against `BYTES_PER_POSITION` directly.++use super::{next_tier, tier_for, BYTES_PER_POSITION, CONTEXT_TIERS};++fn cost(tier: u32) -> u64 {+ tier as u64 * BYTES_PER_POSITION as u64+}++#[test]+fn a_budget_buys_the_largest_tier_it_fully_fits() {+ // Nothing fits: the smallest tier is the floor, not zero.+ assert_eq!(tier_for(0), CONTEXT_TIERS[0]);+ assert_eq!(tier_for(cost(CONTEXT_TIERS[0]) - 1), CONTEXT_TIERS[0]);+ // An exact fit buys that tier; one byte short falls back.+ assert_eq!(tier_for(cost(2048)), 2048);+ assert_eq!(tier_for(cost(4096) - 1), 2048);+ assert_eq!(tier_for(cost(4096)), 4096);+ // Past the top, the top is what you get.+ assert_eq!(tier_for(u64::MAX), *CONTEXT_TIERS.last().unwrap());+}++#[test]+fn the_next_tier_is_the_first_above_wherever_you_stand() {+ assert_eq!(next_tier(0), Some(CONTEXT_TIERS[0]));+ assert_eq!(next_tier(1024), Some(2048));+ assert_eq!(next_tier(1025), Some(2048));+ assert_eq!(next_tier(8192), Some(16_384));+ assert_eq!(next_tier(16_384), None);+ assert_eq!(next_tier(u32::MAX), None);+}
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.rsindex 1e4cf2a4b4..339e4156b0 100644--- a/library/ml/src/main/rust/src/nets/gemma4_vision_tests.rs+++ b/library/ml/src/main/rust/src/nets/gemma4_vision_tests.rs@@ -70,3 +70,85 @@ fn a_trace_past_the_tower_is_refused() { .expect_err("a trace deeper than the tower"); assert!(error.contains("layers"), "unexpected error: {error}"); }++#[test]+fn exported_kernel_shapes_swap_the_first_two_axes() {+ assert_eq!(as_exported(&[1536, 768, 1, 1]), vec![768, 1536]);+ assert_eq!(as_exported(&[768]), vec![768]);+ assert_eq!(as_exported(&[3, 3]), vec![3, 3]);+}++#[test]+fn an_image_grid_scales_to_the_budget_and_rounds_down() {+ // Budget 280: at most 2520 patches. 800x600 scales by ~1.16, then+ // each side rounds down to a multiple of 48: 912x672 px.+ let grid = Grid::for_image(800, 600, 280).expect("a grid");+ assert_eq!((grid.rows, grid.cols), (42, 57));+ assert_eq!(grid.patches(), 42 * 57);+ assert_eq!(grid.soft_tokens(), 266);+ assert_eq!(grid.pixels(), (912, 672));+ // A sliver keeps one 48px block on the short side and is capped+ // on the long one, landing exactly on the budget.+ let grid = Grid::for_image(100_000, 100, 70).expect("a sliver");+ assert_eq!((grid.rows, grid.cols), (3, 210));+ assert_eq!(grid.soft_tokens(), 70);+ let grid = Grid::for_image(100, 100_000, 70).expect("a sliver");+ assert_eq!((grid.rows, grid.cols), (210, 3));+}++#[test]+fn image_grid_refusals_name_the_fault() {+ assert!(Grid::for_image(800, 600, 71).expect_err("budget").contains("soft tokens"));+ assert!(Grid::for_image(0, 600, 280).expect_err("zero width").contains("0x600"));+ assert!(Grid::for_image(800, 0, 280).expect_err("zero height").contains("800x0"));+ assert!(Grid::new(0, 3).is_err(), "no rows");+ assert!(Grid::new(4, 3).is_err(), "rows not divisible by the pooling kernel");+ assert!(Grid::new(300, 300).is_err(), "past the largest budget's patch ceiling");+}++#[test]+fn prepare_sums_the_column_and_row_position_tables() {+ use crate::weights::{graph, write_mixed, Fixture, Weights};+ // Column table raw 1s, row table raw 2s, both scaled by 1.0, so+ // every position value is 1.0 + 2.0 = 3.0. All other tensors are+ // one-element placeholders; the two tables are the only real data.+ let mut fixtures: Vec<Fixture> = Vec::new();+ for i in 0..=(ROW_POSITIONS + 1) {+ if i == COLUMN_POSITIONS {+ fixtures.push(Fixture::I4(+ vec![POSITIONS, D_MODEL, 1, 1],+ vec![1i8; (POSITIONS * D_MODEL) as usize],+ ));+ } else if i == COLUMN_POSITIONS + 1 || i == ROW_POSITIONS + 1 {+ fixtures.push(Fixture::F16(+ vec![POSITIONS, D_MODEL / 32],+ vec![1.0; (POSITIONS * (D_MODEL / 32)) as usize],+ ));+ } else if i == ROW_POSITIONS {+ fixtures.push(Fixture::I4(+ vec![POSITIONS, D_MODEL, 1, 1],+ vec![2i8; (POSITIONS * D_MODEL) as usize],+ ));+ } else {+ fixtures.push(Fixture::F16(vec![1], vec![0.0]));+ }+ }+ let blob = write_mixed(graph::SUPERTONIC_VE, &fixtures);+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let grid = Grid::new(3, 3).expect("a grid");+ // Solid red: R byte 255, G and B zero.+ let pixels = vec![0x00FF_0000i32; 48 * 48];+ let [patchified, positions, angles] =+ prepare(&weights.reader(), grid, &pixels).expect("prepares");+ // 9 patches padded to 16 columns in every input.+ assert_eq!(patchified.len(), (D_MODEL * 16) as usize);+ assert_eq!(positions.len(), (D_MODEL * 16) as usize);+ assert_eq!(angles.len(), (HEAD_DIM * 16) as usize);+ // Channel-major with the pad after each channel's 9 real patches.+ assert!((patchified[0] - 1.0).abs() < 1e-3, "red channel of patch 0");+ assert!((patchified[16] + 1.0).abs() < 1e-3, "green channel of patch 0");+ assert!((positions[0] - 3.0).abs() < 1e-3, "first position value");+ assert!((positions[8] - 3.0).abs() < 1e-3, "last real patch of channel 0");+ assert_eq!(positions[9], 0.0, "the padding is zero");+ assert!(angles.iter().all(|v| v.is_finite()));+}
library/ml/src/main/rust/src/nets/kind_reads_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/kind_reads_tests.rs b/library/ml/src/main/rust/src/nets/kind_reads_tests.rsnew file mode 100644index 0000000000..9ad22b8823--- /dev/null+++ b/library/ml/src/main/rust/src/nets/kind_reads_tests.rs@@ -0,0 +1,154 @@+//! Tests for `Kind::weight_reads` and `Kind::arena_reads`: the exact+//! read tables the segmenter and the barrier scheduler trust. Each+//! expectation is stated from the shader contract in the table's own+//! docs โ fp16-element vs 32-bit-word addressing, and the arena ranges+//! an op's operands occupy.++use super::{Act, Kind, Push, Reads, NO_FUSE};++fn push() -> Push {+ Push {+ in0: 100,+ in1: 200,+ out: 300,+ weight: 10,+ bias: 20,+ act_weight: 30,+ in_c: 4,+ in_h: 2,+ in_w: 3,+ out_c: 5,+ out_h: 2,+ out_w: 3,+ group: 2,+ count: 7,+ res: NO_FUSE,+ shift: NO_FUSE,+ ..Push::default()+ }+}++fn fields(kind: Kind, p: &Push) -> Vec<(&'static str, u64)> {+ kind.weight_reads(p).iter().map(|r| (r.field, r.at)).collect()+}++#[test]+fn weight_reads_use_elements_for_fp16_and_words_for_quantised_kernels() {+ let p = push();+ // fp16 conv: kernel and bias in elements (x2 bytes).+ assert_eq!(fields(Kind::Conv, &p), vec![("weight", 20), ("bias", 40)]);+ assert_eq!(fields(Kind::ConvTranspose, &p), vec![("weight", 20), ("bias", 40)]);+ assert_eq!(fields(Kind::LayerNorm, &p), vec![("weight", 20), ("bias", 40)]);+ // Quantised kernels: kernel in words (x4), bias and scale in elements.+ for kind in [Kind::ConvInt8, Kind::ConvPointInt4, Kind::ConvQ2K, Kind::ConvVecInt8] {+ assert_eq!(+ fields(kind, &p),+ vec![("weight", 40), ("bias", 40), ("act_weight", 60)],+ "{kind:?}"+ );+ }+ // One-table kinds read only the weight.+ for kind in [Kind::RmsNorm, Kind::Constant, Kind::Embed, Kind::AttnScoresRelative] {+ assert_eq!(fields(kind, &p), vec![("weight", 20)], "{kind:?}");+ }+ // The scalar pair lives at act_weight.+ assert_eq!(fields(Kind::Clamp, &p), vec![("act_weight", 60)]);+ assert_eq!(fields(Kind::MulScalar, &p), vec![("act_weight", 60)]);+ // Arena-only kinds read no weights at all.+ for kind in [Kind::Softmax, Kind::Add, Kind::MaxPool, Kind::Argmax, Kind::Rotary, Kind::Activate] {+ assert!(fields(kind, &p).is_empty(), "{kind:?}");+ }+}++#[test]+fn a_prelu_activation_adds_its_slope_to_any_weight_reading_kind() {+ let mut p = push();+ p.act = Act::PRelu(0).code();+ // RmsNorm already reads its gamma; the slope is a second read.+ assert_eq!(fields(Kind::RmsNorm, &p), vec![("weight", 20), ("act_weight", 60)]);+ // A conv carrying PReLU gains the slope read alongside kernel and bias.+ assert_eq!(fields(Kind::Conv, &p), vec![("weight", 20), ("bias", 40), ("act_weight", 60)]);+ // An int8 conv already reads act_weight as its scale, so nothing is added twice.+ assert_eq!(fields(Kind::ConvInt8, &p).len(), 3);+ // A standalone activation reads no weights but does read its slope.+ assert_eq!(fields(Kind::Activate, &p), vec![("act_weight", 60)]);+}++fn ranges(kind: Kind, p: &Push) -> Vec<(u32, u32)> {+ match kind.arena_reads(p) {+ Reads::Ranges(r) => r,+ Reads::Unknown => panic!("{kind:?} should be audited"),+ }+}++#[test]+fn arena_reads_cover_both_operands_at_the_written_extent() {+ let p = push(); // written = 5*2*3 = 30, dense = 4*2*3 = 24+ assert_eq!(ranges(Kind::Add, &p), vec![(100, 30), (200, 30)]);+ assert_eq!(ranges(Kind::Mul, &p), vec![(100, 30), (200, 30)]);+ // The broadcast gate is one value per channel.+ assert_eq!(ranges(Kind::MulBroadcast, &p), vec![(100, 30), (200, 4)]);+ assert_eq!(ranges(Kind::AddBroadcast, &p), vec![(100, 30), (200, 5)]);+ // A constant copies out of the weights file and reads no arena.+ assert!(ranges(Kind::Constant, &p).is_empty());+ // Elementwise kinds read their whole input plane.+ assert_eq!(ranges(Kind::Softmax, &p), vec![(100, 24)]);+ assert_eq!(ranges(Kind::Clamp, &p), vec![(100, 24)]);+}++#[test]+fn arena_reads_for_attention_and_reductions_use_their_own_geometry() {+ let p = push();+ // Scores: Q is in_c x out_h, K is in_c x out_w.+ assert_eq!(ranges(Kind::AttnScores, &p), vec![(100, 8), (200, 12)]);+ // Argmax reads the whole row; its fold re-reads pairs plus the row.+ assert_eq!(ranges(Kind::Argmax, &p), vec![(100, 24)]);+ assert_eq!(ranges(Kind::ArgmaxFold, &p), vec![(100, 8), (200, 3)]);+ // Top-k stage 1 reads count; stage 2 reads candidate pairs and the row.+ let mut stage1 = push();+ stage1.kh = 0;+ assert_eq!(ranges(Kind::TopK, &stage1), vec![(100, 7)]);+ let mut stage2 = push();+ stage2.kh = 1;+ assert_eq!(ranges(Kind::TopK, &stage2), vec![(100, 8), (200, 3)]);+ // Embed reads one id per lane per position: in_c * out_w.+ assert_eq!(ranges(Kind::Embed, &p), vec![(100, 12)]);+ // The gated activation reads both halves: in_c + count.+ assert_eq!(ranges(Kind::GatedActivate, &p), vec![(100, 11)]);+}++#[test]+fn arena_reads_for_convolutions_add_fused_addends_only_when_fused() {+ let p = push();+ assert_eq!(ranges(Kind::Conv, &p), vec![(100, 24)]);+ let mut fused = push();+ fused.res = 400;+ fused.shift = 500;+ assert_eq!(ranges(Kind::Conv, &fused), vec![(100, 24), (400, 30), (500, 5)]);+ // RmsNorm folds only its residual, never a shift.+ assert_eq!(ranges(Kind::RmsNorm, &fused), vec![(100, 24), (400, 30)]);+ // The int4 dot read also covers the staged int8 blocks at kw:+ // in_c/8*5 * out_h*out_w = 0 here (in_c = 4), so use 32 channels.+ let mut dot = push();+ dot.in_c = 32;+ assert_eq!(ranges(Kind::ConvPointInt4Dot, &dot), vec![(100, 192), (0, 120)]);+}++#[test]+fn audited_reads_expose_ranges_and_shape_queries_record_their_asks() {+ use super::tests::{name_of, Shapes};+ use super::WeightSource as _;++ assert_eq!(Reads::Ranges(vec![(2, 3)]).ranges(), Some(&[(2, 3)][..]));+ assert_eq!(Reads::Unknown.ranges(), None);+ assert_eq!(name_of(Kind::ConvPoint), "Conv");+ assert_eq!(name_of(Kind::ConvPointInt8), "ConvInt8");+ assert_eq!(name_of(Kind::ConvVecInt4), "ConvInt4");+ assert_eq!(name_of(Kind::ConvPointQ2K), "ConvQ2K");+ assert_eq!(name_of(Kind::Softmax), "Softmax");++ let shapes = Shapes::new(3);+ assert_eq!(shapes.shaped_words(2, &[9]).expect("shape query"), 2);+ assert_eq!(shapes.count(), 3);+ assert_eq!(shapes.asked.borrow().as_slice(), &[(2, vec![9])]);+}
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.rsindex aeba892d70..409b090f46 100644--- a/library/ml/src/main/rust/src/nets/madlad_part1_tests.rs+++ b/library/ml/src/main/rust/src/nets/madlad_part1_tests.rs@@ -116,3 +116,36 @@ fn embedding_refuses_a_token_past_the_vocabulary_before_reading() { assert!(embed_positions(reader, &[256_000], 0).is_err(), "past the vocabulary"); assert!(embed_positions(reader, &[u32::MAX], 0).is_err()); }++#[test]+fn embedding_gathers_a_q2k_row_channel_major() {+ // Split 0's kernel: every lane of rows 0 and 63999 is (lo=0, hi=2)+ // with all q = 0 and (d, dmin) = (1, 1), so every tap dequantises+ // to -(dmin * d) * hi = -2. Both tokens must read as -2.0 across+ // all 1024 channels.+ let rows = CLASSES_PER_SPLIT as usize;+ let stride = (D_MODEL as usize / 256) * 84;+ let mut payload = vec![0u8; rows * stride];+ for row in [0, rows - 1] {+ for block in 0..D_MODEL as usize / 256 {+ let base = row * stride + block * 84;+ payload[base..base + 16].fill(0x20);+ }+ }+ let blob = crate::weights::write_mixed(+ crate::weights::graph::SUPERTONIC_VE,+ &[+ crate::weights::Fixture::Q2K(vec![CLASSES_PER_SPLIT, D_MODEL], payload),+ crate::weights::Fixture::F16(+ vec![CLASSES_PER_SPLIT * (D_MODEL / 256) * 2],+ vec![1.0; (CLASSES_PER_SPLIT * (D_MODEL / 256) * 2) as usize],+ ),+ ],+ );+ let weights = crate::weights::Weights::parse(&blob, crate::weights::graph::SUPERTONIC_VE)+ .expect("the embed fixture parses");+ let out = embed_positions(weights.reader(), &[0, 63_999], 0).expect("embeds");+ assert_eq!(out.len(), 2 * D_MODEL as usize);+ assert!(out.iter().all(|&v| (v + 2.0).abs() < 1e-3), "every channel is -2.0");+ assert!(embed_positions(weights.reader(), &[], 0).expect("empty").is_empty());+}
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 09b13f67a6..53db7bded1 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -494,4 +494,6 @@ include!("mod_part11.rs"); include!("mod_part12.rs"); include!("mod_part13.rs"); include!("mod_part14.rs");-include!("mod_part15.rs");\ No newline at end of file+include!("mod_part15.rs");+#[cfg(test)] #[path = "kind_reads_tests.rs"] mod kind_reads_tests;+#[cfg(test)] #[path = "builder_validation_tests.rs"] mod builder_validation_tests;
library/ml/src/main/rust/src/nets/mod_part2b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2b.rs b/library/ml/src/main/rust/src/nets/mod_part2b.rsindex e286ce61dc..0c234a1c30 100644--- a/library/ml/src/main/rust/src/nets/mod_part2b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2b.rs@@ -6,6 +6,11 @@ pub struct Builder<'a> { /// Tensors that must keep a stable offset for the whole pass: the inputs and the /// outputs. Everything else is free to be reused once its last reader has run. pinned: Vec<Id>,+ /// The subset of `pinned` declared through [`Builder::persistent`]: tensors whose+ /// contents survive between executions. Inputs are pinned too, but they are+ /// re-uploaded every execution, so only these may be a [`Builder::copy_into`]+ /// destination.+ persistent: Vec<Id>, error: Option<String>, inputs: Vec<Id>, /// One flag per tensor in the file, set when the pass reads it. See
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 4b5ffcba8c..33ca0b1594 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -7,6 +7,7 @@ impl<'a> Builder<'a> { shapes: Vec::new(), nodes: Vec::new(), pinned: Vec::new(),+ persistent: Vec::new(), error: None, inputs: Vec::new(), pad_edge: false,
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 a2eda27570..787048aeb4 100644--- a/library/ml/src/main/rust/src/nets/mod_part6.rs+++ b/library/ml/src/main/rust/src/nets/mod_part6.rs@@ -130,6 +130,7 @@ impl<'a> Builder<'a> { pub fn persistent(&mut self, shape: Shape) -> Id { let id = self.tensor(shape); self.pinned.push(id);+ self.persistent.push(id); id } @@ -166,7 +167,7 @@ impl<'a> Builder<'a> { if ss != sd { self.fail(format!("copying {ss:?} into {sd:?}")); }- if !self.pinned.contains(&dst) {+ if !self.persistent.contains(&dst) { self.fail("copying into a tensor that is not persistent".into()); } self.nodes.push(Node::Concat { parts: vec![src], out: dst });
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 a8eba1b22f..af948ca9be 100644--- a/library/ml/src/main/rust/src/nets/nllb.rs+++ b/library/ml/src/main/rust/src/nets/nllb.rs@@ -445,3 +445,5 @@ pub(crate) fn split_of(id: u32) -> (usize, u32) { } } include!("nllb_part1.rs");++#[cfg(test)] #[path = "nllb_embed_tests.rs"] mod nllb_embed_tests;
library/ml/src/main/rust/src/nets/nllb_embed_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/nllb_embed_tests.rs b/library/ml/src/main/rust/src/nets/nllb_embed_tests.rsnew file mode 100644index 0000000000..b783efbf4c--- /dev/null+++ b/library/ml/src/main/rust/src/nets/nllb_embed_tests.rs@@ -0,0 +1,53 @@+//! NLLB host-embedding tests: the vocabulary refusal, an empty+//! sequence, and the sinusoidal position table's two halves.++use super::{embed_positions, sinusoid, VOCAB};+use crate::weights::Weights;++#[test]+fn embed_refuses_a_token_past_the_vocabulary_and_admits_no_tokens() {+ let weights = Weights::from_data(Vec::new());+ let err = embed_positions(weights.reader(), &[VOCAB], 0).expect_err("past vocab");+ assert!(err.contains("past the 256206-entry vocabulary"), "{err}");+ assert!(embed_positions(weights.reader(), &[], 0).expect("empty").is_empty());+}++#[test]+fn the_sinusoid_is_sines_then_cosines_over_the_same_angles() {+ // Channel 0 is the first sine at angle = position; channel 512+ // (D_MODEL / 2) is the first cosine of that same angle.+ let angle = 2.0f32;+ assert!((sinusoid(2, 0) - angle.sin()).abs() < 1e-6);+ assert!((sinusoid(2, 512) - angle.cos()).abs() < 1e-6);+ // Position 0 zeroes every sine and sets every cosine to 1.+ assert_eq!(sinusoid(0, 0), 0.0);+ assert_eq!(sinusoid(0, 511), 0.0);+ assert_eq!(sinusoid(0, 512), 1.0);+ assert_eq!(sinusoid(0, 1023), 1.0);+}++#[test]+fn an_embedded_token_is_scaled_and_positioned() {+ use super::D_MODEL;+ use crate::weights::{graph, write_mixed, Fixture, Weights};+ // Split 0's kernel: every tap 1 at scale 1.0, so a token embeds+ // as sqrt(1024) = 32 per channel, plus the sinusoid at its+ // position (past 0 + index 0 + 1 + padding 1 = position 2).+ let classes = super::split_classes(0);+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I8(vec![classes, D_MODEL, 1, 1], vec![1i8; (classes * D_MODEL) as usize]),+ Fixture::F16(vec![classes], vec![1.0; classes as usize]),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let out = embed_positions(weights.reader(), &[0], 0).expect("embeds");+ assert_eq!(out.len(), D_MODEL as usize);+ let (sin2, cos2) = (2.0f32.sin(), 2.0f32.cos());+ assert!((out[0] - (32.0 + sin2)).abs() < 1e-3, "first sine channel: {}", out[0]);+ assert!((out[512] - (32.0 + cos2)).abs() < 1e-3, "first cosine channel: {}", out[512]);+ // A step far enough into the sequence runs off the position table.+ let err = embed_positions(weights.reader(), &[0], super::MAX_POSITIONS).expect_err("too far");+ assert!(err.contains("past the model's table"), "{err}");+}
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 924474431c..619f3f8c6a 100644--- a/library/ml/src/main/rust/src/nets/ppocr_det.rs+++ b/library/ml/src/main/rust/src/nets/ppocr_det.rs@@ -297,6 +297,8 @@ fn head_branch(b: &mut Builder, l: &mut Layers, x: Id) -> Id { residual_excite(b, l, narrowed, 6) } +#[cfg(test)] #[path = "ppocr_det_tests.rs"] mod ppocr_det_tests;+ #[cfg(test)] mod tests { use super::super::tests::Shapes;
library/ml/src/main/rust/src/nets/ppocr_det_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_det_tests.rs b/library/ml/src/main/rust/src/nets/ppocr_det_tests.rsnew file mode 100644index 0000000000..4fa0495174--- /dev/null+++ b/library/ml/src/main/rust/src/nets/ppocr_det_tests.rs@@ -0,0 +1,23 @@+//! PP-OCR detection builder tests: the backbone-exposing variant+//! and the input-extent refusals.++use super::{build, build_with_backbone, TENSORS};+use crate::nets::tests::Shapes;++#[test]+fn the_backbone_variant_reports_both_outputs() {+ let plan = build_with_backbone(&Shapes::new(TENSORS), 64, 64).expect("builds");+ assert_eq!(plan.outputs.len(), 2, "probability map and backbone output");+ let plain = build(&Shapes::new(TENSORS), 64, 64).expect("builds");+ assert_eq!(plain.outputs.len(), 1);+}++#[test]+fn bad_extents_are_refused() {+ let err = build(&Shapes::new(TENSORS), 0, 64).expect_err("zero height");+ assert!(err.contains("64x0"), "{err}");+ let err = build(&Shapes::new(TENSORS), 64, 0).expect_err("zero width");+ assert!(err.contains("0x64"), "{err}");+ let err = build(&Shapes::new(TENSORS), 63, 64).expect_err("not a multiple");+ assert!(err.contains("multiple of 32"), "{err}");+}
library/ml/src/main/rust/src/nets/ppocr_rec_batch_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/ppocr_rec_batch_tests.rs b/library/ml/src/main/rust/src/nets/ppocr_rec_batch_tests.rsnew file mode 100644index 0000000000..f1e9f0e325--- /dev/null+++ b/library/ml/src/main/rust/src/nets/ppocr_rec_batch_tests.rs@@ -0,0 +1,22 @@+//! PP-OCR recogniser batch tests: several crops in one plan, and+//! the width/line-count refusals.++use super::build_batch;+use crate::nets::ppocr_rec::TENSORS;+use crate::nets::tests::Shapes;++#[test]+fn a_batch_builds_one_pass_per_line() {+ let plan = build_batch(&Shapes::new(TENSORS), 64, 3).expect("builds");+ assert_eq!(plan.inputs.len(), 3);+ assert_eq!(plan.outputs.len(), 3);+ let one = build_batch(&Shapes::new(TENSORS), 64, 1).expect("builds");+ assert_eq!(one.inputs.len(), 1);+}++#[test]+fn a_batch_refuses_bad_widths_and_empty_batches() {+ assert!(build_batch(&Shapes::new(TENSORS), 0, 1).is_err(), "zero width");+ assert!(build_batch(&Shapes::new(TENSORS), 63, 1).is_err(), "not a multiple of 8");+ assert!(build_batch(&Shapes::new(TENSORS), 64, 0).is_err(), "no lines");+}
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 296d7690a5..8e32a7fbcb 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@@ -130,3 +130,7 @@ fn chain(b: &mut Builder, input: Id) -> Result<Id, String> { } Ok(logits) }++#[cfg(test)]+#[path = "ppocr_rec_batch_tests.rs"]+mod ppocr_rec_batch_tests;
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 9ebebc4c98..e618ad2add 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -191,3 +191,11 @@ include!("reference_part10.rs"); #[cfg(test)] #[path = "reference_tests.rs"] mod reference_tests;++#[cfg(test)]+#[path = "reference_ops_tests.rs"]+mod reference_ops_tests;++#[cfg(test)]+#[path = "reference_ops_mutated_tests.rs"]+mod reference_ops_mutated_tests;
library/ml/src/main/rust/src/nets/reference_ops_mutated_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_ops_mutated_tests.rs b/library/ml/src/main/rust/src/nets/reference_ops_mutated_tests.rsnew file mode 100644index 0000000000..cf3abe4810--- /dev/null+++ b/library/ml/src/main/rust/src/nets/reference_ops_mutated_tests.rs@@ -0,0 +1,347 @@+//! Reference-interpreter tests for hand-corrupted plans and the+//! geometry refusals only a mutated push can reach, plus the fused+//! residual stores. Split from `reference_ops_tests.rs` to keep+//! both files under the repository's line limit.++use super::{run, run_multi, run_multi_at, Given};+use crate::nets::{Act, Builder, Shape};+use crate::weights::{graph, write_mixed, Fixture, Weights};++fn close(got: &[f32], want: &[f32]) {+ assert_eq!(got.len(), want.len(), "length: got {got:?}, want {want:?}");+ for (g, w) in got.iter().zip(want) {+ assert!((g - w).abs() < 1e-3, "got {got:?}, want {want:?}");+ }+}++#[test]+fn the_reference_refuses_an_attention_with_no_head_dimension() {+ // Channels zeroed under a head count: the split gives a head+ // dimension of zero, which the helper refuses by name.+ let err = mutated(&[], &[&[1.0; 8], &[1.0; 8]], |b| {+ let q = b.input(Shape::new(4, 1, 2));+ let k = b.input(Shape::new(4, 1, 2));+ b.attn_scores(q, k, 1)+ }, |p| p.in_c = 0).expect_err("no head dimension");+ assert!(err.contains("heads for 0 channels"), "{err}");+ // A bilinear resize whose input width was zeroed.+ let err = mutated(&[], &[&[1.0, 2.0, 3.0, 4.0]], |b| {+ let x = b.input(Shape::new(1, 2, 2));+ b.resize_to(x, 2, 2)+ }, |p| p.in_w = 0).expect_err("zero extent");+ assert!(err.contains("a resize of a zero extent"), "{err}");+ // A banded score map whose key extent was zeroed: the first+ // in-band key is already past it.+ let err = mutated(+ &[(vec![1, 3, 2], vec![0.0; 6])],+ &[&[1.0, 2.0, 3.0, 4.0]],+ |b| {+ let x = b.input(Shape::new(2, 1, 2));+ b.attn_scores_banded(x, x, crate::nets::BandedScores {+ heads: 1, band: 2, table: 0, offsets: 3, scale: 1.0, cap: 30.0,+ })+ },+ |p| p.in_w = 0,+ ).expect_err("key past the extent");+ assert!(err.contains("right context is zero"), "{err}");+}++#[test]+fn the_reference_refuses_empty_softmax_axes_and_norm_planes() {+ // A softmax whose row axis was zeroed.+ let err = mutated(&[], &[&[1.0, 2.0, 3.0]], |b| {+ let x = b.input(Shape::new(1, 1, 3));+ b.softmax(x)+ }, |p| p.out_w = 0).expect_err("empty axis");+ assert!(err.contains("a softmax over an empty axis"), "{err}");+ // A causal softmax with no queries.+ let err = mutated(&[], &[&[1.0; 4]], |b| {+ let x = b.input(Shape::new(1, 2, 2));+ b.softmax_causal(x)+ }, |p| p.out_h = 0).expect_err("no queries");+ assert!(err.contains("a causal softmax over no queries"), "{err}");+ // An instance norm over zero channels, and over an empty plane.+ let err = mutated(&[], &[&[1.0; 8]], |b| {+ let x = b.input(Shape::new(2, 2, 2));+ b.instance_norm(x, 0.0)+ }, |p| p.in_c = 0).expect_err("zero channels");+ assert!(err.contains("an instance norm over zero channels"), "{err}");+ let err = mutated(&[], &[&[1.0; 8]], |b| {+ let x = b.input(Shape::new(2, 2, 2));+ b.instance_norm(x, 0.0)+ }, |p| p.in_h = 0).expect_err("empty plane");+ assert!(err.contains("an instance norm over an empty plane"), "{err}");+}++#[test]+fn a_windowed_causal_softmax_zeroes_keys_before_the_window() {+ // kh = 2 planted on a causal map: query 2 attends keys 1..3+ // only, and key 0 is written as exactly zero.+ let got = mutated(&[], &[&[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0]], |b| {+ let x = b.input(Shape::new(1, 3, 3));+ b.softmax_causal(x)+ }, |p| p.kh = 2).expect("runs");+ let e = std::f32::consts::E;+ let (lo, hi) = (1.0 / (1.0 + e), e / (1.0 + e));+ close(&got[0], &[+ 1.0, 0.0, 0.0,+ 0.5, 0.5, 0.0,+ 0.0, lo, hi,+ ]);+}++#[test]+fn a_single_key_cached_score_uses_the_plain_attended_range() {+ // One cached key: the score map is one wide, which is the+ // `dil_h == 0` form of the attended-range helper.+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let q = builder.input(Shape::new(2, 1, 1));+ let cache = builder.input(Shape::new(1, 1, 2));+ let out = builder.attn_scores_cached(q, cache, 1);+ let plan = builder.finish(&[out]).expect("builds");+ let got = run_multi(&plan, given.data(), &[&[1.0, 2.0], &[5.0, 6.0]]).expect("runs");+ // (1*5 + 2*6) / sqrt(head_dim = 2), stored through fp16.+ assert_eq!(got[0].len(), 1);+ assert!((got[0][0] - 17.0 / 2f32.sqrt()).abs() < 5e-3, "got {:?}", got[0]);+}++#[test]+fn a_cache_write_past_the_end_writes_nothing() {+ // Single-position cache write at a prefix that is already the+ // cache's length: the shader drops it, and so does the reference.+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let row = builder.input(Shape::new(2, 1, 1));+ let cache = builder.persistent(Shape::new(3, 1, 2));+ builder.cache_write(row, cache);+ let plan = builder.finish(&[cache]).expect("builds");+ let got = run_multi_at(&plan, given.data(), &[&[7.0, 8.0]], 3, 0).expect("runs");+ assert_eq!(got.len(), 1);+ assert!(got[0].iter().all(|&v| v == 0.0), "nothing was written: {:?}", got[0]);+}++#[test]+fn a_padded_int8_conv_reads_zero_outside_the_input() {+ // Centre-tap identity over channel 0 of 32, padded by one: the+ // border taps fall outside the input and are skipped.+ let mut kernel = vec![0i8; 32 * 9];+ kernel[4] = 1; // [ic 0][ky 1][kx 1] in (ic*kh + ky)*kw + kx order+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I8(vec![1, 32, 3, 3], kernel),+ Fixture::F16(vec![1], vec![1.0]),+ Fixture::F16(vec![1], vec![0.0]),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let mut builder = Builder::new(&weights);+ let x = builder.input(Shape::new(32, 2, 2));+ let out = builder.conv_int8(x, 0, 1, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 1, Act::None);+ let plan = builder.finish(&[out]).expect("builds");+ let mut input = vec![0.0f32; 32 * 4];+ input[..4].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);+ let got = run(&plan, weights.data(), &input).expect("runs");+ // The output keeps the input's 2x2 extent; the centre tap is the+ // identity there, and every border tap reads outside and skips.+ close(&got, &[1.0, 2.0, 3.0, 4.0]);+}++/// Build a plan with `record`, corrupt every dispatch push with+/// `mutate`, and run it. For the reference's own validation arms,+/// which only a hand-made (or corrupt) plan can reach.+fn mutated(+ tensors: &[(Vec<u32>, Vec<f32>)],+ inputs: &[&[f32]],+ record: impl FnOnce(&mut Builder) -> crate::nets::Id,+ mutate: impl Fn(&mut crate::nets::Push),+) -> Result<Vec<Vec<f32>>, String> {+ let given = Given::new(tensors).expect("fixture tensors are consistent");+ let mut builder = Builder::new(&given);+ let last = record(&mut builder);+ let mut plan = builder.finish(&[last]).expect("the fixture plan builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ mutate(push);+ }+ }+ run_multi(&plan, given.data(), inputs)+}++#[test]+fn the_reference_refuses_degenerate_geometry_in_a_plan() {+ // An average pool whose window was zeroed.+ let err = mutated(&[], &[&[1.0, 2.0, 3.0, 4.0]], |b| {+ let x = b.input(Shape::new(1, 2, 2));+ b.avg_pool(x, (2, 2), (1, 1))+ }, |p| p.kh = 0).expect_err("empty window");+ assert!(err.contains("an average pool over an empty window"), "{err}");+ // A nearest resize to a zero extent (the input doubles as `like`).+ let err = mutated(&[], &[&[1.0, 2.0, 3.0, 4.0]], |b| {+ let x = b.input(Shape::new(1, 2, 2));+ b.resize_nearest_like(x, x)+ }, |p| p.out_w = 0).expect_err("zero extent");+ assert!(err.contains("a resize of a zero extent"), "{err}");+ // A global pool over a zeroed input height.+ let err = mutated(&[], &[&[1.0; 8]], |b| {+ let x = b.input(Shape::new(2, 2, 2));+ b.global_avg_pool(x)+ }, |p| p.in_h = 0).expect_err("pool over nothing");+ assert!(err.contains("a global average pool over nothing"), "{err}");+ // An embedding table with no rows.+ let err = mutated(+ &[(vec![4, 2], vec![0.0; 8])],+ &[&[0.0, 1.0]],+ |b| {+ let ids = b.input(Shape::new(1, 1, 2));+ b.embed(ids, 0, 4, 2)+ },+ |p| p.in_w = 0,+ ).expect_err("no rows");+ assert!(err.contains("an embedding table with no rows"), "{err}");+ // A layer norm over zero channels.+ let err = mutated(+ &[(vec![2], vec![1.0, 1.0]), (vec![2], vec![0.0, 0.0])],+ &[&[1.0, 2.0, 3.0, 4.0]],+ |b| {+ let x = b.input(Shape::new(2, 1, 2));+ b.layer_norm(x, 0, 0.0)+ },+ |p| p.in_c = 0,+ ).expect_err("zero channels");+ assert!(err.contains("a layer norm over zero channels"), "{err}");+ // RMS norms: zero channels, an unsplittable group count, and a+ // fused quantize scale that is not positive.+ let gamma = &[(vec![2], vec![1.0, 1.0])];+ let one: &[&[f32]] = &[&[1.0, 2.0]];+ let err = mutated(gamma, one, |b| {+ let x = b.input(Shape::new(2, 1, 1));+ b.rms_norm(x, 0, 0.0)+ }, |p| p.in_c = 0).expect_err("rms zero channels");+ assert!(err.contains("an rms norm over zero channels"), "{err}");+ let err = mutated(gamma, one, |b| {+ let x = b.input(Shape::new(2, 1, 1));+ b.rms_norm(x, 0, 0.0)+ }, |p| p.group = 3).expect_err("rms groups");+ assert!(err.contains("2 channels do not split into 3 groups"), "{err}");+ let err = mutated(gamma, one, |b| {+ let x = b.input(Shape::new(2, 1, 1));+ b.rms_norm(x, 0, 0.0)+ }, |p| p.param0_bits = (-1.0f32).to_bits()).expect_err("fused quantize");+ assert!(err.contains("a fused quantize of -1"), "{err}");+ // Rotary heads that do not divide into the planted axis count.+ let rotary = |axes: u32| {+ mutated(&[], &[&[1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], &[1.0; 8]], |b| {+ let x = b.input(Shape::new(4, 1, 2));+ let angles = b.input(Shape::new(4, 1, 2));+ b.rotary(x, angles, 1)+ }, |p| p.rope_axes = axes).expect_err("rotary axes")+ };+ assert!(rotary(3).contains("a rotary head of 4 channels in 3 blocks"));+ assert!(rotary(4).contains("a rotary block of 1 channels"));+}++#[test]+fn the_reference_counts_only_in_bounds_taps_for_a_strided_pool() {+ // Stride 2 planted on a 2x2 pool over a 2x3 input: the second+ // output's window hangs off the right edge, and the divisor is+ // still the whole window (the documented ONNX divergence).+ let got = mutated(&[], &[&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]], |b| {+ let x = b.input(Shape::new(1, 2, 3));+ b.avg_pool(x, (2, 2), (1, 1))+ }, |p| p.stride_w = 2).expect("runs");+ close(&got[0], &[3.0, 2.25]);+}++#[test]+fn an_rms_norm_adds_its_fused_residual_after_the_gamma() {+ // [1, 2] normalised at eps 0: inverse RMS is 1/sqrt(2.5); the+ // folded residual adds the input itself back, elementwise.+ let got = mutated(+ &[(vec![2], vec![1.0, 1.0])],+ &[&[1.0, 2.0]],+ |b| {+ let x = b.input(Shape::new(2, 1, 1));+ b.rms_norm(x, 0, 0.0)+ },+ |p| p.res = p.in0,+ ).expect("runs");+ let inv = 1.0 / 2.5f32.sqrt();+ close(&got[0], &[1.0 + inv, 2.0 + 2.0 * inv]);+}++#[test]+fn a_transposed_conv_adds_its_fused_residual_and_refuses_groups() {+ // Identity-scaled transpose (kernel 2.0, no bias): unfused it+ // would give [6, 10]; with the residual folded in (res = the+ // input's own arena slot) it gives [6+3, 10+5].+ let given = Given::new(&[(vec![1, 1, 1, 1], vec![2.0]), (vec![1], vec![0.0])]).expect("tensors");+ let mut builder = Builder::new(&given);+ let x = builder.input(Shape::new(1, 1, 2));+ let out = builder.conv_transpose(x, 0, 1, (1, 1), (1, 1), (0, 0, 0, 0), Act::None);+ let mut plan = builder.finish(&[out]).expect("builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.res = push.in0;+ }+ }+ let got = run(&plan, given.data(), &[3.0, 5.0]).expect("runs fused");+ close(&got, &[9.0, 15.0]);++ // The same plan with a grouped transpose planted in it.+ let mut builder = Builder::new(&given);+ let x = builder.input(Shape::new(1, 1, 2));+ let out = builder.conv_transpose(x, 0, 1, (1, 1), (1, 1), (0, 0, 0, 0), Act::None);+ let mut plan = builder.finish(&[out]).expect("builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.group = 2;+ }+ }+ let err = run(&plan, given.data(), &[3.0, 5.0]).expect_err("grouped transpose");+ assert!(err.contains("transposed convolution in 2 groups"), "{err}");+}++#[test]+fn a_fused_transposed_conv_skips_taps_that_do_not_land() {+ // 2x2 all-ones transpose at stride 1 over two inputs: half the+ // taps fall off the left/top edges and are skipped, and the+ // folded residual adds the input region back elementwise.+ let given = Given::new(&[(vec![1, 1, 2, 2], vec![1.0; 4]), (vec![1], vec![0.0])]).expect("tensors");+ let mut builder = Builder::new(&given);+ let x = builder.input(Shape::new(1, 1, 2));+ let out = builder.conv_transpose(x, 0, 1, (2, 2), (1, 1), (0, 0, 0, 0), Act::None);+ let mut plan = builder.finish(&[out]).expect("builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.res = push.in0;+ }+ }+ let got = run(&plan, given.data(), &[3.0, 5.0]).expect("runs fused");+ // The output is 2x3 (both axes grow by the kernel extent).+ // Accumulators are [3, 8, 5] per row (edge taps skipped); the+ // residual reads the input base, which the first two stores have+ // already overwritten at indices 0 and 1 in this hand-made plan.+ close(&got, &[6.0, 13.0, 5.0, 3.0, 8.0, 5.0]);+}++#[test]+fn the_reference_refuses_group_counts_that_do_not_split_the_outputs() {+ // Four groups over two output channels (the input splits, the+ // output does not). A 3x3 kernel so the plan carries the spatial+ // Kind::Conv whose interpreter consults the group count.+ let spatial = &[(vec![2, 4, 3, 3], vec![0.0; 72]), (vec![2], vec![0.0, 0.0])];+ let input: &[f32] = &[1.0; 64];+ let err = mutated(spatial, &[input], |b| {+ let x = b.input(Shape::new(4, 4, 4));+ b.conv(x, 0, 2, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None)+ }, |p| p.group = 4).expect_err("output does not split");+ assert!(err.contains("do not split into 4 groups"), "{err}");+ // A group count over zero output channels.+ let err = mutated(spatial, &[input], |b| {+ let x = b.input(Shape::new(4, 4, 4));+ b.conv(x, 0, 2, (3, 3), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::None)+ }, |p| p.out_c = 0).expect_err("no output channels");+ assert!(err.contains("groups for 0 output channels"), "{err}");+}
library/ml/src/main/rust/src/nets/reference_ops_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_ops_tests.rs b/library/ml/src/main/rust/src/nets/reference_ops_tests.rsnew file mode 100644index 0000000000..0d2dec9d53--- /dev/null+++ b/library/ml/src/main/rust/src/nets/reference_ops_tests.rs@@ -0,0 +1,352 @@+//! Tests for reference-interpreter ops that previously had no direct+//! fixture: clamp / mul-scalar / gated activation / softcap / quantize,+//! argmax + top-k, prefix softmax, cache write, the int4 (plain and+//! int8-dot) and Q2_K pointwise convolutions, position crop/pad, and+//! the interpreter's own input-validation errors.+//!+//! Every expectation is hand-computed from the op's definition, not+//! copied from the implementation's output.++use super::{run, run_multi, run_multi_at, Given};+use crate::nets::{Act, Builder, Shape};+use crate::weights::{graph, write_mixed, Fixture, Weights};++/// Build a one-input plan over explicit fp16 tensors and run it.+fn one(+ input_shape: Shape,+ input: &[f32],+ tensors: &[(Vec<u32>, Vec<f32>)],+ record: impl FnOnce(&mut Builder, crate::nets::Id) -> crate::nets::Id,+) -> Vec<f32> {+ let given = Given::new(tensors).expect("fixture tensors are consistent");+ let mut builder = Builder::new(&given);+ let first = builder.input(input_shape);+ let last = record(&mut builder, first);+ let plan = builder.finish(&[last]).expect("the fixture plan builds");+ run(&plan, given.data(), input).expect("the fixture plan runs")+}++fn close(got: &[f32], want: &[f32]) {+ assert_eq!(got.len(), want.len(), "length: got {got:?}, want {want:?}");+ for (g, w) in got.iter().zip(want) {+ assert!((g - w).abs() < 1e-3, "got {got:?}, want {want:?}");+ }+}++#[test]+fn clamp_uses_the_weight_pair_as_bounds() {+ let out = one(+ Shape::new(1, 1, 4),+ &[-5.0, -0.5, 1.5, 9.0],+ &[(vec![2], vec![-1.0, 2.0])],+ |b, x| b.clamp(x, 0),+ );+ close(&out, &[-1.0, -0.5, 1.5, 2.0]);+}++#[test]+fn mul_scalar_multiplies_by_the_weight_scalar() {+ let out = one(+ Shape::new(1, 1, 3),+ &[2.0, -1.0, 0.5],+ &[(vec![1], vec![3.0])],+ |b, x| b.mul_scalar(x, 0),+ );+ close(&out, &[6.0, -3.0, 1.5]);+}++#[test]+fn softcap_is_cap_times_tanh_of_x_over_cap() {+ let out = one(Shape::new(1, 1, 3), &[0.0, 2.0, -20.0], &[], |b, x| b.softcap(x, 2.0));+ // tanh(0)=0; tanh(1)=0.76159416; tanh(-10) saturates to -1.+ close(&out, &[0.0, 2.0 * 0.761_594_16, -2.0]);+}++#[test]+fn quantize_rounds_half_up_and_saturates_to_int8() {+ let out = one(Shape::new(1, 1, 4), &[0.3, -0.3, 100.0, -100.0], &[], |b, x| {+ b.quantize(x, 0.5)+ });+ // floor(x/scale + 0.5) * scale, clamped to [-128, 127] steps:+ // 0.6 -> 1 step, -0.6 -> -1 step (floor(-0.1) = -1), then saturation.+ close(&out, &[0.5, -0.5, 63.5, -64.0]);+}++#[test]+fn gated_activate_multiplies_the_activated_gate_by_the_up_half() {+ // Channels [gate | up]; ReLU zeroes the negative gate.+ let out = one(Shape::new(2, 1, 2), &[3.0, -2.0, 4.0, 5.0], &[], |b, x| {+ b.gated_activate(x, Act::Relu)+ });+ close(&out, &[12.0, 0.0]);+}++#[test]+fn argmax_keeps_the_first_of_tied_maxima() {+ let out = one(Shape::new(1, 1, 4), &[1.0, 5.0, 3.0, 5.0], &[], |b, x| b.argmax(x));+ // Output is the (lo, hi) lane pair of the winning index, 1.+ close(&out, &[1.0, 0.0]);+}++#[test]+fn top_k_orders_by_value_then_lower_index_and_pads_missing_ranks() {+ let out = one(Shape::new(1, 1, 5), &[3.0, 1.0, 4.0, 1.0, 5.0], &[], |b, x| b.top_k(x));+ assert_eq!(out.len(), 64 * 3);+ // (value, lo, hi) triples, highest first; the two 1.0s keep index order.+ close(&out[0..3], &[5.0, 4.0, 0.0]);+ close(&out[3..6], &[4.0, 2.0, 0.0]);+ close(&out[6..9], &[3.0, 0.0, 0.0]);+ close(&out[9..12], &[1.0, 1.0, 0.0]);+ close(&out[12..15], &[1.0, 3.0, 0.0]);+ // Ranks past the row length carry the missing-rank sentinel.+ close(&out[15..18], &[-65504.0, 2047.0, 2047.0]);+}++#[test]+fn prefix_softmax_normalises_only_the_attended_prefix() {+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let first = builder.input(Shape::new(1, 1, 4));+ let last = builder.softmax_prefix(first, false);+ let plan = builder.finish(&[last]).expect("builds");+ // Prefix 0 attends to exactly one key, so it takes all the mass; the+ // untouched tail of the output stays at the arena's zero.+ let out = run_multi_at(&plan, given.data(), &[&[0.0, 0.0, 5.0, 5.0]], 0, 0).expect("runs");+ close(&out[0], &[1.0, 0.0, 0.0, 0.0]);+ // Prefix 1 over two equal logits splits evenly.+ let out = run_multi_at(&plan, given.data(), &[&[2.0, 2.0, 5.0, 5.0]], 1, 0).expect("runs");+ close(&out[0], &[0.5, 0.5, 0.0, 0.0]);+}++#[test]+fn crop_and_pad_positions_go_through_the_unit_pool() {+ let cropped = one(Shape::new(1, 1, 3), &[3.0, 5.0, 7.0], &[], |b, x| {+ b.crop_positions(x, 1)+ });+ close(&cropped, &[3.0]);+ let padded = one(Shape::new(1, 1, 2), &[3.0, 5.0], &[], |b, x| b.pad_positions(x, 4));+ close(&padded, &[3.0, 5.0, 0.0, 0.0]);+}++#[test]+fn an_int4_convolution_applies_per_block_scales_and_bias() {+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I4(vec![1, 2, 1, 1], vec![2, -1]),+ Fixture::F16(vec![1, 1], vec![0.5]),+ Fixture::F16(vec![1], vec![1.0]),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(2, 1, 1));+ let last = builder.conv_int4(first, 0, 1, Act::None);+ let plan = builder.finish(&[last]).expect("builds");+ let out = run(&plan, weights.data(), &[3.0, 4.0]).expect("runs");+ // (3*2 + 4*(-1)) * 0.5 + 1 = 2.+ close(&out, &[2.0]);+}++#[test]+fn a_q2k_convolution_unpacks_the_superblock_affine_pair() {+ let mut kernel = vec![0u8; 84];+ kernel[0] = 0x21; // scale byte: lo = 1, hi = 2+ kernel[16] = 3; // first quant byte: lane 0 carries q = 3+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::Q2K(vec![1, 256], kernel),+ Fixture::F16(vec![2], vec![1.0, 0.5]), // (d, dmin)+ Fixture::F16(vec![1], vec![0.25]),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(256, 1, 1));+ let last = builder.conv_q2k(first, 0, 1, Act::None);+ let plan = builder.finish(&[last]).expect("builds");+ let mut input = vec![0.0f32; 256];+ input[0] = 2.0;+ let out = run(&plan, weights.data(), &input).expect("runs");+ // Only tap 0 is live: 2 * (d*d*q*lo - dmin*d*hi) + bias+ // = 2 * (1*3*1 - 0.5*1*2) + 0.25 = 4.25.+ close(&out, &[4.25]);+}++#[test]+fn the_int4_dot_path_quantises_the_input_per_block() {+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I4(vec![1, 32, 1, 1], vec![1; 32]),+ Fixture::F16(vec![1, 1], vec![2.0]),+ Fixture::F16(vec![1], vec![0.0]),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("parses");+ let mut builder = Builder::new(&weights);+ let first = builder.input(Shape::new(32, 1, 8));+ let last = builder.conv_int4(first, 0, 1, Act::None);+ let plan = builder.finish(&[last]).expect("builds");+ let out = run(&plan, weights.data(), &[1.0; 256]).expect("runs");+ // Per position: 32 taps of (127 * 1) summed, scaled by (1/127 * 2) = 64.+ assert_eq!(out.len(), 8);+ close(&out, &[64.0; 8]);+}++#[test]+fn cache_write_lands_the_row_at_the_prefix_position() {+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let row = builder.input(Shape::new(2, 1, 1));+ let cache = builder.persistent(Shape::new(3, 1, 2));+ builder.cache_write(row, cache);+ let plan = builder.finish(&[cache]).expect("builds");+ // Prefix 1: the row occupies the middle position of the cache, the+ // rest stays zero. Position-major layout: [pos0, pos1, pos2].+ let out = run_multi_at(&plan, given.data(), &[&[7.0, 8.0]], 1, 0).expect("runs");+ close(&out[0], &[0.0, 0.0, 7.0, 8.0, 0.0, 0.0]);+}++#[test]+fn the_reference_rejects_mismatched_inputs_and_odd_weight_bytes() {+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let first = builder.input(Shape::new(1, 1, 2));+ let last = builder.softcap(first, 1.0);+ let plan = builder.finish(&[last]).expect("builds");+ assert!(run_multi(&plan, given.data(), &[]).is_err(), "missing input slice");+ assert!(run(&plan, &[0u8], &[1.0, 2.0]).is_err(), "odd fp16 byte count");+ assert!(run(&plan, given.data(), &[1.0]).is_err(), "short input slice");+}++#[test]+fn a_standalone_activation_applies_the_function_elementwise() {+ let out = one(Shape::new(1, 1, 3), &[0.0, 2.0, -2.0], &[], |b, x| {+ b.activate(x, Act::Sigmoid)+ });+ close(&out, &[0.5, 0.880_797, 0.119_203]);+}++#[test]+fn a_multi_position_cache_write_transposes_into_the_cache() {+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let row = builder.input(Shape::new(2, 1, 3));+ let cache = builder.persistent(Shape::new(4, 1, 2));+ builder.cache_write(row, cache);+ let plan = builder.finish(&[cache]).expect("builds");+ // Three positions written at prefix 1: position-major cache slots+ // 1..4 take (c0, c1) pairs from the channel-major row.+ let out = run_multi_at(&plan, given.data(), &[&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]], 1, 0)+ .expect("runs");+ close(&out[0], &[0.0, 0.0, 1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);+ // At prefix 3 only the first of the three positions still fits;+ // the rest are dropped, matching the shader's bounds check.+ let out = run_multi_at(&plan, given.data(), &[&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]], 3, 0)+ .expect("runs");+ close(&out[0], &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 4.0]);+}++/// Build a one-op plan with `record`, then corrupt `param0_bits` on its+/// dispatch and confirm the reference (not the builder) refuses it.+fn mutated_param0(+ input_shape: Shape,+ input: &[f32],+ tensors: &[(Vec<u32>, Vec<f32>)],+ record: impl FnOnce(&mut Builder, crate::nets::Id) -> crate::nets::Id,+ bits: u32,+) -> String {+ let given = Given::new(tensors).expect("fixture tensors are consistent");+ let mut builder = Builder::new(&given);+ let first = builder.input(input_shape);+ let last = record(&mut builder, first);+ let mut plan = builder.finish(&[last]).expect("the fixture plan builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.param0_bits = bits;+ }+ }+ run(&plan, given.data(), input).expect_err("the reference must refuse")+}++#[test]+fn the_reference_refuses_a_softcap_and_quantize_it_cannot_apply() {+ let err = mutated_param0(Shape::new(1, 1, 1), &[1.0], &[], |b, x| b.softcap(x, 2.0), 0);+ assert!(err.contains("a softcap of 0"), "{err}");+ let err = mutated_param0(+ Shape::new(1, 1, 1),+ &[1.0],+ &[],+ |b, x| b.quantize(x, 0.5),+ (-1.0f32).to_bits(),+ );+ assert!(err.contains("a quantize of -1"), "{err}");+}++#[test]+fn the_reference_refuses_a_banded_cap_and_bad_head_splits_from_a_plan() {+ // A banded score map whose cap arrives negative (builder refuses+ // this at build time; a hand-made plan must not slip it through).+ // The scale travels in param0, the cap in param1.+ let given = Given::new(&[(vec![1, 3, 2], vec![0.0; 6])]).expect("tensors");+ let mut builder = Builder::new(&given);+ let x = builder.input(Shape::new(2, 1, 2));+ let last = builder.attn_scores_banded(x, x, crate::nets::BandedScores {+ heads: 1, band: 2, table: 0, offsets: 3, scale: 1.0, cap: 30.0,+ });+ let mut plan = builder.finish(&[last]).expect("builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.param1_bits = (-1.0f32).to_bits();+ }+ }+ let err = run(&plan, given.data(), &[1.0, 2.0, 3.0, 4.0]).expect_err("negative cap");+ assert!(err.contains("logit cap"), "{err}");++ // Head counts the builder would have caught, planted in a plan.+ let given = Given::new(&[]).expect("no tensors");+ let mut builder = Builder::new(&given);+ let q = builder.input(Shape::new(4, 1, 2));+ let k = builder.input(Shape::new(4, 1, 2));+ let last = builder.attn_scores(q, k, 1);+ let mut plan = builder.finish(&[last]).expect("builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.group = 3;+ }+ }+ let err = run_multi(&plan, given.data(), &[&[1.0; 8], &[1.0; 8]]).expect_err("bad head split");+ assert!(err.contains("do not split into 3 heads"), "{err}");++ // A grouped convolution whose group count was zeroed.+ let given = Given::new(&[(vec![2, 2, 1, 1], vec![1.0, 0.0, 0.0, 1.0]), (vec![2], vec![0.0, 0.0])])+ .expect("tensors");+ let mut builder = Builder::new(&given);+ let first = builder.input(Shape::new(4, 1, 1));+ let last = builder.conv(first, 0, 2, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 2, Act::None);+ let mut plan = builder.finish(&[last]).expect("builds");+ for op in &mut plan.ops {+ if let crate::nets::Op::Dispatch { push, .. } = op {+ push.group = 0;+ }+ }+ let err = run(&plan, given.data(), &[1.0, 2.0, 3.0, 4.0]).expect_err("zero groups");+ assert!(err.contains("zero groups"), "{err}");+}++#[test]+fn a_given_fixture_refuses_values_that_do_not_match_its_dims() {+ let err = match Given::new(&[(vec![2, 2], vec![1.0])]) {+ Ok(_) => panic!("dims and values must disagree"),+ Err(e) => e,+ };+ assert!(err.contains("declares 4 values, got 1"), "{err}");+ // A shape query against a laid-out tensor of a different length.+ use crate::nets::WeightSource as _;+ let given = Given::new(&[(vec![2], vec![1.0, 2.0])]).expect("given");+ let err = given.shaped(0, &[3]).expect_err("shape mismatch");+ assert!(err.contains("holds 2 values"), "{err}");+ assert!(given.shaped(9, &[1]).is_err(), "past the fixture's tensors");+}
library/ml/src/main/rust/src/nets/reference_part10.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part10.rs b/library/ml/src/main/rust/src/nets/reference_part10.rsindex dd42f4b76e..66026f5056 100644--- a/library/ml/src/main/rust/src/nets/reference_part10.rs+++ b/library/ml/src/main/rust/src/nets/reference_part10.rs@@ -264,4 +264,11 @@ dir = dir.parent()?.to_path_buf(); } Some(dir)+ }++ #[test]+ fn repo_root_finds_the_workspace_marker() {+ let root = repo_root().expect("this crate is checked out in the workspace");+ assert!(root.join("settings.gradle.kts").is_file());+ assert!(root.join("library/ml/src/main/rust").is_dir()); }\ No newline at end of file
library/ml/src/main/rust/src/nets/reference_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part9.rs b/library/ml/src/main/rust/src/nets/reference_part9.rsindex b8c238ba85..ac3a7e7271 100644--- a/library/ml/src/main/rust/src/nets/reference_part9.rs+++ b/library/ml/src/main/rust/src/nets/reference_part9.rs@@ -439,4 +439,57 @@ Shape::new(1, modnet::SIZE, modnet::SIZE) ); assert_usable_mask("modnet", &plan, weights.data());+ }++ #[test]+ fn a_synthetic_mask_net_passes_the_usable_mask_check() {+ // The shipped-net assertion, exercised on a one-layer stand-in:+ // a 1x1 identity conv under a sigmoid is a usable mask (finite,+ // in 0..1) and answers its two synthetic inputs differently.+ let given = crate::nets::reference::Given::new(&[+ (vec![1, 1, 1, 1], vec![1.0]),+ (vec![1], vec![0.0]),+ ])+ .expect("tensors");+ let mut builder = crate::nets::Builder::new(&given);+ let x = builder.input(Shape::new(1, 4, 4));+ let conv = builder.conv(x, 0, 1, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, crate::nets::Act::None);+ let out = builder.activate(conv, crate::nets::Act::Sigmoid);+ let plan = builder.finish(&[out]).expect("builds");+ assert_usable_mask("synthetic", &plan, given.data());+ // The asset walk finds the workspace root beside this crate.+ assert!(asset("settings.gradle.kts").is_some());+ assert!(asset("no/such/asset.bin").is_none());+ }++ #[test]+ fn synthetic_ramp_and_blob_have_the_documented_values() {+ let ramped = ramp(Shape::new(2, 2, 2));+ let want = [+ 0.0, 0.5 / 2.2, 0.5 / 2.2, 1.0 / 2.2,+ 0.1 / 2.2, 0.6 / 2.2, 0.6 / 2.2, 1.1 / 2.2,+ ];+ assert_eq!(ramped.len(), want.len());+ for (got, want) in ramped.iter().zip(want) {+ assert!((got - want).abs() < 1e-6, "ramp {ramped:?}");+ }++ let blobbed = blob(Shape::new(1, 4, 4));+ assert_eq!(blobbed.iter().filter(|&&v| (v - 0.9).abs() < 1e-6).count(), 5);+ assert_eq!(blobbed.iter().filter(|&&v| (v - 0.05).abs() < 1e-6).count(), 11);+ assert!((blobbed[2 * 4 + 2] - 0.9).abs() < 1e-6, "centre is inside");+ assert!((blobbed[0] - 0.05).abs() < 1e-6, "corner is outside");+ }++ #[test]+ fn written_values_are_little_endian_f32() {+ let path = std::env::temp_dir()+ .join(format!("modelrunner-reference-write-{}.f32", std::process::id()));+ write(&path, &[1.0, -2.5]);+ let bytes = std::fs::read(&path).expect("the written file");+ std::fs::remove_file(&path).expect("cleanup");+ let mut want = Vec::new();+ want.extend_from_slice(&1.0f32.to_le_bytes());+ want.extend_from_slice(&(-2.5f32).to_le_bytes());+ assert_eq!(bytes, want); }\ No newline at end of file
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 d07da7f3f4..d05c3edd37 100644--- a/library/ml/src/main/rust/src/nets/schedule.rs+++ b/library/ml/src/main/rust/src/nets/schedule.rs@@ -399,3 +399,7 @@ mod tests { is_sound(&p, &s).expect("sound"); } }++#[cfg(test)]+#[path = "schedule_tests.rs"]+mod schedule_tests;
library/ml/src/main/rust/src/nets/schedule_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/schedule_tests.rs b/library/ml/src/main/rust/src/nets/schedule_tests.rsnew file mode 100644index 0000000000..ca6986251d--- /dev/null+++ b/library/ml/src/main/rust/src/nets/schedule_tests.rs@@ -0,0 +1,93 @@+//! Schedule tests beyond the inline hazard cases: the `kinds`+//! survey over a built plan, `is_sound` catching a hand-made+//! barrier-free schedule that conflicts, and an out-of-arena write+//! widening to a full flush.++use super::{is_sound, kinds, schedule, Causes, Schedule, Step};+use crate::nets::tests::Shapes;+use crate::nets::{Binding, Builder, Kind, Op, Plan, Push, Shape};++fn dispatch(in0: u32, out: u32) -> Op {+ Op::Dispatch {+ kind: Kind::Softmax,+ push: Push {+ in0,+ out,+ in_c: 8,+ in_h: 1,+ in_w: 1,+ out_c: 8,+ out_h: 1,+ out_w: 1,+ count: 8,+ ..Push::default()+ },+ invocations: 8,+ }+}++fn plan(ops: Vec<Op>, arena_elems: u32) -> Plan {+ Plan {+ ops,+ arena_elems,+ inputs: vec![Binding { at: 0, shape: Shape::new(1, 1, 1) }],+ pinned: Vec::new(),+ outputs: vec![Binding { at: 0, shape: Shape::new(1, 1, 1) }],+ widen: Vec::new(),+ }+}++#[test]+fn kinds_counts_dispatches_by_kind_most_common_first() {+ let source = Shapes::new(0);+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(1, 1, 4));+ let b = builder.input(Shape::new(1, 1, 4));+ let sum = builder.add(a, b);+ let again = builder.add(sum, b);+ let soft = builder.softmax(again);+ let built = builder.finish(&[soft]).expect("builds");+ assert_eq!(kinds(&built), vec![(Kind::Add, 2), (Kind::Softmax, 1)]);+ // A plan of copies only has no dispatch kinds to count.+ assert!(kinds(&plan(vec![Op::Copy { src: 0, dst: 8, elems: 4 }], 64)).is_empty());+}++#[test]+fn is_sound_rejects_a_barrier_free_schedule_over_a_conflict() {+ // Both ops touch 0..16 bytes in elements 0..8: the second reads+ // what the first wrote, so a schedule with no barrier is unsound.+ let p = plan(vec![dispatch(0, 8), dispatch(8, 24)], 64);+ let unsound = Schedule {+ steps: vec![+ Step { barrier: false, transfer: false },+ Step { barrier: false, transfer: false },+ ],+ causes: Causes::default(),+ };+ let err = is_sound(&p, &unsound).expect_err("the conflict must be reported");+ assert!(err.contains("conflict"), "{err}");+ // The computed schedule inserts the barrier and is sound.+ let computed = schedule(&p);+ assert!(computed.steps[1].barrier);+ is_sound(&p, &computed).expect("the computed schedule is sound");+}++#[test]+fn a_write_outside_the_arena_forces_a_full_flush() {+ // The output claims to land far past the arena: the scheduler+ // cannot bound it, so it counts as unbounded and barriers.+ let p = plan(vec![dispatch(0, 10_000)], 64);+ let s = schedule(&p);+ assert_eq!(s.causes.unbounded, 1);+ assert!(s.steps[0].barrier);+ is_sound(&p, &s).expect("sound");+}++#[test]+fn an_empty_plan_schedules_to_nothing() {+ let p = plan(Vec::new(), 64);+ let s = schedule(&p);+ assert!(s.steps.is_empty());+ assert_eq!(s.barriers(), 0);+ is_sound(&p, &s).expect("vacuously sound");+}
library/ml/src/main/rust/src/nets/tinyclip.rs
diff --git a/library/ml/src/main/rust/src/nets/tinyclip.rs b/library/ml/src/main/rust/src/nets/tinyclip.rsindex 732a4503c3..f57ed96271 100644--- a/library/ml/src/main/rust/src/nets/tinyclip.rs+++ b/library/ml/src/main/rust/src/nets/tinyclip.rs@@ -421,4 +421,8 @@ pub fn embed_positions(weights: Reader<'_>, ids: &[u32]) -> Result<Vec<f32>, Str Ok(out) } -include!("tinyclip_part1.rs");\ No newline at end of file+include!("tinyclip_part1.rs");++#[cfg(test)]+#[path = "tinyclip_embed_tests.rs"]+mod tinyclip_embed_tests;\ No newline at end of file
library/ml/src/main/rust/src/nets/tinyclip_embed_tests.rs
diff --git a/library/ml/src/main/rust/src/nets/tinyclip_embed_tests.rs b/library/ml/src/main/rust/src/nets/tinyclip_embed_tests.rsnew file mode 100644index 0000000000..72ae4b02e7--- /dev/null+++ b/library/ml/src/main/rust/src/nets/tinyclip_embed_tests.rs@@ -0,0 +1,68 @@+//! TinyCLIP text-side tests: the token-count and vocabulary refusals+//! in `embed_positions`, and one full embed over a synthetic file+//! (token row + position row), checked by hand.++use super::{embed_positions, CONTEXT, TOKENS, VOCAB, WIDTH};+use crate::weights::{graph, write_mixed, Fixture, Weights};++#[test]+fn embed_refuses_no_tokens_and_too_many_tokens() {+ let weights = Weights::from_data(Vec::new());+ let err = embed_positions(weights.reader(), &[]).expect_err("no tokens");+ assert!(err.contains("no tokens"), "{err}");+ let ids = vec![0u32; CONTEXT as usize + 1];+ let err = embed_positions(weights.reader(), &ids).expect_err("too many");+ assert!(err.contains("past the"), "{err}");+}++/// A file with the text stack's position table and token table.+/// Every other tensor is a one-element placeholder; the two tables+/// carry the values the embed sums.+fn text_file() -> Weights {+ let mut fixtures: Vec<Fixture> = Vec::new();+ for i in 0..=(TOKENS + 2) {+ if i == TOKENS {+ // int8 token rows of 2, scaled by 0.5 per row below.+ fixtures.push(Fixture::I8(+ vec![VOCAB, WIDTH, 1, 1],+ vec![2i8; (VOCAB * WIDTH) as usize],+ ));+ } else if i == TOKENS + 1 {+ fixtures.push(Fixture::F16(vec![VOCAB], vec![0.5; VOCAB as usize]));+ } else if i == TOKENS + 2 {+ // Position table: position 0 is all 1.0, the rest zero.+ let mut table = vec![0.0f32; (CONTEXT * WIDTH) as usize];+ table[..WIDTH as usize].fill(1.0);+ fixtures.push(Fixture::F16(vec![CONTEXT, WIDTH], table));+ } else {+ fixtures.push(Fixture::F16(vec![1], vec![0.0]));+ }+ }+ let blob = write_mixed(graph::SUPERTONIC_VE, &fixtures);+ Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the text file parses")+}++#[test]+fn embed_sums_the_token_row_and_the_position_row() {+ let weights = text_file();+ // Token 3 dequantises to 2 * 0.5 = 1.0 per channel; position 0+ // adds 1.0 more, so every channel of the only position is 2.0.+ let out = embed_positions(weights.reader(), &[3]).expect("embeds");+ assert_eq!(out.len(), WIDTH as usize);+ assert!(out.iter().all(|&v| (v - 2.0).abs() < 1e-3), "all channels 2.0");+ // Channel-major layout `[channel, position]`: for each channel,+ // position 0 sums token+position (2.0), position 1 token only (1.0).+ let out = embed_positions(weights.reader(), &[3, 3]).expect("embeds");+ assert_eq!(out.len(), 2 * WIDTH as usize);+ for channel in 0..WIDTH as usize {+ assert!((out[channel * 2] - 2.0).abs() < 1e-3, "channel {channel} pos 0");+ assert!((out[channel * 2 + 1] - 1.0).abs() < 1e-3, "channel {channel} pos 1");+ }+}++#[test]+fn embed_refuses_a_token_past_the_vocabulary() {+ let weights = text_file();+ let err = embed_positions(weights.reader(), &[VOCAB]).expect_err("past vocab");+ assert!(err.contains("past the"), "{err}");+}
library/ml/src/main/rust/src/post/dbnet.rs
diff --git a/library/ml/src/main/rust/src/post/dbnet.rs b/library/ml/src/main/rust/src/post/dbnet.rsindex af3d1165f7..0024e3a0ea 100644--- a/library/ml/src/main/rust/src/post/dbnet.rs+++ b/library/ml/src/main/rust/src/post/dbnet.rs@@ -493,3 +493,7 @@ mod tests { assert!(error.contains("10 probabilities"), "{error}"); } }++#[cfg(test)]+#[path = "dbnet_regions_tests.rs"]+mod dbnet_regions_tests;
library/ml/src/main/rust/src/post/dbnet_regions_tests.rs
diff --git a/library/ml/src/main/rust/src/post/dbnet_regions_tests.rs b/library/ml/src/main/rust/src/post/dbnet_regions_tests.rsnew file mode 100644index 0000000000..0e361195c1--- /dev/null+++ b/library/ml/src/main/rust/src/post/dbnet_regions_tests.rs@@ -0,0 +1,96 @@+//! DBNet region tests for the degenerate maps: wrong cell counts,+//! zero extents, blank maps, and a single-pixel component whose+//! contour cannot define an angle.++use super::regions;+use crate::preprocess::Letterbox;++fn fit() -> Letterbox {+ Letterbox::new(16, 16, 16, 1).expect("fits")+}++#[test]+fn regions_refuses_mismatched_and_zero_maps() {+ assert!(regions(&[0.5; 3], 16, 16, &fit(), (16, 16)).is_err(), "wrong count");+ assert!(regions(&[], 0, 16, &fit(), (16, 16)).is_err(), "zero width");+ assert!(regions(&[], 16, 0, &fit(), (16, 16)).is_err(), "zero height");+}++#[test]+fn a_blank_map_has_no_regions() {+ let found = regions(&[0.0; 16 * 16], 16, 16, &fit(), (16, 16)).expect("blank is fine");+ assert!(found.is_empty());+}++#[test]+fn sub_minimum_boxes_are_dropped_and_real_ones_kept() {+ // One pixel: its box is below MIN_SIZE (3.0), so it is examined+ // and dropped, exactly as the reference drops specks.+ let mut map = vec![0.0f32; 16 * 16];+ map[5 * 16 + 5] = 0.95;+ let found = regions(&map, 16, 16, &fit(), (16, 16)).expect("one pixel is fine");+ assert!(found.is_empty(), "a sub-MIN_SIZE box is dropped: {found:?}");++ // A 4x4 block clears both the box threshold and MIN_SIZE.+ let mut map = vec![0.0f32; 16 * 16];+ for y in 4..8 {+ for x in 4..8 {+ map[y * 16 + x] = 0.9;+ }+ }+ let found = regions(&map, 16, 16, &fit(), (16, 16)).expect("a block is fine");+ assert_eq!(found.len(), 1, "one block, one region: {found:?}");+ assert!((found[0].score - 0.9).abs() < 0.01, "score is the block mean: {}", found[0].score);+}++#[test]+fn a_low_score_component_is_examined_and_dropped() {+ // Above the pixel threshold (0.3) but below the box threshold+ // (0.6): labelled, scored, and dropped without a region.+ let mut map = vec![0.0f32; 16 * 16];+ for y in 4..8 {+ for x in 4..8 {+ map[y * 16 + x] = 0.45;+ }+ }+ let found = regions(&map, 16, 16, &fit(), (16, 16)).expect("a faint block is fine");+ assert!(found.is_empty(), "a faint component makes no region: {found:?}");+}++#[test]+fn a_corner_block_and_a_thin_line_still_make_regions() {+ // A block in the very corner: the flood fill's out-of-range+ // neighbours are skipped, not read.+ let mut map = vec![0.0f32; 16 * 16];+ for y in 0..4 {+ for x in 0..4 {+ map[y * 16 + x] = 0.9;+ }+ }+ let found = regions(&map, 16, 16, &fit(), (16, 16)).expect("a corner block is fine");+ assert_eq!(found.len(), 1, "{found:?}");++ // A one-pixel-wide line: a degenerate (collinear) contour whose+ // fitted rectangle has no height on one axis.+ let mut map = vec![0.0f32; 16 * 16];+ for x in 2..10 {+ map[7 * 16 + x] = 0.9;+ }+ let found = regions(&map, 16, 16, &fit(), (16, 16)).expect("a line is fine");+ assert_eq!(found.len(), 1, "the line survives as a region: {found:?}");+}++#[test]+fn many_specks_stop_at_the_candidate_budget() {+ // Isolated hot pixels on a coarse grid: each is a component the+ // labelling examines and drops, and the scan stops at the+ // candidate budget rather than walking the whole map.+ let mut map = vec![0.0f32; 64 * 64];+ for y in (0..64).step_by(2) {+ for x in (0..64).step_by(2) {+ map[y * 64 + x] = 0.95;+ }+ }+ let found = regions(&map, 64, 64, &fit(), (64, 64)).expect("specks are fine");+ assert!(found.is_empty(), "every speck is sub-minimum: {found:?}");+}
library/ml/src/main/rust/src/post/ocr.rs
diff --git a/library/ml/src/main/rust/src/post/ocr.rs b/library/ml/src/main/rust/src/post/ocr.rsindex b8079d5af3..f570d29105 100644--- a/library/ml/src/main/rust/src/post/ocr.rs+++ b/library/ml/src/main/rust/src/post/ocr.rs@@ -351,6 +351,40 @@ mod tests { assert_eq!(got[0].text, "b"); } + #[test]+ fn the_batched_pipeline_skips_failed_and_undecodable_strips() {+ // Three bands: the first decodes, the second's recognition+ // fails outright, the third returns logits no decode can read.+ let map = 64u32;+ let mut probability = blob(map, 8, 4, 56, 12);+ for band in [blob(map, 8, 24, 56, 32), blob(map, 8, 44, 56, 52)] {+ for (i, v) in band.iter().enumerate() {+ if *v > 0.0 {+ probability[i] = *v;+ }+ }+ }+ let fit = Letterbox::square(map, map, map).expect("a 1:1 letterbox");+ let pixels = vec![0xffff_ffffu32 as i32; (map * map) as usize];+ let steps = (REC_WIDTH / ppocr_rec::WIDTH_MULTIPLE) as usize;+ let got = lines_batched(+ &Detection { probability: &probability, width: map, height: map, fit: &fit },+ &Source { pixels: &pixels, width: map, height: map },+ &dictionary(),+ |strips| {+ assert_eq!(strips.len(), 3, "every strip is handed over at once");+ vec![+ Ok(logits(&[1, 2, 3], steps)),+ Err("this strip failed".to_string()),+ Ok(vec![0.0; 10]),+ ]+ },+ )+ .expect("the pipeline runs");+ assert_eq!(got.len(), 1, "{got:?}");+ assert_eq!(got[0].text, "abc");+ }+ #[test] fn a_blank_recognition_contributes_no_line() { // A region whose logits are all blank is a false positive from detection, not an
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.rsindex d56b468ba3..622c394181 100644--- a/library/ml/src/main/rust/src/post/sentencepiece_tests.rs+++ b/library/ml/src/main/rust/src/post/sentencepiece_tests.rs@@ -204,3 +204,12 @@ fn byte_piece_spelling_is_strict() { assert_eq!(byte_piece(b"a"), None); assert_eq!(byte_piece(b""), None); }++#[test]+fn the_unigram_encoder_falls_back_to_byte_pieces_for_uncovered_text() {+ let bytes = latin_with_bytes();+ let table = Table::parse(&bytes).expect("the table parses");+ // `z` has no piece of its own: the dummy prefix piece, then the+ // byte-fallback piece for 0x7A (ids 10..266 in byte order).+ assert_eq!(table.encode_unigram("z"), vec![4, 10 + 0x7A]);+}
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 8133cc4085..a338fddbe9 100644--- a/library/ml/src/main/rust/src/post/supertonic.rs+++ b/library/ml/src/main/rust/src/post/supertonic.rs@@ -455,3 +455,7 @@ include!("supertonic_part2.rs"); #[cfg(test)] #[path = "supertonic_tests.rs"] mod supertonic_tests;++#[cfg(test)]+#[path = "supertonic_host_tests.rs"]+mod supertonic_host_tests;
library/ml/src/main/rust/src/post/supertonic_host_tests.rs
diff --git a/library/ml/src/main/rust/src/post/supertonic_host_tests.rs b/library/ml/src/main/rust/src/post/supertonic_host_tests.rsnew file mode 100644index 0000000000..211e8ba181--- /dev/null+++ b/library/ml/src/main/rust/src/post/supertonic_host_tests.rs@@ -0,0 +1,101 @@+//! Host-side Supertonic tests: `time_shifts` and `Conditioning::read`+//! over a synthetic sampler file whose host tensors are known, and+//! the emoji ranges `normalise` strips. With every MLP weight zero,+//! each block's shift is exactly its linear's bias, so the whole+//! timestep chain is checked against a hand-stated expectation.++use super::{normalise, time_shifts, to_ids, Conditioning, INDEXER_ENTRIES};+use crate::nets::supertonic_sampler as net;+use crate::weights::{graph, write_mixed, Fixture, Weights};++/// A sampler-shaped file: every tensor present, the host ones sized+/// as the code expects, everything else a one-element placeholder.+fn sampler_weights() -> Weights {+ let fixtures: Vec<Fixture> = (0..net::TENSORS)+ .map(|i| {+ let zeros = |n: usize| vec![0.0f32; n];+ match i {+ x if x == net::HOST_THETA => Fixture::F16(vec![32], vec![0.5; 32]),+ x if x == net::HOST_FREQUENCIES => Fixture::F16(vec![32], zeros(32)),+ x if x == net::HOST_MLP_IN => Fixture::F16(vec![256, 64], zeros(256 * 64)),+ x if x == net::HOST_MLP_IN + 1 => Fixture::F16(vec![256], zeros(256)),+ x if x == net::HOST_MLP_OUT => Fixture::F16(vec![64, 256], zeros(64 * 256)),+ x if x == net::HOST_MLP_OUT + 1 => Fixture::F16(vec![64], zeros(64)),+ x if x == net::HOST_TEXT_TOKEN => Fixture::F16(vec![256], vec![1.0; 256]),+ x if x == net::HOST_STYLE_TOKEN => Fixture::F16(vec![256, 50], vec![0.25; 256 * 50]),+ x if x == net::HOST_KEYS_CONDITIONAL => {+ Fixture::F16(vec![1024, 50], vec![0.5; 1024 * 50])+ }+ x if x == net::HOST_KEYS_UNCONDITIONAL => {+ Fixture::F16(vec![1024, 50], vec![-0.5; 1024 * 50])+ }+ x if (net::HOST_TIME_LINEARS..net::HOST_TIME_LINEARS + 8).contains(&x) => {+ let block = (x - net::HOST_TIME_LINEARS) / 2;+ if (x - net::HOST_TIME_LINEARS) % 2 == 0 {+ Fixture::F16(vec![512, 64], zeros(512 * 64))+ } else {+ Fixture::F16(vec![512], vec![(block + 1) as f32; 512])+ }+ }+ _ => Fixture::F16(vec![1], vec![0.0]),+ }+ })+ .collect();+ let blob = write_mixed(graph::SUPERTONIC_VE, &fixtures);+ Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the synthetic sampler parses")+}++#[test]+fn time_shifts_are_the_block_biases_when_the_mlp_is_zero() {+ let weights = sampler_weights();+ let shifts = time_shifts(weights.reader(), 3, 16).expect("shifts");+ assert_eq!(shifts.len(), 4 * 512);+ for block in 0..4 {+ let want = (block + 1) as f32;+ assert!(+ shifts[block * 512..(block + 1) * 512].iter().all(|&v| (v - want).abs() < 1e-3),+ "block {block} should be its bias {want} throughout"+ );+ }+ // No steps is a refusal, checked before any tensor is read.+ assert!(time_shifts(weights.reader(), 0, 0).is_err());+}++#[test]+fn conditioning_reads_theta_keys_token_style_and_every_step() {+ let weights = sampler_weights();+ let conditioning = Conditioning::read(weights.reader()).expect("conditioning");+ assert_eq!(conditioning.theta, vec![0.5; 32]);+ assert_eq!(conditioning.shifts.len(), 16, "one shift set per step");+ assert!(conditioning.shifts.iter().all(|s| s.len() == 4 * 512));+ assert!(conditioning.conditional_keys.iter().all(|&v| v == 0.5));+ assert!(conditioning.unconditional_keys.iter().all(|&v| v == -0.5));+ assert_eq!(conditioning.text_token, vec![1.0; 256]);+ assert!(conditioning.unconditional_style.iter().all(|&v| v == 0.25));+}++#[test]+fn normalise_strips_the_remaining_emoji_ranges() {+ // U+1F300 (symbols/pictographs) and a regional indicator (flags).+ assert!(!normalise("a๐b").contains('๐'));+ assert!(!normalise("a๐ฆb").contains('๐ฆ'));+ // Ordinary letters and digits survive.+ assert!(normalise("abc 123").contains("abc"));+}++#[test]+fn astral_characters_are_dropped_by_the_indexer_not_mapped() {+ // A table mapping only 'a' (to token 5); everything else is -1.+ let mut indexer = vec![0xFFu8; INDEXER_ENTRIES * 2];+ indexer[b'a' as usize * 2..b'a' as usize * 2 + 2].copy_from_slice(&5i16.to_le_bytes());+ // U+20000 (a CJK extension, not an emoji) survives normalise and+ // then falls off the end of the BMP-sized table.+ let ids = to_ids(&indexer, "a\u{20000}", "en").expect("ids");+ assert!(ids.contains(&5), "the mapped letter is present: {ids:?}");+ // And text with nothing else is refused rather than synthesised.+ let err = to_ids(&indexer, "\u{20000}", "en").expect_err("nothing maps");+ assert!(err.contains("nothing in this text"), "{err}");+ // A malformed language code is refused before any of that.+ assert!(to_ids(&indexer, "a", "EN").is_err());+ assert!(to_ids(&indexer[..100], "a", "en").is_err(), "a short table");+}
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 6c38fbfb50..b3762a277a 100644--- a/library/ml/src/main/rust/src/post/whisper.rs+++ b/library/ml/src/main/rust/src/post/whisper.rs@@ -232,6 +232,8 @@ fn argmax(logits: &[f32], suppress: &[u32], also: &[u32]) -> Option<u32> { best.map(|(index, _)| index as u32) } +#[cfg(test)] #[path = "whisper_check_tests.rs"] mod whisper_check_tests;+ #[cfg(test)] mod tests { use super::*;
library/ml/src/main/rust/src/post/whisper_check_tests.rs
diff --git a/library/ml/src/main/rust/src/post/whisper_check_tests.rs b/library/ml/src/main/rust/src/post/whisper_check_tests.rsnew file mode 100644index 0000000000..f83b7995c3--- /dev/null+++ b/library/ml/src/main/rust/src/post/whisper_check_tests.rs@@ -0,0 +1,42 @@+//! Whisper `Decoding::check` tests: a valid generation config and+//! each of its refusals.++use super::{Decoding, PROMPT_TOKENS};++fn valid() -> Decoding {+ Decoding {+ start_of_transcript: 50258,+ end_of_text: 50257,+ transcribe: 50359,+ no_timestamps: 50363,+ max_length: 448,+ languages: vec![50259, 50260],+ suppress: vec![220],+ suppress_at_begin: vec![220],+ }+}++#[test]+fn a_valid_config_is_accepted() {+ assert!(valid().check(51_865).is_ok());+}++#[test]+fn config_refusals_name_the_fault() {+ let mut config = valid();+ config.end_of_text = 51_865;+ assert!(config.check(51_865).expect_err("named id").contains("past the"));++ let mut config = valid();+ config.languages = Vec::new();+ assert!(config.check(51_865).expect_err("no languages").contains("no language tokens"));++ let mut config = valid();+ config.languages = vec![50259, 99_999];+ let err = config.check(51_865).expect_err("language id");+ assert!(err.contains("language token 99999 is past the vocabulary"), "{err}");++ let mut config = valid();+ config.max_length = PROMPT_TOKENS;+ assert!(config.check(51_865).expect_err("no room").contains("leaves nothing"));+}
library/ml/src/main/rust/src/preprocess.rs
diff --git a/library/ml/src/main/rust/src/preprocess.rs b/library/ml/src/main/rust/src/preprocess.rsindex 550adf7745..39453be1dc 100644--- a/library/ml/src/main/rust/src/preprocess.rs+++ b/library/ml/src/main/rust/src/preprocess.rs@@ -451,4 +451,7 @@ pub fn f32_to_f16(value: f32) -> u16 { sign | (half_exponent + half_mantissa + round) as u16 } -include!("preprocess_part1.rs");\ No newline at end of file+include!("preprocess_part1.rs");+#[cfg(test)]+#[path = "preprocess_tests.rs"]+mod preprocess_tests;
library/ml/src/main/rust/src/preprocess_tests.rs
diff --git a/library/ml/src/main/rust/src/preprocess_tests.rs b/library/ml/src/main/rust/src/preprocess_tests.rsnew file mode 100644index 0000000000..980cfdc709--- /dev/null+++ b/library/ml/src/main/rust/src/preprocess_tests.rs@@ -0,0 +1,41 @@+//! Preprocess tests for the validation branches: letterbox geometry+//! refusals and the bitmap shape checks in both resize paths.++use super::{to_letterboxed_f16, to_planar_f16, Letterbox, IMAGENET};+use crate::nets::Shape;++#[test]+fn letterbox_refuses_degenerate_geometry() {+ assert!(Letterbox::new(0, 10, 100, 32).is_err(), "zero width");+ assert!(Letterbox::new(10, 0, 100, 32).is_err(), "zero height");+ assert!(Letterbox::new(10, 10, 0, 32).is_err(), "zero long side");+ assert!(Letterbox::new(10, 10, 100, 0).is_err(), "zero multiple");+ assert!(Letterbox::square(0, 10, 100).is_err(), "zero width, square");+ assert!(Letterbox::square(10, 10, 0).is_err(), "zero side");+}++#[test]+fn letterbox_scales_the_long_side_and_pads_to_the_multiple() {+ // 200x100 at long side 100: scale 0.5, resized 100x50, padded to+ // the next multiple of 32 on both axes (128x64), centred.+ let fit = Letterbox::new(200, 100, 100, 32).expect("fits");+ assert_eq!(fit.shape(), Shape::new(3, 64, 128));+ let square = Letterbox::square(200, 100, 64).expect("fits");+ assert_eq!(square.shape(), Shape::new(3, 64, 64));+}++#[test]+fn the_resize_paths_refuse_mismatched_bitmaps() {+ let fit = Letterbox::new(4, 4, 4, 1).expect("fits");+ let norm = IMAGENET;+ let mut dst = vec![0u16; 3 * 16];+ assert!(to_letterboxed_f16(&[], 0, 4, &fit, &norm, &mut dst).is_err(), "zero bitmap");+ assert!(to_letterboxed_f16(&[0; 3], 4, 4, &fit, &norm, &mut dst).is_err(), "short pixels");+ assert!(to_letterboxed_f16(&[0; 16], 4, 4, &fit, &norm, &mut [0u16; 4]).is_err(), "short dst");++ let mut dst = vec![0u16; 3 * 16];+ assert!(to_planar_f16(&[0; 16], 4, 4, Shape::new(1, 4, 4), &norm, &mut dst).is_err(), "one channel");+ assert!(to_planar_f16(&[], 0, 4, Shape::new(3, 4, 4), &norm, &mut dst).is_err(), "zero bitmap");+ assert!(to_planar_f16(&[0; 3], 4, 4, Shape::new(3, 4, 4), &norm, &mut dst).is_err(), "short pixels");+ assert!(to_planar_f16(&[0; 16], 4, 4, Shape::new(3, 4, 4), &norm, &mut [0u16; 4]).is_err(), "short dst");+}
library/ml/src/main/rust/src/timing.rs
diff --git a/library/ml/src/main/rust/src/timing.rs b/library/ml/src/main/rust/src/timing.rsindex df815c3591..70113985b6 100644--- a/library/ml/src/main/rust/src/timing.rs+++ b/library/ml/src/main/rust/src/timing.rs@@ -69,3 +69,7 @@ fn write(message: &str) { fn write(message: &str) { eprintln!("{message}"); }++#[cfg(test)]+#[path = "timing_tests.rs"]+mod timing_tests;
library/ml/src/main/rust/src/timing_tests.rs
diff --git a/library/ml/src/main/rust/src/timing_tests.rs b/library/ml/src/main/rust/src/timing_tests.rsnew file mode 100644index 0000000000..3a0b82779e--- /dev/null+++ b/library/ml/src/main/rust/src/timing_tests.rs@@ -0,0 +1,10 @@+//! Timing tests: off by default in a plain test process, and the+//! emit path (a log line) is callable without the switch.++use super::{emit, enabled};++#[test]+fn timing_is_off_unless_asked_for_and_emit_still_works() {+ assert!(!enabled(), "no MODELRUNNER_TIMING in the test process");+ emit("modelrunner timing test line");+}
library/ml/src/main/rust/src/vulkan/mod.rs
diff --git a/library/ml/src/main/rust/src/vulkan/mod.rs b/library/ml/src/main/rust/src/vulkan/mod.rsindex d64eefaf82..f6fd85aae7 100644--- a/library/ml/src/main/rust/src/vulkan/mod.rs+++ b/library/ml/src/main/rust/src/vulkan/mod.rs@@ -30,3 +30,7 @@ pub mod segment_extra; #[cfg(test)] mod parity;++#[cfg(test)]+#[path = "segment_tests.rs"]+mod segment_tests;
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 0537f08cf6..c74dab4c07 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -222,6 +222,54 @@ fn spread(count: usize, seed: f32) -> Vec<f32> { (0..count).map(|i| (i as f32 * 0.7 + seed).sin() * 0.8 + 0.1).collect() } +#[test]+fn spread_is_deterministic_bounded_and_asymmetric() {+ let values = spread(4, 0.0);+ let want = [0.1, 0.615_374, 0.888_360, 0.790_568];+ for (got, want) in values.iter().zip(want) {+ assert!((got - want).abs() < 1e-4, "spread {values:?}");+ }+ assert!(spread(64, 0.35).iter().all(|v| (-0.7..=0.9).contains(v)));+ assert_ne!(spread(4, 0.0), spread(4, 0.35), "the seed moves the values");+}++#[test]+fn matches_accepts_agreement_at_fp16_scale() {+ // Identical outputs, and outputs a half-ulp apart, both agree;+ // the helper is the parity gate every device test funnels into.+ matches("same", &[vec![1.0, -2.0]], &[vec![1.0, -2.0]]);+ matches("close", &[vec![1.0, -2.0]], &[vec![1.001, -2.001]]);+}++#[test]+#[should_panic(expected = "on the device and")]+fn matches_refuses_a_real_disagreement() {+ matches("far", &[vec![1.0, -2.0]], &[vec![1.0, 2.0]]);+}++#[test]+#[should_panic(expected = "output count")]+fn matches_refuses_a_mi
Diff truncated.