photos: run TinyCLIP on the in-house runtime
- Commit
b5fbe0554ff4640b14e69221e25424dd4dcafd73- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 05:43 UTC (3 months ago)
- Parents
6fe16ae
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.ktnew file mode 100644index 0000000000..ef4520e0b1--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt@@ -0,0 +1,162 @@+package com.vayunmathur.library.ml++import android.content.res.AssetManager+import android.os.ParcelFileDescriptor+import android.util.Log++/**+ * On-device image and text embedding in a shared 512-d space: TinyCLIP on the Vulkan compute+ * runtime.+ *+ * Two transformers of width 256 with 4 heads of 64 — a 10-layer vision tower over 16x16 patches of a+ * 224x224 image, and a 3-layer causal text tower over up to 77 tokens — at 23.4 million parameters.+ * See `library/ml/src/main/rust/src/nets/tinyclip.rs`.+ *+ * # One bundled asset, 22.6 MiB+ *+ * `tinyclip.maml` ships inside the APK, so this has an [inAssets] and no download. Everything but+ * the layer norms, the biases, the class token and the two position tables is int8, quantised per+ * output channel from the fp32 export; the worst per-tensor correlation against fp32 is 0.99986.+ *+ * It replaces `onnxruntime-android` running a 24 MB int8 ONNX export of the same model, and is+ * *closer* to the fp32 reference than that was — 0.9994 against 0.9829 on a text query, because the+ * export quantised the 49,408-row token table per tensor with a zero point. The APK loses 10.5 MB of+ * arm64 `.so`, not weights.+ *+ * An asset must be stored **uncompressed** for this to work at all: `AssetManager.openFd` throws for+ * a deflated entry. That is what `noCompress += "maml"` in `photos/build.gradle.kts` is for, and it+ * costs nothing on download size since int8 weights barely compress.+ *+ * # The two towers share one net+ *+ * They share no weights, but they do share the file, so both run through one handle and native+ * re-records between them. Switching costs a `device_wait_idle`; an indexing run is [imageEmbedding]+ * throughout and pays for one.+ *+ * # Neither vector is normalised+ *+ * [imageEmbedding] and [textEmbedding] return the raw projection. The caller normalises — in+ * `:photos` that is `ClipEmbedder.l2Normalize`, so the stored BLOB format is decided in one place.+ *+ * # Availability+ *+ * Construction never throws. [isAvailable] is false when `libmodelrunner.so` is missing for this+ * ABI, when the asset is absent, compressed or malformed, or when the device cannot give us a Vulkan+ * device with fp16 compute — and then both embedding calls return null.+ *+ * # Threading+ *+ * Not thread-safe. A text query re-records the network, so two concurrent calls would interleave+ * recordings of the same command buffer. A caller must hold a lock across the embedding calls and+ * [close].+ */+class ClipHandle private constructor(private val source: String) : AutoCloseable {+ private var handle: Long = 0L++ /** True if the graph came up and is the file this runtime was built against. */+ val isAvailable: Boolean get() = handle != 0L++ /**+ * The 512-d embedding of an already-preprocessed image, or null on failure.+ *+ * [pixels] is `3 * 224 * 224` floats, NCHW and RGB, resized to the shortest edge, centre-cropped+ * and normalised by CLIP's mean and standard deviation. Not L2-normalised on return.+ */+ fun imageEmbedding(pixels: FloatArray): FloatArray? {+ if (handle == 0L) return null+ return MlNative.tinyclipImage(handle, pixels)+ }++ /**+ * The 512-d embedding of a tokenised query, in the same space as [imageEmbedding], or null.+ *+ * [ids] must end at `<|endoftext|>` with the tokenizer's padding trimmed off, because that is+ * the position CLIP pools. Not L2-normalised on return.+ */+ fun textEmbedding(ids: IntArray): FloatArray? {+ if (handle == 0L) return null+ if (ids.isEmpty()) return null+ return MlNative.tinyclipText(handle, ids)+ }++ /** Free the network and close the weights file. Idempotent. */+ override fun close() {+ val live = handle+ handle = 0L+ if (live != 0L) MlNative.destroyTinyclip(live)+ }++ override fun toString(): String = "TinyCLIP from $source"++ companion object {+ private const val TAG = "ClipHandle"++ /** The embedding dimension both towers project into. */+ const val DIMENSION = 512++ /** The square RGB input side the vision tower expects. */+ const val IMAGE_SIZE = 224++ /** The longest tokenised query, including both special tokens. */+ const val CONTEXT_LENGTH = 77++ /** The one graph. Native checks its graph id, so a wrong file fails at load. */+ const val GRAPH = "clip/tinyclip.maml"++ /**+ * The model from the APK's assets, which is the only place it lives.+ *+ * No `inDirectory` counterpart, unlike [Small100Handle]: at 22.6 MiB this is bundled, so+ * there is no download directory to look in.+ */+ fun inAssets(assets: AssetManager, path: String = GRAPH): ClipHandle {+ val instance = ClipHandle("the APK's $path")+ instance.handle = if (!MlNative.isAvailable) {+ 0L+ } else {+ try {+ create(assets, path)+ } catch (e: Throwable) {+ Log.e(TAG, "cannot open $path", e)+ 0L+ }+ }+ return instance+ }++ /**+ * Open the asset and hand the descriptor over.+ *+ * `use` rather than a bare `close`, and it is load-bearing in both directions — the same+ * argument [SupertonicSynthesizer]'s asset path makes. On the happy path the descriptor has+ * already been detached and `AssetFileDescriptor.close` only releases the wrapper; if+ * `detachFd` throws instead, the close is the real one, and a leaked descriptor onto the APK+ * would last the life of the process.+ *+ * The inner `finally` covers the remaining window: after the descriptor has been given up+ * but before native has adopted it.+ */+ private fun create(assets: AssetManager, path: String): Long =+ assets.openFd(path).use { afd ->+ val fd = afd.parcelFileDescriptor.detachFd()+ var handed = false+ try {+ val handle = MlNative.createTinyclip(fd, afd.startOffset, afd.length)+ handed = true+ handle+ } finally {+ if (!handed) closeFd(fd)+ }+ }++ /**+ * Close a bare descriptor.+ *+ * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from Kotlin.+ * Failures are swallowed because the caller is already on an error path.+ */+ private fun closeFd(fd: Int) {+ runCatching { ParcelFileDescriptor.adoptFd(fd).close() }+ }+ }+}
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 8225dc20d1..d3c0fdc45c 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@@ -191,6 +191,61 @@ internal object MlNative { */ external fun destroySmall100(handle: Long) + /**+ * Bring up TinyCLIP from its one `.maml`. Returns 0 on failure.+ *+ * One graph, not two, for a different reason from [createSmall100]: the image and text towers+ * share **no weights at all**, but they do share a 22.6 MiB file, so two handles would upload it+ * twice. Native selects between them by re-recording one net, which costs a `device_wait_idle` —+ * and an indexing run is the image tower throughout, so it pays for exactly one.+ *+ * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and [length]+ * are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather than a file of+ * its own. `AssetManager.openFd` throws for a deflated entry, which is what `noCompress +=+ * "maml"` in `photos/build.gradle.kts` is for.+ *+ * Native keeps the descriptor open for the life of the handle, because the 12.6 MiB token+ * embedding is gathered a row at a time on the host rather than read from the upload.+ *+ * **The descriptor must be detached.** Native takes ownership and closes it, on the failure+ * paths as much as the successful one, so a caller must not close it itself.+ *+ * Freed by [destroyTinyclip], not [destroy], [destroyOcr], [destroySupertonic] or+ * [destroySmall100].+ */+ external fun createTinyclip(fd: Int, offset: Long, length: Long): Long++ /**+ * The 512-d image embedding for [pixels], or null on failure.+ *+ * [pixels] is `3 * 224 * 224` floats, NCHW and RGB, already resized to the shortest edge,+ * centre-cropped and normalised by CLIP's mean and standard deviation. That work stays in+ * Kotlin — see `ClipEmbedder.preprocess` — because it is bitmap handling the platform does+ * better.+ *+ * **Not L2-normalised.** `ClipEmbedder.l2Normalize` does that for both towers, so the stored+ * vector format is decided in one place.+ */+ external fun tinyclipImage(handle: Long, pixels: FloatArray): FloatArray?++ /**+ * The 512-d text embedding for [ids], or null on failure.+ *+ * [ids] must be the query's tokens **up to and including `<|endoftext|>`**, with the tokenizer's+ * padding trimmed off. CLIP pools at the end-of-text position, so the trim is what decides which+ * position is pooled — and because the tower is causal, the trimmed sequence gives the identical+ * vector to the padded 77 for a fraction of the work.+ *+ * Not L2-normalised, as [tinyclipImage] is not.+ */+ external fun tinyclipText(handle: Long, ids: IntArray): FloatArray?++ /**+ * Free TinyCLIP's network and its open weights file.+ * Exactly once per non-zero handle from [createTinyclip].+ */+ external fun destroyTinyclip(handle: Long)+ /** * Detect faces in [pixels] and return them flattened, nine floats per face. *
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 65280e8a53..692faee29b 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -35,7 +35,7 @@ use jni::JNIEnv; use crate::nets::{ mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, small100, supertonic_duration,- supertonic_sampler, supertonic_text, supertonic_vocoder, u2netp, Plan,+ supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, Plan, }; use crate::post::ctc::Dictionary; use crate::post::nms::{self, Face, Maps};@@ -1382,6 +1382,244 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySm drop(unsafe { Box::from_raw(handle as *mut Small100Handle) }); } +/// TinyCLIP, as `:photos` holds it. Handed to Kotlin as an opaque `jlong`.+///+/// # One net, two plans+///+/// [`Reshaped`] keyed by [`tinyclip::Mode`], as [`Small100Handle`] is: the two towers share no+/// weights but they do share a 22.6 MiB file, so two `Net`s would upload it twice. Switching towers+/// is a `device_wait_idle` and a re-record — which is why an indexing run, which is `Mode::Image`+/// throughout, pays for exactly one.+///+/// # The weights file stays open+///+/// [`tinyclip::embed_positions`] gathers a 1 KB embedding row per token out of the 12.6 MiB token+/// table on the host, so the [`Streamed`] is retained for the same reason SMaLL-100's is.+struct TinyclipHandle {+ net: Reshaped<tinyclip::Mode>,+ weights: Streamed,+}++fn tinyclip_plan(offsets: &Offsets, mode: tinyclip::Mode) -> Result<Plan, String> {+ tinyclip::build(offsets, mode)+}++/// One column of a `[PROJECTION, 1, len]` output, which is the position both towers pool.+///+/// A position is a *column* in this runtime's layout, so it is strided rather than contiguous —+/// which is why the plan projects every position and this picks one. See `nets::tinyclip`.+fn tinyclip_column(out: &[f32], at: usize, len: usize) -> Result<Vec<f32>, String> {+ let width = tinyclip::PROJECTION as usize;+ if len == 0 || out.len() != width * len {+ return Err(format!("{} values is not {width} x {len}", out.len()));+ }+ (0..width)+ .map(|channel| {+ out.get(channel * len + at).copied().ok_or_else(|| format!("column {at} of {len}"))+ })+ .collect()+}++/// Bring up TinyCLIP from its one `.maml`. Returns 0 on failure.+///+/// The descriptor is an `AssetFileDescriptor`'s, so it carries an offset and a length: the file is+/// a *range of the APK* rather than a file of its own, which is also why the asset has to be stored+/// uncompressed.+///+/// # Safety+///+/// Called only by the JVM, with a descriptor nothing else holds.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createTinyclip<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ fd: jint,+ offset: jlong,+ length: jlong,+) -> jlong {+ // The descriptor first, and adopted into an owning `File` before anything else may fail, as+ // `createSmall100` does: the caller detached it, so a path that returns without wrapping it+ // leaks it for the life of the process.+ if fd < 0 {+ log(&format!("tinyclip is unavailable: descriptor {fd} is not open"));+ return 0;+ }+ // SAFETY: the caller detached the descriptor, so nothing else owns it, and `File` closes it on+ // drop — including on every failure path below.+ let file = unsafe { File::from_raw_fd(fd) };+ match build_tinyclip(file, offset, length) {+ Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+ Err(e) => {+ log(&format!("tinyclip is unavailable: {e}"));+ 0+ }+ }+}++fn build_tinyclip(file: File, offset: jlong, length: jlong) -> Result<TinyclipHandle, String> {+ let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {+ (Ok(at), Ok(len)) => (at, len),+ _ => return Err(format!("the graph spans {offset}+{length}")),+ };+ let weights = Streamed::open(file, at, len, graph::TINYCLIP)?;+ if weights.len() != tinyclip::TENSORS {+ return Err(format!("a file of {} tensors, not {}", weights.len(), tinyclip::TENSORS));+ }+ // Recorded on the image tower, which is what an indexing run uses throughout. A text query+ // rebuilds once and rebuilds back on the next image.+ let net = Reshaped::streamed(+ context::shared()?,+ weights.offsets(),+ &weights,+ tinyclip::Mode::Image,+ tinyclip_plan,+ )?;+ Ok(TinyclipHandle { net, weights })+}++/// The 512-d image embedding for `pixels`, or null on failure.+///+/// `pixels` is `[3, 224, 224]` already normalised by CLIP's mean and standard deviation — the+/// resize, the centre crop and the normalisation are `ClipEmbedder.preprocess`'s, because they are+/// bitmap work the platform does better and they are what the tokenizer's counterpart would be.+///+/// The vector is **not** L2-normalised here. `ClipEmbedder.l2Normalize` does it, on both towers'+/// output and on nothing else, so the stored BLOB format is decided in one place.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createTinyclip` that has not been destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_tinyclipImage<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ pixels: JFloatArray<'l>,+) -> jfloatArray {+ let null = std::ptr::null_mut();+ if handle == 0 {+ return null;+ }+ // SAFETY: the caller guarantees the handle came from `createTinyclip` and is still live. It is+ // `&mut` because switching towers re-records the net, and Kotlin serialises calls on one handle.+ let handle = unsafe { &mut *(handle as *mut TinyclipHandle) };+ let embedded = match read_float_array(&mut env, &pixels) {+ Ok(values) => run_tinyclip_image(handle, &values),+ Err(e) => Err(e),+ };+ match embedded.and_then(|values| new_float_array(&mut env, &values)) {+ Ok(array) => array,+ Err(e) => {+ log(&format!("tinyclip's image tower failed: {e}"));+ null+ }+ }+}++fn run_tinyclip_image(handle: &mut TinyclipHandle, pixels: &[f32]) -> Result<Vec<f32>, String> {+ let side = tinyclip::IMAGE_SIZE as usize;+ let expected = 3 * side * side;+ if pixels.len() != expected {+ return Err(format!("{} pixel values, not {expected}", pixels.len()));+ }+ let net = handle.net.at(tinyclip::Mode::Image)?;+ let out = one_output(net.infer_raw_many(&[pixels])?)?;+ // The class token, position 0. Pooling the mean, or the last position, would produce a+ // normalised 512-d vector that is simply wrong; see `nets::tinyclip`.+ tinyclip_column(&out, 0, tinyclip::VISION_POSITIONS as usize)+}++/// The 512-d text embedding for `ids`, or null on failure.+///+/// `ids` must be the query's tokens **up to and including `<|endoftext|>`**, with the tokenizer's+/// padding trimmed off. CLIP pools at the end-of-text position, so the caller's trim decides which+/// position is pooled — and because the tower is causal, running `ids.len()` positions instead of+/// the padded 77 gives the identical vector for a fraction of the work.+///+/// Not L2-normalised, as `tinyclipImage` is not.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createTinyclip` that has not been destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_tinyclipText<'l>(+ mut env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+ ids: JIntArray<'l>,+) -> jfloatArray {+ let null = std::ptr::null_mut();+ if handle == 0 {+ return null;+ }+ // SAFETY: as `tinyclipImage`.+ let handle = unsafe { &mut *(handle as *mut TinyclipHandle) };+ let embedded = match read_int_array(&mut env, &ids) {+ Ok(values) => run_tinyclip_text(handle, &values),+ Err(e) => Err(e),+ };+ match embedded.and_then(|values| new_float_array(&mut env, &values)) {+ Ok(array) => array,+ Err(e) => {+ log(&format!("tinyclip's text tower failed: {e}"));+ null+ }+ }+}++fn run_tinyclip_text(handle: &mut TinyclipHandle, ids: &[i32]) -> Result<Vec<f32>, String> {+ let tokens: Vec<u32> = ids+ .iter()+ .map(|&id| u32::try_from(id).map_err(|_| format!("{id} is not a token")))+ .collect::<Result<_, _>>()?;+ // The embedding and the learned positions, both on the host and summed in f32. See+ // `nets::tinyclip` for why neither is a shader.+ let embedded = tinyclip::embed_positions(handle.weights.reader(), &tokens)?;+ let len = u32::try_from(tokens.len()).map_err(|_| "a query longer than u32")?;+ let net = handle.net.at(tinyclip::Mode::Text { len })?;+ let out = one_output(net.infer_raw_many(&[&embedded])?)?;+ // The end-of-text position, which the caller's trim made the last one.+ tinyclip_column(&out, tokens.len() - 1, tokens.len())+}++/// Free TinyCLIP's net and its open weights file.+///+/// Exactly once per non-zero handle from `createTinyclip`. When it is the last user of the shared+/// `VkDevice`, the device goes away with it.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createTinyclip`, and must not be used again.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyTinyclip<'l>(+ _env: JNIEnv<'l>,+ _class: JClass<'l>,+ handle: jlong,+) {+ if handle == 0 {+ return;+ }+ // SAFETY: the caller guarantees this handle came from `createTinyclip` and has not been+ // destroyed. `Net`'s Drop waits for the device to go idle before freeing.+ drop(unsafe { Box::from_raw(handle as *mut TinyclipHandle) });+}++fn read_float_array(env: &mut JNIEnv, array: &JFloatArray) -> Result<Vec<f32>, String> {+ let len = env.get_array_length(array).map_err(|e| format!("array length: {e}"))?;+ let mut out = vec![0.0f32; len.max(0) as usize];+ env.get_float_array_region(array, 0, &mut out)+ .map_err(|e| format!("get_float_array_region: {e}"))?;+ Ok(out)+}++fn read_int_array(env: &mut JNIEnv, array: &JIntArray) -> Result<Vec<i32>, String> {+ let len = env.get_array_length(array).map_err(|e| format!("array length: {e}"))?;+ let mut out = vec![0i32; len.max(0) as usize];+ env.get_int_array_region(array, 0, &mut out)+ .map_err(|e| format!("get_int_array_region: {e}"))?;+ Ok(out)+}+ fn new_float_array(env: &mut JNIEnv, values: &[f32]) -> Result<jfloatArray, String> { let array: JFloatArray = env .new_float_array(values.len() as jint)
photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex 9435d7c8f1..f62fa7a654 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -15,13 +15,10 @@ android { applicationId = "com.vayunmathur.photos" } androidResources {- // 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"- // The three .maml 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.+ // The four .maml files are read straight out of the APK by :library:ml, which opens them+ // with `AssetManager.openFd` and streams them into the GPU. `openFd` throws outright for a+ // deflated entry, so this is required rather than an optimisation — and it costs nothing on+ // download size, since int8 and fp16 weights barely deflate. noCompress += "maml" } }@@ -43,9 +40,10 @@ dependencies { implementation(project(":library:map")) implementation(project(":library:image")) implementation(libs.androidx.exifinterface)- // No ncnn anywhere in this APK. Face detection (SCRFD 500M), face embedding- // (MobileFaceNet), subject segmentation (U²-Net portable) and PP-OCRv5 text- // recognition all run on :library:ml, our own Vulkan compute runtime.+ // No ncnn and no onnxruntime anywhere in this APK. Face detection (SCRFD 500M), face+ // embedding (MobileFaceNet), subject segmentation (U²-Net portable), PP-OCRv5 text+ // recognition and TinyCLIP semantic search all run on :library:ml, our own Vulkan compute+ // runtime. implementation(project(":library:ml")) implementRoom(libs)@@ -62,12 +60,4 @@ dependencies { implementation(project(":library:widgets")) implementation(project(":library:biometric")) implementation(project(":library:ocr"))-- // Semantic photo search runs on-device again: TinyCLIP int8 ships in assets/clip/ and is- // executed by ClipEmbedder, so search no longer needs the OpenAssistant app installed.- //- // Reduced ORT build (10 MB native, vs 28 MB for the full one). Its operator set is- // generated from the bundled model_int8.onnx, so swapping in a different CLIP export can- // fail at session creation — regenerate the AAR rather than falling back to the full build.- implementation(libs.onnxruntime.reduced) }
photos/src/main/assets/clip/README.md
diff --git a/photos/src/main/assets/clip/README.md b/photos/src/main/assets/clip/README.mdindex 2fb0bcfb0d..3c1166b70c 100644--- a/photos/src/main/assets/clip/README.md+++ b/photos/src/main/assets/clip/README.md@@ -68,8 +68,12 @@ indexed by either alone. The result is *smaller* than the file it replaces — 23,734,912 bytes against 24,281,512 — because the token embedding is int8 per row rather than uint8 per tensor and nothing is stored twice. The-APK shrinks by much more than that, because `onnxruntime-android`'s ~27 MB of native `.so` leaves-with it.+APK shrinks by much more than that, because `onnxruntime-android`'s native `.so` leaves with it:+`onnxruntime-reduced-android-1.27.0-r1.aar` contributed **10,466,856 bytes** of arm64 `.so`+(3.43 MiB after the APK's own compression), against the 779 KB of `libmodelrunner.so` that was+already there for face detection, subject segmentation and OCR.++A `:photos` release APK built after the port contains **no `onnxruntime` entry at all**. ## What the `.maml` holds
photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt b/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.ktindex fbbf9a8d38..76c04c239e 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt@@ -1,18 +1,14 @@ package com.vayunmathur.photos.util -import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Log+import com.vayunmathur.library.ml.ClipHandle import java.io.IOException import java.nio.ByteBuffer import java.nio.ByteOrder-import java.nio.FloatBuffer-import java.nio.LongBuffer import kotlin.math.roundToInt import kotlin.math.sqrt import kotlinx.coroutines.Dispatchers@@ -24,19 +20,33 @@ import kotlinx.coroutines.withContext * Photos runs its own embedder again. It previously delegated to the OpenAssistant app over IPC * for SigLIP2 vectors, which meant semantic search only worked if a second app was installed and * had finished a ~452 MB model download. The model now ships in the APK- * (`assets/clip/model_int8.onnx`, 24 MB int8) so search works on a clean install with no network.+ * (`assets/clip/tinyclip.maml`, 22.6 MiB int8) so search works on a clean install with no network. *- * The int8 quantization is close to free here: measured cosine against the fp32 export is 0.998- * for image embeddings and 0.9995 for text, at the same latency. TinyCLIP is a plain ViT, which- * quantizes cleanly — unlike depthwise-conv architectures where dynamic int8 collapses.+ * # It runs on `:library:ml`, not onnxruntime *- * The export is a **single combined graph**: `input_ids` + `pixel_values` + `attention_mask` are- * all required on every call, and it returns both `image_embeds` and `text_embeds`. So each call- * passes a cheap dummy for the side it does not need (see [DUMMY_IDS] / [dummyPixels]) and reads- * only the output it wants. The text tower is 3M params, so the waste is small.+ * The two towers are hardcoded forward passes in `library/ml/src/main/rust/src/nets/tinyclip.rs`,+ * executed by our own Vulkan compute runtime through [ClipHandle]. That removed the last+ * `onnxruntime-android` dependency from this APK — 10,466,856 bytes of arm64 `.so`, against the+ * 779 KB `libmodelrunner.so` that was already here for face detection, segmentation and OCR.+ *+ * It is also *more* accurate than the ONNX path it replaces. Cosine against the fp32 export is+ * 0.999864 for an image and 0.999394 for a query, against the int8 export's 0.998478 and 0.982881:+ * that export quantised the 49,408-row token table per *tensor* with a zero point, and this one+ * quantises per row. `photos/src/main/assets/clip/README.md` has the measurements.+ *+ * The two paths agree with each other only to 0.9983 (image) and 0.9835 (text), which is why+ * [EMBEDDER_VERSION] is 4 and not 3 — a library indexed by the old engine and queried through this+ * one would rank noticeably worse than one indexed by either alone.+ *+ * # Two towers, one handle+ *+ * Unlike the ONNX export, which was a single combined graph needing a dummy input for whichever+ * side it was not reading, the two towers are separate passes over one file. An image call does no+ * text work and a query does no vision work. * * Vectors are L2-normalised, stored on the [com.vayunmathur.photos.data.Photo] row by- * [runClipIndexing], and compared with [cosine] at query time.+ * [com.vayunmathur.photos.work.SyncWorker.runClipIndexing], and compared with [cosine] at query+ * time. The stored BLOB format is unchanged from the ONNX engine: 512 little-endian floats. */ object ClipEmbedder { @@ -44,10 +54,14 @@ object ClipEmbedder { const val MODEL_ID = "onnx-community/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M-ONNX" /**- * Bump whenever the embedding space changes so [runClipIndexing] clears every stored vector- * and re-indexes. 3 = TinyCLIP's 512-d space (2 was OpenAssistant's 768-d SigLIP2).+ * Bump whenever the embedding space changes so+ * [com.vayunmathur.photos.work.SyncWorker.runClipIndexing] clears every stored vector and+ * re-indexes.+ *+ * 4 = TinyCLIP's 512-d space on `:library:ml`. 3 was the same model on onnxruntime, and the two+ * agree only to 0.9835 on a text query — see the class docs. 2 was OpenAssistant's 768-d SigLIP2. */- const val EMBEDDER_VERSION = 3+ const val EMBEDDER_VERSION = 4 /** Whether semantic search can run at all. */ enum class Support { READY, UNAVAILABLE }@@ -61,22 +75,18 @@ object ClipEmbedder { private const val TAG = "ClipEmbedder" - private const val MODEL_ASSET = "clip/model_int8.onnx"- /** Square RGB input side the vision tower expects (`preprocessor_config.json`). */- private const val IMAGE_SIZE = 224+ private const val IMAGE_SIZE = ClipHandle.IMAGE_SIZE /** CLIP's channel normalisation, from `preprocessor_config.json`. */ private val MEAN = floatArrayOf(0.48145466f, 0.4578275f, 0.40821073f) private val STD = floatArrayOf(0.26862954f, 0.26130258f, 0.27577711f) - private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() } private val lock = Any() - @Volatile private var session: OrtSession? = null+ @Volatile private var clip: ClipHandle? = null @Volatile private var tokenizer: ClipTokenizer? = null @Volatile private var initTried = false- @Volatile private var cachedDim = 0 /** Fast capability probe. Loads the model on first call. */ fun embeddingSupport(context: Context): Support =@@ -84,39 +94,33 @@ object ClipEmbedder { fun embeddingInfo(context: Context): Info { ensureInit(context)- return Info(MODEL_ID, cachedDim)+ return Info(MODEL_ID, ClipHandle.DIMENSION) } private fun ensureInit(context: Context): Boolean {- session?.let { return true }+ clip?.let { return true } synchronized(lock) {- session?.let { return true }+ clip?.let { return true } if (initTried) return false initTried = true- return try {- val app = context.applicationContext- val tok = ClipTokenizer.load(app)- ?: error("CLIP merges asset missing")- val opts = OrtSession.SessionOptions().apply {- // Single-threaded keeps sustained CPU/battery use low during a long- // indexing run; the model is only 24 MB.- setIntraOpNumThreads(1)- setInterOpNumThreads(1)- }- // Read from assets rather than copying 24 MB into filesDir.- val bytes = app.assets.open(MODEL_ASSET).use { it.readBytes() }- val s = env.createSession(bytes, opts)- cachedDim = (s.outputInfo[OUT_IMAGE]?.info as? ai.onnxruntime.TensorInfo)- ?.shape?.last()?.toInt() ?: 512- session = s- tokenizer = tok- Log.i(TAG, "TinyCLIP embedder ready (dim=$cachedDim)")- true- } catch (t: Throwable) {- Log.e(TAG, "Failed to initialise TinyCLIP embedder", t)- closeLocked()- false+ val app = context.applicationContext+ val tok = ClipTokenizer.load(app)+ if (tok == null) {+ Log.e(TAG, "CLIP merges asset missing")+ return false }+ // Construction never throws: an absent, compressed or malformed asset, a missing+ // `libmodelrunner.so` and a device without fp16 compute all come back unavailable.+ val handle = ClipHandle.inAssets(app.assets)+ if (!handle.isAvailable) {+ Log.e(TAG, "cannot bring up $handle")+ handle.close()+ return false+ }+ clip = handle+ tokenizer = tok+ Log.i(TAG, "TinyCLIP embedder ready (dim=${ClipHandle.DIMENSION})")+ return true } } @@ -136,7 +140,11 @@ object ClipEmbedder { } finally { bitmap.recycle() }- run(pixels, DUMMY_IDS, OUT_IMAGE)+ // The handle re-records the network when the tower changes, so calls on it are+ // serialised for the same reason the ORT session's were.+ val raw = synchronized(lock) { clip?.imageEmbedding(pixels) }+ ?: throw ImageFailedException("the vision tower failed for $uri")+ l2Normalize(raw) } /** Embed [query] into an L2-normalised vector in the SAME space as [imageEmbedding]. */@@ -144,41 +152,26 @@ object ClipEmbedder { withContext(Dispatchers.Default) { check(ensureInit(context)) { "TinyCLIP embedder unavailable" } val tok = tokenizer ?: error("tokenizer not loaded")- run(dummyPixels(), tok.tokenize(query), OUT_TEXT)+ // The tokenizer pads to 77; the tower is causal and pools at `<|endoftext|>`, so the+ // padding is dropped. That gives the identical vector for a quarter of the work on a+ // typical query, and it is what tells native which position to pool.+ val ids = trimToEnd(tok.tokenize(query))+ val raw = synchronized(lock) { clip?.textEmbedding(ids) }+ ?: error("the text tower failed")+ l2Normalize(raw) } /**- * One forward pass of the combined graph, returning the L2-normalised [wanted] output.- * Both inputs must always be supplied even though only one side is read.+ * A tokenizer's fixed-length output cut to end at `<|endoftext|>`.+ *+ * [ClipTokenizer.tokenize] always appends the end token and then zero-pads to+ * [ClipTokenizer.CONTEXT_LENGTH], so the token is present and appears once. If it somehow is+ * not, the whole array is passed through rather than silently pooling position 0 — which would+ * be the `<|startoftext|>` embedding and carry no query at all. */- private fun run(pixels: FloatArray, ids: IntArray, wanted: String): FloatArray {- val s = session ?: error("session not loaded")- val longIds = LongArray(ids.size) { ids[it].toLong() }- // CLIP's text transformer is causal and pools at the end-of-text position, so an- // all-ones mask over the padded sequence matches how the model was trained.- val mask = LongArray(ids.size) { 1L }- val idShape = longArrayOf(1, ids.size.toLong())-- return synchronized(lock) {- val tensors = LinkedHashMap<String, OnnxTensor>(3)- try {- tensors[IN_PIXELS] = OnnxTensor.createTensor(- env,- FloatBuffer.wrap(pixels),- longArrayOf(1, 3, IMAGE_SIZE.toLong(), IMAGE_SIZE.toLong()),- )- tensors[IN_IDS] = OnnxTensor.createTensor(env, LongBuffer.wrap(longIds), idShape)- tensors[IN_MASK] = OnnxTensor.createTensor(env, LongBuffer.wrap(mask), idShape)- s.run(tensors).use { result ->- val out = result.get(wanted).get() as OnnxTensor- val vec = FloatArray(out.info.shape.last().toInt())- out.floatBuffer.get(vec)- l2Normalize(vec)- }- } finally {- tensors.values.forEach { runCatching { it.close() } }- }- }+ private fun trimToEnd(ids: IntArray): IntArray {+ val end = ids.indexOf(ClipTokenizer.END_TOKEN)+ return if (end >= 0) ids.copyOfRange(0, end + 1) else ids } /** Decode [uri], downsampling during decode so a 48 MP photo never lands on the heap. */@@ -237,18 +230,14 @@ object ClipEmbedder { return out } - /** Zeroed pixels for a text-only call; the image side of the graph is ignored. */- private fun dummyPixels() = FloatArray(3 * IMAGE_SIZE * IMAGE_SIZE)- fun close() { synchronized(lock) { closeLocked() } } private fun closeLocked() {- runCatching { session?.close() }- session = null+ runCatching { clip?.close() }+ clip = null tokenizer = null- cachedDim = 0 initTried = false } @@ -289,16 +278,4 @@ object ClipEmbedder { for (i in out.indices) out[i] = buffer.float return out }-- private const val IN_PIXELS = "pixel_values"- private const val IN_IDS = "input_ids"- private const val IN_MASK = "attention_mask"- private const val OUT_IMAGE = "image_embeds"- private const val OUT_TEXT = "text_embeds"-- /** Minimal `<|startoftext|><|endoftext|>` prompt for image-only calls. */- private val DUMMY_IDS = IntArray(ClipTokenizer.CONTEXT_LENGTH).also {- it[0] = ClipTokenizer.START_TOKEN- it[1] = ClipTokenizer.END_TOKEN- } }