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

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

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