Modern Apps git

← Modern-Apps.git

photos: face detection and embedding move to :library:ml

Commit
a217c96fa85c7f09a23fe28a46fd438c0de992fc
Author
vayun-mathur <[email protected]>
When
2026-08-27 03:13 UTC (3 months ago)
Parents
6f892d5

Diff

library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.ktnew file mode 100644index 0000000000..25439f4862--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt@@ -0,0 +1,195 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap+import android.util.Log++/**+ * Face detection and face embedding, for `:photos`'s people clustering.+ *+ * **SCRFD 500M** finds faces and their five keypoints; **MobileFaceNet** (`w600k_mbf`,+ * ArcFace-trained) turns an aligned crop into a 512-d embedding. Both run on Vulkan+ * compute with fp16 weights — see `photos/src/main/assets/README.md` for provenance and+ * the InsightFace licence, and `library/ml/src/main/rust/src/nets/{scrfd,mobilefacenet}.rs`+ * for the forward passes.+ *+ * These replace `com.vayunmathur.ncnn.FaceDetector` and `FaceEmbedder`. Same two models,+ * re-sourced from a licensed ONNX export and run on the GPU instead of ncnn's CPU+ * kernels. The embeddings are **not** bit-identical to ncnn's, so+ * `FaceRecognizer.EMBEDDER_VERSION` has to be bumped alongside this — the stored index+ * would otherwise mix two incompatible embedding spaces and cluster nonsense.+ *+ * GPU-only, like the segmenters: if [FaceDetector.isAvailable] is false the device has no+ * Vulkan fp16 compute and people clustering turns off, rather than falling back.+ */++/** One detected face. Every coordinate is a fraction of the source bitmap, `0..1`. */+data class DetectedFaceBox(+    /** Left edge. */+    val left: Float,+    /** Top edge. */+    val top: Float,+    /** Right edge. */+    val right: Float,+    /** Bottom edge. */+    val bottom: Float,+    /** Left eye, in the detector's keypoint order rather than the viewer's left. */+    val leftEyeX: Float,+    /** Left eye. */+    val leftEyeY: Float,+    /** Right eye. */+    val rightEyeX: Float,+    /** Right eye. */+    val rightEyeY: Float,+    /** Detector confidence, post-sigmoid. */+    val score: Float,+)++/**+ * SCRFD 500M face detection.+ *+ * Not thread-safe: [detect] and [close] must not overlap. See the note in+ * [NativeSegmenter] about why the lock lives with the caller's threading rather than here.+ *+ * @param context used only to read the asset; not retained.+ * @param assetName the `.vkml` in the app's assets.+ */+class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {++    @Volatile private var handle: Long = if (!MlNative.isAvailable) {+        0L+    } else {+        try {+            MlNative.createScrfd(context.assets.open(assetName).use { it.readBytes() })+        } catch (e: Throwable) {+            Log.e(TAG, "cannot load $assetName", e)+            0L+        }+    }++    /** Whether the detector came up. False means people clustering is off. */+    val isAvailable: Boolean get() = handle != 0L++    /** Reused across photos, so an indexing pass does not allocate one array per image. */+    private var pixels: IntArray? = null++    /**+     * Every face in [bitmap], or an empty list if there are none or the detector is+     * unavailable.+     *+     * [bitmap] may be any size: it is letterboxed and normalised natively.+     */+    fun detect(bitmap: Bitmap): List<DetectedFaceBox> {+        val live = handle+        if (live == 0L) return emptyList()+        // `getPixels` cannot read a HARDWARE bitmap, and a null config means an unknown+        // one; copying is the only option.+        val readable = if (bitmap.config == Bitmap.Config.HARDWARE || bitmap.config == null) {+            bitmap.copy(Bitmap.Config.ARGB_8888, false)+        } else {+            bitmap+        } ?: return emptyList()++        return try {+            val count = readable.width * readable.height+            var buffer = pixels+            if (buffer == null || buffer.size != count) {+                buffer = IntArray(count)+                pixels = buffer+            }+            readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)+            val flat = MlNative.detectFaces(live, buffer, readable.width, readable.height)+                ?: return emptyList()+            unpack(flat)+        } finally {+            if (readable !== bitmap) readable.recycle()+        }+    }++    /** Nine floats per face; see `MlNative.detectFaces` for the order. */+    private fun unpack(flat: FloatArray): List<DetectedFaceBox> {+        if (flat.size % FLOATS_PER_FACE != 0) {+            Log.e(TAG, "${flat.size} floats is not a whole number of faces")+            return emptyList()+        }+        val out = ArrayList<DetectedFaceBox>(flat.size / FLOATS_PER_FACE)+        var at = 0+        while (at + FLOATS_PER_FACE <= flat.size) {+            out += DetectedFaceBox(+                left = flat[at],+                top = flat[at + 1],+                right = flat[at + 2],+                bottom = flat[at + 3],+                leftEyeX = flat[at + 4],+                leftEyeY = flat[at + 5],+                rightEyeX = flat[at + 6],+                rightEyeY = flat[at + 7],+                score = flat[at + 8],+            )+            at += FLOATS_PER_FACE+        }+        return out+    }++    override fun close() {+        val toDestroy = handle+        handle = 0L+        pixels = null+        if (toDestroy != 0L) MlNative.destroy(toDestroy)+    }++    companion object {+        /** What `:photos` ships. */+        const val DEFAULT_ASSET: String = "scrfd_500m.vkml"+        private const val TAG = "FaceDetector"+        private const val FLOATS_PER_FACE = 9+    }+}++/**+ * MobileFaceNet face embedding.+ *+ * Takes an aligned 112×112 crop and returns 512 floats. The result is **not**+ * L2-normalised — `FaceRecognizer` does that, as it did with ncnn.+ *+ * Not thread-safe: [embed] and [close] must not overlap.+ *+ * @param context used only to read the asset; not retained.+ * @param assetName the `.vkml` in the app's assets.+ */+class FaceEmbedder(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {++    // The embedder is one input and one output, so it is exactly the segmenter's shape:+    // a 112x112 bitmap in, a 512x1x1 "mask" out. Reusing `NativeSegmenter` rather than+    // adding a second JNI path for the same three calls.+    private val native =+        NativeSegmenter(context, assetName, TAG, MlNative::createMobilefacenet)++    /** Whether the embedder came up. */+    val isAvailable: Boolean get() = native.isAvailable++    /**+     * The 512-d embedding of an aligned [bitmap], or null on failure.+     *+     * [bitmap] should already be the canonical 112×112 crop; anything else is resized+     * natively, which for a face crop is not what the caller wanted.+     */+    fun embed(bitmap: Bitmap): FloatArray? {+        val result = native.segment(bitmap) ?: return null+        if (result.mask.size != EMBEDDING_LENGTH) {+            Log.e(TAG, "a ${result.mask.size}-value embedding, expected $EMBEDDING_LENGTH")+            return null+        }+        return result.mask+    }++    override fun close() = native.close()++    companion object {+        /** What `:photos` ships. */+        const val DEFAULT_ASSET: String = "w600k_mbf.vkml"+        /** Length of the embedding MobileFaceNet produces. */+        const val EMBEDDING_LENGTH = 512+        private const val TAG = "FaceEmbedder"+    }+}
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 1188e5a704..057cec8ed6 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@@ -43,6 +43,30 @@ internal object MlNative {     /** Bring up U²-Net portable. Returns 0 on failure, as [createSelfie]. */     external fun createU2netp(weights: ByteArray): Long +    /** Bring up SCRFD 500M face detection. Returns 0 on failure, as [createSelfie]. */+    external fun createScrfd(weights: ByteArray): Long++    /** Bring up MobileFaceNet face embedding. Returns 0 on failure, as [createSelfie]. */+    external fun createMobilefacenet(weights: ByteArray): Long++    /**+     * Detect faces in [pixels] and return them flattened, nine floats per face.+     *+     * The layout per face is `left, top, right, bottom, leftEyeX, leftEyeY, rightEyeX,+     * rightEyeY, score`, every coordinate a fraction of the bitmap. Letterboxing, the+     * forward pass, the anchor decode and non-maximum suppression all happen natively, so+     * this crosses the boundary once per bitmap rather than once per proposal.+     *+     * An empty array means no faces — the common case, and not a failure. Null is a+     * failure.+     */+    external fun detectFaces(+        handle: Long,+        pixels: IntArray,+        width: Int,+        height: Int,+    ): FloatArray?+     /**      * Run the network over [pixels] and return the mask, or null on failure.      *
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 ad9f66f4bd..83a0b0d2b3 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -30,8 +30,9 @@ use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray}; use jni::sys::{jfloatArray, jint, jlong}; use jni::JNIEnv; -use crate::nets::{selfie, u2netp};-use crate::preprocess::{IMAGENET, RESCALE_ONLY};+use crate::nets::{mobilefacenet, scrfd, selfie, u2netp};+use crate::post::nms::{self, Face, Maps};+use crate::preprocess::{Letterbox, FACE_EMBED, IMAGENET, RESCALE_ONLY, SCRFD}; use crate::vulkan::context; use crate::vulkan::run::Net; use crate::weights::{graph, Weights};@@ -75,6 +76,34 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createU2netp<'l>     open(&mut env, weights, graph::U2NETP, "u2netp") } +/// `FaceDetector`'s constructor: SCRFD 500M at a fixed square. 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_createScrfd<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    weights: JByteArray<'l>,+) -> jlong {+    open(&mut env, weights, graph::SCRFD, "scrfd")+}++/// `FaceEmbedder`'s constructor: MobileFaceNet at 112x112. 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_createMobilefacenet<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    weights: JByteArray<'l>,+) -> jlong {+    open(&mut env, weights, graph::MOBILEFACENET, "mobilefacenet")+}+ 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,@@ -103,6 +132,13 @@ fn build<'l>(     let (plan, normalise) = match graph_id {         graph::SELFIE => (selfie::build(&parsed)?, RESCALE_ONLY),         graph::U2NETP => (u2netp::build(&parsed)?, IMAGENET),+        // A fixed square rather than the tight multiple-of-32 letterbox `scrfd.cpp` uses;+        // see `preprocess::Letterbox::square` for why, and what it costs.+        graph::SCRFD => (+            scrfd::build(&parsed, scrfd::LONG_SIDE, scrfd::LONG_SIDE)?,+            SCRFD,+        ),+        graph::MOBILEFACENET => (mobilefacenet::build(&parsed)?, FACE_EMBED),         other => return Err(format!("no forward pass for graph {other}")),     };     Ok(Handle {@@ -174,6 +210,132 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_segment<'     } } +/// Detect faces in `pixels` and return them flattened, nine floats each.+///+/// The layout per face is `left, top, right, bottom, leftEyeX, leftEyeY, rightEyeX,+/// rightEyeY, score` — deliberately the argument order of the old ncnn JNI's `Face`+/// constructor, so the Kotlin mapping is a straight read and a reviewer can diff the two.+/// Every coordinate is a fraction of the source bitmap, so it survives the caller+/// resizing.+///+/// A flat `float[]` rather than an array of objects: constructing `n` Java objects across+/// JNI is `n` class lookups and `n` constructor calls, and the Kotlin side has to allocate+/// its own data class anyway.+///+/// Returns null on failure or on a `0` handle. An empty array means no faces, which is+/// the common case and not an error.+///+/// # Safety+///+/// `handle` must be `0` or a value returned by+/// [`Java_com_vayunmathur_library_ml_MlNative_createScrfd`] and not yet destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_detectFaces<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    pixels: JIntArray<'l>,+    width: jint,+    height: jint,+) -> jfloatArray {+    let null = std::ptr::null_mut();+    if handle == 0 || width <= 0 || height <= 0 {+        return null;+    }+    // SAFETY: as `segment` — the caller guarantees the handle is live and serialises this+    // against `destroy`.+    let state = unsafe { &mut *(handle as *mut Handle) };++    if let Err(e) = read_pixels(&mut env, &pixels, width, height, &mut state.pixels) {+        log(&e);+        return null;+    }+    match detect(state, width as u32, height as u32) {+        Ok(flat) => match new_float_array(&mut env, &flat) {+            Ok(array) => array,+            Err(e) => {+                log(&format!("cannot return the detections: {e}"));+                null+            }+        },+        Err(e) => {+            log(&format!("face detection failed: {e}"));+            null+        }+    }+}++/// Nine floats per detected face. See the entry point above for the order.+const FACE_FLOATS: usize = 9;++/// Letterbox, run, decode, suppress, and flatten.+fn detect(state: &mut Handle, width: u32, height: u32) -> Result<Vec<f32>, String> {+    let fit = Letterbox::square(width, height, scrfd::LONG_SIDE)?;+    let maps = state.net.infer_letterboxed(&state.pixels, width, height, &fit)?;+    let shapes: Vec<crate::nets::Shape> =+        state.net.output_shapes().iter().map(|b| b.shape).collect();+    if maps.len() != shapes.len() || maps.len() != scrfd::STRIDES.len() * 3 {+        return Err(format!("{} output maps, expected {}", maps.len(), scrfd::STRIDES.len() * 3));+    }++    let mut faces: Vec<Face> = Vec::new();+    for (level, stride) in scrfd::STRIDES.iter().enumerate() {+        let at = level * 3;+        let (score, bbox, keypoints) = match (maps.get(at), maps.get(at + 1), maps.get(at + 2)) {+            (Some(s), Some(b), Some(k)) => (s, b, k),+            _ => return Err(format!("stride {stride} is missing a map")),+        };+        let shape = shapes.get(at).copied().ok_or("a map with no shape")?;+        nms::decode(+            &Maps { score, bbox, keypoints, shape },+            *stride,+            nms::SCORE_THRESHOLD,+            &mut faces,+        )?;+    }+    nms::suppress(&mut faces, nms::IOU_THRESHOLD);+    nms::to_source(&mut faces, &fit, width, height);++    let mut flat = Vec::with_capacity(faces.len() * FACE_FLOATS);+    for face in &faces {+        flat.extend_from_slice(&face.bounds);+        // Landmarks 0 and 1 are the eyes, which is all the alignment in+        // `FaceRecognizer.alignFace` uses. The nose and mouth corners are decoded and+        // dropped here rather than carried across a boundary nothing reads them through.+        let (left_eye, right_eye) = match (face.keypoints.first(), face.keypoints.get(1)) {+            (Some(a), Some(b)) => (*a, *b),+            _ => ((0.0, 0.0), (0.0, 0.0)),+        };+        flat.push(left_eye.0);+        flat.push(left_eye.1);+        flat.push(right_eye.0);+        flat.push(right_eye.1);+        flat.push(face.score);+    }+    Ok(flat)+}++/// Copy a Java `int[]` of ARGB pixels into `into`, checking it against `width` x `height`.+fn read_pixels<'l>(+    env: &mut JNIEnv<'l>,+    pixels: &JIntArray<'l>,+    width: jint,+    height: jint,+    into: &mut Vec<i32>,+) -> Result<(), String> {+    let count = match env.get_array_length(pixels) {+        Ok(n) if n >= 0 => n as usize,+        Ok(n) => return Err(format!("a pixel array of length {n}")),+        Err(e) => return Err(format!("cannot size the pixel array: {e}")),+    };+    if count != (width as usize) * (height as usize) {+        return Err(format!("{count} pixels for a {width}x{height} bitmap"));+    }+    into.resize(count, 0);+    env.get_int_array_region(pixels, 0, into)+        .map_err(|e| format!("cannot read the pixel array: {e}"))+}+ /// The mask's width, so Kotlin does not have to know either network's input size. /// /// # Safety
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 c30f93cbe3..c611d33f77 100644--- a/library/ml/src/main/rust/src/preprocess.rs+++ b/library/ml/src/main/rust/src/preprocess.rs@@ -122,6 +122,49 @@ impl Letterbox {         })     } +    /// Fit a `width` x `height` image into a `side` x `side` square, padding both axes.+    ///+    /// The scale is identical to [`Letterbox::new`]'s — `side / long side` — so a+    /// detection lands in the same place; only the amount of padding differs, and padding+    /// is a constant border either way.+    ///+    /// # Why the square and not the tight fit+    ///+    /// `scrfd.cpp` pads only the short side, to the next multiple of 32, which makes the+    /// net's input shape a function of the photo's aspect ratio. Supporting that properly+    /// means compiling a plan and re-recording a command buffer per shape, which is real+    /// machinery the runtime does not have yet (and which PP-OCR and VITS will need for+    /// their own reasons).+    ///+    /// A square costs up to 2x the arithmetic on a panorama and nothing on a square+    /// photo. Detection runs once per photo during indexing rather than per frame, and+    /// SCRFD's arena at 640x640 is 9.3 MB, so that is a cheap way to avoid the machinery+    /// until something actually needs it. [`crate::nets::scrfd::build`] already accepts+    /// any multiple of 32, so nothing is given up by starting here.+    pub fn square(width: u32, height: u32, side: u32) -> Result<Letterbox, String> {+        if width == 0 || height == 0 {+            return Err(format!("a {width}x{height} image"));+        }+        if side == 0 {+            return Err("a zero-sided square".into());+        }+        // Same truncation as `new`: the long side lands exactly on `side`, the short one+        // follows by the same scale and is truncated.+        let (scale, resized) = if width > height {+            let scale = side as f32 / width as f32;+            (scale, (side, ((height as f32 * scale) as u32).max(1).min(side)))+        } else {+            let scale = side as f32 / height as f32;+            (scale, (((width as f32 * scale) as u32).max(1).min(side), side))+        };+        Ok(Letterbox {+            scale,+            resized,+            padded: (side, side),+            offset: ((side - resized.0) / 2, (side - resized.1) / 2),+        })+    }+     /// The net's input shape for this fit.     pub fn shape(&self) -> Shape {         Shape::new(3, self.padded.1, self.padded.0)@@ -577,6 +620,62 @@ mod tests {         assert_eq!(f16_to_f32(out[row + 31]), 0.0);     } +    #[test]+    fn a_square_letterbox_pads_both_axes_and_keeps_the_scale() {+        // The same 1280x720 photo as the tight-fit test: scale 0.5 and a 640x360 image+        // either way, but padded to 640x640 with 140 rows above instead of 12.+        let tight = Letterbox::new(1280, 720, 640, 32).expect("fits");+        let square = Letterbox::square(1280, 720, 640).expect("fits");+        assert_eq!(square.scale, tight.scale);+        assert_eq!(square.resized, tight.resized);+        assert_eq!(square.padded, (640, 640));+        assert_eq!(square.offset, (0, 140));+    }++    #[test]+    fn a_square_letterbox_recovers_the_original_fraction() {+        // The undo has to work against the larger offset too, which is the whole reason+        // the offset is stored rather than recomputed.+        let fit = Letterbox::square(1280, 720, 640).expect("fits");+        let mut faces = vec![super::super::post::nms::Face {+            score: 0.9,+            bounds: [0.0, 140.0, 640.0, 500.0],+            keypoints: [(320.0, 320.0); 5],+        }];+        super::super::post::nms::to_source(&mut faces, &fit, 1280, 720);+        let got = faces.first().copied().expect("one face");+        assert!((got.bounds[0] - 0.0).abs() < 1e-6, "{:?}", got.bounds);+        assert!((got.bounds[1] - 0.0).abs() < 1e-6, "{:?}", got.bounds);+        assert!((got.bounds[2] - 1279.0 / 1280.0).abs() < 1e-6, "{:?}", got.bounds);+        assert!((got.bounds[3] - 719.0 / 720.0).abs() < 1e-6, "{:?}", got.bounds);+        // The centre of the padded square is the centre of the photo.+        let (x, y) = got.keypoints[0];+        assert!((x - 0.5).abs() < 2e-3, "{x}");+        assert!((y - 0.5).abs() < 2e-3, "{y}");+    }++    #[test]+    fn a_square_letterbox_is_always_exactly_the_side_it_was_asked_for() {+        for (width, height) in [+            (4032, 3024),+            (3024, 4032),+            (1920, 1080),+            (640, 480),+            (1, 4000),+            (4000, 1),+            (1, 1),+            (639, 641),+        ] {+            let fit = Letterbox::square(width, height, 640).expect("fits");+            assert_eq!(fit.padded, (640, 640), "{width}x{height}");+            // The image must fit inside the square with the padding it claims.+            assert!(+                fit.offset.0 + fit.resized.0 <= 640 && fit.offset.1 + fit.resized.1 <= 640,+                "{width}x{height}: {fit:?}"+            );+        }+    }+     #[test]     fn a_mismatched_letterbox_output_length_is_refused() {         let pixels = vec![argb(0, 0, 0); 4];
library/ml/src/main/rust/src/vulkan/run.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run.rs b/library/ml/src/main/rust/src/vulkan/run.rsindex 8d44f354f7..2a83c13010 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -414,18 +414,15 @@ impl Net {     /// `pixels` is `ARGB_8888` as `Bitmap.getPixels` produces it. The returned mask is     /// `output_shape.h * output_shape.w` long, row-major.     ///-    /// Single-input, single-output: this is the bitmap-in, mask-out path both shipping-    /// nets use, and it refuses a plan shaped otherwise rather than silently reading only-    /// the first binding.+    /// Single-input, single-output: this is the bitmap-in, mask-out path the two+    /// segmenters and the face embedder use. It refuses a plan shaped otherwise rather+    /// than silently returning only the first binding.     pub fn infer(         &mut self,         pixels: &[i32],         width: u32,         height: u32,     ) -> Result<Vec<f32>, String> {-        if self.poisoned {-            return Err("a previous submission timed out; this network is unusable".into());-        }         let input = self.plan.input()?;         // Reject a multi-output plan here rather than returning only the first binding:         // `output_scratch` spans every output, so the concatenation would look like a@@ -439,8 +436,73 @@ impl Net {             &self.normalise,             &mut self.input_scratch,         )?;-        // SAFETY: the scratch buffer is `input_shape.len()` fp16 elements, which is-        // exactly what the recorded copy region moves.+        self.submit()?;+        Ok(self.output_scratch.iter().map(|&h| preprocess::f16_to_f32(h)).collect())+    }++    /// Letterbox `pixels` into the plan's input shape, run, and return **every** output.+    ///+    /// SCRFD's path: nine maps come back, in [`crate::nets::Plan::outputs`] order. `fit`+    /// must have been computed for the shape this net was built at, which+    /// [`preprocess::Letterbox::square`] guarantees for a fixed side.+    pub fn infer_letterboxed(+        &mut self,+        pixels: &[i32],+        width: u32,+        height: u32,+        fit: &preprocess::Letterbox,+    ) -> Result<Vec<Vec<f32>>, String> {+        let input = self.plan.input()?;+        if fit.shape() != input.shape {+            return Err(format!(+                "a letterbox of {:?} for a net built at {:?}",+                fit.shape(),+                input.shape+            ));+        }+        preprocess::to_letterboxed_f16(+            pixels,+            width,+            height,+            fit,+            &self.normalise,+            &mut self.input_scratch,+        )?;+        self.submit()?;+        self.split_outputs()+    }++    /// Split the concatenated readback into one vector per output binding.+    ///+    /// The recorded command buffer packs the outputs end to end from offset 0 in the+    /// staging buffer, in declaration order, so this is the mirror of `record`.+    fn split_outputs(&self) -> Result<Vec<Vec<f32>>, String> {+        let mut outputs = Vec::with_capacity(self.plan.outputs.len());+        let mut at = 0usize;+        for binding in &self.plan.outputs {+            let len = binding.shape.len() as usize;+            let end = at.checked_add(len).ok_or("an output offset overflowed")?;+            let slice = self+                .output_scratch+                .get(at..end)+                .ok_or_else(|| format!("the readback is shorter than {end} elements"))?;+            outputs.push(slice.iter().map(|&h| preprocess::f16_to_f32(h)).collect());+            at = end;+        }+        Ok(outputs)+    }++    /// Upload `input_scratch`, submit the recorded buffer, and read `output_scratch` back.+    ///+    /// Factored out of the two `infer` variants because it is the whole of the unsafe,+    /// order-sensitive part: everything about poisoning, the fence and the queue lock is+    /// here once rather than twice.+    fn submit(&mut self) -> Result<(), String> {+        if self.poisoned {+            return Err("a previous submission timed out; this network is unusable".into());+        }+        // SAFETY: the scratch buffer is exactly the fp16 elements the recorded copy+        // regions move, and `u16` has no padding or invalid bit patterns.         let bytes = unsafe {             std::slice::from_raw_parts(                 self.input_scratch.as_ptr().cast::<u8>(),@@ -475,8 +537,7 @@ impl Net {             self.poisoned = false;         } -        self.staging.read_f16(&mut self.output_scratch)?;-        Ok(self.output_scratch.iter().map(|&h| preprocess::f16_to_f32(h)).collect())+        self.staging.read_f16(&mut self.output_scratch)     }      /// The mask's dimensions, which is what the Kotlin wrapper reports to its caller.@@ -484,6 +545,12 @@ impl Net {         let output = self.plan.output()?;         Ok((output.shape.w, output.shape.h))     }++    /// Every output binding, so a multi-output caller can size and shape the maps+    /// [`Net::infer_letterboxed`] returns without rebuilding the plan.+    pub fn output_shapes(&self) -> &[crate::nets::Binding] {+        &self.plan.outputs+    } }  /// Total elements across `bindings`, which is how much staging space one direction needs.
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex aaba3fc5e6..59db0d33a9 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -15,17 +15,13 @@ android {         applicationId = "com.vayunmathur.photos"     }     androidResources {-        // ncnn model files (the two face models here, OCR via :library:ocr) are-        // bundled in this app's assets and their paths passed to the wrappers;-        // the AAR ships none.-        //         // The TinyCLIP .onnx is read straight out of the APK by ClipEmbedder, so leave it         // uncompressed: int8 weights barely deflate, and a compressed asset would have to be         // inflated into a 24 MB heap buffer before ORT could open it.         noCompress += "onnx"-        // u2netp.vkml is read straight out of the APK by SubjectSegmenter for the same-        // reason: fp16 weights barely deflate, and a compressed asset would have to be-        // inflated into a 2.2 MB heap buffer before it could be uploaded.+        // The three .vkml files are read straight out of the APK for the same reason: fp16+        // weights barely deflate, and a compressed asset would have to be inflated into a+        // heap buffer — 6.6 MB for the face embedder — before it could be uploaded.         noCompress += "vkml"     } }@@ -47,14 +43,12 @@ dependencies {     implementation(project(":library:map"))     implementation(project(":library:image"))     implementation(libs.androidx.exifinterface)-    // On-device face detection (SCRFD) and face embedding (MobileFaceNet) run on ncnn-    // via the generalist AAR (BSD-3, no ONNX Runtime / Play Services / MediaPipe). OCR-    // uses it via :library:ocr.+    // No direct ncnn dependency any more: face detection (SCRFD 500M), face embedding+    // (MobileFaceNet) and subject segmentation (U²-Net portable) all run on :library:ml,+    // our own Vulkan compute runtime.     //-    // Subject segmentation left: U²-Net now runs on :library:ml, our own Vulkan compute-    // runtime. The two face models are transformer-adjacent enough that porting them is a-    // later phase, so ncnn stays for now.-    implementation(libs.ncnn.android)+    // `libncnn_android.so` is still in this APK, though, because :library:ocr below pulls+    // it in for PP-OCRv5 text recognition. It leaves when OCR moves across.     implementation(project(":library:ml"))      implementRoom(libs)
photos/src/main/assets/README.md
diff --git a/photos/src/main/assets/README.md b/photos/src/main/assets/README.mdindex c5c4e1b04e..0ebd02aca3 100644--- a/photos/src/main/assets/README.md+++ b/photos/src/main/assets/README.md@@ -51,8 +51,10 @@ Two nodes are rewritten during conversion rather than needing a shader — see convolution kernel, and the `BatchNormalization` after it is folded into that layer's weight and bias. -The ncnn `.param`/`.bin` files are still present and still what `FaceRecognizer.kt`-loads; they go once the Kotlin moves across to `:library:ml`.+The ncnn `.param`/`.bin` files these replace (`scrfd_500m_kps-opt2.*`,+`w600k_mbf.ncnn.*`, 7.9 MB together) are gone. `libncnn_android.so` is still in this+APK, but only because `:library:ocr` pulls it in for PP-OCRv5 text recognition — nothing+in `:photos` itself uses ncnn any more.  ## `clip/` 
photos/src/main/assets/scrfd_500m_kps-opt2.bin
diff --git a/photos/src/main/assets/scrfd_500m_kps-opt2.bin b/photos/src/main/assets/scrfd_500m_kps-opt2.bindeleted file mode 100644index 198c572733..0000000000Binary files a/photos/src/main/assets/scrfd_500m_kps-opt2.bin and /dev/null differ
photos/src/main/assets/scrfd_500m_kps-opt2.param
diff --git a/photos/src/main/assets/scrfd_500m_kps-opt2.param b/photos/src/main/assets/scrfd_500m_kps-opt2.paramdeleted file mode 100644index 5dc0e1ea7d..0000000000--- a/photos/src/main/assets/scrfd_500m_kps-opt2.param+++ /dev/null@@ -1,81 +0,0 @@-7767517-79 91-Input                    input.1                  0 1 input.1-Convolution              Conv_0                   1 1 input.1 288 0=16 1=3 3=2 4=1 5=1 6=432 9=1-ConvolutionDepthWise     Conv_3                   1 1 288 291 0=16 1=3 4=1 5=1 6=144 7=16 9=1-Convolution              Conv_6                   1 1 291 294 0=16 1=1 5=1 6=256 9=1-ConvolutionDepthWise     Conv_9                   1 1 294 297 0=16 1=3 3=2 4=1 5=1 6=144 7=16 9=1-Convolution              Conv_12                  1 1 297 300 0=40 1=1 5=1 6=640 9=1-ConvolutionDepthWise     Conv_15                  1 1 300 303 0=40 1=3 4=1 5=1 6=360 7=40 9=1-Convolution              Conv_18                  1 1 303 306 0=40 1=1 5=1 6=1600 9=1-ConvolutionDepthWise     Conv_21                  1 1 306 309 0=40 1=3 3=2 4=1 5=1 6=360 7=40 9=1-Convolution              Conv_24                  1 1 309 312 0=72 1=1 5=1 6=2880 9=1-ConvolutionDepthWise     Conv_27                  1 1 312 315 0=72 1=3 4=1 5=1 6=648 7=72 9=1-Convolution              Conv_30                  1 1 315 318 0=72 1=1 5=1 6=5184 9=1-ConvolutionDepthWise     Conv_33                  1 1 318 321 0=72 1=3 4=1 5=1 6=648 7=72 9=1-Convolution              Conv_36                  1 1 321 324 0=72 1=1 5=1 6=5184 9=1-Split                    splitncnn_0              1 2 324 324_splitncnn_0 324_splitncnn_1-ConvolutionDepthWise     Conv_39                  1 1 324_splitncnn_1 327 0=72 1=3 3=2 4=1 5=1 6=648 7=72 9=1-Convolution              Conv_42                  1 1 327 330 0=152 1=1 5=1 6=10944 9=1-ConvolutionDepthWise     Conv_45                  1 1 330 333 0=152 1=3 4=1 5=1 6=1368 7=152 9=1-Convolution              Conv_48                  1 1 333 336 0=152 1=1 5=1 6=23104 9=1-Split                    splitncnn_1              1 2 336 336_splitncnn_0 336_splitncnn_1-ConvolutionDepthWise     Conv_51                  1 1 336_splitncnn_1 339 0=152 1=3 3=2 4=1 5=1 6=1368 7=152 9=1-Convolution              Conv_54                  1 1 339 342 0=288 1=1 5=1 6=43776 9=1-ConvolutionDepthWise     Conv_57                  1 1 342 345 0=288 1=3 4=1 5=1 6=2592 7=288 9=1-Convolution              Conv_60                  1 1 345 348 0=288 1=1 5=1 6=82944 9=1-ConvolutionDepthWise     Conv_63                  1 1 348 351 0=288 1=3 4=1 5=1 6=2592 7=288 9=1-Convolution              Conv_66                  1 1 351 354 0=288 1=1 5=1 6=82944 9=1-ConvolutionDepthWise     Conv_69                  1 1 354 357 0=288 1=3 4=1 5=1 6=2592 7=288 9=1-Convolution              Conv_72                  1 1 357 360 0=288 1=1 5=1 6=82944 9=1-ConvolutionDepthWise     Conv_75                  1 1 360 363 0=288 1=3 4=1 5=1 6=2592 7=288 9=1-Convolution              Conv_78                  1 1 363 366 0=288 1=1 5=1 6=82944 9=1-ConvolutionDepthWise     Conv_81                  1 1 366 369 0=288 1=3 4=1 5=1 6=2592 7=288 9=1-Convolution              Conv_84                  1 1 369 372 0=288 1=1 5=1 6=82944 9=1-Convolution              Conv_87                  1 1 324_splitncnn_0 373 0=16 1=1 5=1 6=1152-Convolution              Conv_88                  1 1 336_splitncnn_0 374 0=16 1=1 5=1 6=2432-Convolution              Conv_89                  1 1 372 375 0=16 1=1 5=1 6=4608-Split                    splitncnn_2              1 2 375 375_splitncnn_0 375_splitncnn_1-Interp                   Resize_108               1 1 375_splitncnn_1 394 0=1 1=2.000000e+00 2=2.000000e+00-BinaryOp                 Add_109                  2 1 374 394 395-Split                    splitncnn_3              1 2 395 395_splitncnn_0 395_splitncnn_1-Interp                   Resize_128               1 1 395_splitncnn_1 414 0=1 1=2.000000e+00 2=2.000000e+00-BinaryOp                 Add_129                  2 1 373 414 415-Convolution              Conv_130                 1 1 415 416 0=16 1=3 4=1 5=1 6=2304-Split                    splitncnn_4              1 2 416 416_splitncnn_0 416_splitncnn_1-Convolution              Conv_131                 1 1 395_splitncnn_0 417 0=16 1=3 4=1 5=1 6=2304-Convolution              Conv_132                 1 1 375_splitncnn_0 418 0=16 1=3 4=1 5=1 6=2304-Convolution              Conv_133                 1 1 416_splitncnn_1 419 0=16 1=3 3=2 4=1 5=1 6=2304-BinaryOp                 Add_134                  2 1 417 419 420-Split                    splitncnn_5              1 2 420 420_splitncnn_0 420_splitncnn_1-Convolution              Conv_135                 1 1 420_splitncnn_1 421 0=16 1=3 3=2 4=1 5=1 6=2304-BinaryOp                 Add_136                  2 1 418 421 422-Convolution              Conv_137                 1 1 420_splitncnn_0 423 0=16 1=3 4=1 5=1 6=2304-Convolution              Conv_138                 1 1 422 424 0=16 1=3 4=1 5=1 6=2304-ConvolutionDepthWise     Conv_139                 1 1 416_splitncnn_0 427 0=16 1=3 4=1 5=1 6=144 7=16 9=1-Convolution              Conv_142                 1 1 427 430 0=64 1=1 5=1 6=1024 9=1-ConvolutionDepthWise     Conv_145                 1 1 430 433 0=64 1=3 4=1 5=1 6=576 7=64 9=1-Convolution              Conv_148                 1 1 433 436 0=64 1=1 5=1 6=4096 9=1-Split                    splitncnn_6              1 3 436 436_splitncnn_0 436_splitncnn_1 436_splitncnn_2-Convolution              Conv_151                 1 1 436_splitncnn_2 442 0=2 1=3 4=1 5=1 6=1152-Convolution              Conv_152                 1 1 436_splitncnn_1 bbox_8 0=8 1=3 4=1 5=1 6=4608-Convolution              Conv_153                 1 1 436_splitncnn_0 kps_8 0=20 1=3 4=1 5=1 6=11520-Sigmoid                  Sigmoid_157              1 1 442 score_8-ConvolutionDepthWise     Conv_164                 1 1 423 452 0=16 1=3 4=1 5=1 6=144 7=16 9=1-Convolution              Conv_167                 1 1 452 455 0=64 1=1 5=1 6=1024 9=1-ConvolutionDepthWise     Conv_170                 1 1 455 458 0=64 1=3 4=1 5=1 6=576 7=64 9=1-Convolution              Conv_173                 1 1 458 461 0=64 1=1 5=1 6=4096 9=1-Split                    splitncnn_7              1 3 461 461_splitncnn_0 461_splitncnn_1 461_splitncnn_2-Convolution              Conv_176                 1 1 461_splitncnn_2 467 0=2 1=3 4=1 5=1 6=1152-Convolution              Conv_177                 1 1 461_splitncnn_1 bbox_16 0=8 1=3 4=1 5=1 6=4608-Convolution              Conv_178                 1 1 461_splitncnn_0 kps_16 0=20 1=3 4=1 5=1 6=11520-Sigmoid                  Sigmoid_182              1 1 467 score_16-ConvolutionDepthWise     Conv_189                 1 1 424 477 0=16 1=3 4=1 5=1 6=144 7=16 9=1-Convolution              Conv_192                 1 1 477 480 0=64 1=1 5=1 6=1024 9=1-ConvolutionDepthWise     Conv_195                 1 1 480 483 0=64 1=3 4=1 5=1 6=576 7=64 9=1-Convolution              Conv_198                 1 1 483 486 0=64 1=1 5=1 6=4096 9=1-Split                    splitncnn_8              1 3 486 486_splitncnn_0 486_splitncnn_1 486_splitncnn_2-Convolution              Conv_201                 1 1 486_splitncnn_2 492 0=2 1=3 4=1 5=1 6=1152-Convolution              Conv_202                 1 1 486_splitncnn_1 bbox_32 0=8 1=3 4=1 5=1 6=4608-Convolution              Conv_203                 1 1 486_splitncnn_0 kps_32 0=20 1=3 4=1 5=1 6=11520-Sigmoid                  Sigmoid_207              1 1 492 score_32
photos/src/main/assets/w600k_mbf.ncnn.bin
diff --git a/photos/src/main/assets/w600k_mbf.ncnn.bin b/photos/src/main/assets/w600k_mbf.ncnn.bindeleted file mode 100644index 7f3d4b5ce5..0000000000Binary files a/photos/src/main/assets/w600k_mbf.ncnn.bin and /dev/null differ
photos/src/main/assets/w600k_mbf.ncnn.param
diff --git a/photos/src/main/assets/w600k_mbf.ncnn.param b/photos/src/main/assets/w600k_mbf.ncnn.paramdeleted file mode 100644index 7e3135a25d..0000000000--- a/photos/src/main/assets/w600k_mbf.ncnn.param+++ /dev/null@@ -1,112 +0,0 @@-7767517-110 122-Input                    in0                      0 1 in0-Convolution              conv_0                   1 1 in0 1 0=128 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=3456-PReLU                    prelu_34                 1 1 1 2 0=128-ConvolutionDepthWise     convdw_69                1 1 2 3 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=64-PReLU                    prelu_35                 1 1 3 4 0=128-Convolution              conv_1                   1 1 4 5 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-PReLU                    prelu_36                 1 1 5 6 0=128-ConvolutionDepthWise     convdw_70                1 1 6 7 0=128 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=1152 7=128-PReLU                    prelu_37                 1 1 7 8 0=128-Convolution              conv_2                   1 1 8 9 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-Split                    splitncnn_0              1 2 9 10 11-Convolution              conv_3                   1 1 11 12 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-PReLU                    prelu_38                 1 1 12 13 0=128-ConvolutionDepthWise     convdw_71                1 1 13 14 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=1152 7=128-PReLU                    prelu_39                 1 1 14 15 0=128-Convolution              conv_4                   1 1 15 16 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-BinaryOp                 add_0                    2 1 10 16 17 0=0-Split                    splitncnn_1              1 2 17 18 19-Convolution              conv_5                   1 1 19 20 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-PReLU                    prelu_40                 1 1 20 21 0=128-ConvolutionDepthWise     convdw_72                1 1 21 22 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=1152 7=128-PReLU                    prelu_41                 1 1 22 23 0=128-Convolution              conv_6                   1 1 23 24 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-BinaryOp                 add_1                    2 1 18 24 25 0=0-Split                    splitncnn_2              1 2 25 26 27-Convolution              conv_7                   1 1 27 28 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-PReLU                    prelu_42                 1 1 28 29 0=128-ConvolutionDepthWise     convdw_73                1 1 29 30 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=1152 7=128-PReLU                    prelu_43                 1 1 30 31 0=128-Convolution              conv_8                   1 1 31 32 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-BinaryOp                 add_2                    2 1 26 32 33 0=0-Split                    splitncnn_3              1 2 33 34 35-Convolution              conv_9                   1 1 35 36 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-PReLU                    prelu_44                 1 1 36 37 0=128-ConvolutionDepthWise     convdw_74                1 1 37 38 0=128 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=1152 7=128-PReLU                    prelu_45                 1 1 38 39 0=128-Convolution              conv_10                  1 1 39 40 0=128 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=16384-BinaryOp                 add_3                    2 1 34 40 41 0=0-Convolution              conv_11                  1 1 41 42 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=32768-PReLU                    prelu_46                 1 1 42 43 0=256-ConvolutionDepthWise     convdw_75                1 1 43 44 0=256 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=2304 7=256-PReLU                    prelu_47                 1 1 44 45 0=256-Convolution              conv_12                  1 1 45 46 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-Split                    splitncnn_4              1 2 46 47 48-Convolution              conv_13                  1 1 48 49 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_48                 1 1 49 50 0=256-ConvolutionDepthWise     convdw_76                1 1 50 51 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_49                 1 1 51 52 0=256-Convolution              conv_14                  1 1 52 53 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_4                    2 1 47 53 54 0=0-Split                    splitncnn_5              1 2 54 55 56-Convolution              conv_15                  1 1 56 57 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_50                 1 1 57 58 0=256-ConvolutionDepthWise     convdw_77                1 1 58 59 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_51                 1 1 59 60 0=256-Convolution              conv_16                  1 1 60 61 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_5                    2 1 55 61 62 0=0-Split                    splitncnn_6              1 2 62 63 64-Convolution              conv_17                  1 1 64 65 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_52                 1 1 65 66 0=256-ConvolutionDepthWise     convdw_78                1 1 66 67 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_53                 1 1 67 68 0=256-Convolution              conv_18                  1 1 68 69 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_6                    2 1 63 69 70 0=0-Split                    splitncnn_7              1 2 70 71 72-Convolution              conv_19                  1 1 72 73 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_54                 1 1 73 74 0=256-ConvolutionDepthWise     convdw_79                1 1 74 75 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_55                 1 1 75 76 0=256-Convolution              conv_20                  1 1 76 77 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_7                    2 1 71 77 78 0=0-Split                    splitncnn_8              1 2 78 79 80-Convolution              conv_21                  1 1 80 81 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_56                 1 1 81 82 0=256-ConvolutionDepthWise     convdw_80                1 1 82 83 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_57                 1 1 83 84 0=256-Convolution              conv_22                  1 1 84 85 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_8                    2 1 79 85 86 0=0-Split                    splitncnn_9              1 2 86 87 88-Convolution              conv_23                  1 1 88 89 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_58                 1 1 89 90 0=256-ConvolutionDepthWise     convdw_81                1 1 90 91 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_59                 1 1 91 92 0=256-Convolution              conv_24                  1 1 92 93 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_9                    2 1 87 93 94 0=0-Convolution              conv_25                  1 1 94 95 0=512 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=131072-PReLU                    prelu_60                 1 1 95 96 0=512-ConvolutionDepthWise     convdw_82                1 1 96 97 0=512 1=3 11=3 12=1 13=2 14=1 2=1 3=2 4=1 5=1 6=4608 7=512-PReLU                    prelu_61                 1 1 97 98 0=512-Convolution              conv_26                  1 1 98 99 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=131072-Split                    splitncnn_10             1 2 99 100 101-Convolution              conv_27                  1 1 101 102 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_62                 1 1 102 103 0=256-ConvolutionDepthWise     convdw_83                1 1 103 104 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_63                 1 1 104 105 0=256-Convolution              conv_28                  1 1 105 106 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_10                   2 1 100 106 107 0=0-Split                    splitncnn_11             1 2 107 108 109-Convolution              conv_29                  1 1 109 110 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-PReLU                    prelu_64                 1 1 110 111 0=256-ConvolutionDepthWise     convdw_84                1 1 111 112 0=256 1=3 11=3 12=1 13=1 14=1 2=1 3=1 4=1 5=1 6=2304 7=256-PReLU                    prelu_65                 1 1 112 113 0=256-Convolution              conv_30                  1 1 113 114 0=256 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=65536-BinaryOp                 add_11                   2 1 108 114 115 0=0-Convolution              conv_31                  1 1 115 116 0=512 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=131072-PReLU                    prelu_66                 1 1 116 117 0=512-Convolution              conv_32                  1 1 117 118 0=64 1=1 11=1 12=1 13=1 14=0 2=1 3=1 4=0 5=1 6=32768-PReLU                    prelu_67                 1 1 118 119 0=64-Flatten                  flatten_68               1 1 119 120-InnerProduct             linear_33                1 1 120 out0 0=512 1=1 2=1605632
photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.ktindex 547a5a4c1f..197f62212d 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt@@ -28,6 +28,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue@@ -69,7 +70,13 @@ fun PeoplePage(     val indexing by galleryViewModel.faceIndexing.collectAsState()     val scanned by galleryViewModel.faceScannedCount.collectAsState()     val target by galleryViewModel.indexTargetCount.collectAsState()-    val modelsAvailable = remember { FaceRecognizer.modelsAvailable(context) }+    // Off the main thread: `modelsAvailable` brings the models up, and on `:library:ml`+    // that means parsing two `.vkml` blobs and uploading 7.9 MB to the GPU. Doing it in a+    // bare `remember { }` blocked the first composition of this screen for as long as+    // that took.+    val modelsAvailable by produceState(initialValue = false, context) {+        value = withContext(Dispatchers.IO) { FaceRecognizer.modelsAvailable(context) }+    }      // The contact picker's result carries only the picked contact, with nothing to     // say which cluster was being named, so the cluster id is parked here across
photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.ktindex 9ba7dceb0e..a677eafbba 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt@@ -9,30 +9,32 @@ import android.graphics.Rect import android.util.Log import androidx.core.graphics.createBitmap import androidx.core.graphics.scale-import com.vayunmathur.ncnn.FaceDetector-import com.vayunmathur.ncnn.FaceEmbedder+import com.vayunmathur.library.ml.DetectedFaceBox+import com.vayunmathur.library.ml.FaceDetector+import com.vayunmathur.library.ml.FaceEmbedder import java.nio.ByteBuffer import java.nio.ByteOrder import kotlin.math.sqrt  /**- * On-device face detection + recognition. Everything runs locally on **ncnn**- * (CPU-only, BSD-3 — no ONNX Runtime, no Google Play Services, F-Droid clean).+ * On-device face detection + recognition. Everything runs locally on `:library:ml`'s+ * Vulkan compute runtime — no ONNX Runtime, no Google Play Services, F-Droid clean.  *  * Pipeline:- *  1. Detection — **SCRFD** ([FaceDetector], nihui's `scrfd_500m_kps`) finds- *     faces and returns a bounding box + 5 landmarks (the two eyes are used for- *     alignment). Anchor decode + NMS run natively.+ *  1. Detection — **SCRFD 500M** ([FaceDetector]) finds faces and returns a bounding box+ *     + 5 landmarks (the two eyes are used for alignment). Letterboxing, anchor decode+ *     and NMS all run natively.  *  2. Alignment — the two eye landmarks drive a similarity transform (rotate +  *     uniform scale + translate) onto a canonical [INPUT_SIZE]² crop.  *  3. Embedding — **MobileFaceNet** ([FaceEmbedder], insightface `w600k_mbf`,  *     ArcFace-trained) produces a 512-d embedding from the aligned crop. Pixels- *     are normalised (px - 127.5)/127.5 (handled natively). The result is- *     L2-normalised here.+ *     are normalised (px - 127.5)/127.5 natively. The result is L2-normalised here.  *  4. Matching — cosine similarity clusters faces of the same person  *     (see [CLUSTER_THRESHOLD]).  *- * The models live inside the `ncnn-android` AAR, so they are always available.+ * The models ship as `.vkml` assets in this app. They are **GPU-only**: on a device+ * without Vulkan fp16 compute [modelsAvailable] is false and people clustering turns off,+ * rather than falling back to a second implementation.  */ object FaceRecognizer { @@ -44,9 +46,12 @@ object FaceRecognizer {      * worker compares it against a stored value and, on mismatch, clears existing      * clusters and re-scans so photos are re-grouped with the new embeddings.      * (v5 = BlazeFace + EdgeFace on ONNX Runtime; v6 = SCRFD detector +-     * MobileFaceNet embedder on ncnn — different embeddings, so a re-scan runs.)+     * MobileFaceNet embedder on ncnn; v7 = the same two models on `:library:ml`'s+     * Vulkan runtime — fp16 weights, fp32 accumulation and our own letterbox, so the+     * embeddings are close to v6's but not identical, and mixing the two spaces in one+     * index would cluster badly.)      */-    const val EMBEDDER_VERSION = 6+    const val EMBEDDER_VERSION = 7      /**      * Minimum cosine similarity for a face to join an existing cluster. ArcFace@@ -78,12 +83,11 @@ object FaceRecognizer {         val bottom: Float,     ) -    private val lock = Any()     @Volatile private var detector: FaceDetector? = null     @Volatile private var embedder: FaceEmbedder? = null     @Volatile private var initFailed = false -    /** True if the native models could be loaded (they ship inside the AAR). */+    /** True if the native models could be loaded and the device has fp16 compute. */     fun modelsAvailable(context: Context): Boolean = ensureInit(context)      @Synchronized@@ -92,8 +96,19 @@ object FaceRecognizer {         if (initFailed) return false         return try {             val app = context.applicationContext-            detector = FaceDetector(app, "scrfd_500m_kps-opt2.param", "scrfd_500m_kps-opt2.bin")-            embedder = FaceEmbedder(app, "w600k_mbf.ncnn.param", "w600k_mbf.ncnn.bin")+            val newDetector = FaceDetector(app)+            val newEmbedder = FaceEmbedder(app)+            // GPU-only: a device without Vulkan fp16 compute reports unavailable rather+            // than throwing, so the constructors succeeding is not enough.+            if (!newDetector.isAvailable || !newEmbedder.isAvailable) {+                Log.w(TAG, "no Vulkan fp16 compute; face clustering is off")+                newDetector.close()+                newEmbedder.close()+                initFailed = true+                return false+            }+            detector = newDetector+            embedder = newEmbedder             true         } catch (e: Throwable) {             Log.e(TAG, "Face models unavailable", e)@@ -128,16 +143,20 @@ object FaceRecognizer {             val rect = faceRect(f, argb.width, argb.height) ?: continue             val aligned = alignFace(argb, f, rect) ?: continue             try {-                val embedding = l2Normalize(emb.embed(aligned))+                // Null means the inference failed on this crop; the others may still be+                // fine, so skip this face rather than abandoning the photo.+                val raw = emb.embed(aligned)+                if (raw == null) {+                    Log.e(TAG, "Face embedding failed")+                    continue+                }                 out += DetectedFace(-                    embedding = embedding,+                    embedding = l2Normalize(raw),                     left = f.left,                     top = f.top,                     right = f.right,                     bottom = f.bottom,                 )-            } catch (e: Exception) {-                Log.e(TAG, "Face embedding failed", e)             } finally {                 aligned.recycle()             }@@ -151,7 +170,7 @@ object FaceRecognizer {      * in an [INPUT_SIZE] crop (similarity transform). Falls back to a plain box      * crop when landmarks are unusable.      */-    private fun alignFace(src: Bitmap, f: FaceDetector.Face, box: Rect): Bitmap? {+    private fun alignFace(src: Bitmap, f: DetectedFaceBox, box: Rect): Bitmap? {         val hasEyes = f.leftEyeX != 0f || f.leftEyeY != 0f || f.rightEyeX != 0f || f.rightEyeY != 0f         if (hasEyes) {             // Sort eyes by x so the left-most maps to the left canonical eye.@@ -182,7 +201,7 @@ object FaceRecognizer {     }      /** Expand the normalised detector box by a small margin and clamp to pixels. */-    private fun faceRect(f: FaceDetector.Face, w: Int, h: Int): Rect? {+    private fun faceRect(f: DetectedFaceBox, w: Int, h: Int): Rect? {         val bw = (f.right - f.left) * w         val bh = (f.bottom - f.top) * h         val marginX = bw * 0.15f