library:ml: SCRFD and MobileFaceNet forward passes
- Commit
8fe75f734856b5f87cb0a34d5602aca3bcee1964- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 02:38 UTC (3 months ago)
- Parents
0502e44
Diff
library/ml/src/main/rust/src/nets/mobilefacenet.rs
diff --git a/library/ml/src/main/rust/src/nets/mobilefacenet.rs b/library/ml/src/main/rust/src/nets/mobilefacenet.rsnew file mode 100644index 0000000000..031d52633a--- /dev/null+++ b/library/ml/src/main/rust/src/nets/mobilefacenet.rs@@ -0,0 +1,346 @@+//! MobileFaceNet (`w600k_mbf`), the 512-d face embedding `:photos` clusters people by.+//!+//! # Shape of the network+//!+//! A MobileNetV2-style trunk at a fixed 112x112: a four-convolution stem down to+//! 28x28, then three stages of [`residual`] blocks — 4 at 128 channels, 6 at 256, 2 at+//! 256 again — separated by transitions that widen and halve the resolution. It ends+//! with a global depthwise-ish head: 1x1 to 512, 1x1 down to 64, and a fully-connected+//! layer to 512.+//!+//! 112 -> 56 -> 28 -> 14 -> 7, on four stride-2 convolutions.+//!+//! # Three things worth knowing about it+//!+//! * **Every activation is a `PRelu`, and every one fuses.** All 34 follow a `Conv`+//! directly, so this net dispatches no standalone activation pass — see [`Act::PRelu`],+//! which carries the slope tensor's index. The slope is per *channel*, so a shader+//! that broadcast one value would still produce a plausible-looking embedding.+//! * **The final `Gemm` is a convolution here, not an inner product.** Its weight is+//! `[512, 3136]` over a flattened `64 x 7 x 7`, and `scripts/ml/vkml_convert.py`+//! reshapes that to `[512, 64, 7, 7]` — a kernel covering the whole spatial extent,+//! which the existing `conv.comp` computes exactly. That is why there is no+//! `InnerProduct` pipeline.+//! * **The `BatchNormalization` after it is folded into that layer** by the converter,+//! so it is invisible here. A batch norm at inference is a per-channel affine, so the+//! fold is exact rather than an approximation.+//!+//! The **L2 normalisation of the output stays in Kotlin**, where `FaceRecognizer`+//! already does it. The embedding this returns is unnormalised, as ncnn's was.+//!+//! Preprocessing is `(value - 127.5) / 127.5` on an aligned 112x112 crop. Note the+//! divisor: [`super::scrfd`] uses `1 / 128`, and sharing a constant between the two+//! would be wrong in one of them.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// The side length the graph is lowered at. Fixed, unlike [`super::scrfd`].+pub const SIZE: u32 = 112;+/// Length of the embedding this produces.+pub const EMBEDDING: u32 = 512;+/// Tensors in the file: 49 convolutions and one folded `Gemm` at two each, plus 34+/// `PRelu` slopes at one.+pub const TENSORS: usize = 134;++/// Hands out `.vkml` tensor indices in the order the layers appear.+///+/// Unlike [`super::selfie`]'s, this cannot be a counter that steps by two: a `PRelu`+/// contributes one tensor and a convolution two, so the two kinds are asked for+/// separately and the stride is whatever the graph's order implies. `--print-layers`+/// reports the resulting index next to each layer, which is what this was transcribed+/// against.+struct Layers {+ next: usize,+}++impl Layers {+ /// A convolution's weight and bias.+ fn conv(&mut self) -> usize {+ let index = self.next;+ self.next += 2;+ index+ }++ /// A `PRelu`'s per-channel slope.+ fn slope(&mut self) -> usize {+ let index = self.next;+ self.next += 1;+ index+ }+}++/// A 1x1 convolution, which is most of this net.+fn project(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: bool) -> Id {+ let weight = l.conv();+ let act = if act { Act::PRelu(l.slope()) } else { Act::None };+ b.conv(x, weight, out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)+}++/// A 3x3 depthwise convolution with a fused `PRelu`, `pads = [1, 1, 1, 1]`.+fn depthwise(b: &mut Builder, l: &mut Layers, x: Id, stride: u32) -> Id {+ let channels = b.shape(x).c;+ let weight = l.conv();+ let slope = l.slope();+ b.conv(+ x,+ weight,+ channels,+ (3, 3),+ (stride, stride),+ (1, 1),+ (1, 1, 1, 1),+ channels,+ Act::PRelu(slope),+ )+}++/// One residual block: expand 1x1, depthwise 3x3, project 1x1, and add the input back.+///+/// The projection has **no** activation — the `PRelu` sits before the add, not after+/// it — which is what makes the residual path linear.+fn residual(b: &mut Builder, l: &mut Layers, x: Id) -> Id {+ let channels = b.shape(x).c;+ let expanded = project(b, l, x, channels, true);+ let spatial = depthwise(b, l, expanded, 1);+ let projected = project(b, l, spatial, channels, false);+ b.add(x, projected)+}++/// A transition: widen to `wide`, halve the resolution, then project to `out`.+fn transition(b: &mut Builder, l: &mut Layers, x: Id, wide: u32, out: u32) -> Id {+ let widened = project(b, l, x, wide, true);+ let halved = depthwise(b, l, widened, 2);+ project(b, l, halved, out, false)+}++/// Compile the whole forward pass.+pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {+ let mut b = Builder::new(weights);+ let mut layers = Layers { next: 0 };+ let l = &mut layers;+ let input = b.input(Shape::new(3, SIZE, SIZE));++ // Stem: 112 -> 56 -> 28.+ let weight = l.conv();+ let slope = l.slope();+ let x = b.conv(+ input,+ weight,+ 128,+ (3, 3),+ (2, 2),+ (1, 1),+ (1, 1, 1, 1),+ 1,+ Act::PRelu(slope),+ );+ // A grouped 3x3 at `group = 64`, so two input channels per group — neither dense+ // nor depthwise, and the one layer in either face model that is genuinely both.+ let weight = l.conv();+ let slope = l.slope();+ let x = b.conv(+ x,+ weight,+ 128,+ (3, 3),+ (1, 1),+ (1, 1),+ (1, 1, 1, 1),+ 64,+ Act::PRelu(slope),+ );+ let x = project(&mut b, l, x, 128, true);+ let x = depthwise(&mut b, l, x, 2);+ let mut x = project(&mut b, l, x, 128, false);++ // 4 blocks at 128 channels, 28x28.+ for _ in 0..4 {+ x = residual(&mut b, l, x);+ }++ // 28 -> 14, widening to 256.+ let mut x = transition(&mut b, l, x, 256, 256);+ // 6 blocks at 256 channels, 14x14.+ for _ in 0..6 {+ x = residual(&mut b, l, x);+ }++ // 14 -> 7. Widens to 512 and comes back down to 256, which is why `transition`+ // takes both counts.+ let mut x = transition(&mut b, l, x, 512, 256);+ // 2 blocks at 256 channels, 7x7.+ for _ in 0..2 {+ x = residual(&mut b, l, x);+ }++ // Head: 512, then a narrow 64 that the fully-connected layer reads.+ let x = project(&mut b, l, x, 512, true);+ let narrow = project(&mut b, l, x, 64, true);+ // The `Gemm`, as a convolution whose kernel is the whole 7x7 map. Output is+ // `512 x 1 x 1`, which the host reads as a flat 512-vector.+ let weight = l.conv();+ let embedding = b.conv(+ narrow,+ weight,+ EMBEDDING,+ (SIZE / 16, SIZE / 16),+ (1, 1),+ (1, 1),+ (0, 0, 0, 0),+ 1,+ Act::None,+ );+ b.finish(&[embedding])+}++#[cfg(test)]+mod tests {+ use super::super::tests::Shapes;+ use super::super::{Kind, Op};+ use super::*;++ fn plan() -> Plan {+ let source = Shapes::new(TENSORS);+ build(&source).expect("mobilefacenet builds")+ }++ fn dispatches(plan: &Plan, kind: Kind) -> usize {+ plan.ops+ .iter()+ .filter(|op| matches!(op, Op::Dispatch { kind: k, .. } if *k == kind))+ .count()+ }++ #[test]+ fn the_op_inventory_matches_the_onnx() {+ // The counts `scripts/ml/vkml_convert.py` asserts against the ONNX itself. The+ // 49 convolutions include the `Gemm`, which is lowered as one, so the export's+ // 49 `Conv` plus 1 `Gemm` is 50 dispatches here.+ let plan = plan();+ assert_eq!(dispatches(&plan, Kind::Conv), 50);+ assert_eq!(dispatches(&plan, Kind::Add), 12);+ // No pooling, no resize, no concatenation and no transposed convolution: this is+ // the plainest graph in the runtime.+ assert_eq!(dispatches(&plan, Kind::ConvTranspose), 0);+ assert_eq!(dispatches(&plan, Kind::MaxPool), 0);+ assert_eq!(dispatches(&plan, Kind::Resize), 0);+ assert_eq!(dispatches(&plan, Kind::ResizeNearest), 0);+ assert_eq!(dispatches(&plan, Kind::GlobalAvgPool), 0);+ assert_eq!(dispatches(&plan, Kind::MulBroadcast), 0);+ assert_eq!(plan.ops.iter().filter(|o| matches!(o, Op::Copy { .. })).count(), 0);+ }++ #[test]+ fn the_pass_consumes_the_whole_tensor_table() {+ let source = Shapes::new(TENSORS);+ assert!(build(&source).is_ok());+ assert_eq!(source.asked.borrow().len(), TENSORS);+ }++ #[test]+ fn every_convolution_but_the_residual_projections_fuses_a_prelu() {+ // 34 `PRelu` in the export, all fused. The 16 that do not have one are the 12+ // residual projections, the 3 transition projections and the final `Gemm` —+ // exactly the layers whose output is added to or read as a result.+ let plan = plan();+ let fused = plan+ .ops+ .iter()+ .filter(|op| matches!(op, Op::Dispatch { push, .. } if push.act == Act::PRelu(0).code()))+ .count();+ assert_eq!(fused, 34);+ }++ #[test]+ fn each_fused_prelu_reads_its_own_slope() {+ // A transcription that reused one index, or that let the counter drift by+ // treating a slope as two tensors, would land several layers on the same offset.+ let plan = plan();+ let mut slopes: Vec<u32> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { push, .. } if push.act == Act::PRelu(0).code() => {+ Some(push.act_weight)+ }+ _ => None,+ })+ .collect();+ let total = slopes.len();+ slopes.sort_unstable();+ slopes.dedup();+ assert_eq!(slopes.len(), total, "two layers share a PReLU slope");+ }++ #[test]+ fn the_layer_table_matches_the_onnx_export() {+ let source = Shapes::new(TENSORS);+ let _ = build(&source);+ let asked = source.asked.borrow();+ let shape_at = |index: usize| -> Vec<u32> {+ asked+ .iter()+ .find(|(i, _)| *i == index)+ .map(|(_, dims)| dims.clone())+ .unwrap_or_default()+ };+ // Layer 0, the stem.+ assert_eq!(shape_at(0), vec![128, 3, 3, 3]);+ // Its slope, one tensor after the bias. A rank-3 `[c, 1, 1]`, which is what+ // ONNX exports a per-channel `PRelu` as.+ assert_eq!(shape_at(2), vec![128, 1, 1]);+ // Tensor 3, the `group = 64` convolution: two input channels per group, so+ // `[128, 2, 3, 3]`. Read as depthwise it would be `[128, 1, 3, 3]`.+ assert_eq!(shape_at(3), vec![128, 2, 3, 3]);+ // Tensor 9, the first depthwise proper.+ assert_eq!(shape_at(9), vec![128, 1, 3, 3]);+ // Tensor 46, the first transition widening to 256.+ assert_eq!(shape_at(46), vec![256, 128, 1, 1]);+ // Tensor 129, the narrow 64-channel layer the fully-connected one reads.+ assert_eq!(shape_at(129), vec![64, 512, 1, 1]);+ // Tensor 132, the `Gemm` as a 7x7 kernel over 64 channels. `[512, 3136]` — the+ // shape it has in the ONNX — would mean the converter did not reshape it.+ assert_eq!(shape_at(132), vec![512, 64, 7, 7]);+ }++ #[test]+ fn the_input_and_output_are_the_shapes_kotlin_expects() {+ let plan = plan();+ assert_eq!(plan.input().expect("one input").shape, Shape::new(3, SIZE, SIZE));+ // `512 x 1 x 1`, which the host reads as a flat 512-vector.+ assert_eq!(plan.output().expect("one output").shape, Shape::new(EMBEDDING, 1, 1));+ }++ #[test]+ fn the_resolution_halves_exactly_four_times() {+ // 112 -> 56 -> 28 -> 14 -> 7. If the stem's grouped 3x3 were given stride 2 by+ // mistake the net would still build, at a quarter of the spatial extent, and the+ // final 7x7 kernel would then cover the whole map of a *different* size.+ let plan = plan();+ let strided: Vec<u32> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::Conv, push, .. } if push.stride_h == 2 => {+ Some(push.in_h)+ }+ _ => None,+ })+ .collect();+ assert_eq!(strided, vec![112, 56, 28, 14]);+ }++ #[test]+ fn no_op_reads_a_region_it_also_writes() {+ super::super::tests::assert_no_aliasing(&plan());+ }++ #[test]+ fn the_arena_is_bounded() {+ let plan = plan();+ let bytes = plan.arena_elems as u64 * 2;+ // 128x56x56 fp16 is 800 KB and is the widest thing here, so a few MB is the+ // whole net. This runs once per detected face during an indexing pass.+ assert!(bytes < 8 * 1024 * 1024, "arena is {bytes} bytes");+ }+}
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 e1a1d0d955..497666d34b 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -31,6 +31,8 @@ /// so it adds nothing to the shipped `.so`. #[cfg(test)] pub mod reference;+pub mod mobilefacenet;+pub mod scrfd; pub mod selfie; pub mod u2netp;
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 527eca0d8c..b8249d3369 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -654,7 +654,7 @@ fn uniform(state: &mut u32) -> f32 { #[cfg(test)] mod tests {- use super::super::{selfie, u2netp, Act, Builder};+ use super::super::{mobilefacenet, scrfd, selfie, u2netp, Act, Builder}; use super::*; /// Build a plan whose only ops come from `record`, run it, and return the output.@@ -1251,4 +1251,84 @@ mod tests { ); assert_usable_mask("u2netp", &plan, weights.data()); }++ #[test]+ #[ignore = "runs the full shipped nets; minutes in a debug build"]+ fn the_shipped_scrfd_net_produces_usable_detection_maps() {+ let Some(bytes) = asset("photos/src/main/assets/scrfd_500m.vkml") else {+ return;+ };+ let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::SCRFD)+ .expect("the shipped scrfd asset parses");+ // 128x128 rather than the 640 it runs at on device: the plan lowers at any+ // multiple of 32, and a 1/25th-area run exercises every one of the 60 layers,+ // both nearest upsamples and all nine heads for a twenty-fifth of the arithmetic.+ let plan = scrfd::build(&weights, 128, 128).expect("scrfd builds at 128x128");+ let shape = plan.input().expect("one input").shape;+ let got = run_multi(&plan, weights.data(), &[&blob(shape)]).expect("scrfd runs");++ assert_eq!(got.len(), 9);+ for (group, stride) in got.chunks_exact(3).zip(scrfd::STRIDES) {+ let [score, bbox, keypoints] = match group {+ [a, b, c] => [a, b, c],+ other => panic!("stride {stride}: {} maps", other.len()),+ };+ // Scores come through a sigmoid, so they are probabilities. Boxes and+ // keypoints are raw distances in stride units and only have to be finite.+ for (i, &value) in score.iter().enumerate() {+ assert!((0.0..=1.0).contains(&value), "stride {stride} score {i} is {value}");+ }+ for (name, map) in [("box", bbox), ("keypoint", keypoints)] {+ for (i, &value) in map.iter().enumerate() {+ assert!(value.is_finite(), "stride {stride} {name} {i} is {value}");+ }+ }+ let peak = score.iter().fold(0.0f32, |a, &b| a.max(b));+ let spread = bbox.iter().fold(0.0f32, |a, &b| a.max(b.abs()));+ println!("scrfd/{stride}: peak score {peak:.4} largest box distance {spread:.3}");+ // A box map that is identically zero means the regression branch never ran,+ // which is what reading the wrong tensor index for a head produces.+ assert!(spread > 1e-3, "stride {stride} predicts no box extent at all");+ }+ }++ #[test]+ #[ignore = "runs the full shipped nets; minutes in a debug build"]+ fn the_shipped_mobilefacenet_net_embeds_two_faces_differently() {+ let Some(bytes) = asset("photos/src/main/assets/w600k_mbf.vkml") else {+ return;+ };+ let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::MOBILEFACENET)+ .expect("the shipped mobilefacenet asset parses");+ let plan = mobilefacenet::build(&weights).expect("mobilefacenet builds");+ let shape = plan.input().expect("one input").shape;+ assert_eq!(+ plan.output().expect("one output").shape,+ Shape::new(mobilefacenet::EMBEDDING, 1, 1)+ );++ let first = run(&plan, weights.data(), &ramp(shape)).expect("embeds a ramp");+ let second = run(&plan, weights.data(), &blob(shape)).expect("embeds a blob");+ for (label, embedding) in [("ramp", &first), ("blob", &second)] {+ assert_eq!(embedding.len(), mobilefacenet::EMBEDDING as usize);+ for (i, &value) in embedding.iter().enumerate() {+ assert!(value.is_finite(), "{label} component {i} is {value}");+ }+ let norm = embedding.iter().map(|v| v * v).sum::<f32>().sqrt();+ println!("mobilefacenet/{label}: L2 norm {norm:.4}");+ // Unnormalised on purpose — `FaceRecognizer` L2-normalises in Kotlin — so+ // this only has to be a vector rather than the origin. A collapsed net,+ // which is what a wrong PReLU slope index produces, lands at zero.+ assert!(norm > 1e-2, "{label} embeds to the origin");+ }++ // Cosine similarity, which is exactly what the clustering compares. Two inputs+ // this unlike must not map to the same direction; a net whose final `Gemm` was+ // reshaped wrongly tends to return near-identical vectors for everything.+ let dot: f32 = first.iter().zip(&second).map(|(a, b)| a * b).sum();+ let magnitude = |v: &[f32]| v.iter().map(|x| x * x).sum::<f32>().sqrt();+ let cosine = dot / (magnitude(&first) * magnitude(&second));+ println!("mobilefacenet: cosine between the two {cosine:.4}");+ assert!(cosine < 0.99, "two unlike inputs embed to the same direction");+ } }
library/ml/src/main/rust/src/nets/scrfd.rs
diff --git a/library/ml/src/main/rust/src/nets/scrfd.rs b/library/ml/src/main/rust/src/nets/scrfd.rsnew file mode 100644index 0000000000..faa363d9c1--- /dev/null+++ b/library/ml/src/main/rust/src/nets/scrfd.rs@@ -0,0 +1,464 @@+//! SCRFD 500M with keypoints, the face detector `:photos` finds faces with.+//!+//! # Shape of the network+//!+//! Three parts, and the middle one is where the complexity is:+//!+//! * A **backbone** of 29 convolutions — a stem, then 14 depthwise/pointwise pairs —+//! which is a plain sequential stack with no residuals at all. It branches three+//! times, at strides 8, 16 and 32, with 72, 152 and 288 channels.+//! * A **PAFPN neck**: three 1x1 laterals reduce all three branches to 16 channels, a+//! top-down path upsamples and adds, a bottom-up path downsamples and adds, and seven+//! 3x3 convolutions sit along it. None of the neck's convolutions has an activation.+//! * Three identical **heads**, one per stride, each four convolutions deep and ending+//! in three outputs: a 2-channel score map, an 8-channel box map and a 20-channel+//! keypoint map. Two anchors per cell, so those are 1, 4 and 10 values per anchor.+//!+//! Nine outputs in total, which is what [`super::Plan::outputs`] being a list is for.+//!+//! # Dynamically shaped, unlike every other net here+//!+//! The export's input is `[1, 3, ?, ?]`: SCRFD runs at 640 on the long side with the+//! short side padded up to a multiple of 32, so the shape depends on the photo's aspect+//! ratio. [`build`] therefore takes the size, and a plan is compiled per shape rather+//! than once.+//!+//! Multiples of 32 are required rather than merely conventional. Five stride-2+//! convolutions take the input to 1/32, and the neck's two upsamples and two+//! downsamples assume the three branch extents are exactly 2x apart. At a size that is+//! not a multiple of 32 the floor-divisions disagree by a row, an `Add` in the neck gets+//! two different shapes and [`build`] fails — which is the right outcome, but it is+//! cheaper to say so up front.+//!+//! # What is deliberately left to the host+//!+//! The ONNX ends each head with `Transpose` + `Reshape`, and `Sigmoid` on the scores.+//! The transpose and reshape are a relabelling — they flatten `[1, c, h, w]` to+//! `[h * w * anchors, c / anchors]` — and NCHW indexing does that for free, so the plan+//! stops at the convolution outputs and the anchor decode reads them directly. The+//! sigmoid **is** kept, fused into the score convolution, because it is arithmetic:+//! applying it before a pure permutation rather than after is identical.+//!+//! So anchor decode, non-maximum suppression and undoing the letterbox all happen in+//! Rust on the maps this returns. See `post::nms`.+//!+//! Preprocessing is mean 127.5 and norm **1/128** — note the divisor, which is *not*+//! [`super::mobilefacenet`]'s 1/127.5. Sharing one constant between them would be wrong+//! in one of the two.++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// The long side the detector runs at.+pub const LONG_SIDE: u32 = 640;+/// Both extents must be a multiple of this. See the note on shapes above.+pub const EXTENT_MULTIPLE: u32 = 32;+/// The three strides the heads predict at.+pub const STRIDES: [u32; 3] = [8, 16, 32];+/// Anchors per cell, at every stride.+pub const ANCHORS: u32 = 2;+/// Tensors in the file: 60 convolutions, weight and bias each.+pub const TENSORS: usize = 120;++/// Channels the neck reduces every branch to.+const NECK: u32 = 16;+/// Channels inside each head.+const HEAD: u32 = 64;++/// Hands out `.vkml` tensor indices in the order the layers appear. Every layer here is+/// a convolution, so this steps by two throughout — unlike+/// [`super::mobilefacenet`]'s, which has `PRelu` slopes to interleave.+struct Layers {+ next: usize,+}++impl Layers {+ fn take(&mut self) -> usize {+ let index = self.next;+ self.next += 2;+ index+ }+}++/// The backbone's 14 depthwise/pointwise pairs, as `(stride, output channels)`.+///+/// Read off `vkml_convert.py --print-layers`. The stem convolution before them is+/// written out at its call site because it is the only dense one.+const TRUNK: [(u32, u32); 14] = [+ (1, 16),+ (2, 40),+ (1, 40),+ (2, 72),+ (1, 72),+ (1, 72), // -> stride 8+ (2, 152),+ (1, 152), // -> stride 16+ (2, 288),+ (1, 288),+ (1, 288),+ (1, 288),+ (1, 288),+ (1, 288), // -> stride 32+];++/// Indices into [`TRUNK`] whose pointwise output the neck reads.+const BRANCHES: [usize; 3] = [5, 7, 13];++/// A 3x3 depthwise convolution, `pads = [1, 1, 1, 1]`, with a fused ReLU.+fn depthwise(b: &mut Builder, l: &mut Layers, x: Id, stride: u32) -> Id {+ let channels = b.shape(x).c;+ b.conv(+ x,+ l.take(),+ channels,+ (3, 3),+ (stride, stride),+ (1, 1),+ (1, 1, 1, 1),+ channels,+ Act::Relu,+ )+}++/// A 1x1 convolution.+fn point(b: &mut Builder, l: &mut Layers, x: Id, out: u32, act: Act) -> Id {+ b.conv(x, l.take(), out, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, act)+}++/// A 3x3 convolution at `stride`, `pads = [1, 1, 1, 1]`.+fn spatial(b: &mut Builder, l: &mut Layers, x: Id, out: u32, stride: u32, act: Act) -> Id {+ b.conv(+ x,+ l.take(),+ out,+ (3, 3),+ (stride, stride),+ (1, 1),+ (1, 1, 1, 1),+ 1,+ act,+ )+}++/// One head: four convolutions, then the score, box and keypoint maps.+///+/// The score map fuses a sigmoid; the other two are raw, because a box is a distance and+/// a keypoint an offset. Returns them in that order.+fn head(b: &mut Builder, l: &mut Layers, x: Id) -> (Id, Id, Id) {+ let x = depthwise(b, l, x, 1);+ let x = point(b, l, x, HEAD, Act::Relu);+ let x = depthwise(b, l, x, 1);+ let shared = point(b, l, x, HEAD, Act::Relu);++ let score = spatial(b, l, shared, ANCHORS, 1, Act::Sigmoid);+ let bbox = spatial(b, l, shared, ANCHORS * 4, 1, Act::None);+ let keypoints = spatial(b, l, shared, ANCHORS * 10, 1, Act::None);+ (score, bbox, keypoints)+}++/// Compile the forward pass for an input of `height` x `width`.+///+/// Both must be multiples of [`EXTENT_MULTIPLE`]; see the module docs for why that is a+/// requirement and not a convention.+pub fn build(weights: &dyn WeightSource, height: u32, width: u32) -> Result<Plan, String> {+ if height == 0 || width == 0 {+ return Err(format!("a {width}x{height} input"));+ }+ if !height.is_multiple_of(EXTENT_MULTIPLE) || !width.is_multiple_of(EXTENT_MULTIPLE) {+ return Err(format!(+ "a {width}x{height} input: both extents must be a multiple of \+ {EXTENT_MULTIPLE}, or the neck's three branches are not exactly 2x apart"+ ));+ }++ let mut b = Builder::new(weights);+ let mut layers = Layers { next: 0 };+ let l = &mut layers;+ let input = b.input(Shape::new(3, height, width));++ // Backbone. The stem is the only dense convolution; everything after it is a+ // depthwise/pointwise pair, and there are no residual connections anywhere.+ let mut x = spatial(&mut b, l, input, 16, 2, Act::Relu);+ let mut branches = Vec::with_capacity(BRANCHES.len());+ for (pair, &(stride, out)) in TRUNK.iter().enumerate() {+ x = depthwise(&mut b, l, x, stride);+ x = point(&mut b, l, x, out, Act::Relu);+ if BRANCHES.contains(&pair) {+ branches.push(x);+ }+ }+ let [c3, c4, c5] = match branches.as_slice() {+ [a, b, c] => [*a, *b, *c],+ other => return Err(format!("the backbone branched {} times, not 3", other.len())),+ };++ // Neck, in the export's node order — which is also ascending tensor order, so the+ // counter above stays a counter. The two `Add`s of the bottom-up path have to be+ // interleaved between the downsamples that feed them.+ //+ // Laterals: everything down to 16 channels.+ let p3 = point(&mut b, l, c3, NECK, Act::None);+ let p4 = point(&mut b, l, c4, NECK, Act::None);+ let p5 = point(&mut b, l, c5, NECK, Act::None);++ // Top-down. `resize_nearest_like`, not `resize_like`: the export is `mode=nearest`,+ // and the bilinear kernel would blur every lateral these are added to.+ let up5 = b.resize_nearest_like(p5, p4);+ let merged4 = b.add(p4, up5);+ let up4 = b.resize_nearest_like(merged4, p3);+ let merged3 = b.add(p3, up4);++ let fpn3 = spatial(&mut b, l, merged3, NECK, 1, Act::None);+ let fpn4 = spatial(&mut b, l, merged4, NECK, 1, Act::None);+ let fpn5 = spatial(&mut b, l, p5, NECK, 1, Act::None);++ // Bottom-up: stride 8 back down onto stride 16, then that onto stride 32.+ let down3 = spatial(&mut b, l, fpn3, NECK, 2, Act::None);+ let pan4 = b.add(fpn4, down3);+ let down4 = spatial(&mut b, l, pan4, NECK, 2, Act::None);+ let pan5 = b.add(fpn5, down4);++ let out4 = spatial(&mut b, l, pan4, NECK, 1, Act::None);+ let out5 = spatial(&mut b, l, pan5, NECK, 1, Act::None);++ // Heads. Note the stride-8 head reads `fpn3` directly: the export has no+ // `pafpn_conv` on that level, only on the two the bottom-up path touched.+ let mut outputs = Vec::with_capacity(9);+ for level in [fpn3, out4, out5] {+ let (score, bbox, keypoints) = head(&mut b, l, level);+ outputs.push(score);+ outputs.push(bbox);+ outputs.push(keypoints);+ }+ // Grouped by stride, three at a time — so the decode is `outputs.chunks_exact(3)`+ // over `STRIDES`. The ONNX declares its nine outputs grouped the other way, by kind+ // then stride; the order here is the one that makes the post-processing loop+ // obviously right, and it is the only place the two conventions meet.+ b.finish(&outputs)+}++#[cfg(test)]+mod tests {+ use super::super::tests::Shapes;+ use super::super::{Kind, Op};+ use super::*;++ fn plan() -> Plan {+ let source = Shapes::new(TENSORS);+ build(&source, 640, 640).expect("scrfd builds at 640x640")+ }++ fn dispatches(plan: &Plan, kind: Kind) -> usize {+ plan.ops+ .iter()+ .filter(|op| matches!(op, Op::Dispatch { kind: k, .. } if *k == kind))+ .count()+ }++ #[test]+ fn the_op_inventory_matches_the_onnx() {+ // The counts `scripts/ml/vkml_convert.py` asserts against the ONNX itself.+ let plan = plan();+ assert_eq!(dispatches(&plan, Kind::Conv), 60);+ assert_eq!(dispatches(&plan, Kind::Add), 4);+ assert_eq!(dispatches(&plan, Kind::ResizeNearest), 2);+ // The export's two `Resize` nodes are both nearest, so the bilinear pipeline+ // must not appear. This is the assertion that catches `resize_like` being used+ // by habit.+ assert_eq!(dispatches(&plan, Kind::Resize), 0);+ assert_eq!(dispatches(&plan, Kind::ConvTranspose), 0);+ assert_eq!(dispatches(&plan, Kind::MaxPool), 0);+ assert_eq!(dispatches(&plan, Kind::GlobalAvgPool), 0);+ assert_eq!(dispatches(&plan, Kind::MulBroadcast), 0);+ assert_eq!(plan.ops.iter().filter(|o| matches!(o, Op::Copy { .. })).count(), 0);+ }++ #[test]+ fn the_pass_consumes_the_whole_tensor_table() {+ let source = Shapes::new(TENSORS);+ assert!(build(&source, 640, 640).is_ok());+ assert_eq!(source.asked.borrow().len(), TENSORS);+ }++ #[test]+ fn there_are_nine_outputs_grouped_by_stride() {+ // Two anchors per cell: 2 score channels, 8 box channels, 20 keypoint channels,+ // at 1/8, 1/16 and 1/32 of a 640x640 input.+ let plan = plan();+ assert_eq!(plan.outputs.len(), 9);+ let shapes: Vec<Shape> = plan.outputs.iter().map(|b| b.shape).collect();+ assert_eq!(+ shapes,+ vec![+ Shape::new(2, 80, 80),+ Shape::new(8, 80, 80),+ Shape::new(20, 80, 80),+ Shape::new(2, 40, 40),+ Shape::new(8, 40, 40),+ Shape::new(20, 40, 40),+ Shape::new(2, 20, 20),+ Shape::new(8, 20, 20),+ Shape::new(20, 20, 20),+ ]+ );+ }++ #[test]+ fn the_anchor_count_matches_the_onnx_output_lengths() {+ // The export declares its score maps as 12800, 3200 and 800 rows. Those are+ // `h * w * anchors` at each stride, and they are what pin `ANCHORS` at 2 rather+ // than the channel counts, which 1 anchor of 2 classes would also explain.+ let plan = plan();+ let rows: Vec<u32> = plan+ .outputs+ .chunks_exact(3)+ .filter_map(|group| group.first())+ .map(|score| score.shape.h * score.shape.w * ANCHORS)+ .collect();+ assert_eq!(rows, vec![12800, 3200, 800]);+ }++ #[test]+ fn only_the_score_maps_are_activated() {+ // The three sigmoids in the export are all on scores. A sigmoid on a box map+ // would clamp every distance into `0..1` and shrink every detection to a point.+ let plan = plan();+ let sigmoids = plan+ .ops+ .iter()+ .filter(|op| matches!(op, Op::Dispatch { push, .. } if push.act == Act::Sigmoid.code()))+ .count();+ assert_eq!(sigmoids, 3);+ for (group, stride) in plan.outputs.chunks_exact(3).zip(STRIDES) {+ match group {+ [score, bbox, keypoints] => {+ assert_eq!(score.shape.c, ANCHORS, "stride {stride} score");+ assert_eq!(bbox.shape.c, ANCHORS * 4, "stride {stride} box");+ assert_eq!(keypoints.shape.c, ANCHORS * 10, "stride {stride} keypoints");+ }+ other => panic!("stride {stride}: {other:?}"),+ }+ }+ }++ #[test]+ fn the_neck_reduces_all_three_branches_to_sixteen_channels() {+ // The laterals are the only place 72, 152 and 288 channels appear as *inputs*,+ // so this pins that the branches were taken at the right depths. Taking one a+ // pair too early gives a lateral the wrong input channel count, and the weight+ // shape check would then fail against the real asset — but not against a stub.+ let source = Shapes::new(TENSORS);+ let _ = build(&source, 640, 640);+ let asked = source.asked.borrow();+ let shape_at = |index: usize| -> Vec<u32> {+ asked+ .iter()+ .find(|(i, _)| *i == index)+ .map(|(_, dims)| dims.clone())+ .unwrap_or_default()+ };+ assert_eq!(shape_at(58), vec![16, 72, 1, 1]);+ assert_eq!(shape_at(60), vec![16, 152, 1, 1]);+ assert_eq!(shape_at(62), vec![16, 288, 1, 1]);+ }++ #[test]+ fn the_layer_table_matches_the_onnx_export() {+ let source = Shapes::new(TENSORS);+ let _ = build(&source, 640, 640);+ let asked = source.asked.borrow();+ let shape_at = |index: usize| -> Vec<u32> {+ asked+ .iter()+ .find(|(i, _)| *i == index)+ .map(|(_, dims)| dims.clone())+ .unwrap_or_default()+ };+ // Tensor 0, the stem: the only dense convolution in the backbone.+ assert_eq!(shape_at(0), vec![16, 3, 3, 3]);+ // Tensor 2, the first depthwise.+ assert_eq!(shape_at(2), vec![16, 1, 3, 3]);+ // Tensors 64..76, the neck's seven 3x3s, all 16 to 16.+ for index in [64, 66, 68, 70, 72, 74, 76] {+ assert_eq!(shape_at(index), vec![16, 16, 3, 3], "tensor {index}");+ }+ // Tensor 78, the stride-8 head's depthwise over the neck's 16 channels.+ assert_eq!(shape_at(78), vec![16, 1, 3, 3]);+ // Tensors 86, 88, 90: the stride-8 score, box and keypoint convolutions.+ assert_eq!(shape_at(86), vec![2, 64, 3, 3]);+ assert_eq!(shape_at(88), vec![8, 64, 3, 3]);+ assert_eq!(shape_at(90), vec![20, 64, 3, 3]);+ // The stride-32 head, 14 tensors later twice over. The three heads have their+ // own weights in this export rather than sharing them.+ assert_eq!(shape_at(114), vec![2, 64, 3, 3]);+ assert_eq!(shape_at(118), vec![20, 64, 3, 3]);+ }++ #[test]+ fn the_backbone_downsamples_five_times() {+ // 640 -> 320 -> 160 -> 80 -> 40 -> 20, which is what puts the three branches at+ // strides 8, 16 and 32. The neck adds two more stride-2 convolutions on 16+ // channels, hence seven in total.+ let plan = plan();+ let strided: Vec<(u32, u32)> = plan+ .ops+ .iter()+ .filter_map(|op| match op {+ Op::Dispatch { kind: Kind::Conv, push, .. } if push.stride_h == 2 => {+ Some((push.in_c, push.in_h))+ }+ _ => None,+ })+ .collect();+ assert_eq!(+ strided,+ vec![+ // Backbone: the stem, then four depthwise reductions.+ (3, 640),+ (16, 320),+ (40, 160),+ (72, 80),+ (152, 40),+ // Neck: the bottom-up path, both on 16 channels.+ (16, 80),+ (16, 40),+ ]+ );+ }++ #[test]+ fn a_non_rectangular_input_is_lowered_at_its_own_aspect_ratio() {+ // The letterboxed shape for a landscape photo: 640 long, short side padded to a+ // multiple of 32. Every extent below has to halve cleanly five times.+ let source = Shapes::new(TENSORS);+ let plan = build(&source, 384, 640).expect("builds at 640x384");+ let shapes: Vec<Shape> = plan.outputs.iter().map(|b| b.shape).collect();+ assert_eq!(shapes.first().copied(), Some(Shape::new(2, 48, 80)));+ assert_eq!(shapes.get(8).copied(), Some(Shape::new(20, 12, 20)));+ }++ #[test]+ fn an_extent_that_is_not_a_multiple_of_32_is_refused() {+ // 100 halves to 50, 25, 13, 7, 4 — and 13 is where the neck's assumption that+ // the branches are 2x apart breaks. Refused with a reason rather than failing+ // later inside an `Add`.+ let source = Shapes::new(TENSORS);+ let error = build(&source, 100, 640).expect_err("not a multiple of 32");+ assert!(error.contains("multiple of 32"), "{error}");+ }++ #[test]+ fn no_op_reads_a_region_it_also_writes() {+ super::super::tests::assert_no_aliasing(&plan());+ }++ #[test]+ fn the_arena_is_bounded() {+ let plan = plan();+ let bytes = plan.arena_elems as u64 * 2;+ // 16x320x320 fp16 is 3.3 MB and the widest thing here is the stem's output at+ // 16x320x320. A detector run is one-shot per photo during indexing, so this has+ // more headroom than the selfie net, but it still has to fit alongside the+ // embedder.+ assert!(bytes < 64 * 1024 * 1024, "arena is {bytes} bytes");+ }+}
library/ml/src/main/rust/tests/assets.rs
diff --git a/library/ml/src/main/rust/tests/assets.rs b/library/ml/src/main/rust/tests/assets.rsindex a5a1686e55..f39332eda2 100644--- a/library/ml/src/main/rust/tests/assets.rs+++ b/library/ml/src/main/rust/tests/assets.rs@@ -13,7 +13,7 @@ use std::path::{Path, PathBuf}; -use modelrunner::nets::{selfie, u2netp};+use modelrunner::nets::{mobilefacenet, scrfd, selfie, u2netp}; use modelrunner::weights::{graph, Weights}; /// The repo root, found by walking up for `settings.gradle.kts` rather than by counting@@ -56,6 +56,39 @@ fn the_shipped_u2netp_asset_builds_the_u2netp_forward_pass() { assert!(!plan.ops.is_empty()); } +#[test]+fn the_shipped_mobilefacenet_asset_builds_the_mobilefacenet_forward_pass() {+ let weights = load("photos/src/main/assets/w600k_mbf.vkml", graph::MOBILEFACENET);+ assert_eq!(weights.len(), mobilefacenet::TENSORS);+ let plan =+ mobilefacenet::build(&weights).expect("the shipped asset matches nets::mobilefacenet");+ assert!(!plan.ops.is_empty());+}++#[test]+fn the_shipped_scrfd_asset_builds_the_scrfd_forward_pass() {+ let weights = load("photos/src/main/assets/scrfd_500m.vkml", graph::SCRFD);+ assert_eq!(weights.len(), scrfd::TENSORS);+ let plan = scrfd::build(&weights, scrfd::LONG_SIDE, scrfd::LONG_SIDE)+ .expect("the shipped asset matches nets::scrfd");+ assert_eq!(plan.outputs.len(), 9);+}++#[test]+fn the_scrfd_pass_builds_at_every_letterbox_shape_a_photo_can_produce() {+ // The detector is compiled per shape, so the whole family has to lower — not just+ // the square case. These are the short sides a 640-long-side letterbox rounds to for+ // aspect ratios from 1:1 to about 3:1, which covers any real photo.+ let weights = load("photos/src/main/assets/scrfd_500m.vkml", graph::SCRFD);+ for short in (scrfd::EXTENT_MULTIPLE..=scrfd::LONG_SIDE).step_by(32) {+ for (height, width) in [(short, scrfd::LONG_SIDE), (scrfd::LONG_SIDE, short)] {+ let plan = scrfd::build(&weights, height, width)+ .unwrap_or_else(|e| panic!("{width}x{height}: {e}"));+ assert_eq!(plan.outputs.len(), 9, "{width}x{height}");+ }+ }+}+ #[test] fn neither_asset_will_load_as_the_other_network() { // The `graph_id` in the header exists for exactly this: the two files are both