library:ml: port vision, OCR, CLIP and Whisper to onnxruntime-reduced
- Commit
c4b4bddfed4b9a83f0b50f6248ac537911c6ab92- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 20:01 UTC (2 months ago)
- Parents
7d0dbc7
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex fbf315e3b0..212b5d6d9f 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -80,6 +80,7 @@ androidxTestCore = "1.7.0" androidxTestExtJunit = "1.3.0" # Google libraries+# One key for the entire protobuf toolchain # One key for the entire protobuf toolchain — protobuf-java, protobuf-javalite and the protoc # compiler. Generated sources and the runtime that parses them must come from the same release, # so these are deliberately not separable: a bump here moves compiler and runtime together.@@ -107,6 +108,10 @@ apksig = "8.7.3" # JavaScript engines & HTML quickjs = "1.0.15" +# On-device AI+onnxruntimeReduced = "1.27.0-r1"+litertlmAndroid = "0.14.0"+ # Git jgit = "7.8.0.202609011348-r" @@ -288,6 +293,17 @@ apksig = { module = "com.android.tools.build:apksig", version.ref = "apksig" } # JavaScript engines & HTML quickjs-kt = { module = "io.github.dokar3:quickjs-kt", version.ref = "quickjs" } +# On-device AI: reduced-operator ORT rebuild (arm64-only). Version tracks upstream plus an+# -rN suffix for the operator-set revision, so a rebuild with different ops gets a new version.+# Same source as onnxruntime-android, built with --include_ops_by_config: 10 MB of native code+# instead of 28 MB. A model with an operator outside the configured set fails at session+# creation, not at inference — regenerate the AAR rather than falling back to a full build.+onnxruntime-reduced-android = { module = "io.github.vayun-mathur:onnxruntime-reduced-android", version.ref = "onnxruntimeReduced" }+# Conversational LLM (Gemma) via LiteRT-LM. litertlm 0.14.0 is compiled against coroutines+# 1.11.0 (close$default moved onto the SendChannel interface via -Xjvm-default=all); older+# versions crash its JNI callback with NoSuchMethodError, so keep kotlinxCoroutines at 1.11.0.+litertlm-android = { module = "com.google.ai.edge.litertlm:litertlm-android", version.ref = "litertlmAndroid" }+ # Git jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" }
library/ml/build.gradle.kts
diff --git a/library/ml/build.gradle.kts b/library/ml/build.gradle.ktsindex 88311e6b04..f7bd832020 100644--- a/library/ml/build.gradle.kts+++ b/library/ml/build.gradle.kts@@ -29,3 +29,10 @@ rustNativeLib( emptyList() }, )++dependencies {+ // On-device inference executor going forward: reduced-operator ONNX Runtime rebuild+ // (arm64-only, 10 MB native). Coexists with the modelrunner JNI below during migration;+ // MAML deletion removes the rustNativeLib wiring above.+ implementation(libs.onnxruntime.reduced.android)+}
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.ktindex bd20ca6266..411886b78b 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt@@ -1,37 +1,30 @@ package com.vayunmathur.library.ml +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.res.AssetManager-import android.os.ParcelFileDescriptor import android.util.Log+import java.nio.FloatBuffer+import java.nio.LongBuffer /**- * On-device image and text embedding in a shared 512-d space: TinyCLIP on the Vulkan compute- * runtime.+ * On-device image and text embedding in a shared 512-d space: TinyCLIP on the reduced ONNX+ * Runtime build. * * 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+ * # One bundled asset *- * `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.+ * `clip/model_int8.onnx` ships inside the APK, so this has an [inAssets] and no download. 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 and reads only the output it wants. *- * 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,466,856 bytes of arm64 `.so` with the runtime, 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.+ * An asset must be stored **uncompressed** for the byte-read below to avoid an inflate into+ * a heap buffer: `noCompress += "onnx"` in `photos/build.gradle.kts`. Int8 weights barely+ * deflate, so it costs nothing on download size. * * # Neither vector is normalised *@@ -40,21 +33,19 @@ import android.util.Log * * # 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.+ * Construction never throws. [isAvailable] is false when the asset is absent or has an+ * operator outside the reduced build — 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].+ * Not thread-safe. 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+ private var session: OrtSession? = null+ private var assetPath: String = GRAPH /** True if the graph came up and is the file this runtime was built against. */- val isAvailable: Boolean get() = handle != 0L+ val isAvailable: Boolean get() = session != null /** * The 512-d embedding of an already-preprocessed image, or null on failure.@@ -63,8 +54,18 @@ class ClipHandle private constructor(private val source: String) : AutoCloseable * 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)+ val live = session ?: return null+ return try {+ run(+ live,+ pixels, DUMMY_IDS,+ attentionMask(DUMMY_IDS.size),+ OUT_IMAGE,+ )+ } catch (e: Throwable) {+ Log.e(TAG, "clip image embedding failed", e)+ null+ } } /**@@ -74,20 +75,62 @@ class ClipHandle private constructor(private val source: String) : AutoCloseable * the position CLIP pools. Not L2-normalised on return. */ fun textEmbedding(ids: IntArray): FloatArray? {- if (handle == 0L) return null+ val live = session ?: return null if (ids.isEmpty()) return null- return MlNative.tinyclipText(handle, ids)+ return try {+ run(+ live,+ dummyPixels(), ids,+ attentionMask(ids.size),+ OUT_TEXT,+ )+ } catch (e: Throwable) {+ Log.e(TAG, "clip text embedding failed", e)+ null+ } } - /** Free the network and close the weights file. Idempotent. */+ /** Free the session. Idempotent. */ override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyTinyclip(live)+ session = null+ OnnxSessions.close("asset:$assetPath") } override fun toString(): String = "TinyCLIP from $source" + private fun run(+ session: OrtSession,+ pixels: FloatArray,+ ids: IntArray,+ mask: LongArray,+ wanted: String,+ ): FloatArray {+ val env = OrtEnvironment.getEnvironment()+ val pixelTensor = OnnxTensor.createTensor(+ env, FloatBuffer.wrap(pixels), longArrayOf(1, 3, IMAGE_SIZE.toLong(), IMAGE_SIZE.toLong()),+ )+ val longIds = LongArray(ids.size) { ids[it].toLong() }+ val idShape = longArrayOf(1, ids.size.toLong())+ val idTensor = OnnxTensor.createTensor(env, LongBuffer.wrap(longIds), idShape)+ val maskTensor = OnnxTensor.createTensor(env, LongBuffer.wrap(mask), idShape)+ pixelTensor.use {+ idTensor.use {+ maskTensor.use {+ val inputs = LinkedHashMap<String, OnnxTensor>(3)+ inputs[IN_PIXELS] = pixelTensor+ inputs[IN_IDS] = idTensor+ inputs[IN_MASK] = maskTensor+ session.run(inputs, setOf(wanted)).use { result ->+ val out = result.get(wanted).get() as OnnxTensor+ val vec = FloatArray(out.info.shape.last().toInt())+ out.floatBuffer.get(vec)+ return vec+ }+ }+ }+ }+ }+ companion object { private const val TAG = "ClipHandle" @@ -100,63 +143,33 @@ class ClipHandle private constructor(private val source: String) : AutoCloseable /** 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 bundled export. Native checks nothing about it; a wrong file fails at load. */+ const val GRAPH = "clip/model_int8.onnx"++ 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"++ private val DUMMY_IDS = IntArray(CONTEXT_LENGTH) /** * The model from the APK's assets, which is the only place it lives. *- * No `inDirectory` counterpart: at 22.6 MiB this is bundled, so+ * No `inDirectory` counterpart: at ~24 MB 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- }- }+ instance.assetPath = path+ instance.session = OnnxSessions.openAssetManager(assets, path)+ if (instance.session == null) Log.e(TAG, "cannot open $path") 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)- }- }+ private fun attentionMask(size: Int): LongArray = LongArray(size) { 1L } - /**- * 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() }- }+ private fun dummyPixels(): FloatArray = FloatArray(3 * IMAGE_SIZE * IMAGE_SIZE) } }
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.ktindex 6f7927a29a..06ef637d7f 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt@@ -1,26 +1,43 @@ package com.vayunmathur.library.ml +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap import android.util.Log+import java.nio.FloatBuffer+import kotlin.math.max+import kotlin.math.min /** * 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.+ * ArcFace-trained) turns an aligned crop into a 512-d embedding. Both run on the reduced+ * ONNX Runtime build — see `photos/src/main/assets/README.md` for provenance and the+ * InsightFace licence. *- * 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.+ * These replace `com.vayunmathur.ncnn.FaceDetector` and `FaceEmbedder` (and the Vulkan+ * `MlNative` path between them). Same two models, re-sourced from a licensed ONNX export.+ * 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.+ * # SCRFD decode+ *+ * The export declares nine outputs: three score maps, three box maps, three keypoint maps+ * at strides 8, 16 and 32. Each is flattened from a `[H, W, anchors]` transpose+ * (`perm [2,3,0,1]`), so the layout is **cell-major**: element `(row, col, anchor)` sits+ * at `flat[(row * w + col) * 2 + anchor]`. This differs from the MAML path, which read+ * the convolution outputs before the transpose and decoded anchor-major — ported+ * accordingly. The box math (centre at `col * stride` with no half-cell offset, `+1` on+ * extents, five keypoints as stride-scaled offsets) and the greedy stable NMS+ * (score ≥ 0.5 keep, IoU strictly above 0.45 suppresses) mirror `post::nms`.+ *+ * The input is letterboxed into a 640×640 square (`OnnxPreprocess.SquareFit`, scale+ * `640 / long side`, truncated, centred, border raw-zero through the SCRFD+ * normalisation), and boxes are mapped back onto the source bitmap as `0..1` fractions. */ /** One detected face. Every coordinate is a fraction of the source bitmap, `0..1`. */@@ -52,97 +69,190 @@ data class DetectedFaceBox( * [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 `.maml` in the app's assets.+ * @param assetName the `.onnx` in the app's assets. */ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {+ private val app = context.applicationContext+ private val asset = assetName+ private val lock = Any() - @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- }- }+ @Volatile private var session: OrtSession? = null+ @Volatile private var loadTried = false /** 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+ val isAvailable: Boolean get() = ensure() /** * 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.+ * [bitmap] may be any size: it is letterboxed and normalised here. */ 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+ if (!ensure()) return emptyList()+ val live = session ?: return emptyList()+ val (pixels, readable) = OnnxPreprocess.readablePixels(bitmap) ?: return emptyList()+ try {+ val fit = OnnxPreprocess.SquareFit.of(readable.width, readable.height, LONG_SIDE)+ val input = OnnxPreprocess.letterboxPlanar(+ pixels, readable.width, readable.height, LONG_SIDE, fit, OnnxPreprocess.SCRFD,+ )+ val env = OrtEnvironment.getEnvironment()+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, LONG_SIDE.toLong(), LONG_SIDE.toLong())).use { tensor ->+ live.run(mapOf(INPUT to tensor)).use { result ->+ fun floats(name: String): FloatArray {+ val out = FloatArray(sessionOutputSize(live, name))+ ((result.get(name).get()) as OnnxTensor).floatBuffer.get(out)+ return out+ }+ val faces = ArrayList<Face>()+ for (level in STRIDES.indices) {+ decode(+ floats(SCORES[level]), floats(BOXES[level]), floats(KEYPOINTS[level]),+ STRIDES[level], LONG_SIDE / STRIDES[level], faces,+ )+ }+ suppress(faces)+ return faces.map { toSource(it, fit, readable.width, readable.height) }+ } }- 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)+ } catch (e: Throwable) {+ Log.e(TAG, "scrfd inference failed", e)+ return emptyList() } 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()+ override fun close() {+ synchronized(lock) {+ session = null+ OnnxSessions.close(sessionKey()) }- 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+ }++ private fun sessionKey() = "asset:$asset"++ private fun ensure(): Boolean {+ session?.let { return true }+ synchronized(lock) {+ session?.let { return true }+ if (loadTried) return false+ loadTried = true+ session = OnnxSessions.openAsset(app, asset)+ return session != null }- return out } - override fun close() {- val toDestroy = handle- handle = 0L- pixels = null- if (toDestroy != 0L) MlNative.destroy(toDestroy)+ private data class Face(+ val score: Float,+ val bounds: FloatArray,+ val keypoints: Array<FloatArray>,+ )++ private fun sessionOutputSize(session: OrtSession, name: String): Int {+ val info = session.outputInfo[name]?.info as? ai.onnxruntime.TensorInfo+ ?: error("no output $name")+ return info.shape.map { if (it < 0) 1 else it.toInt() }.reduce(Int::times)+ }++ /** Decode one stride's maps into proposals. Cell-major: `(row, col, anchor)`. */+ private fun decode(+ score: FloatArray,+ bbox: FloatArray,+ keypoints: FloatArray,+ stride: Int,+ cells: Int,+ out: MutableList<Face>,+ ) {+ for (anchor in 0 until ANCHORS) {+ for (row in 0 until cells) {+ for (col in 0 until cells) {+ val cell = row * cells + col+ val s = score[cell * ANCHORS + anchor]+ if (s < SCORE_THRESHOLD) continue+ val cx = (col * stride).toFloat()+ val cy = (row * stride).toFloat()+ val b = cell * ANCHORS * 4 + anchor * 4+ val x0 = cx - bbox[b] * stride+ val y0 = cy - bbox[b + 1] * stride+ val x1 = cx + bbox[b + 2] * stride + 1f+ val y1 = cy + bbox[b + 3] * stride + 1f+ val kBase = cell * ANCHORS * KEYPOINT_COUNT * 2 + anchor * KEYPOINT_COUNT * 2+ val points = Array(KEYPOINT_COUNT) { k ->+ floatArrayOf(+ cx + keypoints[kBase + k * 2] * stride,+ cy + keypoints[kBase + k * 2 + 1] * stride,+ )+ }+ out += Face(s, floatArrayOf(x0, y0, x1, y1), points)+ }+ }+ }+ }++ /** Greedy stable NMS: by score, drop overlaps with IoU strictly above threshold. */+ private fun suppress(faces: MutableList<Face>) {+ faces.sortByDescending { it.score }+ val kept = ArrayList<Face>(faces.size)+ for (face in faces) {+ val overlaps = kept.any { other ->+ val iw = min(face.bounds[2], other.bounds[2]) - max(face.bounds[0], other.bounds[0])+ val ih = min(face.bounds[3], other.bounds[3]) - max(face.bounds[1], other.bounds[1])+ if (iw <= 0f || ih <= 0f) return@any false+ val intersection = iw * ih+ val union = area(face) + area(other) - intersection+ union > 0f && intersection / union > IOU_THRESHOLD+ }+ if (!overlaps) kept += face+ }+ faces.clear()+ faces.addAll(kept)+ }++ private fun area(face: Face): Float {+ val w = max(face.bounds[2] - face.bounds[0], 0f)+ val h = max(face.bounds[3] - face.bounds[1], 0f)+ return w * h+ }++ /** Map out of letterboxed space onto the source bitmap as `0..1` fractions. */+ private fun toSource(face: Face, fit: OnnxPreprocess.SquareFit, width: Int, height: Int): DetectedFaceBox {+ val limitX = (max(width, 1) - 1).toFloat()+ val limitY = (max(height, 1) - 1).toFloat()+ fun undo(value: Float, pad: Int, limit: Float): Float =+ ((value - pad) / fit.scale).coerceIn(0f, limit)+ fun nx(value: Float, pad: Int): Float = undo(value, pad, limitX) / width+ fun ny(value: Float, pad: Int): Float = undo(value, pad, limitY) / height+ val leftEye = face.keypoints[0]+ val rightEye = face.keypoints[1]+ return DetectedFaceBox(+ left = nx(face.bounds[0], fit.offsetX),+ top = ny(face.bounds[1], fit.offsetY),+ right = nx(face.bounds[2], fit.offsetX),+ bottom = ny(face.bounds[3], fit.offsetY),+ leftEyeX = nx(leftEye[0], fit.offsetX),+ leftEyeY = ny(leftEye[1], fit.offsetY),+ rightEyeX = nx(rightEye[0], fit.offsetX),+ rightEyeY = ny(rightEye[1], fit.offsetY),+ score = face.score,+ ) } companion object { /** What `:photos` ships. */- const val DEFAULT_ASSET: String = "scrfd_500m.maml"+ const val DEFAULT_ASSET: String = "scrfd_500m.onnx" private const val TAG = "FaceDetector"- private const val FLOATS_PER_FACE = 9+ private const val LONG_SIDE = 640+ private const val INPUT = "input.1"+ private const val ANCHORS = 2+ private const val KEYPOINT_COUNT = 5+ private const val SCORE_THRESHOLD = 0.5f+ private const val IOU_THRESHOLD = 0.45f+ private val STRIDES = intArrayOf(8, 16, 32)+ private val SCORES = arrayOf("443", "468", "493")+ private val BOXES = arrayOf("446", "471", "496")+ private val KEYPOINTS = arrayOf("449", "474", "499") } } @@ -155,41 +265,82 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl * Not thread-safe: [embed] and [close] must not overlap. * * @param context used only to read the asset; not retained.- * @param assetName the `.maml` in the app's assets.+ * @param assetName the `.onnx` in the app's assets. */ class FaceEmbedder(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {+ private val app = context.applicationContext+ private val asset = assetName+ private val lock = Any() - // 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)+ @Volatile private var session: OrtSession? = null+ @Volatile private var loadTried = false /** Whether the embedder came up. */- val isAvailable: Boolean get() = native.isAvailable+ val isAvailable: Boolean get() = ensure() /** * 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.+ * [bitmap] should already be the canonical 112×112 crop; anything else is stretched+ * here, 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")+ if (!ensure()) return null+ val live = session ?: return null+ val (pixels, readable) = OnnxPreprocess.readablePixels(bitmap) ?: return null+ try {+ val input = OnnxPreprocess.stretchPlanar(+ pixels, readable.width, readable.height,+ SIZE, SIZE, OnnxPreprocess.FACE_EMBED,+ )+ val env = OrtEnvironment.getEnvironment()+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, SIZE.toLong(), SIZE.toLong())).use { tensor ->+ live.run(mapOf(INPUT to tensor)).use { result ->+ val out = result[0] as OnnxTensor+ val vec = FloatArray(EMBEDDING_LENGTH)+ out.floatBuffer.get(vec)+ if (vec.size != EMBEDDING_LENGTH) {+ Log.e(TAG, "a ${vec.size}-value embedding, expected $EMBEDDING_LENGTH")+ return null+ }+ return vec+ }+ }+ } catch (e: Throwable) {+ Log.e(TAG, "mobilefacenet inference failed", e) return null+ } finally {+ if (readable !== bitmap) readable.recycle() }- return result.mask } - override fun close() = native.close()+ override fun close() {+ synchronized(lock) {+ session = null+ OnnxSessions.close(sessionKey())+ }+ }++ private fun sessionKey() = "asset:$asset"++ private fun ensure(): Boolean {+ session?.let { return true }+ synchronized(lock) {+ session?.let { return true }+ if (loadTried) return false+ loadTried = true+ session = OnnxSessions.openAsset(app, asset)+ return session != null+ }+ } companion object { /** What `:photos` ships. */- const val DEFAULT_ASSET: String = "w600k_mbf.maml"+ const val DEFAULT_ASSET: String = "w600k_mbf.onnx" /** Length of the embedding MobileFaceNet produces. */ const val EMBEDDING_LENGTH = 512 private const val TAG = "FaceEmbedder"+ private const val SIZE = 112+ private const val INPUT = "input.1" } }
library/ml/src/main/java/com/vayunmathur/library/ml/OnnxPreprocess.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/OnnxPreprocess.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/OnnxPreprocess.ktnew file mode 100644index 0000000000..52d7b32905--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/OnnxPreprocess.kt@@ -0,0 +1,198 @@+package com.vayunmathur.library.ml++import android.graphics.Bitmap+import kotlin.math.max++/**+ * Image preprocessing for the ONNX models, ported from+ * `library/ml/src/main/rust/src/preprocess.rs`.+ *+ * Every vision model takes planar NCHW fp32, but each wants a different fit and normalisation:+ * the segmenters stretch, SCRFD letterboxes into a square, and the constants differ per net+ * (SCRFD's divisor is 128 where MobileFaceNet's is 127.5 — see the Rust `preprocess.rs`, whose+ * comments record why each constant is what it is).+ *+ * The resize is centre-sampled bilinear (`(out + 0.5) * scale - 0.5`), matching the native+ * `sample()`. It is deliberately not `Bitmap.createScaledBitmap`: that rounds differently at+ * edges and would shift every mask by subpixel amounts relative to the MAML behaviour.+ */+internal object OnnxPreprocess {+ /** Per-model normalisation: `(value / 255 - mean) / std`, with channel order. */+ data class Normalise(+ val mean: FloatArray,+ val std: FloatArray,+ /** True when channel 0 of the input is blue (PP-OCR), false for RGB. */+ val bgr: Boolean = false,+ )++ /** MediaPipe Selfie Segmentation: scale to `0..1`, nothing else. */+ val RESCALE_ONLY = Normalise(floatArrayOf(0f, 0f, 0f), floatArrayOf(1f, 1f, 1f))++ /** U^2-Net portable: ImageNet statistics, RGB. */+ val IMAGENET = Normalise(+ floatArrayOf(0.485f, 0.456f, 0.406f),+ floatArrayOf(0.229f, 0.224f, 0.225f),+ )++ /** PP-OCRv5 detection: ImageNet statistics over BGR channels. */+ val PPOCR_DET = Normalise(+ floatArrayOf(0.485f, 0.456f, 0.406f),+ floatArrayOf(0.229f, 0.224f, 0.225f),+ bgr = true,+ )++ /** PP-OCRv5 recognition: `(value / 255 - 0.5) / 0.5` over BGR. */+ val PPOCR_REC = Normalise(+ floatArrayOf(0.5f, 0.5f, 0.5f),+ floatArrayOf(0.5f, 0.5f, 0.5f),+ bgr = true,+ )++ /** SCRFD: `(value - 127.5) / 128` on the `0..255` scale, RGB. */+ val SCRFD = Normalise(+ floatArrayOf(0.5f, 0.5f, 0.5f),+ floatArrayOf(128f / 255f, 128f / 255f, 128f / 255f),+ )++ /** MobileFaceNet: `(value - 127.5) / 127.5` on the `0..255` scale, RGB. */+ val FACE_EMBED = Normalise(+ floatArrayOf(0.5f, 0.5f, 0.5f),+ floatArrayOf(0.5f, 0.5f, 0.5f),+ )++ /** How an image was fitted into a square detector input. Mirrors `Letterbox::square`. */+ data class SquareFit(+ val scale: Float,+ val resizedW: Int,+ val resizedH: Int,+ val offsetX: Int,+ val offsetY: Int,+ ) {+ companion object {+ fun of(width: Int, height: Int, side: Int): SquareFit {+ val (scale, rw, rh) = if (width > height) {+ val s = side.toFloat() / width+ Triple(s, side, max(1, (height * s).toInt()).coerceAtMost(side))+ } else {+ val s = side.toFloat() / height+ Triple(s, max(1, (width * s).toInt()).coerceAtMost(side), side)+ }+ return SquareFit(scale, rw, rh, (side - rw) / 2, (side - rh) / 2)+ }+ }+ }++ /**+ * Readable pixels from [bitmap], copying off HARDWARE configs.+ *+ * Returns null when the bitmap is recycled. The caller recycles the copy; see+ * `NativeSegmenter.segment` for the discipline.+ */+ fun readablePixels(bitmap: Bitmap): Pair<IntArray, Bitmap>? {+ val readable = if (bitmap.config == Bitmap.Config.HARDWARE || bitmap.config == null) {+ bitmap.copy(Bitmap.Config.ARGB_8888, false)+ } else {+ bitmap+ } ?: return null+ val pixels = IntArray(readable.width * readable.height)+ readable.getPixels(pixels, 0, readable.width, 0, 0, readable.width, readable.height)+ return Pair(pixels, readable)+ }++ /**+ * Stretch [pixels] ([width]×[height] ARGB) to [outW]×[outH] planar NCHW floats.+ *+ * The segmenter fit: a straight scale, aspect not preserved. Matches `to_planar_f16`+ * (modulo fp16 rounding, which the fp32 ONNX graph does not need).+ */+ fun stretchPlanar(+ pixels: IntArray,+ width: Int,+ height: Int,+ outW: Int,+ outH: Int,+ norm: Normalise,+ ): FloatArray {+ val plane = outW * outH+ val out = FloatArray(3 * plane)+ val xScale = width.toFloat() / outW+ val yScale = height.toFloat() / outH+ for (y in 0 until outH) {+ val (y0, y1, wy) = sample(y, yScale, height)+ for (x in 0 until outW) {+ val (x0, x1, wx) = sample(x, xScale, width)+ val at = y * outW + x+ for (c in 0..2) {+ val src = if (norm.bgr) 2 - c else c+ val top = lerp(channel(pixels, width, x0, y0, src), channel(pixels, width, x1, y0, src), wx)+ val bottom = lerp(channel(pixels, width, x0, y1, src), channel(pixels, width, x1, y1, src), wx)+ val value = lerp(top, bottom, wy) / 255f+ out[c * plane + at] = (value - norm.mean[c]) / norm.std[c]+ }+ }+ }+ return out+ }++ /**+ * Letterbox [pixels] into a [side]×[side] square per [fit], planar NCHW floats.+ *+ * The SCRFD fit: scaled image centred at the fit offset, border filled with raw zero+ * through the normalisation (the net sees `(0 - 127.5) / 128` at the edges, not grey).+ */+ fun letterboxPlanar(+ pixels: IntArray,+ width: Int,+ height: Int,+ side: Int,+ fit: SquareFit,+ norm: Normalise,+ ): FloatArray {+ val plane = side * side+ val out = FloatArray(3 * plane)+ val border = FloatArray(3) { (0f - norm.mean[it]) / norm.std[it] }+ val xScale = width.toFloat() / fit.resizedW+ val yScale = height.toFloat() / fit.resizedH+ for (y in 0 until side) {+ val insideRow = y >= fit.offsetY && y < fit.offsetY + fit.resizedH+ val (y0, y1, wy) = if (insideRow) sample(y - fit.offsetY, yScale, height) else Triple(0, 0, 0f)+ for (x in 0 until side) {+ val at = y * side + x+ if (!insideRow || x < fit.offsetX || x >= fit.offsetX + fit.resizedW) {+ for (c in 0..2) out[c * plane + at] = border[c]+ continue+ }+ val (x0, x1, wx) = sample(x - fit.offsetX, xScale, width)+ for (c in 0..2) {+ val src = if (norm.bgr) 2 - c else c+ val top = lerp(channel(pixels, width, x0, y0, src), channel(pixels, width, x1, y0, src), wx)+ val bottom = lerp(channel(pixels, width, x0, y1, src), channel(pixels, width, x1, y1, src), wx)+ val value = lerp(top, bottom, wy) / 255f+ out[c * plane + at] = (value - norm.mean[c]) / norm.std[c]+ }+ }+ }+ return out+ }++ private fun sample(out: Int, scale: Float, extent: Int): Triple<Int, Int, Float> {+ val source = (out + 0.5f) * scale - 0.5f+ val clamped = max(source, 0f)+ val low = clamped.toInt()+ val weight = clamped - low+ val lo = low.coerceAtMost(extent - 1)+ val hi = (lo + 1).coerceAtMost(extent - 1)+ return Triple(lo, hi, weight)+ }++ private fun channel(pixels: IntArray, width: Int, x: Int, y: Int, channel: Int): Float {+ val argb = pixels[y * width + x]+ return when (channel) {+ 0 -> ((argb shr 16) and 0xFF).toFloat()+ 1 -> ((argb shr 8) and 0xFF).toFloat()+ else -> (argb and 0xFF).toFloat()+ }+ }++ private fun lerp(a: Float, b: Float, t: Float): Float = a + (b - a) * t+}
library/ml/src/main/java/com/vayunmathur/library/ml/OnnxSessions.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/OnnxSessions.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/OnnxSessions.ktnew file mode 100644index 0000000000..3be69fc1bf--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/OnnxSessions.kt@@ -0,0 +1,95 @@+package com.vayunmathur.library.ml++import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession+import android.content.Context+import android.util.Log+import java.io.Closeable++/**+ * Shared ONNX Runtime executor for the models that run on+ * `io.github.vayun-mathur:onnxruntime-reduced-android`.+ *+ * One process-wide [OrtEnvironment], one [OrtSession] per model file. Sessions are created+ * single-threaded (`setIntraOpNumThreads(1)`), matching the prior `ClipEmbedder` policy: vision+ * and audio models are small enough that extra threads cost more battery than latency.+ *+ * A model with an operator outside the reduced build's configured set fails at [open] time, not+ * at inference — callers must treat a null return as "model unavailable" and degrade, never+ * crash. See the catalog comment on `onnxruntime-reduced-android` in `gradle/libs.versions.toml`.+ *+ * Sessions are not thread-safe: the caller must serialize runs on a session, as the MAML handles+ * (`ClipHandle` and friends) already document.+ */+object OnnxSessions {+ private const val TAG = "OnnxSessions"++ private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }+ private val lock = Any()+ private val sessions = mutableMapOf<String, OrtSession>()++ /**+ * Open (or reuse) the session for [key], reading the model bytes via [readModel].+ *+ * Returns null when the model cannot run here: missing file, corrupt bytes, or an operator+ * the reduced build does not include. Never throws.+ */+ fun open(key: String, readModel: () -> ByteArray): OrtSession? {+ synchronized(lock) {+ sessions[key]?.let { return it }+ return try {+ val bytes = readModel()+ val opts = OrtSession.SessionOptions().apply {+ setIntraOpNumThreads(1)+ setInterOpNumThreads(1)+ }+ val session = env.createSession(bytes, opts)+ sessions[key] = session+ Log.i(TAG, "ORT session open for $key")+ session+ } catch (t: Throwable) {+ Log.e(TAG, "cannot open ORT session for $key", t)+ null+ }+ }+ }++ /** Open a model bundled in assets, e.g. `clip/model_int8.onnx`. */+ fun openAsset(context: Context, assetPath: String): OrtSession? =+ open("asset:$assetPath") {+ context.applicationContext.assets.open(assetPath).use { it.readBytes() }+ }++ /** Open a model from an [AssetManager], e.g. when only assets (not a Context) are at hand. */+ fun openAssetManager(assets: android.content.res.AssetManager, assetPath: String): OrtSession? =+ open("asset:$assetPath") {+ assets.open(assetPath).use { it.readBytes() }+ }++ /** Open a model from a downloaded file, e.g. under `getExternalFilesDir`. */+ fun openFile(path: String): OrtSession? =+ open("file:$path") { java.io.File(path).readBytes() }++ /** Drop the cached session for [key]. Idempotent. */+ fun close(key: String) {+ synchronized(lock) {+ sessions.remove(key)?.let { runCatching { it.close() } }+ }+ }++ /** Drop every cached session. Idempotent. For tests and process teardown. */+ fun closeAll() {+ synchronized(lock) {+ sessions.keys.toList().forEach { close(it) }+ }+ }+}++/** A model handle that owns exactly one cached [OnnxSessions] entry. */+abstract class OnnxHandle protected constructor(private val sessionKey: String) : Closeable {+ /** True when the session opened and can run. */+ abstract val isAvailable: Boolean++ /** Release this handle's session. Idempotent. */+ override fun close() = OnnxSessions.close(sessionKey)+}
library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.ktindex e82f1eae69..a7b4355143 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SelfieSegmenter.kt@@ -1,46 +1,104 @@ package com.vayunmathur.library.ml +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap+import android.util.Log+import java.nio.FloatBuffer /** * Person-versus-background segmentation, for `:camera`'s portrait bokeh. *- * **MediaPipe Selfie Segmentation** (Apache-2.0), run on Vulkan compute at 256×256 with- * fp16 weights. See `camera/src/main/assets/README.md` for provenance and- * `library/ml/src/main/rust/src/nets/selfie.rs` for the forward pass.+ * **MediaPipe Selfie Segmentation** (Apache-2.0) at 256×256, run on the reduced ONNX Runtime+ * build. See `camera/src/main/assets/README.md` for provenance.+ *+ * Replaces the Vulkan `NativeSegmenter` path (`MlNative::createSelfie`): the graph is the+ * upstream export (`pixel_values [1,3,256,256]` in, `alphas [1,1,256,256]` out), so the+ * resize (`OnnxPreprocess.stretchPlanar`, straight scale) and `RESCALE_ONLY` normalisation+ * now happen here in Kotlin rather than natively. * * Replaces `com.vayunmathur.ncnn.PortraitSegmenter` and its `erdnet` model, which shipped * with no upstream URL, license or conversion recipe. This is a different model rather * than a port of that one, so its masks differ. *- * GPU-only: if [isAvailable] is false the device has no Vulkan fp16 compute and [segment]- * returns null, which callers treat as "no mask" rather than as an error.+ * CPU-backed: if [isAvailable] is false the model is missing or has an operator outside+ * the reduced build, and [segment] returns null, which callers treat as "no mask" rather+ * than as an error. * * Not thread-safe: [segment] and [close] must not overlap. * * @param context used only to read the asset; not retained.- * @param assetName the `.maml` in the app's assets.+ * @param assetName the `.onnx` in the app's assets. */ class SelfieSegmenter(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {+ private val app = context.applicationContext+ private val asset = assetName+ private val lock = Any() - private val native =- NativeSegmenter(context, assetName, "SelfieSegmenter", MlNative::createSelfie)+ @Volatile private var session: OrtSession? = null+ @Volatile private var loadTried = false /** Whether the network came up. False means portrait bokeh is off on this device. */- val isAvailable: Boolean get() = native.isAvailable+ val isAvailable: Boolean get() = ensure() /** * Run the network over [bitmap] and return a 256×256 mask, or null on failure. *- * [bitmap] may be any size and any config: it is resized and normalised natively.+ * [bitmap] may be any size and any config: it is resized and normalised here. */- fun segment(bitmap: Bitmap): SegmentationMask? = native.segment(bitmap)+ fun segment(bitmap: Bitmap): SegmentationMask? {+ if (!ensure()) return null+ val live = session ?: return null+ val (pixels, readable) = OnnxPreprocess.readablePixels(bitmap) ?: return null+ try {+ val input = OnnxPreprocess.stretchPlanar(+ pixels, readable.width, readable.height,+ SIZE, SIZE, OnnxPreprocess.RESCALE_ONLY,+ )+ val env = OrtEnvironment.getEnvironment()+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, SIZE.toLong(), SIZE.toLong())).use { tensor ->+ live.run(mapOf(INPUT to tensor)).use { result ->+ val out = result[0] as OnnxTensor+ val flat = FloatArray(SIZE * SIZE)+ out.floatBuffer.get(flat)+ return SegmentationMask(SIZE, SIZE, flat)+ }+ }+ } catch (e: Throwable) {+ Log.e(TAG, "selfie inference failed", e)+ return null+ } finally {+ if (readable !== bitmap) readable.recycle()+ }+ }++ override fun close() {+ synchronized(lock) {+ session = null+ OnnxSessions.close(sessionKey())+ }+ }++ private fun sessionKey() = "asset:$asset" - override fun close() = native.close()+ private fun ensure(): Boolean {+ session?.let { return true }+ synchronized(lock) {+ session?.let { return true }+ if (loadTried) return false+ loadTried = true+ session = OnnxSessions.openAsset(app, asset)+ return session != null+ }+ } companion object { /** What `:camera` ships. */- const val DEFAULT_ASSET: String = "selfie_segmentation.maml"+ const val DEFAULT_ASSET: String = "selfie_segmentation.onnx"+ private const val TAG = "SelfieSegmenter"+ private const val SIZE = 256+ private const val INPUT = "pixel_values" } }
library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.ktindex 88b9d96c47..91e9c16030 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SubjectSegmenter.kt@@ -1,50 +1,106 @@ package com.vayunmathur.library.ml +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap+import android.util.Log+import java.nio.FloatBuffer /** * General salient-object detection, for `:photos`'s auto-select-subject. *- * **U²-Net portable** (Apache-2.0), run on Vulkan compute at 320×320 with fp16 weights.- * Unlike [SelfieSegmenter] it is not person-specific: it predicts a per-pixel saliency map- * and so picks out arbitrary subjects. See `photos/src/main/assets/README.md` for- * provenance and `library/ml/src/main/rust/src/nets/u2netp.rs` for the forward pass.+ * **U²-Net portable** (Apache-2.0) at 320×320, run on the reduced ONNX Runtime build. Unlike+ * [SelfieSegmenter] it is not person-specific: it predicts a per-pixel saliency map and so+ * picks out arbitrary subjects. See `photos/src/main/assets/README.md` for provenance.+ *+ * Replaces the Vulkan `NativeSegmenter` path (`MlNative::createU2netp`): the graph is the+ * upstream export (`input.1 [1,3,320,320]` in, seven `[1,1,320,320]` maps out), of which+ * only output 0 — the fused `d0`, the same output the MAML `record(&[d0])` produced — is+ * read. The stretch resize and ImageNet normalisation now happen here in Kotlin. * * Replaces `com.vayunmathur.ncnn.Segmenter`. Same network, re-sourced from a licensed ONNX * export — the ncnn model's op inventory matched it exactly — so masks should look the * same as before, unlike `:camera`'s. *- * Its activation arena is 76 MiB of device memory, so [close] it when the editor session- * ends rather than holding it for the life of the process.- *- * GPU-only: if [isAvailable] is false the device has no Vulkan fp16 compute and [segment]+ * CPU-backed: if [isAvailable] is false the model is missing or un-runnable and [segment] * returns null, which the caller treats as "no subject found". * * Not thread-safe: [segment] and [close] must not overlap. * * @param context used only to read the asset; not retained.- * @param assetName the `.maml` in the app's assets.+ * @param assetName the `.onnx` in the app's assets. */ class SubjectSegmenter(context: Context, assetName: String = DEFAULT_ASSET) : AutoCloseable {+ private val app = context.applicationContext+ private val asset = assetName+ private val lock = Any() - private val native =- NativeSegmenter(context, assetName, "SubjectSegmenter", MlNative::createU2netp)+ @Volatile private var session: OrtSession? = null+ @Volatile private var loadTried = false - /** Whether the network came up. False means auto-select-subject is off on this device. */- val isAvailable: Boolean get() = native.isAvailable+ /** Whether the network came up. False means auto-select-subject is off. */+ val isAvailable: Boolean get() = ensure() /** * Run the network over [bitmap] and return a 320×320 saliency map, or null on failure. *- * [bitmap] may be any size and any config: it is resized and normalised natively.+ * [bitmap] may be any size and any config: it is resized and normalised here. */- fun segment(bitmap: Bitmap): SegmentationMask? = native.segment(bitmap)+ fun segment(bitmap: Bitmap): SegmentationMask? {+ if (!ensure()) return null+ val live = session ?: return null+ val (pixels, readable) = OnnxPreprocess.readablePixels(bitmap) ?: return null+ try {+ val input = OnnxPreprocess.stretchPlanar(+ pixels, readable.width, readable.height,+ SIZE, SIZE, OnnxPreprocess.IMAGENET,+ )+ val env = OrtEnvironment.getEnvironment()+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, SIZE.toLong(), SIZE.toLong())).use { tensor ->+ live.run(mapOf(INPUT to tensor), setOf(OUTPUT)).use { result ->+ val out = result[0] as OnnxTensor+ val flat = FloatArray(SIZE * SIZE)+ out.floatBuffer.get(flat)+ return SegmentationMask(SIZE, SIZE, flat)+ }+ }+ } catch (e: Throwable) {+ Log.e(TAG, "u2netp inference failed", e)+ return null+ } finally {+ if (readable !== bitmap) readable.recycle()+ }+ } - override fun close() = native.close()+ override fun close() {+ synchronized(lock) {+ session = null+ OnnxSessions.close(sessionKey())+ }+ }++ private fun sessionKey() = "asset:$asset"++ private fun ensure(): Boolean {+ session?.let { return true }+ synchronized(lock) {+ session?.let { return true }+ if (loadTried) return false+ loadTried = true+ session = OnnxSessions.openAsset(app, asset)+ return session != null+ }+ } companion object { /** What `:photos` ships. */- const val DEFAULT_ASSET: String = "u2netp.maml"+ const val DEFAULT_ASSET: String = "u2netp.onnx"+ private const val TAG = "SubjectSegmenter"+ private const val SIZE = 320+ private const val INPUT = "input.1"+ /** The fused `d0` output: graph output 0, the only one the MAML path produced. */+ private const val OUTPUT = "1959" } }
library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.ktindex 31686725cc..217d54b149 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/TextRecognizer.kt@@ -1,8 +1,20 @@ package com.vayunmathur.library.ml +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap import android.util.Log+import java.nio.FloatBuffer+import kotlin.math.abs+import kotlin.math.atan2+import kotlin.math.cos+import kotlin.math.max+import kotlin.math.min+import kotlin.math.roundToInt+import kotlin.math.sin+import kotlin.math.sqrt /** * One recognised line of text, in source-bitmap pixel coordinates.@@ -25,35 +37,33 @@ data class RecognizedLine( } /**- * On-device text recognition: PP-OCRv5 mobile detection and recognition on Vulkan compute.+ * On-device text recognition: PP-OCRv5 mobile detection and recognition on the reduced ONNX+ * Runtime build. *- * Replaces the ncnn PP-OCR path. The detector is DBNet over a PP-HGNetV2 backbone and the- * recogniser is a PP-LCNetV3 backbone into a two-block transformer with a CTC head, both- * converted to `.maml` by `scripts/ml/ppocr_fold.py`. The recogniser is the **latin** model- * - 836 characters covering Latin-script languages, no CJK - which is what keeps it under- * 4 MB.+ * The detector is DBNet over a PP-HGNetV2 backbone and the recogniser is a PP-LCNetV3+ * backbone into a two-block transformer with a CTC head. The recogniser is the **latin**+ * model - 836 characters covering Latin-script languages, no CJK - which is what keeps it+ * under 8 MB. *- * Everything between the two networks happens natively: the rotated crop out of each- * detected quad, the CTC collapse, and reading order. So [recognize] crosses the JNI- * boundary once per bitmap rather than once per line.+ * Replaces the Vulkan `MlNative` path (`createPpocr`/`recognizeText`): both graphs are the+ * upstream exports (`ppocr_det`: `x [B,3,H,W]` in, `fetch_name_0 [B,1,H,W]` probability map+ * out; `ppocr_rec`: `x [B,3,48,W]` in, `fetch_name_0 [B,T,838]` logits out). Everything+ * between the two networks — DBNet regions, the rotated crop, CTC collapse, reading order —+ * is ported from `post::{dbnet,crop,ctc,ocr}` and now runs here in Kotlin rather than+ * natively, crossing one session per region instead of one JNI call per bitmap. * * # Availability *- * The constructor never throws. [isAvailable] is false when `libmodelrunner.so` is missing- * for this ABI, when an asset is absent, or when the device cannot give us a Vulkan device- * with fp16 compute - and then [recognize] returns an empty list. Vulkan 1.1 with- * `shaderFloat16` is available across the minSdk 31 fleet, so this is a guard rather than- * an expected path.+ * The constructor never throws. [isAvailable] is false when a model is absent or has an+ * operator outside the reduced build - and then [recognize] returns an empty list. * * # Threading * * Not thread-safe, and holding a lock across the whole of [recognize] and [close] is- * required rather than advisable: the native handle is freed by [close] and reading it- * afterwards is a use-after-free. See `BokehAnalyzer`, whose comments record what that- * looked like when it happened.+ * required rather than advisable. *- * Not cheap to construct either - two nets, two arenas, two command buffers - so build one- * per batch of images and [close] it, rather than one per image.+ * Not cheap to construct either - two sessions - so build one per batch of images and+ * [close] it, rather than one per image. */ class TextRecognizer( context: Context,@@ -61,94 +71,460 @@ class TextRecognizer( recognitionAsset: String = RECOGNITION_ASSET, dictionaryAsset: String = DICTIONARY_ASSET, ) : AutoCloseable {- private var handle: Long = 0L- private var pixels: IntArray? = null+ private val app = context.applicationContext+ private val detAsset = detectionAsset+ private val recAsset = recognitionAsset+ private val lock = Any()++ @Volatile private var det: OrtSession? = null+ @Volatile private var rec: OrtSession? = null+ @Volatile private var dictionary: List<String>? = null+ @Volatile private var loadTried = false init {- handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- val assets = context.assets- val detection = assets.open(detectionAsset).use { it.readBytes() }- val recognition = assets.open(recognitionAsset).use { it.readBytes() }- val keys = assets.open(dictionaryAsset).use { it.readBytes() }.decodeToString()- MlNative.createPpocr(detection, recognition, keys)- } catch (e: Throwable) {- Log.e(TAG, "cannot open the PP-OCRv5 assets", e)- 0L- }+ try {+ val text = app.assets.open(dictionaryAsset).use { it.readBytes() }.decodeToString()+ dictionary = parseDictionary(text)+ } catch (e: Throwable) {+ Log.e(TAG, "cannot open the PP-OCRv5 dictionary", e)+ dictionary = null } } /** True if both networks came up and the dictionary parsed. */- val isAvailable: Boolean get() = handle != 0L+ val isAvailable: Boolean get() = ensure() /** * Recognise every line in [bitmap], in reading order. * * Returns an empty list when there is no text, when the engine is unavailable, or when- * the pass failed - all three are "no text here" to a caller, and the reason is in- * logcat under `ModelRunner`. The caller's [bitmap] is not recycled.+ * the pass failed - all three are "no text here" to a caller. The caller's [bitmap] is+ * not recycled. */ fun recognize(bitmap: Bitmap): List<RecognizedLine> {- if (handle == 0L) return emptyList()- // `HARDWARE` bitmaps cannot be read with getPixels, and a null config means the- // bitmap was already recycled.- val readable = if (bitmap.config == Bitmap.Config.ARGB_8888) {- bitmap- } else {- bitmap.copy(Bitmap.Config.ARGB_8888, false) ?: return emptyList()- }+ if (!ensure()) return emptyList()+ val detSession = det ?: return emptyList()+ val recSession = rec ?: return emptyList()+ val dict = dictionary ?: return emptyList()+ val (pixels, readable) = OnnxPreprocess.readablePixels(bitmap) ?: return emptyList() try {- val count = readable.width * readable.height- val buffer = pixels?.takeIf { it.size == count } ?: IntArray(count).also { pixels = it }- readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)- val packed = MlNative.recognizeText(handle, buffer, readable.width, readable.height)- ?: return emptyList()- return parse(packed)+ val fit = OnnxPreprocess.SquareFit.of(readable.width, readable.height, DET_SIDE)+ val input = OnnxPreprocess.letterboxPlanar(+ pixels, readable.width, readable.height, DET_SIDE, fit, OnnxPreprocess.PPOCR_DET,+ )+ val env = OrtEnvironment.getEnvironment()+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, DET_SIDE.toLong(), DET_SIDE.toLong())).use { tensor ->+ detSession.run(mapOf(DET_INPUT to tensor)).use { result ->+ val map = FloatArray(DET_SIDE * DET_SIDE)+ ((result.get(DET_OUTPUT).get()) as OnnxTensor).floatBuffer.get(map)+ val regions = dbnetRegions(map, DET_SIDE, DET_SIDE, fit)+ val lines = ArrayList<RecognizedLine>(regions.size)+ for (region in regions) {+ val line = recognizeRegion(+ region, pixels, readable.width, readable.height,+ recSession, env, dict,+ ) ?: continue+ lines += line+ }+ orderReading(lines)+ return lines+ }+ }+ } catch (e: Throwable) {+ Log.e(TAG, "OCR failed", e)+ return emptyList() } finally { if (readable !== bitmap) readable.recycle() } } - /** Free both networks. Idempotent. */+ /** Free both sessions. Idempotent. */ override fun close() {- val live = handle- handle = 0L- pixels = null- if (live != 0L) MlNative.destroyOcr(live)+ synchronized(lock) {+ det = null+ rec = null+ OnnxSessions.close("asset:$detAsset")+ OnnxSessions.close("asset:$recAsset")+ }+ }++ private fun ensure(): Boolean {+ if (det != null && rec != null && dictionary != null) return true+ synchronized(lock) {+ if (det != null && rec != null && dictionary != null) return true+ if (loadTried) return false+ loadTried = true+ det = OnnxSessions.openAsset(app, detAsset)+ rec = OnnxSessions.openAsset(app, recAsset)+ return det != null && rec != null && dictionary != null+ }+ }++ // -- Dictionary -----------------------------------------------------------++ private fun parseDictionary(text: String): List<String>? {+ val entries = text.lineSequence()+ .map { it.trimEnd('\r') }+ .filter { it.isNotEmpty() }+ .toList()+ if (entries.size != DICTIONARY_ENTRIES) {+ Log.e(TAG, "${entries.size} dictionary entries, expected $DICTIONARY_ENTRIES")+ return null+ }+ if (entries.any { it.codePointCount(0, it.length) != 1 }) {+ Log.e(TAG, "a dictionary entry is not a single character")+ return null+ }+ return entries + " "+ }++ // -- DBNet ----------------------------------------------------------------++ private data class RotatedRect(+ var cx: Float, var cy: Float,+ var width: Float, var height: Float,+ var angle: Float,+ ) {+ fun normalise() {+ while (angle >= 0f) {+ angle -= 90f+ val t = width; width = height; height = t+ }+ while (angle < -90f) {+ angle += 90f+ val t = width; width = height; height = t+ }+ }+ }++ private data class Region(val rect: RotatedRect, val score: Float, val vertical: Boolean)++ private fun dbnetRegions(+ probability: FloatArray,+ width: Int,+ height: Int,+ fit: OnnxPreprocess.SquareFit,+ ): List<Region> {+ val cells = width * height+ val text = BooleanArray(cells) { probability[it] >= DB_THRESHOLD }+ val labelled = BooleanArray(cells)+ val stack = ArrayList<Int>(1024)+ val boundary = ArrayList<Pair<Float, Float>>(256)+ val found = ArrayList<Region?>(64)+ for (start in 0 until cells) {+ if (found.size >= MAX_CANDIDATES) break+ if (!text[start] || labelled[start]) continue+ labelled[start] = true+ stack.clear()+ stack += start+ boundary.clear()+ var total = 0.0+ var count = 0+ while (stack.isNotEmpty()) {+ val at = stack.removeAt(stack.lastIndex)+ val x = at % width+ val y = at / width+ total += probability[at]+ count+++ val edge = x == 0 || y == 0 || x + 1 == width || y + 1 == height ||+ !text[at - 1] || !text[at + 1] || !text[at - width] || !text[at + width]+ if (edge) boundary += Pair(x.toFloat(), y.toFloat())+ for (dy in -1..1) {+ val ny = y + dy+ if (ny < 0 || ny >= height) continue+ for (dx in -1..1) {+ val nx = x + dx+ if (nx < 0 || nx >= width) continue+ val next = ny * width + nx+ if (text[next] && !labelled[next]) {+ labelled[next] = true+ stack += next+ }+ }+ }+ }+ val score = if (count > 0) (total / count).toFloat() else 0f+ if (score < BOX_THRESHOLD) {+ found += null+ continue+ }+ val rect = minAreaRect(boundary) ?: run { found += null; continue }+ if (max(rect.width, rect.height) < MIN_SIZE) {+ found += null+ continue+ }+ if (rect.width > rect.height) {+ val t = rect.width; rect.width = rect.height; rect.height = t+ rect.angle += 90f+ }+ val vertical = rect.height > rect.width * ELONGATED && rect.angle in -30f..30f+ if (vertical || rect.angle <= 0f) rect.angle += 180f+ rect.height += rect.width * (ENLARGE_RATIO - 1f)+ rect.width *= ENLARGE_RATIO+ rect.cx = (rect.cx - fit.offsetX) / fit.scale+ rect.cy = (rect.cy - fit.offsetY) / fit.scale+ rect.width /= fit.scale+ rect.height /= fit.scale+ found += Region(rect, score, vertical)+ }+ return found.filterNotNull()+ }++ private fun convexHull(points: List<Pair<Float, Float>>): List<Pair<Float, Float>> {+ if (points.size < 3) return points.toList()+ val sorted = points.sortedWith(compareBy({ it.first }, { it.second })).distinct()+ fun cross(o: Pair<Float, Float>, a: Pair<Float, Float>, b: Pair<Float, Float>): Float =+ (a.first - o.first) * (b.second - o.second) - (a.second - o.second) * (b.first - o.first)+ val hull = ArrayList<Pair<Float, Float>>(sorted.size + 1)+ for (pass in 0..1) {+ val lower = hull.size+ val iter = if (pass == 0) sorted else sorted.asReversed()+ for (point in iter) {+ while (hull.size >= lower + 2) {+ val a = hull[hull.size - 2]+ val b = hull[hull.size - 1]+ if (cross(a, b, point) > 0f) break+ hull.removeAt(hull.lastIndex)+ }+ hull += point+ }+ hull.removeAt(hull.lastIndex)+ }+ return hull+ }++ private fun minAreaRect(points: List<Pair<Float, Float>>): RotatedRect? {+ val hull = convexHull(points)+ if (hull.isEmpty()) return null+ val first = hull[0]+ if (hull.size == 1) {+ return RotatedRect(first.first, first.second, 0f, 0f, 0f).also { it.normalise() }+ }+ var best: RotatedRect? = null+ var bestArea = Float.MAX_VALUE+ for (index in hull.indices) {+ val a = hull[index]+ val b = hull[(index + 1) % hull.size]+ val dx = b.first - a.first+ val dy = b.second - a.second+ val length = sqrt(dx * dx + dy * dy)+ if (length < 1e-9f) continue+ val ux = dx / length+ val uy = dy / length+ var lowU = Float.MAX_VALUE; var highU = -Float.MAX_VALUE+ var lowV = Float.MAX_VALUE; var highV = -Float.MAX_VALUE+ for ((x, y) in hull) {+ val u = x * ux + y * uy+ val v = -x * uy + y * ux+ lowU = min(lowU, u); highU = max(highU, u)+ lowV = min(lowV, v); highV = max(highV, v)+ }+ val area = (highU - lowU) * (highV - lowV)+ if (area >= bestArea) continue+ bestArea = area+ val midU = (lowU + highU) * 0.5f+ val midV = (lowV + highV) * 0.5f+ best = RotatedRect(+ midU * ux - midV * uy, midU * uy + midV * ux,+ highU - lowU, highV - lowV,+ atan2(dy, dx) * 180f / Math.PI.toFloat(),+ ).also { it.normalise() }+ }+ return best ?: RotatedRect(first.first, first.second, 0f, 0f, 0f).also { it.normalise() }+ }++ // -- Crop -----------------------------------------------------------------++ private fun rectCorners(rect: RotatedRect): Array<Pair<Float, Float>> {+ val radians = rect.angle * Math.PI.toFloat() / 180f+ val sin = sin(radians)+ val cos = cos(radians)+ val along = rect.height * 0.5f+ val across = rect.width * 0.5f+ val alongX = -sin; val alongY = cos+ val acrossX = cos; val acrossY = sin+ fun corner(a: Float, b: Float) = Pair(+ rect.cx + alongX * a + acrossX * b,+ rect.cy + alongY * a + acrossY * b,+ )+ return arrayOf(+ corner(-along, -across), corner(along, -across),+ corner(along, across), corner(-along, across),+ )+ }++ private fun cropWidth(region: Region): Int {+ val short = max(region.rect.width, 1f)+ val long = max(region.rect.height, 1f)+ val scaled = max(REC_HEIGHT * long / short, 1f)+ val wanted = min(kotlin.math.round(scaled).toInt(), REC_WIDTH).coerceAtLeast(WIDTH_MULTIPLE)+ return ((wanted + WIDTH_MULTIPLE - 1) / WIDTH_MULTIPLE) * WIDTH_MULTIPLE+ }++ private fun warp(+ pixels: IntArray, width: Int, height: Int,+ corners: Array<Pair<Float, Float>>, outW: Int, outH: Int,+ ): IntArray {+ val origin = corners[0]+ val along = Pair(corners[1].first - corners[0].first, corners[1].second - corners[0].second)+ val across = Pair(corners[3].first - corners[0].first, corners[3].second - corners[0].second)+ val out = IntArray(outW * outH)+ for (y in 0 until outH) {+ val v = (y + 0.5f) / outH+ for (x in 0 until outW) {+ val u = (x + 0.5f) / outW+ val sx = origin.first + along.first * u + across.first * v+ val sy = origin.second + along.second * u + across.second * v+ out[y * outW + x] = bilinear(pixels, width, height, sx, sy)+ }+ }+ return out+ }++ private fun bilinear(pixels: IntArray, width: Int, height: Int, x: Float, y: Float): Int {+ val cx = x.coerceIn(0f, (width - 1).toFloat())+ val cy = y.coerceIn(0f, (height - 1).toFloat())+ val x0 = cx.toInt()+ val y0 = cy.toInt()+ val wx = cx - x0+ val wy = cy - y0+ val x1 = min(x0 + 1, width - 1)+ val y1 = min(y0 + 1, height - 1)+ fun at(px: Int, py: Int): Int = pixels[py * width + px]+ fun channel(shift: Int): Int {+ fun take(packed: Int): Float = ((packed shr shift) and 0xFF).toFloat()+ val top = take(at(x0, y0)) + (take(at(x1, y0)) - take(at(x0, y0))) * wx+ val bottom = take(at(x0, y1)) + (take(at(x1, y1)) - take(at(x0, y1))) * wx+ return (top + (bottom - top) * wy).roundToInt().coerceIn(0, 255)+ }+ return (0xFF shl 24) or (channel(16) shl 16) or (channel(8) shl 8) or channel(0)+ }++ // -- Recognition ----------------------------------------------------------++ private fun recognizeRegion(+ region: Region,+ pixels: IntArray, width: Int, height: Int,+ recSession: OrtSession, env: OrtEnvironment, dict: List<String>,+ ): RecognizedLine? {+ val corners = rectCorners(region.rect)+ val content = cropWidth(region).coerceIn(WIDTH_MULTIPLE, REC_WIDTH)+ val cropped = warp(pixels, width, height, corners, content, REC_HEIGHT)+ val strip = if (content == REC_WIDTH) {+ cropped+ } else {+ val pad = (0xFF shl 24) or (PAD_LEVEL shl 16) or (PAD_LEVEL shl 8) or PAD_LEVEL+ val out = IntArray(REC_WIDTH * REC_HEIGHT) { pad }+ for (row in 0 until REC_HEIGHT) {+ cropped.copyInto(out, row * REC_WIDTH, row * content, row * content + content)+ }+ out+ }+ // Recognition normalisation is BGR `(v / 255 - 0.5) / 0.5`, planar, 48 x 320.+ val plane = REC_WIDTH * REC_HEIGHT+ val input = FloatArray(3 * plane)+ for (y in 0 until REC_HEIGHT) {+ for (x in 0 until REC_WIDTH) {+ val argb = strip[y * REC_WIDTH + x]+ val ch = intArrayOf(argb and 0xFF, (argb shr 8) and 0xFF, (argb shr 16) and 0xFF)+ for (c in 0..2) {+ input[c * plane + y * REC_WIDTH + x] = (ch[c] / 255f - 0.5f) / 0.5f+ }+ }+ }+ OnnxTensor.createTensor(env, FloatBuffer.wrap(input), longArrayOf(1, 3, REC_HEIGHT.toLong(), REC_WIDTH.toLong())).use { tensor ->+ recSession.run(mapOf(REC_INPUT to tensor)).use { result ->+ val timesteps = REC_TIMESTEPS+ val flat = FloatArray(timesteps * LOGITS)+ ((result.get(REC_OUTPUT).get()) as OnnxTensor).floatBuffer.get(flat)+ // Export is batch-major [T, 838]; the decode reads class-major [838, T].+ val used = content / WIDTH_MULTIPLE+ val decoded = ctcDecode(flat, timesteps, used, dict) ?: return null+ val text = decoded.first.trim()+ if (text.isEmpty()) return null+ val quad = corners.map { Pair(it.first, it.second) }+ return RecognizedLine(text, decoded.second, quad, region.vertical)+ }+ }+ }++ private fun ctcDecode(+ batchMajor: FloatArray, timesteps: Int, used: Int, dict: List<String>,+ ): Pair<String, Float>? {+ if (timesteps == 0 || used > timesteps) return null+ fun at(label: Int, step: Int): Float = batchMajor[step * LOGITS + label]+ val text = StringBuilder()+ var total = 0.0+ var kept = 0+ var previous = -1+ for (step in 0 until used) {+ var best = 0+ var peak = at(0, step)+ for (label in 1 until LOGITS) {+ val value = at(label, step)+ if (value > peak) {+ peak = value+ best = label+ }+ }+ if (best != previous) {+ val character = if (best == 0) null else dict.getOrNull(best - 1)+ if (character != null) {+ var denominator = 0.0+ for (label in 0 until LOGITS) {+ denominator += Math.exp((at(label, step) - peak).toDouble())+ }+ text.append(character)+ total += 1.0 / denominator+ kept+++ }+ }+ previous = best+ }+ val confidence = if (kept > 0) (total / kept).toFloat() else 0f+ return Pair(text.toString(), confidence)+ }++ private fun orderReading(lines: MutableList<RecognizedLine>) {+ fun centre(line: RecognizedLine): Pair<Float, Float> {+ val sx = line.corners.sumOf { it.first.toDouble() }.toFloat() / 4f+ val sy = line.corners.sumOf { it.second.toDouble() }.toFloat() / 4f+ return Pair(sx, sy)+ }+ lines.sortWith { a, b ->+ val (ax, ay) = centre(a)+ val (bx, by) = centre(b)+ val bandA = (ay / ROW_BAND).toInt()+ val bandB = (by / ROW_BAND).toInt()+ if (bandA != bandB) bandA - bandB else ax.compareTo(bx)+ } } private companion object { private const val TAG = "TextRecognizer"- const val DETECTION_ASSET = "ppocr_det.maml"- const val RECOGNITION_ASSET = "ppocr_rec.maml"+ const val DETECTION_ASSET = "ppocr_det.onnx"+ const val RECOGNITION_ASSET = "ppocr_rec.onnx" const val DICTIONARY_ASSET = "ppocr_keys.txt" - /** Text, then eight quad coordinates, then confidence, then the vertical flag. */- private const val FIELDS = 11-- /**- * Unpack what `MlNative.recognizeText` returns.- *- * A malformed region is dropped rather than throwing: the native side and this- * function have to agree about eleven fields, and losing one line is a better- * failure than losing the image.- */- fun parse(packed: String): List<RecognizedLine> {- if (packed.isEmpty()) return emptyList()- return packed.split('\n').mapNotNull { row ->- val fields = row.split('\t')- if (fields.size != FIELDS) return@mapNotNull null- val numbers = fields.drop(1).map { it.toFloatOrNull() ?: return@mapNotNull null }- RecognizedLine(- text = fields[0],- confidence = numbers[8],- corners = List(4) { Pair(numbers[it * 2], numbers[it * 2 + 1]) },- vertical = numbers[9] != 0f,- )- }- }+ private const val DET_SIDE = 960+ private const val DET_INPUT = "x"+ private const val DET_OUTPUT = "fetch_name_0"+ private const val REC_INPUT = "x"+ private const val REC_OUTPUT = "fetch_name_0"+ private const val REC_HEIGHT = 48+ private const val REC_WIDTH = 320+ private const val WIDTH_MULTIPLE = 8+ private const val REC_TIMESTEPS = 40+ private const val LOGITS = 838+ private const val DICTIONARY_ENTRIES = 836++ private const val DB_THRESHOLD = 0.3f+ private const val BOX_THRESHOLD = 0.6f+ private const val ENLARGE_RATIO = 1.95f+ private const val MIN_SIZE = 3.0f+ private const val MAX_CANDIDATES = 1000+ private const val ELONGATED = 2.7f+ private const val PAD_LEVEL = 128+ private const val ROW_BAND = 16f } }
library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.ktindex 95553fa213..adf49ba26b 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/WhisperHandle.kt@@ -1,30 +1,32 @@ package com.vayunmathur.library.ml +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.res.AssetManager-import android.os.ParcelFileDescriptor import android.util.Log+import java.nio.FloatBuffer+import java.nio.LongBuffer /**- * On-device speech recognition in ~99 languages: whisper-base on the Vulkan compute runtime.+ * On-device speech recognition in ~99 languages: whisper-base on the reduced ONNX Runtime+ * build. * * A two-convolution stem that turns `[80, 3000]` log-mel frames into 1500 positions, 6 encoder * layers, and 6 decoder layers with self and cross attention; `d_model` 512, 8 heads of 64, and a * 51,865-entry vocabulary tied between the input embedding and the logits projection. 72.6 million- * parameters. See `library/ml/src/main/rust/src/nets/whisper.rs`.+ * parameters. *- * # One bundled asset, 70.6 MiB+ * # Two bundled assets *- * `whisper_base.maml` ships inside the APK, so this has an [inAssets] and no download. Everything- * but the layer norms, the biases and the two position tables is int8, quantised per output channel- * from `openai/whisper-base`'s fp32 checkpoint.+ * `whisper-base/encoder_model_int8.onnx` and `whisper-base/decoder_model_merged_int8.onnx`+ * ship inside the APK, so this has an [inAssets] and no download. The decoder is the merged+ * export: it takes all 24 `past_key_values.*` inputs on every call (zero-length with+ * `use_cache_branch = false` on the first step, which makes it compute cross-attention K/V+ * from `encoder_hidden_states`) and returns `present.*` for the next step. *- * It replaces `onnxruntime-reduced-android` running two int8 ONNX exports totalling 76.9 MB, and is- * **four times closer** to the fp32 checkpoint than they were: over the encoder's output, mean- * absolute error 0.029 against their 0.110, on a tensor whose largest value is 22.8. The APK loses- * 10,466,856 bytes of arm64 `.so` with the runtime — about 3.6 MiB of the packaged size.- *- * 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 `speech/build.gradle.kts` is for.+ * An asset must be stored **uncompressed**: `noCompress += "onnx"` in+ * `speech/build.gradle.kts`. * * # The special ids come from the asset, not from here *@@ -36,27 +38,30 @@ import android.util.Log * # Latency * * The encoder is ~43.7 GMAC per 30-second window regardless of how much speech is in it, and every- * decode step re-records the network because the self-attention cache grows. This is not a real-time- * recogniser; call it from a worker.+ * decode step runs the full decoder. This is not a real-time recogniser; call it from a worker. * * # Availability *- * Construction never throws. [isAvailable] is false when `libmodelrunner.so` is missing for this- * ABI, when the asset is absent, compressed or malformed, when the ids do not describe this model,- * or when the device cannot give us a Vulkan device with fp16 compute — and then [transcribe]- * returns null.+ * Construction never throws. [isAvailable] is false when an asset is absent or has an+ * operator outside the reduced build, or when the ids do not describe this model — and then+ * [transcribe] returns null. * * # Threading *- * Not thread-safe, and more sharply than most handles here: a transcription re-records the network- * once per decoded token, so two concurrent calls would interleave recordings of the same command- * buffer. A caller must hold a lock across [transcribe] and [close].+ * Not thread-safe, and more sharply than most handles here: a transcription threads the KV+ * cache through one decode step per token, so two concurrent calls would interleave cache+ * states. A caller must hold a lock across [transcribe] and [close]. */ class WhisperHandle private constructor(private val source: String) : AutoCloseable {- private var handle: Long = 0L+ private var encoder: OrtSession? = null+ private var decoder: OrtSession? = null+ private var special: IntArray = IntArray(0)+ private var suppress: Set<Int> = emptySet()+ private var suppressAtBegin: Set<Int> = emptySet()+ private var assetDir: String = DIR - /** True if the graph came up and the ids describe the model it was built from. */- val isAvailable: Boolean get() = handle != 0L+ /** True if both graphs came up and the ids describe the model they were built from. */+ val isAvailable: Boolean get() = encoder != null && decoder != null /** * Transcribe one 30-second log-mel window into token ids, or null on failure.@@ -66,20 +71,181 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea * timestamp ones. */ fun transcribe(mel: FloatArray, languageToken: Int): IntArray? {- if (handle == 0L) return null+ val enc = encoder ?: return null+ val dec = decoder ?: return null if (mel.size != MELS * FRAMES) return null- return MlNative.transcribeWhisper(handle, mel, languageToken)+ if (special.size != SPECIAL_IDS) return null+ return try {+ val env = OrtEnvironment.getEnvironment()+ encode(enc, env, mel).use { hidden ->+ val lang = if (languageToken < 0) {+ detectLanguage(dec, env, hidden) ?: return null+ } else {+ languageToken+ }+ val prompt = intArrayOf(+ special[0], lang, special[2], special[3],+ )+ greedyDecode(dec, env, hidden, prompt).toIntArray()+ }+ } catch (e: Throwable) {+ Log.e(TAG, "whisper transcription failed", e)+ null+ } } - /** Free the network and close the weights file. Idempotent. */+ /** Free both networks. Idempotent. */ override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyWhisper(live)+ encoder = null+ decoder = null+ OnnxSessions.close("asset:$assetDir/$ENCODER")+ OnnxSessions.close("asset:$assetDir/$DECODER") } override fun toString(): String = "whisper-base from $source" + private fun encode(enc: OrtSession, env: OrtEnvironment, mel: FloatArray): OnnxTensor {+ val shape = longArrayOf(1, MELS.toLong(), FRAMES.toLong())+ OnnxTensor.createTensor(env, FloatBuffer.wrap(mel), shape).use { input ->+ enc.run(mapOf("input_features" to input)).use { result ->+ val out = result.get(0) as OnnxTensor+ val buf = FloatArray(out.info.shape.fold(1L) { a, b -> a * b }.toInt())+ out.floatBuffer.get(buf)+ return OnnxTensor.createTensor(env, FloatBuffer.wrap(buf), out.info.shape)+ }+ }+ }++ private fun detectLanguage(dec: OrtSession, env: OrtEnvironment, hidden: OnnxTensor): Int? {+ return try {+ emptyPast(env).use { past ->+ val ids = OnnxTensor.createTensor(+ env, LongBuffer.wrap(longArrayOf(special[0].toLong())), longArrayOf(1, 1),+ )+ ids.use {+ dec.run(feeds(hidden, past, it, useCache = false)).use { result ->+ val logits = result.get(0) as OnnxTensor+ val vocab = logits.info.shape.last().toInt()+ val row = FloatArray(vocab)+ logits.floatBuffer.position(0)+ logits.floatBuffer.get(row)+ val fallback = 50259+ var best = fallback+ var bestScore = -Float.MAX_VALUE+ for (id in languages) {+ if (id < vocab && row[id] > bestScore) {+ bestScore = row[id]+ best = id+ }+ }+ best+ }+ }+ }+ } catch (e: Throwable) {+ Log.w(TAG, "language detection failed, assuming en", e)+ 50259+ }+ }++ private fun greedyDecode(+ dec: OrtSession,+ env: OrtEnvironment,+ hidden: OnnxTensor,+ prompt: IntArray,+ ): List<Int> {+ val out = ArrayList<Int>()+ val limit = (special[4] - prompt.size).coerceAtMost(MAX_NEW_TOKENS)+ var past = emptyPast(env)+ var step = 0+ var next = -1+ try {+ while (step < limit) {+ val ids = if (step == 0) prompt else intArrayOf(next)+ val longIds = LongArray(ids.size) { ids[it].toLong() }+ val idTensor = OnnxTensor.createTensor(+ env, LongBuffer.wrap(longIds), longArrayOf(1, ids.size.toLong()),+ )+ val result = idTensor.use { dec.run(feeds(hidden, past, it, useCache = step > 0)) }+ past.close()+ next = argmax(+ result.get(0) as OnnxTensor,+ suppress = suppress,+ alsoSuppress = if (step == 0) suppressAtBegin else emptySet(),+ )+ past = Past(env, result)+ step+++ if (next == special[1]) break+ out.add(next)+ }+ } finally {+ past.close()+ }+ return out+ }++ private fun argmax(logits: OnnxTensor, suppress: Set<Int>, alsoSuppress: Set<Int>): Int {+ val shape = logits.info.shape+ val seqLen = shape[1].toInt()+ val vocab = shape[2].toInt()+ val row = FloatArray(vocab)+ val buf = logits.floatBuffer+ buf.position((seqLen - 1) * vocab)+ buf.get(row)+ var best = 0+ var bestScore = -Float.MAX_VALUE+ for (i in 0 until vocab) {+ if (i in suppress || i in alsoSuppress) continue+ if (row[i] > bestScore) {+ bestScore = row[i]+ best = i+ }+ }+ return best+ }++ private fun feeds(+ hidden: OnnxTensor,+ past: Past,+ ids: OnnxTensor,+ useCache: Boolean,+ ): Map<String, OnnxTensor> {+ val map = LinkedHashMap<String, OnnxTensor>(20)+ map["input_ids"] = ids+ map["encoder_hidden_states"] = hidden+ for ((name, tensor) in past.tensors()) map[name] = tensor+ map["use_cache_branch"] = if (useCache) past.cacheTrue else past.cacheFalse+ return map+ }++ private var languages: IntArray = IntArray(0)++ private fun emptyPast(env: OrtEnvironment): Past = Past(env, null)++ private inner class Past(private val env: OrtEnvironment, private val result: OrtSession.Result?) {+ val cacheFalse: OnnxTensor = OnnxTensor.createTensor(env, booleanArrayOf(false))+ val cacheTrue: OnnxTensor = OnnxTensor.createTensor(env, booleanArrayOf(true))+ private val empties = ArrayList<OnnxTensor>()++ fun tensors(): List<Pair<String, OnnxTensor>> = PAST_NAMES.map { name ->+ val tensor = if (result == null) {+ OnnxTensor.createTensor(env, FloatBuffer.allocate(0), EMPTY_SHAPE)+ .also { empties.add(it) }+ } else {+ result.get(name.replace("past_key_values", "present")).get() as OnnxTensor+ }+ name to tensor+ }++ fun close() {+ empties.forEach { runCatching { it.close() } }+ empties.clear()+ runCatching { cacheFalse.close() }+ runCatching { cacheTrue.close() }+ runCatching { result?.close() }+ }+ }+ companion object { private const val TAG = "WhisperHandle" @@ -89,8 +255,12 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea /** Mel frames in one 30-second window at a 160-sample hop. */ const val FRAMES = 3000 - /** The one graph. Native checks its graph id, so a wrong file fails at load. */- const val GRAPH = "whisper-base/whisper_base.maml"+ /** Asset directory. */+ const val DIR = "whisper-base"++ /** The two graphs. A wrong file fails at load. */+ const val ENCODER = "encoder_model_int8.onnx"+ const val DECODER = "decoder_model_merged_int8.onnx" /** * The five values [inAssets] wants in `special`, in order:@@ -111,72 +281,39 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea languages: IntArray, suppress: IntArray, suppressAtBegin: IntArray,- path: String = GRAPH,+ path: String = DIR, ): WhisperHandle { val instance = WhisperHandle("the APK's $path")- instance.handle = if (!MlNative.isAvailable || special.size != SPECIAL_IDS) {- if (special.size != SPECIAL_IDS) {- Log.e(TAG, "${special.size} special ids, not $SPECIAL_IDS")- }- 0L- } else {- try {- create(assets, path, special, languages, suppress, suppressAtBegin)- } catch (e: Throwable) {- Log.e(TAG, "cannot open $path", e)- 0L- }+ if (special.size != SPECIAL_IDS) {+ Log.e(TAG, "${special.size} special ids, not $SPECIAL_IDS")+ return instance }+ instance.assetDir = path+ instance.special = special.copyOf()+ instance.languages = languages.copyOf()+ instance.suppress = suppress.toSet()+ instance.suppressAtBegin = suppressAtBegin.toSet()+ instance.encoder = OnnxSessions.openAssetManager(assets, "$path/$ENCODER")+ instance.decoder = OnnxSessions.openAssetManager(assets, "$path/$DECODER")+ if (!instance.isAvailable) Log.e(TAG, "cannot open $path") 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,- special: IntArray,- languages: IntArray,- suppress: IntArray,- suppressAtBegin: IntArray,- ): Long = assets.openFd(path).use { afd ->- val fd = afd.parcelFileDescriptor.detachFd()- var handed = false- try {- val handle = MlNative.createWhisper(- fd,- afd.startOffset,- afd.length,- special,- languages,- suppress,- suppressAtBegin,- )- handed = true- handle- } finally {- if (!handed) closeFd(fd)- }- }+ /** One 30 s window cannot say more than this; guards against a runaway loop. */+ private const val MAX_NEW_TOKENS = 224 - /**- * 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() }+ private const val N_LAYERS = 6+ private const val N_HEADS = 8L+ private const val HEAD_DIM = 64L++ private val EMPTY_SHAPE = longArrayOf(1, N_HEADS, 0, HEAD_DIM)++ private val PAST_NAMES: List<String> = buildList {+ for (i in 0 until N_LAYERS) {+ for (kind in listOf("decoder", "encoder")) {+ for (kv in listOf("key", "value")) add("past_key_values.$i.$kind.$kv")+ }+ } } } }
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex 4b6641583e..ac27e7c4c2 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -29,9 +29,9 @@ dependencies { // display images implementation(project(":library:image")) - // ai: this repo's own Vulkan runtime, which replaced com.google.ai.edge.litertlm and- // its 19.83 MB liblitertlm_jni.so. The weights are the same Gemma 4 E2B, converted to- // .maml by scripts/ml/maml_convert.py.+ // ai: conversational LLM (Gemma) via LiteRT-LM. Vision/OCR/speech models run on+ // :library:ml's reduced ONNX Runtime build; see library/ml/build.gradle.kts.+ implementation(libs.litertlm.android) implementation(project(":library:ml")) // ToolRegistry reflects over AssistantToolSet's @Tool methods. This used to arrive // transitively through the litertlm AAR, so removing that dependency took it away.
speech/build.gradle.kts
diff --git a/speech/build.gradle.kts b/speech/build.gradle.ktsindex a8c41adb91..8c213b33ec 100644--- a/speech/build.gradle.kts+++ b/speech/build.gradle.kts@@ -16,26 +16,20 @@ android { } androidResources {- // Load-bearing, not an optimisation. `AssetManager.openFd` throws for a deflated entry,- // and the fd is how Supertonic's ~105 MB and whisper-base's 70.6 MiB of weights reach the- // GPU without being copied through the Java heap three times - see- // SupertonicSynthesizer.inAssets and WhisperHandle.inAssets. It costs nothing on download- // size either: int8 and fp16 weights are already incompressible.+ // Load-bearing, not an optimisation. The two whisper-base int8 ONNX exports are read+ // straight out of the APK, and a compressed asset would have to be inflated into a+ // heap buffer before ORT could open it. Int8 weights barely deflate, so it costs+ // nothing on download size. (The remaining `maml` entry covers the Supertonic and+ // legacy bundles until Phase 4 deletes them.) noCompress += "maml"+ noCompress += "onnx" } } dependencies {- // Both directions run on :library:ml, our own Vulkan compute runtime, and this app links no- // third-party inference runtime at all.- //- // Text-to-speech is Supertonic 3: four networks for all 31 languages, every one of them on the- // GPU - the duration predictor, the text encoder, a flow-matching sampler and a ConvNeXt- // vocoder. Speech-to-text is whisper-base, one 70.6 MiB `.maml` holding a 6-layer audio encoder- // and a 6-layer KV-cached decoder, with the decode loop in `post::whisper`.- //- // Both bundles ship in `assets/` and are streamed from a file descriptor, which is what- // `noCompress += "maml"` above is for.- implementation(project(":library:ml"))+ // Speech-to-text is whisper-base on the reduced ONNX Runtime build (two int8 exports in+ // `assets/whisper-base/`, decode loop in WhisperHandle). Text-to-speech is Supertonic 3+ // (§Phase 2 ports it next); until then it stays on :library:ml's Vulkan runtime.+ implementation(libs.onnxruntime.reduced.android) // No `:library:downloadservice` and no DataStore: both models ship in the APK, so this app // downloads nothing and stores no preferences. They went when Piper's 1,834 MB of voices did. }
speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnx
diff --git a/speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnx b/speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnxnew file mode 100644index 0000000000..abbe80534fBinary files /dev/null and b/speech/src/main/assets/whisper-base/decoder_model_merged_int8.onnx differ
speech/src/main/assets/whisper-base/encoder_model_int8.onnx
diff --git a/speech/src/main/assets/whisper-base/encoder_model_int8.onnx b/speech/src/main/assets/whisper-base/encoder_model_int8.onnxnew file mode 100644index 0000000000..2738b5f948Binary files /dev/null and b/speech/src/main/assets/whisper-base/encoder_model_int8.onnx differ