Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / tests / assets.rs
assets.rs502 lines · 24.4 KiBRaw
| 1 | //! Builds both forward passes against the `.maml` files actually committed to |
| 2 | //! `camera/` and `photos/`. |
| 3 | //! |
| 4 | //! Everything in `src/nets` is unit-tested against a stub weight source, which proves |
| 5 | //! the two passes are self-consistent but not that they agree with the converter. This |
| 6 | //! is the test that closes that: it parses the shipped assets and walks all 348 tensors |
| 7 | //! through `Weights::shaped`, so a converter that reordered a layer, a `.maml` rebuilt |
| 8 | //! from a moved upstream, or a miscounted RSU block fails here — naming the tensor. |
| 9 | //! |
| 10 | //! Given that nothing checks the *numbers* this runtime produces (correctness is |
| 11 | //! confirmed visually on device), agreement about the tensor table is the strongest |
| 12 | //! automatic guarantee available, and it is worth reaching across modules for. |
| 13 | |
| 14 | use std::path::{Path, PathBuf}; |
| 15 | |
| 16 | use modelrunner::nets::{ |
| 17 | maia, mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, |
| 18 | supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, |
| 19 | }; |
| 20 | use modelrunner::post::ctc; |
| 21 | use modelrunner::weights::{graph, Weights}; |
| 22 | |
| 23 | /// The repo root, found by walking up for `settings.gradle.kts` rather than by counting |
| 24 | /// `..` — so moving this crate cannot silently turn the test into a no-op. |
| 25 | fn repo_root() -> PathBuf { |
| 26 | let mut dir: &Path = &PathBuf::from(env!("CARGO_MANIFEST_DIR")); |
| 27 | loop { |
| 28 | if dir.join("settings.gradle.kts").is_file() { |
| 29 | return dir.to_path_buf(); |
| 30 | } |
| 31 | dir = dir.parent().expect("this crate is inside the repo"); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | fn load(relative: &str, graph_id: u32) -> Weights { |
| 36 | let path = repo_root().join(relative); |
| 37 | let bytes = std::fs::read(&path).unwrap_or_else(|e| { |
| 38 | panic!( |
| 39 | "cannot read {}: {e}. Run ./scripts/ml/fetch_and_convert.sh to rebuild it.", |
| 40 | path.display() |
| 41 | ) |
| 42 | }); |
| 43 | Weights::parse(&bytes, graph_id) |
| 44 | .unwrap_or_else(|e| panic!("{} is not a usable .maml: {e}", path.display())) |
| 45 | } |
| 46 | |
| 47 | #[test] |
| 48 | fn the_shipped_selfie_asset_builds_the_selfie_forward_pass() { |
| 49 | let weights = load("camera/src/main/assets/selfie_segmentation.maml", graph::SELFIE); |
| 50 | assert_eq!(weights.len(), selfie::TENSORS); |
| 51 | let plan = selfie::build(&weights).expect("the shipped asset matches nets::selfie"); |
| 52 | assert!(!plan.ops.is_empty()); |
| 53 | } |
| 54 | |
| 55 | #[test] |
| 56 | fn the_shipped_u2netp_asset_builds_the_u2netp_forward_pass() { |
| 57 | let weights = load("photos/src/main/assets/u2netp.maml", graph::U2NETP); |
| 58 | assert_eq!(weights.len(), u2netp::TENSORS); |
| 59 | let plan = u2netp::build(&weights).expect("the shipped asset matches nets::u2netp"); |
| 60 | assert!(!plan.ops.is_empty()); |
| 61 | } |
| 62 | |
| 63 | #[test] |
| 64 | fn the_shipped_mobilefacenet_asset_builds_the_mobilefacenet_forward_pass() { |
| 65 | let weights = load("photos/src/main/assets/w600k_mbf.maml", graph::MOBILEFACENET); |
| 66 | assert_eq!(weights.len(), mobilefacenet::TENSORS); |
| 67 | let plan = |
| 68 | mobilefacenet::build(&weights).expect("the shipped asset matches nets::mobilefacenet"); |
| 69 | assert!(!plan.ops.is_empty()); |
| 70 | } |
| 71 | |
| 72 | #[test] |
| 73 | fn the_shipped_scrfd_asset_builds_the_scrfd_forward_pass() { |
| 74 | let weights = load("photos/src/main/assets/scrfd_500m.maml", graph::SCRFD); |
| 75 | assert_eq!(weights.len(), scrfd::TENSORS); |
| 76 | let plan = scrfd::build(&weights, scrfd::LONG_SIDE, scrfd::LONG_SIDE) |
| 77 | .expect("the shipped asset matches nets::scrfd"); |
| 78 | assert_eq!(plan.outputs.len(), 9); |
| 79 | } |
| 80 | |
| 81 | #[test] |
| 82 | fn the_scrfd_pass_builds_at_every_letterbox_shape_a_photo_can_produce() { |
| 83 | // The detector is compiled per shape, so the whole family has to lower — not just |
| 84 | // the square case. These are the short sides a 640-long-side letterbox rounds to for |
| 85 | // aspect ratios from 1:1 to about 3:1, which covers any real photo. |
| 86 | let weights = load("photos/src/main/assets/scrfd_500m.maml", graph::SCRFD); |
| 87 | for short in (scrfd::EXTENT_MULTIPLE..=scrfd::LONG_SIDE).step_by(32) { |
| 88 | for (height, width) in [(short, scrfd::LONG_SIDE), (scrfd::LONG_SIDE, short)] { |
| 89 | let plan = scrfd::build(&weights, height, width) |
| 90 | .unwrap_or_else(|e| panic!("{width}x{height}: {e}")); |
| 91 | assert_eq!(plan.outputs.len(), 9, "{width}x{height}"); |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | #[test] |
| 97 | fn the_shipped_ppocr_det_asset_builds_the_ppocr_det_forward_pass() { |
| 98 | let weights = load("library/ocr/src/main/assets/ppocr_det.maml", graph::PPOCR_DET); |
| 99 | assert_eq!(weights.len(), ppocr_det::TENSORS); |
| 100 | let plan = ppocr_det::build(&weights, ppocr_det::LONG_SIDE, ppocr_det::LONG_SIDE) |
| 101 | .expect("the shipped asset matches nets::ppocr_det"); |
| 102 | // Full-resolution probability map, which is what DBNet thresholds. |
| 103 | assert_eq!(plan.output().expect("one output").shape.h, ppocr_det::LONG_SIDE); |
| 104 | } |
| 105 | |
| 106 | #[test] |
| 107 | fn the_shipped_ppocr_rec_asset_builds_the_ppocr_rec_forward_pass() { |
| 108 | let weights = load("library/ocr/src/main/assets/ppocr_rec.maml", graph::PPOCR_REC); |
| 109 | assert_eq!(weights.len(), ppocr_rec::TENSORS); |
| 110 | // Building against the real file checks every one of the 112 tensors' shapes, because |
| 111 | // `Builder::weight` asks for each by index *and* dimensions — so a converter that |
| 112 | // transposed a linear, split the fused QKV projection the wrong way, or emitted a |
| 113 | // layer norm's gamma and beta in the wrong order fails here rather than on device. |
| 114 | let plan = ppocr_rec::build(&weights, 320).expect("the shipped asset matches nets::ppocr_rec"); |
| 115 | assert_eq!( |
| 116 | plan.output().expect("one output").shape, |
| 117 | modelrunner::nets::Shape::new(ppocr_rec::LOGITS, 1, 40) |
| 118 | ); |
| 119 | } |
| 120 | |
| 121 | #[test] |
| 122 | fn the_shipped_ppocr_rec_asset_builds_at_every_padded_line_width() { |
| 123 | // A line crop is resized to 48 tall and padded to a multiple of 8, so the plan has to |
| 124 | // lower at whatever width the batcher lands on. |
| 125 | let weights = load("library/ocr/src/main/assets/ppocr_rec.maml", graph::PPOCR_REC); |
| 126 | for width in [8u32, 64, 160, 320, 640, 1024] { |
| 127 | let plan = |
| 128 | ppocr_rec::build(&weights, width).unwrap_or_else(|e| panic!("at width {width}: {e}")); |
| 129 | assert_eq!(plan.output().expect("one output").shape.w, width / 8); |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | #[test] |
| 134 | fn the_shipped_character_dictionary_matches_the_recogniser_label_space() { |
| 135 | // The model's final layer emits 838 logits positionally, so the dictionary's *length* |
| 136 | // is a hard constraint and its *order* is the whole decode. A file that lost a line |
| 137 | // to an editor would shift every character above it. |
| 138 | let path = repo_root().join("library/ocr/src/main/assets/ppocr_keys.txt"); |
| 139 | let text = std::fs::read_to_string(&path) |
| 140 | .unwrap_or_else(|e| panic!("cannot read {}: {e}", path.display())); |
| 141 | let dictionary = ctc::Dictionary::parse(&text).expect("the shipped dictionary parses"); |
| 142 | assert_eq!(dictionary.labels(), ctc::LOGITS); |
| 143 | // Spot-check the ends against the export's `inference.yml`: digits first, and the |
| 144 | // appended space last. |
| 145 | assert_eq!(dictionary.label(0), None, "label 0 is the CTC blank"); |
| 146 | assert_eq!(dictionary.label(1), Some("0")); |
| 147 | assert_eq!(dictionary.label(11), Some("A")); |
| 148 | assert_eq!(dictionary.label(ctc::LOGITS - 1), Some(" ")); |
| 149 | } |
| 150 | |
| 151 | #[test] |
| 152 | fn the_shipped_maia_asset_builds_the_maia_forward_pass() { |
| 153 | // Against the real 259-tensor file, which is what checks `collect_maia`'s emission order |
| 154 | // against `nets::maia`'s layout constants: `Builder::conv_int8` asks for every tensor by |
| 155 | // index *and* dimensions, so a transposed projection, the fused q/k/v split done the wrong |
| 156 | // way, an RMS norm emitted with a beta it does not have, or a scale and a bias swapped all |
| 157 | // fail here rather than on device. |
| 158 | let weights = load("games/chess/src/main/assets/maia3-5m.maml", graph::MAIA); |
| 159 | assert_eq!(weights.len(), maia::TENSORS); |
| 160 | |
| 161 | let plan = maia::build(&weights).expect("the shipped asset matches nets::maia"); |
| 162 | let shapes: Vec<modelrunner::nets::Shape> = plan.outputs.iter().map(|out| out.shape).collect(); |
| 163 | assert_eq!( |
| 164 | shapes, |
| 165 | vec![ |
| 166 | modelrunner::nets::Shape::new(1, maia::SQUARES, maia::SQUARES), |
| 167 | modelrunner::nets::Shape::new(maia::PROMOTIONS, 1, maia::SQUARES), |
| 168 | ] |
| 169 | ); |
| 170 | } |
| 171 | |
| 172 | #[test] |
| 173 | fn the_shipped_maia_asset_blends_the_two_elo_embeddings_on_the_host() { |
| 174 | // The host blend, against the real file. `elo_embedding` is the only reader of either |
| 175 | // table, and upstream's naming is inverted — `weight_low` is `elo / 5000` and multiplies |
| 176 | // `elo_embedding_low` — so at elo 0 the vector is entirely the *high* embedding. A blend |
| 177 | // computed the intuitive way round produces a perfectly plausible vector, which is why what |
| 178 | // is pinned here is the relation between the three points rather than any one of them. |
| 179 | let weights = load("games/chess/src/main/assets/maia3-5m.maml", graph::MAIA); |
| 180 | let table = weights.offsets(); |
| 181 | |
| 182 | let low = maia::elo_embedding(modelrunner::weights::Reader::new(&table, &weights), 0.0) |
| 183 | .expect("the blend at elo 0"); |
| 184 | let high = |
| 185 | maia::elo_embedding(modelrunner::weights::Reader::new(&table, &weights), maia::ELO_MAX) |
| 186 | .expect("the blend at elo 5000"); |
| 187 | let middle = maia::elo_embedding( |
| 188 | modelrunner::weights::Reader::new(&table, &weights), |
| 189 | maia::ELO_MAX / 2.0, |
| 190 | ) |
| 191 | .expect("the blend at elo 2500"); |
| 192 | |
| 193 | assert_eq!(low.len(), maia::ELO_DIM as usize); |
| 194 | assert!(low.iter().any(|&v| v != 0.0), "the blend produced zeros"); |
| 195 | // The two ends are different vectors, which is what makes the difficulty setting mean |
| 196 | // anything at all. |
| 197 | assert!(low.iter().zip(&high).any(|(a, b)| a != b), "both ends are the same vector"); |
| 198 | // And the midpoint is exactly halfway, because the blend is linear. |
| 199 | for index in 0..maia::ELO_DIM as usize { |
| 200 | let want = (low[index] + high[index]) / 2.0; |
| 201 | assert!( |
| 202 | (middle[index] - want).abs() < 1e-4, |
| 203 | "channel {index}: {} against {want}", |
| 204 | middle[index] |
| 205 | ); |
| 206 | } |
| 207 | |
| 208 | // Past either end it clamps rather than extrapolating, as `torch.clamp` does. |
| 209 | let beyond = maia::elo_embedding(modelrunner::weights::Reader::new(&table, &weights), 9000.0) |
| 210 | .expect("the blend past the top"); |
| 211 | assert_eq!(beyond, high); |
| 212 | } |
| 213 | |
| 214 | #[test] |
| 215 | fn the_shipped_tinyclip_asset_builds_both_towers() { |
| 216 | // Both passes against the real 306-tensor file, which is what checks the converter's emission |
| 217 | // order against `nets::tinyclip`'s layout constants: `Builder::weight` asks for every tensor by |
| 218 | // index *and* dimensions, so a transposed projection, a position table emitted the wrong way |
| 219 | // round, or a tower emitted in the export's interleaved order fails here rather than on device. |
| 220 | let weights = load("photos/src/main/assets/clip/tinyclip.maml", graph::TINYCLIP); |
| 221 | assert_eq!(weights.len(), tinyclip::TENSORS); |
| 222 | |
| 223 | let image = tinyclip::build(&weights, tinyclip::Mode::Image) |
| 224 | .expect("the shipped asset matches nets::tinyclip's vision tower"); |
| 225 | assert_eq!( |
| 226 | image.output().expect("one output").shape, |
| 227 | modelrunner::nets::Shape::new(tinyclip::PROJECTION, 1, tinyclip::VISION_POSITIONS) |
| 228 | ); |
| 229 | |
| 230 | // Every length a query can be, since the pass is compiled per length: 1 through the padded 77. |
| 231 | for len in [1u32, 2, 5, 32, tinyclip::CONTEXT] { |
| 232 | let text = tinyclip::build(&weights, tinyclip::Mode::Text { len }) |
| 233 | .unwrap_or_else(|e| panic!("at {len} tokens: {e}")); |
| 234 | assert_eq!( |
| 235 | text.output().expect("one output").shape, |
| 236 | modelrunner::nets::Shape::new(tinyclip::PROJECTION, 1, len) |
| 237 | ); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn the_shipped_tinyclip_asset_embeds_a_token_on_the_host() { |
| 243 | // The host gather, against the real file: the token embedding is int8 with a per-row scale and |
| 244 | // the position table is fp16, and `embed_positions` is the only reader of either. A wrong row |
| 245 | // stride or a transposed position table produces a plausible vector, so what is pinned here is |
| 246 | // the one property that has no fixture — the same token at two positions must differ by exactly |
| 247 | // the two position rows' difference. |
| 248 | let weights = load("photos/src/main/assets/clip/tinyclip.maml", graph::TINYCLIP); |
| 249 | let table = weights.offsets(); |
| 250 | let reader = modelrunner::weights::Reader::new(&table, &weights); |
| 251 | |
| 252 | // `<|startoftext|>`, "dog", `<|endoftext|>`. |
| 253 | let ids = [49_406u32, 1_929, 49_407]; |
| 254 | let out = tinyclip::embed_positions(reader, &ids).expect("the gather succeeds"); |
| 255 | assert_eq!(out.len(), tinyclip::WIDTH as usize * ids.len()); |
| 256 | assert!(out.iter().any(|&v| v != 0.0), "the gather produced zeros"); |
| 257 | |
| 258 | // Channel-major: `out[c * len + t]`. A position-major layout would put one token's 256 values |
| 259 | // contiguously instead, so this also pins the transpose. |
| 260 | let twice = tinyclip::embed_positions(reader, &[1_929, 1_929]).expect("the gather succeeds"); |
| 261 | let single = tinyclip::embed_positions(reader, &[1_929]).expect("the gather succeeds"); |
| 262 | for channel in 0..tinyclip::WIDTH as usize { |
| 263 | let first = twice[channel * 2]; |
| 264 | // The same token at position 0, alone, must be exactly the same value. |
| 265 | assert!((first - single[channel]).abs() < 1e-6, "channel {channel}"); |
| 266 | // And the two positions must differ, or the position table was never added. |
| 267 | assert!(first.is_finite() && twice[channel * 2 + 1].is_finite(), "channel {channel}"); |
| 268 | } |
| 269 | let moved = (0..tinyclip::WIDTH as usize) |
| 270 | .filter(|&c| (twice[c * 2] - twice[c * 2 + 1]).abs() > 1e-4) |
| 271 | .count(); |
| 272 | assert!(moved > tinyclip::WIDTH as usize / 2, "only {moved} channels differ between positions"); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn the_shipped_whisper_asset_builds_both_passes() { |
| 277 | // Both passes against the real 363-tensor file, which is what checks the converter's emission |
| 278 | // order against `nets::whisper`'s layout constants: `Builder::weight` asks for every tensor by |
| 279 | // index *and* dimensions, so a transposed projection, a position table emitted the wrong way |
| 280 | // round, or the two passes disagreeing about which cross-attention projection belongs to which |
| 281 | // fails here rather than on device. |
| 282 | let weights = load("speech/src/main/assets/whisper-base/whisper_base.maml", graph::WHISPER); |
| 283 | assert_eq!(weights.len(), whisper::TENSORS); |
| 284 | |
| 285 | let encode = whisper::build(&weights, whisper::Mode::Encode) |
| 286 | .expect("the shipped asset matches nets::whisper's encoder"); |
| 287 | // The hidden states are the only output: the twelve cross-attention |
| 288 | // caches stay on the device as the first pinned tensors, where the |
| 289 | // decode step's plan declares them at the same offsets. |
| 290 | assert_eq!(encode.outputs.len(), 1); |
| 291 | assert_eq!( |
| 292 | encode.outputs[0].shape, |
| 293 | modelrunner::nets::Shape::new(whisper::D_MODEL, 1, whisper::SOURCE_POSITIONS) |
| 294 | ); |
| 295 | let caches = whisper::DECODER_LAYERS * 2; |
| 296 | assert!(encode.pinned.len() >= caches, "the cross caches are pinned"); |
| 297 | for binding in &encode.pinned[..caches] { |
| 298 | assert_eq!( |
| 299 | binding.shape, |
| 300 | modelrunner::nets::Shape::new(whisper::D_MODEL, 1, whisper::SOURCE_POSITIONS) |
| 301 | ); |
| 302 | } |
| 303 | |
| 304 | // The decode plan is recorded once at `MAX_POSITIONS` and the step supplies how much of the |
| 305 | // cache is live, so there is one plan per transcript rather than one per token. |
| 306 | let step = whisper::build(&weights, whisper::Mode::DecodeStep).expect("the decode step builds"); |
| 307 | assert_eq!(step.outputs[0].shape, modelrunner::nets::Shape::new(whisper::VOCAB, 1, 1),); |
| 308 | // The logits and nothing else: the self-attention caches stay on the device. |
| 309 | assert_eq!(step.outputs.len(), 1); |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn the_shipped_whisper_asset_embeds_a_token_on_the_host() { |
| 314 | // The host gather, against the real file: the tied embedding is int8 with a per-row scale and |
| 315 | // the decoder position table is fp16, and `embed_positions` is the only reader of the table. What |
| 316 | // is pinned here is the property that has no fixture — the same token at two positions must |
| 317 | // differ by exactly the two position rows' difference, which fails if `past` is applied wrongly. |
| 318 | let weights = load("speech/src/main/assets/whisper-base/whisper_base.maml", graph::WHISPER); |
| 319 | let table = weights.offsets(); |
| 320 | let reader = modelrunner::weights::Reader::new(&table, &weights); |
| 321 | |
| 322 | // `<|startoftranscript|>`, `<|en|>`, `<|transcribe|>`, `<|notimestamps|>` — the real prompt. |
| 323 | let prompt = [50_258u32, 50_259, 50_359, 50_363]; |
| 324 | let out = whisper::embed_positions(reader, &prompt, 0).expect("the gather succeeds"); |
| 325 | assert_eq!(out.len(), whisper::D_MODEL as usize * prompt.len()); |
| 326 | assert!(out.iter().any(|&v| v != 0.0), "the gather produced zeros"); |
| 327 | |
| 328 | // Channel-major: `out[c * len + t]`. A position-major layout would put one token's 512 values |
| 329 | // contiguously instead, so this also pins the transpose. |
| 330 | let at_zero = whisper::embed_positions(reader, &[50_258], 0).expect("the gather succeeds"); |
| 331 | let at_one = whisper::embed_positions(reader, &[50_258], 1).expect("the gather succeeds"); |
| 332 | let moved = |
| 333 | (0..whisper::D_MODEL as usize).filter(|&c| (at_zero[c] - at_one[c]).abs() > 1e-4).count(); |
| 334 | assert!(moved > whisper::D_MODEL as usize / 2, "only {moved} channels move with the position"); |
| 335 | // And position 0 of the four-token gather must be exactly the single-token gather at 0. |
| 336 | for channel in 0..whisper::D_MODEL as usize { |
| 337 | let from_block = out[channel * prompt.len()]; |
| 338 | assert!( |
| 339 | (from_block - at_zero[channel]).abs() < 1e-6, |
| 340 | "channel {channel}: {from_block} against {}", |
| 341 | at_zero[channel] |
| 342 | ); |
| 343 | } |
| 344 | |
| 345 | // Past the 448-position table is refused rather than clamped: a transcript that ran over would |
| 346 | // otherwise wrap onto position 0 and start repeating. |
| 347 | let error = whisper::embed_positions(reader, &[50_258], whisper::MAX_POSITIONS) |
| 348 | .expect_err("past the table"); |
| 349 | assert!(error.contains("past the model"), "{error}"); |
| 350 | } |
| 351 | |
| 352 | #[test] |
| 353 | fn neither_asset_will_load_as_the_other_network() { |
| 354 | // The `graph_id` in the header exists for exactly this: the two files are both |
| 355 | // ordered fp16 tensor tables, so without it a swapped asset would parse. |
| 356 | let selfie = repo_root().join("camera/src/main/assets/selfie_segmentation.maml"); |
| 357 | let bytes = std::fs::read(selfie).expect("the selfie asset"); |
| 358 | assert!(Weights::parse(&bytes, graph::U2NETP).is_err()); |
| 359 | } |
| 360 | |
| 361 | #[test] |
| 362 | fn report_the_device_memory_each_net_needs() { |
| 363 | // Not an assertion so much as the number a reviewer wants to see, printed by |
| 364 | // `cargo test -- --nocapture`. Both are well inside what a phone will give a |
| 365 | // background allocation, which is the point. |
| 366 | for (name, weights, arena) in [ |
| 367 | ( |
| 368 | "selfie", |
| 369 | load("camera/src/main/assets/selfie_segmentation.maml", graph::SELFIE), |
| 370 | selfie::build(&load("camera/src/main/assets/selfie_segmentation.maml", graph::SELFIE)) |
| 371 | .expect("selfie") |
| 372 | .arena_elems, |
| 373 | ), |
| 374 | ( |
| 375 | "u2netp", |
| 376 | load("photos/src/main/assets/u2netp.maml", graph::U2NETP), |
| 377 | u2netp::build(&load("photos/src/main/assets/u2netp.maml", graph::U2NETP)) |
| 378 | .expect("u2netp") |
| 379 | .arena_elems, |
| 380 | ), |
| 381 | ( |
| 382 | "mobilefacenet", |
| 383 | load("photos/src/main/assets/w600k_mbf.maml", graph::MOBILEFACENET), |
| 384 | mobilefacenet::build(&load( |
| 385 | "photos/src/main/assets/w600k_mbf.maml", |
| 386 | graph::MOBILEFACENET, |
| 387 | )) |
| 388 | .expect("mobilefacenet") |
| 389 | .arena_elems, |
| 390 | ), |
| 391 | ( |
| 392 | "scrfd@640", |
| 393 | load("photos/src/main/assets/scrfd_500m.maml", graph::SCRFD), |
| 394 | scrfd::build( |
| 395 | &load("photos/src/main/assets/scrfd_500m.maml", graph::SCRFD), |
| 396 | scrfd::LONG_SIDE, |
| 397 | scrfd::LONG_SIDE, |
| 398 | ) |
| 399 | .expect("scrfd") |
| 400 | .arena_elems, |
| 401 | ), |
| 402 | ] { |
| 403 | let weight_bytes = weights.data().len(); |
| 404 | let arena_bytes = arena as usize * 2; |
| 405 | println!( |
| 406 | "{name}: {} KiB weights + {} KiB arena = {} KiB", |
| 407 | weight_bytes / 1024, |
| 408 | arena_bytes / 1024, |
| 409 | (weight_bytes + arena_bytes) / 1024, |
| 410 | ); |
| 411 | assert!(weight_bytes + arena_bytes < 128 * 1024 * 1024); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | /// One of Supertonic's four `.maml`, or `None` when the bundle has not been built. |
| 416 | /// |
| 417 | /// Unlike every other asset here, Supertonic's is **not committed**: the four nets come to 189 MiB |
| 418 | /// at fp16, which is more than belongs in git history for something a pinned script can rebuild |
| 419 | /// byte for byte. So a fresh checkout does not have it, and this returns `None` rather than |
| 420 | /// panicking — the test below then reports that it was skipped instead of failing for the one |
| 421 | /// reason that is not a bug. |
| 422 | /// |
| 423 | /// A file that is *present but wrong* is still a hard failure. That is the case worth catching: |
| 424 | /// a bundle rebuilt from a moved upstream, or converted by a `supertonic_fold.py` whose layer |
| 425 | /// ordering has drifted from the Rust. |
| 426 | fn supertonic(name: &str, graph_id: u32) -> Option<Weights> { |
| 427 | let path = repo_root().join("speech/src/main/assets/supertonic").join(name); |
| 428 | let bytes = std::fs::read(&path).ok()?; |
| 429 | Some( |
| 430 | Weights::parse(&bytes, graph_id) |
| 431 | .unwrap_or_else(|e| panic!("{} is not a usable .maml: {e}", path.display())), |
| 432 | ) |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn the_bundled_supertonic_assets_build_all_four_forward_passes() { |
| 437 | // The four hardcoded passes against the four converted files, which is the strongest automatic |
| 438 | // check that the bundle `:speech` ships is the one the Rust was written for: `Builder::finish` |
| 439 | // refuses a plan that does not read every tensor in its file, and each `build` walks its |
| 440 | // tensors through `Weights::shaped`, so a reordered or re-shaped layer fails here naming the |
| 441 | // tensor rather than producing silent nonsense on a phone. |
| 442 | // |
| 443 | // Widths are arbitrary but non-trivial: every Supertonic plan is utterance-shaped, so a build |
| 444 | // at one length exercises the shape arithmetic that `Net::rebuild` repeats per sentence. |
| 445 | let (frames, chars) = (32u32, 16u32); |
| 446 | |
| 447 | let Some(duration) = supertonic("supertonic_dp.maml", graph::SUPERTONIC_DP) else { |
| 448 | println!( |
| 449 | "skipped: no bundle in speech/src/main/assets/supertonic. \ |
| 450 | Run python scripts/ml/fetch_supertonic.py to build it." |
| 451 | ); |
| 452 | return; |
| 453 | }; |
| 454 | assert_eq!(duration.len(), supertonic_duration::TENSORS); |
| 455 | assert!(!supertonic_duration::build(&duration, chars) |
| 456 | .expect("the duration pass") |
| 457 | .ops |
| 458 | .is_empty()); |
| 459 | |
| 460 | let text = supertonic("supertonic_ttl.maml", graph::SUPERTONIC_TTL).expect("the text encoder"); |
| 461 | assert_eq!(text.len(), supertonic_text::TENSORS); |
| 462 | assert!(!supertonic_text::build(&text, chars).expect("the text pass").ops.is_empty()); |
| 463 | |
| 464 | let sampler = supertonic("supertonic_ve.maml", graph::SUPERTONIC_VE).expect("the sampler"); |
| 465 | assert_eq!(sampler.len(), supertonic_sampler::TENSORS); |
| 466 | assert!(!supertonic_sampler::build(&sampler, frames, chars) |
| 467 | .expect("the sampler pass") |
| 468 | .ops |
| 469 | .is_empty()); |
| 470 | |
| 471 | let vocoder = supertonic("supertonic_voc.maml", graph::SUPERTONIC_VOC).expect("the vocoder"); |
| 472 | assert_eq!(vocoder.len(), supertonic_vocoder::TENSORS); |
| 473 | assert!(!supertonic_vocoder::build(&vocoder, frames).expect("the vocoder pass").ops.is_empty()); |
| 474 | |
| 475 | let total: usize = [&duration, &text, &sampler, &vocoder].iter().map(|w| w.data().len()).sum(); |
| 476 | println!("supertonic: {} MiB of weights across four nets", total / (1 << 20)); |
| 477 | } |
| 478 | |
| 479 | /// The six files `SupertonicBundle.isPresent` requires before `:speech` will advertise a voice. |
| 480 | /// |
| 481 | /// Kotlin's check is a directory listing, so it cannot notice a file that is the right name and the |
| 482 | /// wrong size. This is the counterpart that does: the codepoint table is a fixed 65,536 `int16` and |
| 483 | /// each voice style a fixed 12,928 fp16, both fixed by the architecture rather than by the export, |
| 484 | /// so a length check here is as strong as a digest would be. |
| 485 | #[test] |
| 486 | fn the_bundled_supertonic_inputs_are_the_sizes_the_runtime_assumes() { |
| 487 | let dir = repo_root().join("speech/src/main/assets/supertonic"); |
| 488 | let Ok(indexer) = std::fs::read(dir.join("unicode_indexer.bin")) else { |
| 489 | println!("skipped: no bundle. Run python scripts/ml/fetch_supertonic.py to build it."); |
| 490 | return; |
| 491 | }; |
| 492 | // `post::supertonic::INDEXER_ENTRIES` int16, one per BMP codepoint. |
| 493 | assert_eq!(indexer.len(), 65_536 * 2, "the codepoint table"); |
| 494 | |
| 495 | // `style_ttl` transposed to [256, 50] then `style_dp` flattened to 128, as fp16. |
| 496 | let style_elems = 256 * 50 + 128; |
| 497 | for voice in ["F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5"] { |
| 498 | let name = format!("style_{voice}.bin"); |
| 499 | let bytes = std::fs::read(dir.join(&name)).unwrap_or_else(|e| panic!("{name}: {e}")); |
| 500 | assert_eq!(bytes.len(), style_elems * 2, "{name}"); |
| 501 | } |
| 502 | } |