camera: swap model
- Commit
71f51cf0d89b335677cf92acfba7ce6cd3396628- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-14 03:00 UTC (1 month ago)
- Parents
f5bc174
Diff
camera/build.gradle.kts
diff --git a/camera/build.gradle.kts b/camera/build.gradle.ktsindex a69c953393..50a3e908bc 100644--- a/camera/build.gradle.kts+++ b/camera/build.gradle.kts@@ -15,8 +15,8 @@ android { applicationId = "com.vayunmathur.camera" } androidResources {- // selfie_segmentation.maml is read straight out of the APK by SelfieSegmenter, so- // leave it uncompressed: fp16 weights barely deflate, and a compressed asset would+ // *.maml are read straight out of the APK by the segmenters, so+ // leave them uncompressed: fp16 weights barely deflate, and a compressed asset would // have to be inflated into a heap buffer before it could be uploaded. noCompress += "maml" }@@ -43,8 +43,10 @@ dependencies { implementation(libs.androidx.camera.extensions) implementation(libs.androidx.exifinterface) implementation(libs.zxing.core)- // On-device portrait segmentation. MediaPipe Selfie Segmentation (Apache-2.0) on our- // own Vulkan compute runtime; see camera/src/main/assets/README.md.+ // On-device portrait segmentation and matting. MediaPipe Selfie Segmentation+ // (Apache-2.0) for the preview plus MODNet photographic-portrait matting+ // (Apache-2.0) for still capture, both on our own Vulkan compute runtime;+ // see camera/src/main/assets/README.md. // // ncnn is gone from the whole tree, not just this app: `:translate` was the last consumer and // it now runs SMaLL-100 on `:library:ml` too, so `libncnn_android.so` is in no APK here.
camera/src/main/assets/README.md
diff --git a/camera/src/main/assets/README.md b/camera/src/main/assets/README.mdindex d2586175c6..55ac2c12d6 100644--- a/camera/src/main/assets/README.md+++ b/camera/src/main/assets/README.md@@ -30,3 +30,31 @@ and the hardcoded forward pass in This file is inside `assets/`, so it is packaged into the APK. That is deliberate rather than overlooked: it is ~1 KB, and Apache-2.0 §4 asks that attribution notices travel with the distributed work, which here is the weights next to it.++## `modnet.maml`++Apache-2.0, from the official MODNet repository https://github.com/ZHKKKe/MODNet+(MobileNetV2 backbone, `modnet_photographic_portrait_matting` weights), via the+mirror https://huggingface.co/DavG25/modnet-pretrained-models+(`models/modnet_photographic_portrait_matting.onnx`, 25,888,640 B fp32,+SHA-256 `07c308cf…84df9`) — MODNet portrait matting, the model purpose-built+for trimap-free portrait alpha with hair detail.++Not the ONNX itself: `scripts/ml/modnet_fold.py` folds the export's Slice-fed+batch norms into their convolutions and rewrites the SE block's MatMuls as 1x1+convolutions, then converts to the fp16 `.maml` weights container that+`:library:ml` reads. The source ONNX SHA-256 is in the `.maml` header, so+a shipped asset traces back to this line without needing the ONNX on disk.++Run at 512×512 RGB, `(value / 255 - 0.5) / 0.5` (the demo's+`ToTensor` + `Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))`), output a single+512×512 alpha channel through a sigmoid. Consumed by `ModnetSegmenter` from+`PortraitBokeh.StillBokehRenderer` — still capture only; the 15 fps preview+keeps `selfie_segmentation.maml` above.++Update: re-download the mirror file, verify the SHA-256, then+`./scripts/ml/modnet_fold.py model.onnx --graph modnet -o+camera/src/main/assets/modnet.maml`, which reports a moved digest to re-pin.+If the ordered layer table changed too, the converter says so+and the hardcoded forward pass in+`library/ml/src/main/rust/src/nets/modnet.rs` has to be updated with it.
camera/src/main/assets/modnet.maml
diff --git a/camera/src/main/assets/modnet.maml b/camera/src/main/assets/modnet.mamlnew file mode 100644index 0000000000..5bb612f1adBinary files /dev/null and b/camera/src/main/assets/modnet.maml differ
camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt
diff --git a/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt b/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.ktindex 49f5453efa..cb05c60d24 100644--- a/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt+++ b/camera/src/main/java/com/vayunmathur/camera/util/PortraitBokeh.kt@@ -22,7 +22,7 @@ import android.os.Build import com.vayunmathur.library.log.Log import androidx.core.graphics.createBitmap import androidx.core.graphics.scale-import com.vayunmathur.library.ml.SelfieSegmenter+import com.vayunmathur.library.ml.ModnetSegmenter import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt@@ -222,7 +222,7 @@ private const val CHANNEL_MAX = 255f private const val CHANNEL_MAX_INT = 255 private const val FULL_CIRCLE_DEGREES = 360f -// Segmentation input: the model runs at 256x256 internally, so there is nothing to gain from+// Segmentation input: MODNet runs at 512x512 internally, so there is nothing to gain from // feeding it the full-resolution still. Matches the preview analyzer's cap. The downscale and // the normalise both happen natively now (library/ml/src/main/rust/src/preprocess.rs), so this // only bounds how much gets copied across JNI.@@ -237,14 +237,19 @@ private const val BLUR_LONG_SIDE = 1440 /** * Bakes the portrait bokeh the viewfinder previews into a captured still. *- * Owns its own [SelfieSegmenter] (created on first use) because the preview's instance lives in+ * Owns its own [ModnetSegmenter] (created on first use) because the preview's+ * [SelfieSegmenter][com.vayunmathur.library.ml.SelfieSegmenter] lives in * [BokehAnalyzer], which is disposed with the composable and runs on a different thread. The two * share one `VkDevice` regardless — `:library:ml` reference-counts it — so this costs buffers and * pipelines, not a second driver context.+ *+ * MODNet rather than Selfie: the still path runs once per shutter, so it can afford the+ * 512×512 alpha matte with strand-level hair detail; the preview keeps the cheaper+ * 256×256 Selfie pass at ~15 fps. */ class StillBokehRenderer(private val context: Context) : AutoCloseable { - private var segmenter: SelfieSegmenter? = null+ private var segmenter: ModnetSegmenter? = null @Volatile private var closed = false /**@@ -370,7 +375,7 @@ class StillBokehRenderer(private val context: Context) : AutoCloseable { * the caller keeps the sharp frame. */ private fun buildMask(src: Bitmap, rotationDegrees: Int): Bitmap? {- val seg = segmenter ?: SelfieSegmenter(context).also { segmenter = it }+ val seg = segmenter ?: ModnetSegmenter(context).also { segmenter = it } // Both helpers hand back their input when there is nothing to do, so only recycle the // intermediates we actually allocated – never the caller's bitmap.
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 3cc6dd200a..16744c086b 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -47,6 +47,14 @@ internal object MlNative { /** Bring up U²-Net portable. Returns 0 on failure, as [createSelfie]. */ external fun createU2netp(weights: ByteArray): Long + /**+ * Bring up MODNet photographic-portrait matting. Returns 0 on failure, as [createSelfie].+ *+ * Failure is expected and normal on a device without `VK_KHR_shader_float16_int8`,+ * like the other segmenters. The caller keeps the sharp frame.+ */+ external fun createModnet(weights: ByteArray): Long+ /** Bring up SCRFD 500M face detection. Returns 0 on failure, as [createSelfie]. */ external fun createScrfd(weights: ByteArray): Long
library/ml/src/main/java/com/vayunmathur/library/ml/ModnetSegmenter.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/ModnetSegmenter.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/ModnetSegmenter.ktnew file mode 100644index 0000000000..5d094e6361--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/ModnetSegmenter.kt@@ -0,0 +1,47 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap++/**+ * Portrait alpha matting, for `:camera`'s still-capture portrait bokeh.+ *+ * **MODNet photographic-portrait-matting** (Apache-2.0), run on Vulkan compute at 512×512 with+ * fp16 weights. Unlike [SelfieSegmenter] it predicts a true alpha matte with strand-level+ * detail rather than a binary person mask. See `camera/src/main/assets/README.md` for+ * provenance and `library/ml/src/main/rust/src/nets/modnet.rs` for the forward pass.+ *+ * Still-capture only: the 15 fps preview keeps [SelfieSegmenter], whose 256×256 pass is+ * cheaper per frame. This runs once per shutter, so its larger arena is acceptable —+ * the same tradeoff [SubjectSegmenter] documents.+ *+ * GPU-only: if [isAvailable] is false the device has no Vulkan fp16 compute and [segment]+ * returns null, which the caller treats as "no mask" and keeps the sharp frame.+ *+ * Not thread-safe: [segment] and [close] must not overlap.+ *+ * @param context used only to read the asset; not retained.+ * @param assetName the `.maml` in the app's assets.+ */+class ModnetSegmenter(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {++ private val native =+ NativeSegmenter(context, assetName, "ModnetSegmenter", MlNative::createModnet)++ /** Whether the network came up. False means still-capture bokeh is off on this device. */+ val isAvailable: Boolean get() = native.isAvailable++ /**+ * Run the network over [bitmap] and return a 512×512 matte, or null on failure.+ *+ * [bitmap] may be any size and any config: it is resized and normalised natively.+ */+ fun segment(bitmap: Bitmap): SegmentationMask? = native.segment(bitmap)++ override fun close() = native.close()++ companion object {+ /** What `:camera` ships for still capture. */+ const val DEFAULT_ASSET: String = "modnet.maml"+ }+}
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex 50f31e645c..c755ff15d5 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -203,6 +203,7 @@ uint kv_stride(uint head_dim) { #define ACT_PRELU 4u #define ACT_CLIP01 5u #define ACT_SWISH 6u+#define ACT_RELU6 7u #define ACT_GELU 8u // This invocation's output element, across a 2D grid of workgroups.@@ -324,6 +325,11 @@ float activate(float x, uint kind, uint channel) { // both, and substituting one for the other is a plausible-looking accuracy loss. return x / (1.0 + exp(-x)); }+ if (kind == ACT_RELU6) {+ // ONNX `Clip` at `(0, 6)`: MobileNetV2's ReLU6, which every backbone+ // convolution of MODNet carries. See `nets::Act::Relu6`.+ return clamp(x, 0.0, 6.0);+ } if (kind == ACT_GELU) { // The exact GELU, `0.5 x (1 + erf(x / sqrt(2)))`, which is what Supertonic's four nets // spell as an `Erf`.
library/ml/src/main/rust/shaders/instancenorm.comp
diff --git a/library/ml/src/main/rust/shaders/instancenorm.comp b/library/ml/src/main/rust/shaders/instancenorm.compnew file mode 100644index 0000000000..1ca6c286db--- /dev/null+++ b/library/ml/src/main/rust/shaders/instancenorm.comp@@ -0,0 +1,58 @@+#version 450+//! Instance normalisation over the **spatial** axes, with no affine.+//!+//! Sixteen uses, all MODNet's `IBNorm` second halves+//! (`InstanceNorm2d(affine=False)` over one channel-split half).+//!+//! # One invocation per channel, reducing over its plane+//!+//! This runtime stores a tensor `[C, H, W]` with the width innermost, so one+//! channel's `H x W` plane is contiguous: `plane` loads back to back. That is+//! the transpose of `layernorm.comp`, whose reduction strides across channels+//! — and the reason this is a separate pipeline rather than a flag on it.+//!+//! # Two passes, not Welford+//!+//! Mean then variance, reading the plane twice. The largest plane here is+//! 128x128 (the 16-channel halves at full resolution); both passes sit in+//! cache, and a single-pass algorithm would save bandwidth that is not being+//! spent.+//!+//! Accumulation is `float` like everywhere else here. There is no gamma/beta:+//! the export's scale and bias are constant 1 and 0 (verified by+//! `scripts/ml/modnet_fold.py`), so `epsilon` is the only parameter and it+//! arrives in the push block.++#include "common.glsl"++void main() {+ uint channel = global_index();+ if (channel >= p.count) {+ return;+ }+ // `count` is `in_c`, so `channel` walks the channels and the plane extent+ // is that channel's contiguous run.+ uint plane = p.in_h * p.in_w;+ uint base = channel * plane;+ float epsilon = uintBitsToFloat(p.param1_bits);++ float total = 0.0;+ for (uint i = 0u; i < plane; i++) {+ total += float(arena[p.in0 + base + i]);+ }+ float mean = total / float(plane);++ float variance = 0.0;+ for (uint i = 0u; i < plane; i++) {+ float centred = float(arena[p.in0 + base + i]) - mean;+ variance += centred * centred;+ }+ // Biased variance, dividing by N rather than N-1, which is what every framework's+ // instance norm does at inference.+ float inverse = 1.0 / sqrt(variance / float(plane) + epsilon);++ for (uint i = 0u; i < plane; i++) {+ float centred = float(arena[p.in0 + base + i]) - mean;+ arena[p.out_at + base + i] = float16_t(centred * inverse);+ }+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex f50b58ac15..8873eaaaf5 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -36,8 +36,8 @@ use jni::sys::{jfloatArray, jint, jintArray, jlong, jstring}; use jni::JNIEnv; use crate::nets::{- gemma4, gemma4_audio, gemma4_vision, madlad, madlad_part1, maia, mobilefacenet, nllb, nnfp,- ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,+ gemma4, gemma4_audio, gemma4_vision, madlad, madlad_part1, maia, mobilefacenet, modnet, nllb,+ nnfp, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, Plan, }; use crate::post::ctc::Dictionary;@@ -50,7 +50,7 @@ use crate::post::supertonic; use crate::post::translate; use crate::post::whisper as whisper_post; use crate::preprocess::{- Letterbox, FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD,+ Letterbox, FACE_EMBED, IMAGENET, MODNET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD, }; use crate::vulkan::context; use crate::vulkan::reshape::Reshaped;@@ -124,6 +124,21 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createMobileface open(&mut env, weights, graph::MOBILEFACENET, "mobilefacenet") } +/// `ModnetSegmenter`'s constructor: MODNet photographic-portrait matting at a+/// fixed 512x512. Returns 0 on failure.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env` and a `weights` array it owns.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createModnet<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ weights: JByteArray<'l>,+) -> jlong {+ open(&mut env, weights, graph::MODNET, "modnet")+}+ fn open<'l>(env: &mut JNIEnv<'l>, weights: JByteArray<'l>, graph_id: u32, name: &str) -> jlong { match build(env, weights, graph_id) { Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,@@ -159,6 +174,7 @@ fn build<'l>( SCRFD, ), graph::MOBILEFACENET => (mobilefacenet::build(&parsed)?, FACE_EMBED),+ graph::MODNET => (modnet::build(&parsed)?, MODNET), other => return Err(format!("no forward pass for graph {other}")), }; Ok(Handle {
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 aba659f985..ac52cd306c 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -43,6 +43,7 @@ pub mod madlad; pub mod madlad_extra; pub mod madlad_extra2; pub mod madlad_part1;+pub mod modnet; pub mod nllb; pub mod nllb_extra; pub mod nllb_extra2;@@ -122,6 +123,14 @@ pub enum Act { /// runtime needs one parameterless clamp rather than an activation carrying two /// floats through the push block. Clip01,+ /// `clamp(x, 0, 6)`: ONNX `Clip` at MobileNetV2's ReLU6 bounds.+ ///+ /// Every backbone convolution of MODNet's MobileNetV2 encoder is followed by+ /// one (35 uses, all `(0.0, 6.0)` — verified by `scripts/ml/modnet_fold.py`,+ /// which rejects any other bounds). A rewrite to plain ReLU would change the+ /// trained math, so this is fused into the producing convolution like every+ /// other activation here rather than rewritten away.+ Relu6, /// `x / (1 + exp(-x))`, i.e. ONNX `Sigmoid` multiplied by its own input. /// /// Seven uses in PP-OCRv5 recognition, where the export spells it out as@@ -151,6 +160,7 @@ impl Act { Act::PRelu(_) => 4, Act::Clip01 => 5, Act::Swish => 6,+ Act::Relu6 => 7, Act::Gelu => 8, } }@@ -240,6 +250,21 @@ pub enum Kind { /// `d_model` 120 that is 120 loads a stride apart per position, which is nothing /// against what a contiguous layout would cost in permutes. LayerNorm,+ /// Instance normalisation over the **spatial** axes, with no affine.+ ///+ /// [`Kind::LayerNorm`] transposed: where that one reduces `C` strided values per+ /// position, this reduces one channel's contiguous `H x W` plane — so one+ /// invocation per channel, and the whole pass is contiguous reads. Sixteen uses,+ /// all MODNet's `IBNorm` second halves (`InstanceNorm2d(affine=False)`), each+ /// over one [`Builder::slice_channels`] half rejoined by [`Builder::concat`].+ ///+ /// No gamma/beta: the export's scale and bias are constant 1 and 0 (verified+ /// by `scripts/ml/modnet_fold.py`, which rejects anything else), so there are+ /// no weight reads at all — epsilon rides [`Push::param1_bits`] like the other+ /// norms'. The batch-norm halves of those same `IBNorm`s are folded into their+ /// convolutions by the fold script instead, which is why this is the only new+ /// pipeline MODNet needs.+ InstanceNorm, /// Root-mean-square normalisation over the channel axis, with a per-channel gain. /// /// [`Kind::LayerNorm`] without the mean subtraction and without beta:
library/ml/src/main/rust/src/nets/mod_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part1.rs b/library/ml/src/main/rust/src/nets/mod_part1.rsindex ea2b1e7ce9..35f46c2cfb 100644--- a/library/ml/src/main/rust/src/nets/mod_part1.rs+++ b/library/ml/src/main/rust/src/nets/mod_part1.rs@@ -302,12 +302,14 @@ impl Kind { } // Purely elementwise or arena-only. `attn_scores`, `softmax`, `attn_apply` and // `rotary` all take their second operand from the arena, and the cached attention- // pair take theirs from a cache in the arena too.+ // pair take theirs from a cache in the arena too. Instance norm joins them:+ // its scale and bias are constant 1 and 0, so it reads no weights at all. Kind::MaxPool | Kind::AvgPool | Kind::Resize | Kind::ResizeNearest | Kind::GlobalAvgPool+ | Kind::InstanceNorm | Kind::Add | Kind::MulBroadcast | Kind::AddBroadcast@@ -440,6 +442,7 @@ impl Kind { | Kind::ResizeNearest | Kind::GlobalAvgPool | Kind::LayerNorm+ | Kind::InstanceNorm | Kind::Softmax | Kind::SoftmaxCausal | Kind::SoftmaxPrefix
library/ml/src/main/rust/src/nets/mod_part10.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part10.rs b/library/ml/src/main/rust/src/nets/mod_part10.rsindex 23e4eb996e..2483d76f1d 100644--- a/library/ml/src/main/rust/src/nets/mod_part10.rs+++ b/library/ml/src/main/rust/src/nets/mod_part10.rs@@ -9,6 +9,7 @@ impl Node { | Node::Binary { out, .. } | Node::Affine { out, .. } | Node::LayerNorm { out, .. }+ | Node::InstanceNorm { out, .. } | Node::RmsNorm { out, .. } | Node::AttnScores { out, .. } | Node::AttnScoresCached { out, .. }@@ -58,6 +59,7 @@ impl Node { | Node::Resize { input, .. } | Node::Affine { input, .. } | Node::LayerNorm { input, .. }+ | Node::InstanceNorm { input, .. } | Node::Softmax { input, .. } | Node::Softcap { input, .. } | Node::Argmax { input, .. }
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex 73ab21c5cc..7a86a91eca 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -240,6 +240,11 @@ pub(crate) enum Node { beta: u32, epsilon: f32, },+ InstanceNorm {+ input: Id,+ out: Id,+ epsilon: f32,+ }, RmsNorm { input: Id, out: Id,
library/ml/src/main/rust/src/nets/mod_part5.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part5.rs b/library/ml/src/main/rust/src/nets/mod_part5.rsindex 62d205bba0..e9cadab752 100644--- a/library/ml/src/main/rust/src/nets/mod_part5.rs+++ b/library/ml/src/main/rust/src/nets/mod_part5.rs@@ -244,6 +244,19 @@ impl<'a> Builder<'a> { self.push_layer_norm(input, gamma, beta, epsilon) } + /// Instance normalisation over the spatial axes, with no affine.+ ///+ /// `(x - mean(ch)) / sqrt(var(ch) + epsilon)` per channel. What MODNet's+ /// `IBNorm` second halves are (`InstanceNorm2d(affine=False)`); the fold+ /// script guarantees scale 1 / bias 0, so this takes no weights. See+ /// [`Kind::InstanceNorm`].+ pub fn instance_norm(&mut self, input: Id, epsilon: f32) -> Id {+ let shape = self.shape_of(input);+ let out = self.tensor(shape);+ self.nodes.push(Node::InstanceNorm { input, out, epsilon });+ out+ }+ /// Root-mean-square normalisation over the channel axis, with a per-channel gain. /// /// [`layer_norm`](Self::layer_norm) without the mean subtraction and without beta, so
library/ml/src/main/rust/src/nets/mod_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9.rs b/library/ml/src/main/rust/src/nets/mod_part9.rsindex 9fa40f35bb..a4b2a9374e 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -383,6 +383,28 @@ impl<'a> Builder<'a> { invocations: positions, }); }+ Node::InstanceNorm { input, out, epsilon } => {+ let so = shape(*out);+ // One invocation per channel, each reducing over its own plane, so+ // the dispatch is the channel count rather than the element count.+ ops.push(Op::Dispatch {+ kind: Kind::InstanceNorm,+ push: Push {+ in0: at(*input)?,+ out: at(*out)?,+ in_c: so.c,+ in_h: so.h,+ in_w: so.w,+ out_c: so.c,+ out_h: so.h,+ out_w: so.w,+ param1_bits: epsilon.to_bits(),+ count: so.c,+ ..Push::default()+ },+ invocations: so.c,+ });+ } Node::RmsNorm { input, out, gamma, epsilon, groups, res, quant_scale } => { let so = shape(*out); // One invocation per group per position, reducing over that group's channels.
library/ml/src/main/rust/src/nets/modnet.rs
diff --git a/library/ml/src/main/rust/src/nets/modnet.rs b/library/ml/src/main/rust/src/nets/modnet.rsnew file mode 100644index 0000000000..87df8973c8--- /dev/null+++ b/library/ml/src/main/rust/src/nets/modnet.rs@@ -0,0 +1,370 @@+//! MODNet photographic-portrait matting, the `:camera` still-capture matte, at a fixed 512x512.+//!+//! # Shape of the network+//!+//! A MobileNetV2 encoder (inverted-residual blocks down to 16x16, ReLU6+//! throughout) with a squeeze-excite gate on the trunk, then three decoder+//! branches back up to full resolution: a low-resolution semantic branch, a+//! high-resolution detail branch fed by two encoder taps, and a fusion branch+//! over both plus the input image, ending in a 1x1 plus sigmoid. See+//! `analysis/modnet/onnx/modnet_onnx.py` (`MODNet`, `LRBranch`, `HRBranch`,+//! `FusionBranch`) for the architecture this transcribes.+//!+//! # IBNorm: the one structural idiom+//!+//! Every branch convolution is followed by an `IBNorm`: the output split in+//! two along channels, a frozen batch norm over the first half, an+//! affine-free instance norm over the second, re-concatenated, then a ReLU.+//! The batch-norm halves are folded into their convolutions by+//! `scripts/ml/modnet_fold.py` (a `Slice` sits between the convolution and+//! the norm, so `maml_convert`'s direct-follower fold cannot fire); what is+//! transcribed here is `conv -> slice_channels -> instance_norm -> concat ->+//! activate(Relu)`, via [`ibnorm`].+//!+//! # Three things about it that are easy to get wrong+//!+//! * **The projections are linear.** Every inverted-residual bottleneck ends in+//! a 1x1 with no activation — the export has no `Clip`/`Relu` between those+//! convolutions and their consumer — and the residuals add those linear+//! outputs. Fusing a ReLU6 into a projection would clamp every skip+//! connection in the backbone.+//! * **The 1x1s called `MatMul` are convolutions.** The squeeze-excite gate's+//! two projections arrive as `MatMul` against 2-D constants; the fold script+//! rewrites them as 1x1 `Conv` layers, and the surrounding+//! `Unsqueeze`/`Concat`/`Reshape`/`Expand` shape scaffolding is dead code+//! that is not transcribed — the gate is `global_avg_pool`, two 1x1s and a+//! [`mul_channel`](Builder::mul_channel), whose broadcast is what the+//! `Expand` was spelling out.+//! * **The encoder taps are mid-network tensors.** The high-resolution branch+//! reads the backbone's 16-channel 256x256 output and the 24-channel 128x128+//! residual output, so those stay live across the whole low-resolution+//! branch; the arena packing in [`Builder::finish`] accounts for it.+//!+//! Preprocessing is `(value / 255 - 0.5) / 0.5` over RGB — see+//! [`crate::preprocess::MODNET`].++use super::{Act, Builder, Id, Plan, Shape, WeightSource};++/// The side length the graph is lowered at.+pub const SIZE: u32 = 512;+/// Tensors in the file: 71 layers, weight and bias each.+pub const TENSORS: usize = 142;++/// Hands out `.maml` tensor indices in the order the layers appear. See+/// [`super::u2netp`] for why this is a counter.+struct Layers {+ next: usize,+}++impl Layers {+ fn take(&mut self) -> usize {+ let index = self.next;+ self.next += 2;+ index+ }+}++/// A 3x3 convolution at unchanged resolution.+fn conv3x3(b: &mut Builder, layers: &mut Layers, x: Id, out: u32, act: Act) -> Id {+ b.conv_same(x, layers.take(), out, 3, 1, act)+}++/// A MobileNetV2 inverted-residual block: expand 1x1 (ReLU6), depthwise 3x3+/// (ReLU6), linear projection 1x1, optionally added back to the input.+fn inverted_residual(+ b: &mut Builder,+ layers: &mut Layers,+ x: Id,+ expand: u32,+ out: u32,+ stride: u32,+ residual: bool,+) -> Id {+ let expanded = b.conv_same(x, layers.take(), expand, 1, 1, Act::Relu6);+ // Depthwise: one group per channel, so the kernel is `[expand, 1, 3, 3]`.+ let pad = 1;+ let spatial = b.conv(+ expanded,+ layers.take(),+ expand,+ (3, 3),+ (stride, stride),+ (1, 1),+ (pad, pad, pad, pad),+ expand,+ Act::Relu6,+ );+ let projected = b.conv_same(spatial, layers.take(), out, 1, 1, Act::None);+ if residual {+ b.add(x, projected)+ } else {+ projected+ }+}++/// One `Conv2dIBNormRelu`: convolution (no fused activation — the ReLU comes+/// after the rejoin), channel split, instance norm over the second half,+/// re-concatenation, standalone ReLU.+fn ibnorm(+ b: &mut Builder,+ layers: &mut Layers,+ x: Id,+ out: u32,+ kernel: u32,+ stride: u32,+ split: u32,+) -> Id {+ let pad = kernel / 2;+ let h = if kernel == 1 {+ b.conv_same(x, layers.take(), out, 1, 1, Act::None)+ } else {+ b.conv(+ x,+ layers.take(),+ out,+ (kernel, kernel),+ (stride, stride),+ (1, 1),+ (pad, pad, pad, pad),+ 1,+ Act::None,+ )+ };+ let a = b.slice_channels(h, 0, split);+ let c = b.slice_channels(h, split, out - split);+ let c = b.instance_norm(c, 1e-5);+ let h = b.concat(&[a, c]);+ b.activate(h, Act::Relu)+}++/// 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: 512 -> 256.+ let x = b.conv(+ input,+ l.take(),+ 32,+ (3, 3),+ (2, 2),+ (1, 1),+ (1, 1, 1, 1),+ 1,+ Act::Relu6,+ );++ // Backbone. Kept tensors: `enc2x` (16ch @ 256) and `enc4x` (24ch @ 128)+ // feed the high-resolution branch below.+ let x = b.conv(x, l.take(), 32, (3, 3), (1, 1), (1, 1), (1, 1, 1, 1), 32, Act::Relu6);+ let enc2x = b.conv_same(x, l.take(), 16, 1, 1, Act::None);+ let x = inverted_residual(&mut b, l, enc2x, 96, 24, 2, false);+ let x = inverted_residual(&mut b, l, x, 144, 24, 1, true);+ let enc4x = x;+ let x = inverted_residual(&mut b, l, x, 144, 32, 2, false);+ let x = inverted_residual(&mut b, l, x, 192, 32, 1, true);+ let x = inverted_residual(&mut b, l, x, 192, 32, 1, true);+ let x = inverted_residual(&mut b, l, x, 192, 64, 2, false);+ let x = inverted_residual(&mut b, l, x, 384, 64, 1, true);+ let x = inverted_residual(&mut b, l, x, 384, 64, 1, true);+ let x = inverted_residual(&mut b, l, x, 384, 64, 1, true);+ let x = inverted_residual(&mut b, l, x, 384, 96, 1, false);+ let x = inverted_residual(&mut b, l, x, 576, 96, 1, true);+ let x = inverted_residual(&mut b, l, x, 576, 96, 1, true);+ let x = inverted_residual(&mut b, l, x, 576, 160, 2, false);+ let x = inverted_residual(&mut b, l, x, 960, 160, 1, true);+ let x = inverted_residual(&mut b, l, x, 960, 160, 1, true);+ let x = inverted_residual(&mut b, l, x, 960, 320, 1, false);+ let trunk = b.conv_same(x, l.take(), 1280, 1, 1, Act::Relu6);++ // Squeeze-excite gate over the trunk: pooled to Cx1x1, two 1x1s+ // (rewritten from MatMuls by the fold script), sigmoid, broadcast back.+ let pooled = b.global_avg_pool(trunk);+ let gate = b.conv_same(pooled, l.take(), 320, 1, 1, Act::Relu);+ let gate = b.conv_same(gate, l.take(), 1280, 1, 1, Act::Sigmoid);+ let gated = b.mul_channel(trunk, gate);++ // Low-resolution branch: 16 -> 32 -> 64.+ let lr = b.resize_to(gated, 32, 32);+ let lr = ibnorm(&mut b, l, lr, 96, 5, 1, 48);+ let lr = b.resize_to(lr, 64, 64);+ let lr8x = ibnorm(&mut b, l, lr, 32, 5, 1, 16);++ // High-resolution branch inputs, straight off the source image.+ let img2x = b.resize_to(input, 256, 256);+ let img4x = b.resize_to(input, 128, 128);++ // Encoder taps projected across, then detail refinement at 128.+ let tohr2x = ibnorm(&mut b, l, enc2x, 32, 1, 1, 16);+ let hr = b.concat(&[img2x, tohr2x]);+ let hr = ibnorm(&mut b, l, hr, 32, 3, 2, 16);+ let tohr4x = ibnorm(&mut b, l, enc4x, 32, 1, 1, 16);+ let hr = b.concat(&[hr, tohr4x]);+ let hr = ibnorm(&mut b, l, hr, 64, 3, 1, 32);+ let lr4x = b.resize_to(lr8x, 128, 128);+ let hr = b.concat(&[hr, lr4x, img4x]);+ let hr = ibnorm(&mut b, l, hr, 64, 3, 1, 32);+ let hr = ibnorm(&mut b, l, hr, 64, 3, 1, 32);+ let hr = ibnorm(&mut b, l, hr, 32, 3, 1, 16);++ // Detail refinement at 256, reusing the projected 2x tap.+ let hr = b.resize_to(hr, 256, 256);+ let hr = b.concat(&[hr, tohr2x]);+ let hr = ibnorm(&mut b, l, hr, 64, 3, 1, 32);+ let hr = ibnorm(&mut b, l, hr, 32, 3, 1, 16);+ let hr = ibnorm(&mut b, l, hr, 32, 3, 1, 16);+ let hr2x = ibnorm(&mut b, l, hr, 32, 3, 1, 16);++ // Fusion branch: semantic stream upsampled, merged with detail and image.+ let f = b.resize_to(lr8x, 128, 128);+ let f = ibnorm(&mut b, l, f, 32, 5, 1, 16);+ let f = b.resize_to(f, 256, 256);+ let f = b.concat(&[f, hr2x]);+ let f = ibnorm(&mut b, l, f, 32, 3, 1, 16);+ let f = b.resize_to(f, 512, 512);+ let f = b.concat(&[f, input]);+ let f = ibnorm(&mut b, l, f, 16, 3, 1, 8);++ // 1x1 to one channel and the sigmoid that makes it an alpha.+ let matte = b.conv_same(f, l.take(), 1, 1, 1, Act::Sigmoid);+ b.finish(&[matte])+}++#[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("modnet builds")+ }++ /// Whether two kinds are the same graph operation, folding `Conv`'s tiled lowering in.+ fn same_op(found: Kind, wanted: Kind) -> bool {+ let fold = |k: Kind| if matches!(k, Kind::ConvPoint) { Kind::Conv } else { k };+ fold(found) == fold(wanted)+ }++ fn dispatches(plan: &Plan, kind: Kind) -> usize {+ plan.ops+ .iter()+ .filter(|op| matches!(op, Op::Dispatch { kind: k, .. } if same_op(*k, kind)))+ .count()+ }++ #[test]+ fn the_op_inventory_matches_the_folded_onnx() {+ // The counts `scripts/ml/modnet_fold.py --print-graph` reports over the+ // folded export, minus its dead shape scaffolding (the SE block's+ // `Unsqueeze`/`Concat`/`Reshape`/`Expand` cluster, which the gate+ // transcribes as pool-plus-two-1x1s-plus-broadcast instead): 71+ // convolutions (69 + 2 SE MatMuls rewritten as 1x1s), 10 backbone+ // residuals, the SE gate multiply, 16 IBNorm rejoins plus 6 structural+ // branch merges, 16 instance norms, one squeeze, and 17 standalone+ // ReLUs (16 post-rejoin plus the SE block's own — every one an+ // `Activate` because a `Concat` produced the value, not a convolution).+ let plan = plan();+ assert_eq!(dispatches(&plan, Kind::Conv), 71);+ // Six of the ten backbone residuals dispatch as their own op; the+ // other four fold into their producing convolution's store — the+ // inverted-residual tails whose skip side is already written when the+ // projection runs. See `Builder::add`.+ assert_eq!(dispatches(&plan, Kind::Add), 6);+ assert_eq!(dispatches(&plan, Kind::MulBroadcast), 1);+ assert_eq!(dispatches(&plan, Kind::InstanceNorm), 16);+ assert_eq!(dispatches(&plan, Kind::GlobalAvgPool), 1);+ // 16 post-rejoin ReLUs, one per IBNorm site. The SE block's own ReLU+ // is fused into its 1x1 rather than standalone, and both sigmoids are+ // fused the same way — so unlike the ONNX census (17 Relu, 2 Sigmoid)+ // only the 16 rejoins dispatch here.+ assert_eq!(dispatches(&plan, Kind::Activate), 16);+ assert_eq!(dispatches(&plan, Kind::Resize), 9);+ // `Concat` lowers to one copy per part: 16 two-part IBNorm rejoins+ // plus 6 structural branch merges (5 two-part, 1 three-part) — and each+ // `slice_channels` half is one copy too.+ let copies = plan.ops.iter().filter(|op| matches!(op, Op::Copy { .. })).count();+ assert_eq!(copies, 16 * 2 + 5 * 2 + 3 + 32);+ // No pooling, no transposed convolution.+ assert_eq!(dispatches(&plan, Kind::MaxPool), 0);+ assert_eq!(dispatches(&plan, Kind::ConvTranspose), 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 the_layer_table_matches_the_folded_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![32, 3, 3, 3]);+ // Layer 1, the first depthwise: `[32, 1, 3, 3]` is what group == channels+ // looks like, and the shape most likely to be wrong if grouping is misread.+ assert_eq!(shape_at(2), vec![32, 1, 3, 3]);+ // Layer 51, the backbone head: 320 channels in, 1280 out.+ assert_eq!(shape_at(102), vec![1280, 320, 1, 1]);+ // Layer 52, the first rewritten SE MatMul: `[320, 1280, 1, 1]`.+ assert_eq!(shape_at(104), vec![320, 1280, 1, 1]);+ // Layer 54, the first branch head: 5x5 over the 1280-channel trunk.+ assert_eq!(shape_at(108), vec![96, 1280, 5, 5]);+ // Layer 70, the final 1x1 to one channel.+ assert_eq!(shape_at(140), vec![1, 16, 1, 1]);+ }++ #[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));+ assert_eq!(plan.output().expect("one output").shape, Shape::new(1, SIZE, SIZE));+ }++ #[test]+ fn the_ibnorm_splits_cover_the_whole_channel_output() {+ // Each IBNorm site slices `[0:k)` and `[k:channels)` and concatenates+ // them back: a split point past the end, or a rejoin of anything but+ // the two halves, would change the channel count the next convolution+ // was lowered against. This walks the plan checking that every+ // `Concat` of two `SliceChannels` restores its source's channels.+ // (Structural rather than value-checked: the parity script covers values.)+ let plan = plan();+ let rejoins = plan+ .ops+ .iter()+ .filter(|op| matches!(op, Op::Dispatch { kind: Kind::Activate, .. }))+ .count();+ // One standalone ReLU per IBNorm rejoin.+ assert_eq!(rejoins, 16);+ }++ #[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;+ // This one runs once per shutter in `StillBokehRenderer`, not per frame,+ // so it may spend what U^2-Netp spends: tens of megabytes for the 64-+ // channel 256x256 detail tensors and the live encoder taps.+ assert!(bytes < 128 * 1024 * 1024, "arena is {bytes} bytes");+ }+}
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 a4fb828239..1d624b270b 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -59,6 +59,8 @@ mod act { pub const CLIP01: u32 = 5; /// `x * sigmoid(x)`. pub const SWISH: u32 = 6;+ /// `clamp(x, 0, 6)`, MobileNetV2's ReLU6.+ pub const RELU6: u32 = 7; /// The exact GELU. See `super::super::Act::Gelu`. pub const GELU: u32 = 8; }@@ -81,6 +83,7 @@ fn activate(x: f32, kind: u32, slope: f32) -> f32 { } act::CLIP01 => x.clamp(0.0, 1.0), act::SWISH => x / (1.0 + (-x).exp()),+ act::RELU6 => x.clamp(0.0, 6.0), // The exact GELU, not the tanh approximation: [`super::erf`] is the same A&S 7.1.26 // series the shader uses, so the two agree well inside fp16. act::GELU => 0.5 * x * (1.0 + super::erf(x * std::f32::consts::FRAC_1_SQRT_2)),@@ -165,12 +168,13 @@ pub struct Reference { include!("reference_part1.rs"); include!("reference_part2.rs");+include!("reference_part11.rs"); include!("reference_part3.rs"); include!("reference_part4.rs"); #[cfg(test)] mod tests { use super::super::{- embed_lanes, maia, mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,+ embed_lanes, maia, mobilefacenet, modnet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, Act, Builder, EMBED_LANE, }; use super::*;
library/ml/src/main/rust/src/nets/reference_part1.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part1.rs b/library/ml/src/main/rust/src/nets/reference_part1.rsindex 9fa8d56a24..95805ee246 100644--- a/library/ml/src/main/rust/src/nets/reference_part1.rs+++ b/library/ml/src/main/rust/src/nets/reference_part1.rs@@ -58,6 +58,7 @@ impl Reference { Kind::Mul => self.mul(push), Kind::Affine => self.affine(push), Kind::LayerNorm => self.layer_norm(push),+ Kind::InstanceNorm => self.instance_norm(push), Kind::RmsNorm => self.rms_norm(push), Kind::AttnScores => self.attn_scores(push), Kind::Softmax => self.softmax(push, SoftmaxMode::Full),@@ -467,34 +468,4 @@ impl Reference { } Ok(()) }-- /// Max pooling, floored and unpadded — which is what all 33 uses are.- fn max_pool(&mut self, p: &Push) -> Result<(), String> {- for oc in 0..p.out_c {- let plane = oc * p.in_h * p.in_w;- for oy in 0..p.out_h {- for ox in 0..p.out_w {- // The most negative fp16 rather than -inf, as `maxpool.comp` uses:- // every window here is fully inside the input, so it is never the- // answer.- let mut best = -65504.0f32;- for ky in 0..p.kh {- let iy = oy * p.stride_h + ky;- if iy >= p.in_h {- continue;- }- for kx in 0..p.kw {- let ix = ox * p.stride_w + kx;- if ix >= p.in_w {- continue;- }- best = best.max(self.load(p.in0, plane + iy * p.in_w + ix)?);- }- }- self.store(p.out, nchw(p, oc, oy, ox), best)?;- }- }- }- Ok(())- } }
library/ml/src/main/rust/src/nets/reference_part11.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part11.rs b/library/ml/src/main/rust/src/nets/reference_part11.rsnew file mode 100644index 0000000000..38fc6fd3bb--- /dev/null+++ b/library/ml/src/main/rust/src/nets/reference_part11.rs@@ -0,0 +1,68 @@+impl Reference {+ /// Max pooling, floored and unpadded — which is what all 33 uses are.+ fn max_pool(&mut self, p: &Push) -> Result<(), String> {+ for oc in 0..p.out_c {+ let plane = oc * p.in_h * p.in_w;+ for oy in 0..p.out_h {+ for ox in 0..p.out_w {+ // The most negative fp16 rather than -inf, as `maxpool.comp` uses:+ // every window here is fully inside the input, so it is never the+ // answer.+ let mut best = -65504.0f32;+ for ky in 0..p.kh {+ let iy = oy * p.stride_h + ky;+ if iy >= p.in_h {+ continue;+ }+ for kx in 0..p.kw {+ let ix = ox * p.stride_w + kx;+ if ix >= p.in_w {+ continue;+ }+ best = best.max(self.load(p.in0, plane + iy * p.in_w + ix)?);+ }+ }+ self.store(p.out, nchw(p, oc, oy, ox), best)?;+ }+ }+ }+ Ok(())+ }++ /// Instance normalisation over the spatial axes, per channel, with no affine.+ ///+ /// Mirrors `shaders/instancenorm.comp`: biased variance like every inference+ /// norm, epsilon inside the square root like `torch.nn.InstanceNorm2d`.+ /// `count` is the channel count, because one invocation handles a whole plane.+ fn instance_norm(&mut self, p: &Push) -> Result<(), String> {+ if p.in_c == 0 {+ return Err("an instance norm over zero channels".into());+ }+ let plane = p.in_h * p.in_w;+ if plane == 0 {+ return Err("an instance norm over an empty plane".into());+ }+ let epsilon = f32::from_bits(p.param1_bits);+ for c in 0..p.count {+ let base = c * plane;+ let mut total = 0.0;+ for i in 0..plane {+ total += self.load(p.in0, base + i)?;+ }+ let mean = total / plane as f32;++ let mut variance = 0.0;+ for i in 0..plane {+ let centred = self.load(p.in0, base + i)? - mean;+ variance += centred * centred;+ }+ let inverse = 1.0 / (variance / plane as f32 + epsilon).sqrt();++ for i in 0..plane {+ let centred = self.load(p.in0, base + i)? - mean;+ self.store(p.out, base + i, centred * inverse)?;+ }+ }+ Ok(())+ }+}
library/ml/src/main/rust/src/nets/reference_part5.rs
diff --git a/library/ml/src/main/rust/src/nets/reference_part5.rs b/library/ml/src/main/rust/src/nets/reference_part5.rsindex 61721187ed..9c6e23ba2f 100644--- a/library/ml/src/main/rust/src/nets/reference_part5.rs+++ b/library/ml/src/main/rust/src/nets/reference_part5.rs@@ -379,6 +379,7 @@ assert_eq!(Act::PRelu(0).code(), act::PRELU); assert_eq!(Act::Clip01.code(), act::CLIP01); assert_eq!(Act::Swish.code(), act::SWISH);+ assert_eq!(Act::Relu6.code(), act::RELU6); assert_eq!(Act::Gelu.code(), act::GELU); }
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 97ac9815d2..5982408ec0 100644--- a/library/ml/src/main/rust/src/nets/reference_part9.rs+++ b/library/ml/src/main/rust/src/nets/reference_part9.rs@@ -139,6 +139,17 @@ println!("whisper encoder: wrote {} values", hidden.len()); return; }+ if graph == "modnet" {+ let path = std::env::var("PARITY_MAML").expect("PARITY_MAML");+ let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"));+ let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::MODNET)+ .expect("the modnet asset parses");+ let plan = modnet::build(&weights).expect("modnet builds");+ let matte = run(&plan, weights.data(), &input).expect("modnet runs");+ write(&dir.join("reference.f32"), &matte);+ println!("modnet at 512: wrote {} values", matte.len());+ return;+ } if graph == "maia" { let path = std::env::var("PARITY_MAML").expect("PARITY_MAML"); let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"));@@ -413,4 +424,20 @@ Shape::new(1, u2netp::SIZE, u2netp::SIZE) ); assert_usable_mask("u2netp", &plan, weights.data());+ }++ #[test]+ #[ignore = "runs the full shipped nets; minutes in a debug build"]+ fn the_shipped_modnet_net_produces_a_usable_mask() {+ let Some(bytes) = asset("camera/src/main/assets/modnet.maml") else {+ return;+ };+ let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::MODNET)+ .expect("the shipped modnet asset parses");+ let plan = modnet::build(&weights).expect("modnet builds");+ assert_eq!(+ plan.output().expect("one output").shape,+ Shape::new(1, modnet::SIZE, modnet::SIZE)+ );+ assert_usable_mask("modnet", &plan, weights.data()); }\ No newline at end of file
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 225a0b5f05..550adf7745 100644--- a/library/ml/src/main/rust/src/preprocess.rs+++ b/library/ml/src/main/rust/src/preprocess.rs@@ -88,6 +88,7 @@ pub const PPOCR_REC: Normalise = const _: () = assert!(PPOCR_DET.bgr && PPOCR_REC.bgr); const _: () = assert!(!IMAGENET.bgr && !RESCALE_ONLY.bgr); const _: () = assert!(!SCRFD.bgr && !FACE_EMBED.bgr);+const _: () = assert!(!MODNET.bgr); /// `(value - 127.5) / 128` on the `0..255` scale, which is what SCRFD wants. ///@@ -109,6 +110,16 @@ pub const SCRFD: Normalise = Normalise { pub const FACE_EMBED: Normalise = Normalise { mean: [0.5, 0.5, 0.5], std: [0.5, 0.5, 0.5], bgr: false }; +/// `(value / 255 - 0.5) / 0.5` on RGB channels, which is what MODNet wants.+///+/// Numerically the same affine as [`FACE_EMBED`], and a separate constant+/// because it is not the same net: the demo preprocess is+/// `ToTensor()` then `Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))` over RGB,+/// and a shared constant would silently couple the two nets' preprocessing.+/// See [`SCRFD`] for why near-identical constants stay separate.+pub const MODNET: Normalise =+ Normalise { mean: [0.5, 0.5, 0.5], std: [0.5, 0.5, 0.5], bgr: false };+ /// How an image was fitted into the detector's input, and what it takes to undo it. /// /// SCRFD runs at 640 on the long side with the short side padded up to a multiple of 32,
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 44659e068a..15dd37f1d9 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -41,6 +41,8 @@ const ADD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add.comp.spv")); const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_bcast.comp.spv")); const AFFINE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/affine.comp.spv")); const LAYERNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/layernorm.comp.spv"));+const INSTANCENORM: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/instancenorm.comp.spv")); const RMSNORM: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rmsnorm.comp.spv")); const ATTN_SCORES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/attn_scores.comp.spv")); const SOFTMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/softmax.comp.spv"));@@ -88,7 +90,7 @@ const ARGMAX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/argmax.comp.spv" /// Every shader, in the order `Shaders::create` destructures them (the Q2_K pair, /// `QUANTIZE`, and the `compute_pipeline` / `shader_module` helpers live in /// `pipeline_extra.rs` for length).-pub(crate) const SPIRV: [&[u8]; 45] = [+pub(crate) const SPIRV: [&[u8]; 46] = [ CONV, CONV_TRANSPOSE, MAXPOOL,@@ -100,6 +102,7 @@ pub(crate) const SPIRV: [&[u8]; 45] = [ MUL_BCAST, AFFINE, LAYERNORM,+ INSTANCENORM, ATTN_SCORES, SOFTMAX, ATTN_APPLY,@@ -179,6 +182,7 @@ pub struct Shaders { pub(crate) mul_bcast: vk::Pipeline, pub(crate) affine: vk::Pipeline, pub(crate) layernorm: vk::Pipeline,+ pub(crate) instancenorm: vk::Pipeline, pub(crate) attn_scores: vk::Pipeline, pub(crate) softmax: vk::Pipeline, pub(crate) attn_apply: vk::Pipeline,
library/ml/src/main/rust/src/vulkan/pipeline_extra.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rsindex dd1a692087..2d4498aaf4 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs@@ -121,6 +121,7 @@ impl Shaders { mul_bcast, affine, layernorm,+ instancenorm, attn_scores, softmax, attn_apply,@@ -180,6 +181,7 @@ impl Shaders { mul_bcast, affine, layernorm,+ instancenorm, attn_scores, softmax, attn_apply,@@ -231,6 +233,7 @@ impl Shaders { Kind::MulBroadcast => self.mul_bcast, Kind::Affine => self.affine, Kind::LayerNorm => self.layernorm,+ Kind::InstanceNorm => self.instancenorm, Kind::RmsNorm => self.rmsnorm, Kind::AttnScores => self.attn_scores, Kind::Softmax => self.softmax,@@ -284,6 +287,7 @@ impl Shaders { self.mul_bcast, self.affine, self.layernorm,+ self.instancenorm, self.attn_scores, self.softmax, self.attn_apply,
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex ebb2c4734a..c499d0ca72 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -251,6 +251,14 @@ pub mod graph { /// with the chunks inside EMBED that upload was 3.6 GB (TEXT 1.1 GB + /// EMBED 3.6 GB = OOM-reboot on a Pixel 8). The head file is ~402 MB. pub const GEMMA4_HEAD: u32 = 26;++ /// MODNet photographic-portrait matting, 512x512 in, 512x512 alpha out. See+ /// [`crate::nets::modnet`].+ ///+ /// The next free id after Gemma 4's head at 26, with 7..10 and 15 staying retired.+ /// `maml_convert.py` has `GRAPHS["modnet"]` at the same number; the file is+ /// produced by `scripts/ml/modnet_fold.py` rather than `maml_convert.py` directly.+ pub const MODNET: u32 = 27; } /// One tensor's entry in the table: where it is and what shape it is.
library/ml/src/main/rust/src/weights_part7.rs
diff --git a/library/ml/src/main/rust/src/weights_part7.rs b/library/ml/src/main/rust/src/weights_part7.rsindex f2d187a3fc..d078ea08fc 100644--- a/library/ml/src/main/rust/src/weights_part7.rs+++ b/library/ml/src/main/rust/src/weights_part7.rs@@ -83,6 +83,7 @@ impl Graph { Act::PRelu(_) => Err("emitter: a PReLU, which phase 1 does not serialise".into()), Act::Clip01 => Ok(5), Act::Swish => Ok(6),+ Act::Relu6 => Ok(7), Act::Gelu => Ok(8), } };
scripts/ml/fetch_and_convert.sh
diff --git a/scripts/ml/fetch_and_convert.sh b/scripts/ml/fetch_and_convert.shindex 95a1243220..b62687ad3b 100644--- a/scripts/ml/fetch_and_convert.sh+++ b/scripts/ml/fetch_and_convert.sh@@ -4,6 +4,7 @@ # they are converted from. # # camera/src/main/assets/selfie_segmentation.maml MediaPipe Selfie Segmentation+# camera/src/main/assets/modnet.maml MODNet photographic portrait matting # photos/src/main/assets/u2netp.maml U^2-Net portable (saliency) # photos/src/main/assets/scrfd_500m.maml SCRFD 500M (face detection) # photos/src/main/assets/w600k_mbf.maml MobileFaceNet (face embedding)@@ -48,8 +49,14 @@ set -euo pipefail # Pinned to a commit rather than to `main`: the file SHA-256 below would catch a # silent upstream change anyway, but a pinned revision means --update tells you the # upstream *revision* that moved, not just that some bytes differ.+#+# MODNet is the exception: no pinned upstream commit exists for the mirror file,+# so its row records the mirror URL and the SHA-256 of the copy the `.maml` was+# built from (see camera/src/main/assets/README.md). A moved mirror fails the+# hash check the same way. MODELS=( "camera/src/main/assets/selfie_segmentation.maml selfie 3241ac4ad8aa35bdaf33946776db29f7c283a413aa0b0dacb9483594b4531aad https://huggingface.co/onnx-community/mediapipe_selfie_segmentation/resolve/be49485c8e027524be38591817fc5cd31bd9d00e/onnx/model.onnx"+ "camera/src/main/assets/modnet.maml modnet 07c308cf0fc7e6e8b2065a12ed7fc07e1de8feb37dc7839d7b7f15dd66584df9 https://huggingface.co/DavG25/modnet-pretrained-models/resolve/main/models/modnet_photographic_portrait_matting.onnx modnet_fold.py" "photos/src/main/assets/u2netp.maml u2netp 309c8469258dda742793dce0ebea8e6dd393174f89934733ecc8b14c76f4ddd8 https://huggingface.co/BritishWerewolf/U-2-Netp/resolve/7112208dbac3a3642496c8d54e2f0f9bb3dc1dc8/onnx/model.onnx" "photos/src/main/assets/scrfd_500m.maml scrfd 5e4447f50245bbd7966bd6c0fa52938c61474a04ec7def48753668a9d8b4ea3a https://huggingface.co/immich-app/buffalo_s/resolve/0ff1751885575e62e084dff70549ce24a11fa5dc/detection/model.onnx" "photos/src/main/assets/w600k_mbf.maml mobilefacenet 9cc6e4a75f0e2bf0b1aed94578f144d15175f357bdc05e815e5c4a02b319eb4f https://huggingface.co/immich-app/buffalo_s/resolve/0ff1751885575e62e084dff70549ce24a11fa5dc/recognition/model.onnx"
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex ba3d4f8b0c..af74f4add6 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -237,6 +237,11 @@ GRAPHS = { # differ (Q2_K verbatim vs int8 requantised), so the Rust forward pass reads either # file. A separate id would fork the runtime for no reason; the digest tells them apart. "madlad400-q2k": 25,+ # MODNet photographic-portrait matting (MobileNetV2 backbone), for `:camera`'s+ # still-capture portrait matte. Converted via `modnet_fold.py`, not this script+ # directly: the export's Slice-fed batch norms and SE MatMuls are folded first.+ # Next free id after MADLAD's 25, with 7..10 and 15 staying retired.+ "modnet": 27, } # Graphs read from a GGUF file rather than safetensors/ONNX/TFLite. The Q2_K port reads@@ -306,6 +311,9 @@ EXPECTED_DIGEST = { # agree); only the payloads differ (Q2_K verbatim vs int8 requantised), hence a # separate digest on the same graph id. See `collect_madlad_q2k`. "madlad400-q2k": "f17cbb4fb9f44eb8a4d94d93f5a00e7ec868d11628a12ea1b2078fbc700124b7",+ # MODNet photographic portrait matting, folded by `modnet_fold.py`. Pinned+ # after `nets::modnet` was checked against this table layer for layer.+ "modnet": "f6ad3e1cdcf38679f89ed15891576a46a2b8c9d3cc110fbd26b746df4194da2a", } # Graphs that are one **module** of a larger export, keyed by the node-name prefix that@@ -352,6 +360,14 @@ GEOMETRY = { "outputs": ["516"], "shape": [3, 112, 112], },+ # MODNet photographic portrait matting. Dynamic HW like scrfd: the export is+ # dynamic-batch/dynamic-shape and the branch Resizes are scale-factor based,+ # so the fixed 512x512 run resolves structurally. Transcribed at SIZE=512.+ "modnet": {+ "input": "input",+ "outputs": ["output"],+ "shape": [3, None, None],+ }, } # Op-type counts, as a coarse first check that the graph is the one we lowered by@@ -376,6 +392,19 @@ EXPECTED_OPS = { "Conv": 49, "PRelu": 34, "Add": 12, "BatchNormalization": 1, "Flatten": 1, "Gemm": 1, },+ # MODNet photographic portrait matting, AFTER `modnet_fold.py`: the 16+ # IBNorm batch norms are folded into their Convs and the 2 SE MatMuls are+ # rewritten as 1x1 Convs, so this counts the folded graph (Conv 69+2, no+ # BatchNormalization, no MatMul). The 16 InstanceNormalizations and 35+ # Clip(0,6)/17 Relu/2 Sigmoid are structural, transcribed in+ # `nets::modnet` rather than emitted.+ "modnet": {+ "Conv": 71, "Add": 10, "Mul": 1, "Concat": 24,+ "InstanceNormalization": 16, "GlobalAveragePool": 1,+ "Relu": 17, "Clip": 35, "Sigmoid": 2,+ "Resize": 9, "Slice": 32, "Shape": 3, "Gather": 2, "Unsqueeze": 4,+ "Reshape": 2, "Expand": 1, "Constant": 241,+ }, # Two towers in one graph. `MatMul` 107 is the 80 weighted projections plus the 26 attention # products and the one `logit_scale` product; `Erf` 13 is the 13 layers' GELU; `Softmax` 13 is # their attention, and the causal mask the text tower's three need is a `-3.4e38` constant
scripts/ml/modnet_fold.py
diff --git a/scripts/ml/modnet_fold.py b/scripts/ml/modnet_fold.pynew file mode 100644index 0000000000..e983b76a34--- /dev/null+++ b/scripts/ml/modnet_fold.py@@ -0,0 +1,293 @@+#!/usr/bin/env python3+"""Fold a MODNet photographic-portrait export into `.maml`, ahead of time.++The official MODNet weights (Apache-2.0, `ZHKKKe/MODNet`, mirrored for this+repo) export with two constructs `:library:ml` cannot lower verbatim:++* `IBNorm`: every branch convolution is followed by a channel split whose+ first half runs through a frozen `BatchNormalization` and whose second half+ runs through an `InstanceNormalization(affine=False)`, re-concatenated.+ `maml_convert.collect_layers` only folds a batch norm that directly follows+ its convolution (`BatchNormalization` after a `Slice` is rejected), and the+ slice between them blocks the fold.+* The SE block's two projections arrive as `MatMul` against 2-D constants,+ which `collect_layers` does not emit (only `Gemm`-over-`Flatten` is+ lowered, and these feed `Reshape`, not `Flatten`).++# Why this is a separate script++Same reason as `ppocr_fold.py`: `maml_convert.py`'s contract is that a+`.maml` is the ONNX's tensors *verbatim*, so teaching it slice-aware folds+and MatMul rewrites would tax every other model. The fold happens here, once,+ahead of time; the Rust transcribes the folded table.++# What is folded, and why it is exact++* Each `Conv -> Slice[0:k] -> BatchNormalization(frozen)` half is pushed into+ the producer convolution's weight rows `[0:k)` and bias rows, in fp64:+ `W'[o] = W[o] * s[o]`, `b'[o] = (b[o] - mean[o]) * s[o] + beta[o]` with+ `s = gamma / sqrt(var + eps)`. At inference a frozen batch norm is a+ per-channel affine, so this is exact, and the slice survives untouched —+ only which rows are scaled changes, which the digest records via the+ unchanged shapes plus the folded values' provenance in `--print-graph`.+* Each SE `MatMul(x, W)` with a constant 2-D `W` becomes a `Conv` node with+ kernel `[out, in, 1, 1]` and a synthesised zero bias: a matrix product over+ a `[1, C]` row vector is a 1x1 convolution, exactly. The surrounding+ `Unsqueeze`/`Concat`/`Reshape` shape scaffolding is left in place and dies+ as dead code — the Rust never transcribes it, the way U^2-Netp's 266+ `Constant` + 114 `Shape` nodes are ignored.++Deliberately **not** folded:++* `InstanceNormalization(affine=False)`: per-inference statistics, so there+ is nothing to fold. The runtime implements it as `Kind::InstanceNorm`+ (see `nets/modnet.rs`); the fold script only verifies every one is+ `affine=False` (scale 1, bias 0) with the export's epsilon.+* `Clip(0, 6)` (ReLU6): a real nonlinearity, fused into the producing+ convolution as `Act::Relu6` by the Rust transcription, not rewritten here.+* Standalone `Relu` after a `Concat` (the 16 IBNorm rejoins): no convolution+ produced that value, so the Rust runs it as `Kind::Activate`.++ ./scripts/ml/modnet_fold.py model.onnx --graph modnet -o out.maml+ ./scripts/ml/modnet_fold.py model.onnx --graph modnet --print-graph+"""++import argparse+import copy+import hashlib+import os+import sys++import numpy as np+import onnx+from onnx import numpy_helper++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+import maml_convert # noqa: E402 (needs the path above)++# Every IBNorm in this export: BatchNorm over channels [0:k), InstanceNorm+# over [k:), epsilon from the InstanceNorm2d default.+IBN_EPSILON = 1e-5+TOLERANCE = 1e-6+++def const_arrays(model):+ """Every constant tensor by name, from initializers and Constant nodes."""+ inits = {i.name: i for i in model.graph.initializer}+ consts = {}+ for node in model.graph.node:+ if node.op_type == "Constant":+ for attr in node.attribute:+ if attr.name == "value":+ consts[node.output[0]] = attr.t+ def array(name):+ t = inits.get(name, consts.get(name))+ return numpy_helper.to_array(t) if t is not None else None+ return inits, consts, array+++def fold_ibnorm(model):+ """Push each Slice-fed frozen BatchNorm into its producer Conv's rows.++ Returns the count of folded sites. Verifies the full IBNorm shape at each+ site: Conv -> Slice[0:k] -> BN -> Concat <- IN <- Slice[k:] with the IN+ affine-free, and the Concat feeding only the post-join Relu path.+ """+ inits, consts, array = const_arrays(model)+ nodes = list(model.graph.node)+ out2node = {}+ for n in nodes:+ for o in n.output:+ out2node[o] = n+ consumers = {}+ for n in nodes:+ for i in n.input:+ consumers.setdefault(i, []).append(n)++ folded = 0+ for bn in [n for n in nodes if n.op_type == "BatchNormalization"]:+ # The BN half must hang off a channel-axis Slice [0:k) of a Conv.+ sl = out2node.get(bn.input[0])+ if sl is None or sl.op_type != "Slice":+ raise SystemExit(f"{bn.output[0]}: batch norm input is not a Slice")+ axes = array(sl.input[3])+ if axes is None or list(axes) != [1]:+ raise SystemExit(f"{sl.output[0]}: IBNorm slice is not channel-axis")+ starts, ends = array(sl.input[1]), array(sl.input[2])+ if starts is None or list(starts) != [0] or ends is None or len(ends) != 1:+ raise SystemExit(f"{sl.output[0]}: BN slice is not [0:k)")+ k = int(ends[0])+ conv = out2node.get(sl.input[0])+ if conv is None or conv.op_type != "Conv":+ raise SystemExit(f"{sl.output[0]}: BN slice source is not a Conv")+ # The sibling slice [k:] must feed an affine-free InstanceNorm, and+ # both halves must rejoin at one Concat.+ sib = [c for c in consumers.get(sl.input[0], []) if c is not sl]+ if len(sib) != 1 or sib[0].op_type != "Slice":+ raise SystemExit(f"{sl.input[0]}: expected exactly two Slice consumers")+ sib = sib[0]+ s_starts, s_ends = array(sib.input[1]), array(sib.input[2])+ if list(s_starts) != [k]:+ raise SystemExit(f"{sib.output[0]}: IN slice does not start at {k}")+ inorm = consumers.get(sib.output[0], [])+ if len(inorm) != 1 or inorm[0].op_type != "InstanceNormalization":+ raise SystemExit(f"{sib.output[0]}: IN slice does not feed InstanceNorm")+ inorm = inorm[0]+ sc, bi = array(inorm.input[1]), array(inorm.input[2])+ if sc is None or bi is None or not np.all(sc == 1) or not np.all(bi == 0):+ raise SystemExit(f"{inorm.output[0]}: InstanceNorm is not affine-free")+ eps = next((a.f for a in inorm.attribute if a.name == "epsilon"), 1e-5)+ if abs(eps - IBN_EPSILON) > TOLERANCE:+ raise SystemExit(f"{inorm.output[0]}: epsilon {eps} is not {IBN_EPSILON}")+ bn_cons = consumers.get(bn.output[0], [])+ in_cons = consumers.get(inorm.output[0], [])+ if len(bn_cons) != 1 or len(in_cons) != 1 or bn_cons[0] is not in_cons[0]:+ raise SystemExit(f"{bn.output[0]}: BN/IN halves do not rejoin at one Concat")+ if bn_cons[0].op_type != "Concat":+ raise SystemExit(f"{bn.output[0]}: halves rejoin at {bn_cons[0].op_type}")+ # Fold: scale Conv rows [0:k) and bias rows by the BN affine, fp64.+ attrs = {a.name: a for a in bn.attribute}+ epsilon = attrs["epsilon"].f if "epsilon" in attrs else 1e-5+ gamma = array(bn.input[1]).astype(np.float64)+ beta = array(bn.input[2]).astype(np.float64)+ mean = array(bn.input[3]).astype(np.float64)+ var = array(bn.input[4]).astype(np.float64)+ if any(v is None for v in (gamma, beta, mean, var)):+ raise SystemExit(f"{bn.output[0]}: batch norm parameter is computed")+ if gamma.shape[0] != k:+ raise SystemExit(f"{bn.output[0]}: BN channels {gamma.shape[0]} != slice {k}")+ w_name, b_name = conv.input[1], conv.input[2] if len(conv.input) > 2 else None+ if b_name is None:+ raise SystemExit(f"{conv.output[0]}: IBNorm Conv has no bias to fold into")+ w = array(w_name).astype(np.float64)+ b = array(b_name).astype(np.float64)+ scale = gamma / np.sqrt(var + epsilon)+ w[:k] = w[:k] * scale.reshape([-1] + [1] * (w.ndim - 1))+ b[:k] = (b[:k] - mean) * scale + beta+ folded_w = numpy_helper.from_array(w.astype(np.float32), name=w_name)+ folded_b = numpy_helper.from_array(b.astype(np.float32), name=b_name)+ if w_name in inits:+ model.graph.initializer.remove(inits[w_name])+ model.graph.initializer.append(folded_w)+ else:+ raise SystemExit(f"{w_name}: IBNorm Conv weight is not an initializer")+ if b_name in inits:+ model.graph.initializer.remove(inits[b_name])+ model.graph.initializer.append(folded_b)+ else:+ raise SystemExit(f"{b_name}: IBNorm Conv bias is not an initializer")+ # Drop the BN node, rewiring its consumer to read the Slice directly.+ for c in bn_cons:+ c.input[:] = [sl.output[0] if i == bn.output[0] else i for i in c.input]+ model.graph.node.remove(bn)+ folded += 1+ return folded+++def rewrite_se_matmuls(model):+ """Rewrite the SE block's constant MatMuls as 1x1 Convs with zero bias.++ A `MatMul(x, W)` over a row vector is a 1x1 convolution with kernel+ `[out, in, 1, 1]`; the surrounding Unsqueeze/Concat/Reshape scaffolding+ stays and is ignored structurally, like U^2-Netp's shape machinery.+ """+ inits, consts, array = const_arrays(model)+ rewritten = 0+ for node in list(model.graph.node):+ if node.op_type != "MatMul":+ continue+ if len(node.input) != 2 or array(node.input[1]) is None:+ raise SystemExit(f"{node.output[0]}: non-constant SE MatMul")+ w = array(node.input[1])+ if w.ndim != 2:+ raise SystemExit(f"{node.output[0]}: SE weight is {w.ndim}-D")+ out_c, in_c = w.shape[1], w.shape[0]+ kernel = w.T.reshape(out_c, in_c, 1, 1).astype(np.float32)+ k_name = node.input[1] + "__conv1x1_weight"+ b_name = node.input[1] + "__conv1x1_bias"+ model.graph.initializer.append(+ numpy_helper.from_array(kernel, name=k_name))+ model.graph.initializer.append(+ numpy_helper.from_array(np.zeros(out_c, dtype=np.float32), name=b_name))+ node.op_type = "Conv"+ node.input[:] = [node.input[0], k_name, b_name]+ del node.attribute[:]+ rewritten += 1+ return rewritten+++def fold(model):+ """Folded copy of `model`: BNs pushed into Convs, MatMuls as Convs."""+ model = copy.deepcopy(model)+ n_bn = fold_ibnorm(model)+ n_mm = rewrite_se_matmuls(model)+ return model, n_bn, n_mm+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("onnx")+ parser.add_argument("--graph", required=True, choices=sorted(maml_convert.GRAPHS))+ parser.add_argument("-o", "--out", help="where to write the .maml")+ parser.add_argument("--print-graph", action="store_true", help="dump the folded op flow")+ parser.add_argument("--print-layers", action="store_true")+ parser.add_argument("--print-digest", action="store_true")+ args = parser.parse_args()++ model = onnx.load(args.onnx)+ folded, n_bn, n_mm = fold(model)+ if args.print_graph:+ print(f"folded {n_bn} IBNorm batch norms, rewrote {n_mm} SE MatMuls as 1x1 Conv")+ for n in folded.graph.node:+ if n.op_type not in ("Constant",):+ print(f" {n.op_type:22s} {n.name}")++ onnx_sha256 = hashlib.sha256()+ with open(args.onnx, "rb") as f:+ for block in iter(lambda: f.read(1 << 20), b""):+ onnx_sha256.update(block)+ layers, tensors = maml_convert.collect_layers(+ folded, quantise=args.graph in maml_convert.INT8_GRAPHS+ )+ if args.print_layers:+ for layer in layers:+ print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}")+ if args.print_digest:+ print(f' "{args.graph}": "{maml_convert.layer_table_digest(layers)}",')+ maml_convert.check_graph(folded, args.graph)++ digest = maml_convert.layer_table_digest(layers)+ pinned = maml_convert.EXPECTED_DIGEST.get(args.graph)+ if pinned is None:+ message = (+ f"{args.graph} has no pinned layer table digest. Add\n"+ f' "{args.graph}": "{digest}",\n'+ "to EXPECTED_DIGEST once the Rust net agrees with this table, so that a later\n"+ "change to either side fails loudly instead of shifting every tensor."+ )+ if not args.print_digest:+ raise SystemExit(message)+ print(message, file=sys.stderr)+ elif digest != pinned:+ message = (+ f"layer table digest {digest}\n"+ f" pinned {pinned}\n"+ "The ordered Conv/ConvTranspose table changed, so the hardcoded forward\n"+ f"pass in library/ml/src/main/rust/src/nets/{args.graph}.rs no longer\n"+ "matches this export. Re-read it with --print-layers, update the Rust,\n"+ "then re-pin with --print-digest."+ )+ if not args.print_digest:+ raise SystemExit(message)+ print(message, file=sys.stderr)+ if args.out:+ blob, count = maml_convert.build(+ layers, tensors, maml_convert.GRAPHS[args.graph], onnx_sha256.digest()+ )+ with open(args.out, "wb") as f:+ f.write(blob)+ print(f"wrote {args.out} ({len(blob)} bytes, {count} tensors)")+++if __name__ == "__main__":+ main()
scripts/ml/onnx_parity.py
diff --git a/scripts/ml/onnx_parity.py b/scripts/ml/onnx_parity.pyindex 577752eda1..623fa1c0e6 100644--- a/scripts/ml/onnx_parity.py+++ b/scripts/ml/onnx_parity.py@@ -79,6 +79,12 @@ PROBE = { # nothing useful for this graph: there is no fp32 ONNX for whisper. What a low correlation would # mean is a structural error, which is what this is for. "whisper": None,+ # MODNet photographic portrait matting: the graph's own output, the 512x512+ # alpha matte. Run with `--width 512` — the export is dynamic-shape and the+ # Rust is lowered at SIZE=512, so any other width compares different grids.+ # Pass the folded `.maml` via `--maml` (a runtime download, not a bundled+ # asset at parity time).+ "modnet": None, } # Graphs whose input is a latent rather than an image, and how wide it is. One that is a