Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / library / ml / src / main / rust / tests / pure_logic.rs

pure_logic.rs236 lines · 12.0 KiBRaw
1//! Host-only pure logic for `modelrunner`: no device, no `.maml` asset, no network.
2//!
3//! `tests/assets.rs` proves the shipped files build the shipped passes. This file proves the
4//! pieces underneath them behave before any asset is read: the fp16 math preprocessing stands
5//! on, the letterbox geometry the detector shares with its post-processing, the tokenizer and
6//! CTC edges that would otherwise decode to fluent nonsense, and the input/output shapes the
7//! Kotlin uploads and reads back. Everything here runs on the host with `cargo test`.
8
9use modelrunner::nets::{
10 mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, u2netp, Shape, WeightSource,
11};
12use modelrunner::post::ctc::{decode, Dictionary, DICTIONARY_ENTRIES, LOGITS};
13use modelrunner::post::sentencepiece::Table;
14use modelrunner::post::sentencepiece_flavours::{FAIRSEQ, GEMMA};
15use modelrunner::preprocess::{
16 f16_to_f32, f32_to_f16, to_planar_f16, Letterbox, RESCALE_ONLY,
17};
18
19/// A weight source that knows only how many tensors the pass wants.
20///
21/// Hands back the tensor index as the offset, which is meaningless as an address but makes the
22/// plan reproducible. The net modules check every shape through `shaped`, so a transcription
23/// that asks for the wrong dims still fails here — just against the stub rather than a file.
24struct Stub {
25 count: usize,
26}
27
28impl WeightSource for Stub {
29 fn shaped(&self, index: usize, _dims: &[u32]) -> Result<u32, String> {
30 Ok(index as u32)
31 }
32
33 fn shaped_words(&self, index: usize, _dims: &[u32]) -> Result<u32, String> {
34 Ok(index as u32)
35 }
36
37 fn count(&self) -> usize {
38 self.count
39 }
40}
41
42/// The smallest table `Table::parse` accepts under the fairseq convention.
43fn fairseq_fixture() -> Vec<u8> {
44 let mut out = b"SPM1".to_vec();
45 let pieces = ["<s>", "<pad>", "</s>", "<unk>"];
46 out.extend((pieces.len() as u32).to_le_bytes());
47 for (index, piece) in pieces.iter().enumerate() {
48 out.extend((-(index as i32)).to_le_bytes());
49 out.extend((piece.len() as u16).to_le_bytes());
50 out.extend(piece.as_bytes());
51 }
52 out
53}
54
55/// A CTC dictionary of `a` repeated to the real length, so `decode` accepts it.
56fn ctc_fixture() -> Dictionary {
57 let mut text = String::new();
58 for _ in 0..DICTIONARY_ENTRIES {
59 text.push('a');
60 text.push('\n');
61 }
62 Dictionary::parse(&text).expect("the fixture dictionary parses")
63}
64
65#[test]
66fn half_precision_encodings_match_the_bit_layout_preprocessing_relies_on() {
67 // Exact codes rather than round trips: the input path writes these bits and the mask path
68 // reads them back, so a conversion that rounded correctly but placed the fields wrongly
69 // would still pass a tolerance check and fail on device.
70 assert_eq!(f32_to_f16(0.0), 0x0000);
71 assert_eq!(f32_to_f16(-0.0), 0x8000);
72 assert_eq!(f32_to_f16(1.0), 0x3c00);
73 assert_eq!(f32_to_f16(-1.0), 0xbc00);
74 assert_eq!(f32_to_f16(f32::INFINITY), 0x7c00);
75 assert_eq!(f32_to_f16(f32::NEG_INFINITY), 0xfc00);
76 // The border preprocessing pads with: raw zero through the SCRFD affine is about -0.996,
77 // which must survive the trip rather than flush to zero.
78 let border = (0.0 - 127.5) / 128.0;
79 let back = f16_to_f32(f32_to_f16(border));
80 assert!((back - border).abs() < 1e-3, "{back} vs {border}");
81 // Overflow saturates and NaN stays a NaN; underflow keeps its sign.
82 assert_eq!(f16_to_f32(f32_to_f16(1e30)), f32::INFINITY);
83 assert!(f16_to_f32(f32_to_f16(f32::NAN)).is_nan());
84 assert!(f16_to_f32(f32_to_f16(-1e-30)).is_sign_negative());
85}
86
87#[test]
88fn letterbox_geometry_stays_on_multiples_and_centres_the_image() {
89 // A square photo needs no padding and reports the input shape Kotlin uploads.
90 let square = Letterbox::new(1000, 1000, 640, 32).expect("fits");
91 assert_eq!(square.resized, (640, 640));
92 assert_eq!(square.padded, (640, 640));
93 assert_eq!(square.offset, (0, 0));
94 assert_eq!(square.shape(), Shape::new(3, 640, 640));
95 // A portrait photo pads left and right; the transposed case of the landscape test in
96 // `post::nms`, which is where a swapped width and height shows up.
97 let portrait = Letterbox::new(720, 1280, 640, 32).expect("fits");
98 assert_eq!(portrait.resized, (360, 640));
99 assert_eq!(portrait.padded, (384, 640));
100 assert_eq!(portrait.offset, (12, 0));
101 // An odd pad splits 2 above and 3 below under integer division, so the extra row lands
102 // at the bottom rather than shifting every coordinate by half a pixel.
103 let odd = Letterbox::new(640, 27, 640, 32).expect("fits");
104 assert_eq!(odd.padded, (640, 32));
105 assert_eq!(odd.offset.1, 2);
106 // Truncation, not rounding: 1000x667 at scale 0.64 gives 426.88, which truncates to 426.
107 let truncated = Letterbox::new(1000, 667, 640, 32).expect("fits");
108 assert_eq!(truncated.resized.1, 426);
109 // Every camera aspect ratio pads to multiples of 32, which is what the detector refuses
110 // anything else for.
111 for (width, height) in [(4032, 3024), (3024, 4032), (1920, 1080), (640, 480), (1, 1)] {
112 let fit = Letterbox::new(width, height, 640, 32).expect("fits");
113 assert!(fit.padded.0.is_multiple_of(32), "{width}x{height}: {fit:?}");
114 assert!(fit.padded.1.is_multiple_of(32), "{width}x{height}: {fit:?}");
115 }
116 // Zero-sized inputs are refused, and a buffer of the wrong length is refused with the
117 // element count rather than written short.
118 assert!(Letterbox::new(0, 100, 640, 32).is_err());
119 let pixels = vec![0i32; 4];
120 let mut out = vec![0u16; 2];
121 let error = to_planar_f16(&pixels, 2, 2, Shape::new(3, 2, 2), &RESCALE_ONLY, &mut out)
122 .expect_err("wrong length");
123 assert!(error.contains("output elements"), "{error}");
124}
125
126#[test]
127fn ctc_decoding_refuses_malformed_inputs_before_touching_the_net() {
128 let dictionary = ctc_fixture();
129 assert_eq!(dictionary.labels(), LOGITS);
130 assert_eq!(dictionary.label(0), None);
131 assert_eq!(dictionary.label(1), Some("a"));
132 assert_eq!(dictionary.label(LOGITS - 1), Some(" "));
133 // A short table would shift every character above the gap, so it is refused at load.
134 let error = Dictionary::parse("a\nb\nc\n").expect_err("too short");
135 assert!(error.contains("3 dictionary entries"), "{error}");
136 // An empty map means the recogniser produced nothing, which must not read as blank text.
137 let error = decode(&[], 0, &dictionary).expect_err("an empty map");
138 assert!(error.contains("no logits"), "{error}");
139 // A ragged array is not a whole number of timesteps and is refused rather than read short.
140 let error = decode(&vec![0.0; LOGITS + 3], 1, &dictionary).expect_err("ragged");
141 assert!(error.contains("not a whole number"), "{error}");
142 // Asking for more timesteps than the map holds is refused rather than read past the end.
143 let mut two_steps = vec![0.0; LOGITS * 2];
144 if let Some(slot) = two_steps.get_mut(1 * 2) {
145 *slot = 10.0;
146 }
147 let error = decode(&two_steps, 3, &dictionary).expect_err("three of two");
148 assert!(error.contains("3 of 2 timesteps"), "{error}");
149 // One winning timestep decodes class-major: label 1 of step 0 sits at index `1 * steps`.
150 let mut one_step = vec![0.0; LOGITS];
151 if let Some(slot) = one_step.get_mut(1) {
152 *slot = 10.0;
153 }
154 let got = decode(&one_step, 1, &dictionary).expect("decodes");
155 assert_eq!(got.text, "a");
156 assert!(got.confidence > 0.9, "{}", got.confidence);
157}
158
159#[test]
160fn sentencepiece_tables_reject_malformed_bytes_before_decoding() {
161 let bytes = fairseq_fixture();
162 let table = Table::parse(&bytes).expect("the minimal table parses");
163 assert_eq!(table.len(), 4);
164 assert!(!table.has_byte_fallback());
165 assert_eq!(table.piece(0), Some("<s>".as_bytes()));
166 // Empty text encodes to nothing and decodes back to nothing; an id past the table is
167 // skipped rather than replacing the whole string.
168 assert!(table.encode("").is_empty());
169 assert_eq!(table.decode(&[]), "");
170 assert_eq!(table.decode(&[999]), "");
171 // Not a table at all, a header cut short, and a table with bytes trailing it.
172 // (Table carries no Debug so neither expect_err nor unwrap_err is
173 // available; match the Err arm out explicitly.)
174 let error = match Table::parse(&[]) {
175 Err(e) => e,
176 Ok(_) => panic!("empty input must not parse"),
177 };
178 assert!(error.contains("SPM1"), "{error}");
179 let error = match Table::parse(b"BAD!") {
180 Err(e) => e,
181 Ok(_) => panic!("bad magic must not parse"),
182 };
183 assert!(error.contains("SPM1"), "{error}");
184 let cut = bytes.get(..10).unwrap_or(&[]).to_vec();
185 assert!(Table::parse(&cut).is_err());
186 let mut trailing = bytes.clone();
187 trailing.push(0);
188 let error = match Table::parse(&trailing) {
189 Err(e) => e,
190 Ok(_) => panic!("trailing byte must not parse"),
191 };
192 assert!(error.contains("bytes left"), "{error}");
193 // The same bytes under the wrong convention are refused: id 0 is `<s>`, not `<pad>`.
194 let error = match Table::parse_with(&bytes, GEMMA) {
195 Err(e) => e,
196 Ok(_) => panic!("wrong flavour must not parse"),
197 };
198 assert!(error.contains("not <pad>"), "{error}");
199 // The flavour travelled with the parse, so callers read back what they asked for.
200 assert_eq!(table.specials(), FAIRSEQ);
201}
202
203#[test]
204fn vision_passes_advertise_the_shapes_the_kotlin_uploads() {
205 // Fixed-shape nets: the input is what preprocessing writes and the output is what the
206 // host reads back, so both are pinned without running anything on a device.
207 let selfie = selfie::build(&Stub { count: selfie::TENSORS }).expect("selfie builds");
208 assert_eq!(selfie.input().expect("one input").shape, Shape::new(3, selfie::SIZE, selfie::SIZE));
209 assert_eq!(selfie.output().expect("one output").shape, Shape::new(1, selfie::SIZE, selfie::SIZE));
210 let u2netp = u2netp::build(&Stub { count: u2netp::TENSORS }).expect("u2netp builds");
211 assert_eq!(u2netp.input().expect("one input").shape, Shape::new(3, u2netp::SIZE, u2netp::SIZE));
212 assert_eq!(u2netp.output().expect("one output").shape, Shape::new(1, u2netp::SIZE, u2netp::SIZE));
213 let embed = mobilefacenet::build(&Stub { count: mobilefacenet::TENSORS }).expect("embedder builds");
214 assert_eq!(embed.input().expect("one input").shape, Shape::new(3, mobilefacenet::SIZE, mobilefacenet::SIZE));
215 assert_eq!(embed.output().expect("one output").shape, Shape::new(mobilefacenet::EMBEDDING, 1, 1));
216 let matte = modnet::build(&Stub { count: modnet::TENSORS }).expect("modnet builds");
217 assert_eq!(matte.input().expect("one input").shape, Shape::new(3, modnet::SIZE, modnet::SIZE));
218 assert_eq!(matte.output().expect("one output").shape, Shape::new(1, modnet::SIZE, modnet::SIZE));
219 // Dynamically shaped nets lower at the shape they are given: SCRFD groups nine maps by
220 // stride, detection returns a full-resolution probability map, and recognition emits one
221 // logit row per eighth of the width.
222 let detect = scrfd::build(&Stub { count: scrfd::TENSORS }, 640, 640).expect("scrfd builds");
223 assert_eq!(detect.outputs.len(), 9);
224 assert_eq!(detect.outputs[0].shape, Shape::new(2, 80, 80));
225 assert_eq!(detect.outputs[8].shape, Shape::new(20, 20, 20));
226 let text = ppocr_det::build(&Stub { count: ppocr_det::TENSORS }, 960, 960).expect("detector builds");
227 assert_eq!(text.output().expect("one output").shape.h, ppocr_det::LONG_SIDE);
228 let line = ppocr_rec::build(&Stub { count: ppocr_rec::TENSORS }, 320).expect("recogniser builds");
229 assert_eq!(line.output().expect("one output").shape, Shape::new(ppocr_rec::LOGITS, 1, 40));
230 // Shapes the builders refuse rather than lower badly: a non-multiple SCRFD extent that
231 // would break the neck, and a recognition width that would drop a column per stride.
232 let error = scrfd::build(&Stub { count: scrfd::TENSORS }, 100, 640).expect_err("ragged extent");
233 assert!(error.contains("multiple of 32"), "{error}");
234 let error = ppocr_rec::build(&Stub { count: ppocr_rec::TENSORS }, 100).expect_err("ragged width");
235 assert!(error.contains("multiple of 8"), "{error}");
236}