library: shared MlHandle base for every ML model handle
- Commit
8b6c68ad3375f2f2720cba8c2cf9ccabcc88c0ec- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 19:55 UTC (4 days ago)
- Parents
235c062
Every model handle in library/ml carried the same lifetime code: a Long handle that is 0 when the model did not come up, an isAvailable getter, an idempotent close that destroys through a per-model native function, a bare-fd close helper, and one of three descriptor factories (bundled asset, on-disk file, or graph plus tokenizer bytes). The fd handover in particular was copied eight times, each copy with its own long comment explaining why the handed guard and the asset use block are load-bearing. Add MlHandle as the shared base: it owns the handle, isAvailable and close (destroying through a function reference), and its companion owns closeFd, the guarded load helper, and the three descriptor factories with the ownership rule documented once. ClipHandle, MaiaHandle, NnfpHandle, WhisperHandle, NllbHandle, MadladHandle, Gemma4AudioHandle, Gemma4VisionHandle, Gemma4Handle, MusicGate and SupertonicSynthesizer now extend it; Gemma4Prefix uses its closeFd instead of a private copy. Faces, Segmentation and TextRecognizer are left alone: their handles are volatile or synchronised with deferred destroy, so the plain base would change their semantics. Behaviour is preserved: construction still never throws, unavailable still degrades every operation to its empty value, native create and destroy calls, arguments and log messages are unchanged, and the one ownership subtlety (native adopts the fd, the guard covers only the detach-to-call window) is the same code in one place. Measured with tools/structure_check.py lines: 1,648,380 to 1,648,022 total source lines (-358), all of it in library/ml (78,080 to 77,722). The other audited candidates were measured flat and skipped: a shared ViewModel base saves nothing over AndroidViewModel itself across 87 unlike StateFlow shapes, EmptyState already serves 96 call sites, and MainActivity already sits on MaActivity. Verified: :library:ml compileDebugKotlin, testDebugUnitTest and Android lint pass (the Rust cargo tasks are excluded because they fail on the pre-existing Cargo.lock update error, untouched by this change); detekt reports only the pre-existing TextRecognizer ReturnCount finding.
Diff
library/ml/AGENTS.md
diff --git a/library/ml/AGENTS.md b/library/ml/AGENTS.mdindex b0874b6c65..c576a1f8e3 100644--- a/library/ml/AGENTS.md+++ b/library/ml/AGENTS.md@@ -22,6 +22,7 @@ - com/vayunmathur/library/ml/VulkanSessions.kt - com/vayunmathur/library/ml/VulkanBridge.kt - com/vayunmathur/library/ml/VulkanWire.kt+- com/vayunmathur/library/ml/MlHandle.kt — shared native-handle lifetime (`handle`/`isAvailable`/idempotent `close`) plus the asset/file descriptor factories every `*Handle` and `SupertonicSynthesizer`/`MusicGate` build on - com/vayunmathur/library/ml/WhisperHandle.kt - com/vayunmathur/library/ml/NllbHandle.kt - com/vayunmathur/library/ml/GemmaTypes.kt
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 4616494166..45b70399d4 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,8 +1,6 @@ package com.vayunmathur.library.ml import android.content.res.AssetManager-import android.os.ParcelFileDescriptor-import com.vayunmathur.library.log.Log /** * On-device image and text embedding in a shared 512-d space: TinyCLIP on the Vulkan compute@@ -50,11 +48,7 @@ import com.vayunmathur.library.log.Log * 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+class ClipHandle private constructor(private val source: String) : MlHandle(MlNative::destroyTinyclip) { /** * The 512-d embedding of an already-preprocessed image, or null on failure.@@ -79,13 +73,6 @@ class ClipHandle private constructor(private val source: String) : AutoCloseable 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" /** Model constants and the asset factory for [ClipHandle]. */@@ -112,52 +99,11 @@ class ClipHandle private constructor(private val source: String) : AutoCloseable */ 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 (expected: Exception) {- Log.error(TAG, "cannot open $path", expected)- 0L- }+ instance.handle = load(TAG, path) {+ createFromAsset(assets, path) { fd, off, len -> MlNative.createTinyclip(fd, off, len) } } 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/Gemma4AudioHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.ktindex 257716dcef..8a4cb3537a 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt@@ -1,6 +1,5 @@ package com.vayunmathur.library.ml -import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.Log import java.io.File @@ -40,13 +39,11 @@ import java.io.File * Not thread-safe. A new clip length re-records the plan, so two concurrent encodes would race on * the recording. */-class Gemma4AudioHandle private constructor(private val file: File) : AutoCloseable {+class Gemma4AudioHandle private constructor(private val file: File) : MlHandle(MlNative::destroyGemma4Audio) { - private var handle: Long = if (MlNative.isAvailable) create(file) else 0L-- /** Whether the tower came up. False leaves the assistant without audio rather than crashing. */- val isAvailable: Boolean- get() = handle != 0L+ init {+ handle = if (MlNative.isAvailable) create(file) else 0L+ } /** * Soft tokens for [samples] as one flat `n * 1536` array, or null.@@ -68,12 +65,6 @@ class Gemma4AudioHandle private constructor(private val file: File) : AutoClosea return MlNative.encodeAudioGemma4(handle, samples) } - override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyGemma4Audio(live)- }- override fun toString(): String = "Gemma 4 audio tower at $file" /** Model constants and factories for the Gemma 4 audio tower. */@@ -153,32 +144,7 @@ class Gemma4AudioHandle private constructor(private val file: File) : AutoClosea fun inDirectory(directory: File): Gemma4AudioHandle = Gemma4AudioHandle(File(directory, AUDIO)) - /**- * Open the graph and hand the descriptor over.- *- * Native adopts it and closes it on every path including failure, so [handed] guards only- * the window between detaching and the call being made.- */- private fun create(file: File): Long {- if (!file.isFile) {- Log.status(TAG, "${file.name} is missing")- return 0L- }- val fd = runCatching {- ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)- .use { it.detachFd() }- }.getOrElse {- Log.status(TAG, "cannot open ${file.name}: $it")- return 0L- }- var handed = false- try {- val live = MlNative.createGemma4Audio(fd, 0L, file.length())- handed = true- return live- } finally {- if (!handed) runCatching { ParcelFileDescriptor.adoptFd(fd).close() }- }- }+ private fun create(file: File): Long =+ createFromFile(file, TAG) { fd, len -> MlNative.createGemma4Audio(fd, 0L, len) } } }
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.ktindex ad2cb2b11d..5499a0085e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt@@ -1,6 +1,5 @@ package com.vayunmathur.library.ml -import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.Log import java.io.File import java.text.Normalizer@@ -37,9 +36,11 @@ import java.text.Normalizer * position, so two concurrent turns would interleave their tokens into the same conversation. * The caller must hold a lock across a whole turn, not merely across a call. */-class Gemma4Handle private constructor(internal val directory: File) : AutoCloseable {+class Gemma4Handle private constructor(internal val directory: File) : MlHandle(MlNative::destroyGemma4) { - internal var handle: Long = if (MlNative.isAvailable) create(directory) else 0L+ init {+ handle = if (MlNative.isAvailable) create(directory) else 0L+ } /** * Why the last construction failed, for the error the user sees.@@ -69,10 +70,6 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose // benchmark() and loadPrefix() live in Gemma4Prefix.kt and delegate back here. fun benchmark() = runBenchmark() - /** Whether the model came up. False leaves the assistant off rather than crashing. */- val isAvailable: Boolean- get() = handle != 0L- /** * Load the baked cache for [prefix], if it is present and matches. Returns whether it did. *@@ -519,12 +516,6 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose } } - override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyGemma4(live)- }- override fun toString(): String = "Gemma 4 E2B in $directory" /**
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.ktindex 0b7a2bce82..98191eb25c 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt@@ -193,7 +193,7 @@ private fun createGemma4Native( val textFd = openModelFd(text, Gemma4Handle.TEXT, onFailure = { headLease.close() }) ?: return 0L val embedFd = openModelFd(embed, Gemma4Handle.EMBED, onFailure = {- closeGemma4Fd(textFd)+ MlHandle.closeFd(textFd) headLease.close() }) ?: return 0L var handed = false@@ -209,8 +209,8 @@ private fun createGemma4Native( return live } finally { if (!handed) {- closeGemma4Fd(textFd)- closeGemma4Fd(embedFd)+ MlHandle.closeFd(textFd)+ MlHandle.closeFd(embedFd) headLease.close() } }@@ -219,7 +219,7 @@ private fun createGemma4Native( /** Open file descriptor lease for the optional GPU head, or null (with a log) on failure. */ private class HeadLease(val fd: Int, val length: Long) : AutoCloseable { override fun close() {- if (fd >= 0) closeGemma4Fd(fd)+ if (fd >= 0) MlHandle.closeFd(fd) } } @@ -279,16 +279,6 @@ private fun openModelFd(file: File, name: String, onFailure: () -> Unit): Int? { } } -/**- * 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 closeGemma4Fd(fd: Int) {- runCatching { ParcelFileDescriptor.adoptFd(fd).close() }-}- /** * Bytes this device will spend on the KV cache. *
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.ktindex 3de16e938f..f02b55dc4e 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt@@ -1,7 +1,6 @@ package com.vayunmathur.library.ml import android.graphics.Bitmap-import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.Log import androidx.core.graphics.scale import java.io.File@@ -31,13 +30,11 @@ import java.io.File * Not thread-safe. A new aspect ratio re-records the plan, so two concurrent encodes would race * on the recording. */-class Gemma4VisionHandle private constructor(private val file: File) : AutoCloseable {+class Gemma4VisionHandle private constructor(private val file: File) : MlHandle(MlNative::destroyGemma4Vision) { - private var handle: Long = if (MlNative.isAvailable) create(file) else 0L-- /** Whether the tower came up. False leaves the assistant text-only rather than crashing. */- val isAvailable: Boolean- get() = handle != 0L+ init {+ handle = if (MlNative.isAvailable) create(file) else 0L+ } /** * Soft tokens for [image] as one flat `n * 1536` array, or null.@@ -70,12 +67,6 @@ class Gemma4VisionHandle private constructor(private val file: File) : AutoClose return MlNative.encodeImageGemma4(handle, pixels, width, height) } - override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyGemma4Vision(live)- }- override fun toString(): String = "Gemma 4 vision tower at $file" /** Model constants and factories for the Gemma 4 vision tower. */@@ -106,32 +97,7 @@ class Gemma4VisionHandle private constructor(private val file: File) : AutoClose fun inDirectory(directory: File): Gemma4VisionHandle = Gemma4VisionHandle(File(directory, VISION)) - /**- * Open the graph and hand the descriptor over.- *- * Native adopts it and closes it on every path including failure, so [handed] guards only- * the window between detaching and the call being made.- */- private fun create(file: File): Long {- if (!file.isFile) {- Log.status(TAG, "${file.name} is missing")- return 0L- }- val fd = runCatching {- ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)- .use { it.detachFd() }- }.getOrElse {- Log.status(TAG, "cannot open ${file.name}: $it")- return 0L- }- var handed = false- try {- val live = MlNative.createGemma4Vision(fd, 0L, file.length())- handed = true- return live- } finally {- if (!handed) runCatching { ParcelFileDescriptor.adoptFd(fd).close() }- }- }+ private fun create(file: File): Long =+ createFromFile(file, TAG) { fd, len -> MlNative.createGemma4Vision(fd, 0L, len) } } }
library/ml/src/main/java/com/vayunmathur/library/ml/MadladHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MadladHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MadladHandle.ktindex cb00ca97c9..54b5b6a2a6 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MadladHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MadladHandle.kt@@ -1,7 +1,5 @@ package com.vayunmathur.library.ml -import android.os.ParcelFileDescriptor-import com.vayunmathur.library.log.Log import java.io.File /**@@ -49,25 +47,12 @@ import java.io.File * 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 [translate] and [close]. */-class MadladHandle private constructor(private val directory: File) : AutoCloseable {- private var handle: Long = 0L+class MadladHandle private constructor(private val directory: File) : MlHandle(MlNative::destroyMadlad) { init {- handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- create(directory)- } catch (expected: Exception) {- Log.error(TAG, "cannot open the MADLAD model in $directory", expected)- 0L- }- }+ handle = load(TAG, "the MADLAD model in $directory") { create(directory) } } - /** True if the graph came up and the tokenizer table is the vocabulary the model was built on. */- val isAvailable: Boolean get() = handle != 0L- /** * Translate [text] into the language [targetTag] names (e.g. `"<2en>"`), * or null on failure.@@ -88,13 +73,6 @@ class MadladHandle private constructor(private val directory: File) : AutoClosea return MlNative.translateMadlad(handle, normalised, targetTag) } - /** Free the network and close the weights file. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyMadlad(live)- }- override fun toString(): String = "MADLAD400-3B-MT in $directory" /** Model file names and the on-disk factory for [MadladHandle]. */@@ -118,43 +96,9 @@ class MadladHandle private constructor(private val directory: File) : AutoClosea */ fun inDirectory(directory: File): MadladHandle = MadladHandle(directory) - /**- * Open the graph, read the tokenizer table, and hand the descriptor over.- *- * The two `finally`s are what make the descriptor safe rather than usually safe. A raw- * descriptor has no destructor, so every path out of here has to close what it opened:- * the outer one covers a missing or unreadable file, and the inner one covers the- * window after the descriptor has been given up but before native has adopted it.- */- private fun create(directory: File): Long {- val graph = File(directory, GRAPH)- require(graph.isFile) { "$GRAPH is missing from $directory" }- val tokenizer = File(directory, TOKENIZER)- require(tokenizer.isFile) { "$TOKENIZER is missing from $directory" }-- // Offset 0 and the whole file: only an asset needs a range, because only an asset- // shares its descriptor with the rest of the APK.- val fd = ParcelFileDescriptor.open(graph, ParcelFileDescriptor.MODE_READ_ONLY)- .use { it.detachFd() }- var handed = false- try {- val handle =- MlNative.createMadlad(fd, 0L, graph.length(), tokenizer.readBytes())- handed = true- return handle- } finally {- if (!handed) closeFd(fd)+ private fun create(directory: File): Long =+ createFromFiles(File(directory, GRAPH), File(directory, TOKENIZER)) { fd, len, bytes ->+ MlNative.createMadlad(fd, 0L, len, bytes) }- }-- /**- * 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/MaiaHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.ktindex 44c884e991..54288d127f 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MaiaHandle.kt@@ -1,8 +1,6 @@ package com.vayunmathur.library.ml import android.content.res.AssetManager-import android.os.ParcelFileDescriptor-import com.vayunmathur.library.log.Log /** * On-device human-move prediction for chess: Maia3-5M on the Vulkan compute runtime.@@ -57,11 +55,7 @@ import com.vayunmathur.library.log.Log * * Not thread-safe. A caller must hold a lock across [logits] and [close]. */-class MaiaHandle 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+class MaiaHandle private constructor(private val source: String) : MlHandle(MlNative::destroyMaia) { /** * The [MOVES] move logits for a board, or null on failure.@@ -84,13 +78,6 @@ class MaiaHandle private constructor(private val source: String) : AutoCloseable return MlNative.maiaLogits(handle, planes, selfElo, oppoElo) } - /** Free the network and close the weights file. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyMaia(live)- }- override fun toString(): String = "Maia3-5M from $source" /** Board/move dimensions, model constants and the asset factory for [MaiaHandle]. */@@ -120,52 +107,10 @@ class MaiaHandle private constructor(private val source: String) : AutoCloseable */ fun inAssets(assets: AssetManager, path: String = GRAPH): MaiaHandle { val instance = MaiaHandle("the APK's $path")- instance.handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- create(assets, path)- } catch (expected: Exception) {- Log.error(TAG, "cannot open $path", expected)- 0L- }+ instance.handle = load(TAG, path) {+ createFromAsset(assets, path) { fd, off, len -> MlNative.createMaia(fd, off, len) } } 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 [ClipHandle]'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.createMaia(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/MlHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlHandle.ktnew file mode 100644index 0000000000..a3d1c13eff--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlHandle.kt@@ -0,0 +1,110 @@+package com.vayunmathur.library.ml++import android.content.res.AssetManager+import android.os.ParcelFileDescriptor+import com.vayunmathur.library.log.Log+import java.io.File++/**+ * Shared lifetime for a native model handle: a `Long` that is 0 when the model did not come up.+ *+ * Construction never throws and [close] is idempotent, in every subclass: [isAvailable] is false+ * when `libmodelrunner.so` is missing for this ABI, when the model file is absent, compressed or+ * malformed, or when the device cannot give us a Vulkan device with fp16 compute — and then every+ * operation on the subclass degrades to its empty value. Not thread-safe unless a subclass says+ * otherwise: a caller holds a lock across its operations and [close].+ *+ * The descriptor helpers own the one ownership rule for a raw fd, which has no destructor: native+ * adopts it and closes it on every path including failure, so the `handed` guard covers only the+ * window between detaching and the native call being made; on any other way out the fd is closed+ * here or it leaks for the life of the process. An asset is a range of the APK (hence offset and+ * length, and `use` so a failing `detachFd` still closes); a plain file is offset 0, whole file.+ */+abstract class MlHandle(private val destroy: (Long) -> Unit) : AutoCloseable {+ internal 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++ /** Free the network and close the weights file. Idempotent. */+ override fun close() {+ val live = handle+ handle = 0L+ if (live != 0L) destroy(live)+ }++ /** Factory and descriptor helpers shared by every handle. See the class docs. */+ companion object {+ /** Close a bare descriptor; failures are swallowed, callers are already on an error path. */+ internal fun closeFd(fd: Int) {+ runCatching { ParcelFileDescriptor.adoptFd(fd).close() }+ }++ /** [create] guarded the way every factory here is: unavailable or throwing means 0. */+ internal fun load(tag: String, what: String, create: () -> Long): Long =+ if (!MlNative.isAvailable) {+ 0L+ } else {+ try {+ create()+ } catch (expected: Exception) {+ Log.error(tag, "cannot open $what", expected)+ 0L+ }+ }++ /** Open the asset at [path] and hand its descriptor to [create]. See the class docs. */+ internal fun createFromAsset(+ assets: AssetManager,+ path: String,+ create: (fd: Int, offset: Long, length: Long) -> Long,+ ): Long = assets.openFd(path).use { afd ->+ handOff(afd.parcelFileDescriptor.detachFd()) {+ create(it, afd.startOffset, afd.length)+ }+ }++ /** Open [graph] and hand its descriptor plus [tokenizer]'s bytes to [create]. */+ internal fun createFromFiles(+ graph: File,+ tokenizer: File,+ create: (fd: Int, length: Long, tokenizer: ByteArray) -> Long,+ ): Long {+ require(graph.isFile) { "${graph.name} is missing" }+ require(tokenizer.isFile) { "${tokenizer.name} is missing" }+ return handOff(openFd(graph)) { create(it, graph.length(), tokenizer.readBytes()) }+ }++ /** Open [file] and hand its descriptor to [create]; a missing/unreadable file is 0. */+ internal fun createFromFile(+ file: File,+ tag: String,+ create: (fd: Int, length: Long) -> Long,+ ): Long {+ if (!file.isFile) {+ Log.status(tag, "${file.name} is missing")+ return 0L+ }+ val fd = runCatching { openFd(file) }.getOrElse {+ Log.status(tag, "cannot open ${file.name}: $it")+ return 0L+ }+ return handOff(fd) { create(it, file.length()) }+ }++ private fun openFd(file: File): Int =+ ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)+ .use { it.detachFd() }++ private fun handOff(fd: Int, create: (Int) -> Long): Long {+ var handed = false+ try {+ val handle = create(fd)+ handed = true+ return handle+ } finally {+ if (!handed) closeFd(fd)+ }+ }+ }+}
library/ml/src/main/java/com/vayunmathur/library/ml/MusicGate.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MusicGate.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MusicGate.ktindex 21e9d194f5..fbeafaf1a0 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MusicGate.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MusicGate.kt@@ -39,11 +39,7 @@ package com.vayunmathur.library.ml * it. Treat the probabilities as a well-founded signal to tune against, not as ground * truth. See `detector/ARCHITECTURE.md` section 3. */-class MusicGate private constructor() : AutoCloseable {- private var handle: Long = 0L-- /** False when the native library is missing. Every other member is then inert. */- val isAvailable: Boolean get() = handle != 0L+class MusicGate private constructor() : MlHandle(MlNative::destroyMusicGate) { /** * Feed [count] samples from the front of [pcm] and collect one probability in `0f..1f`@@ -63,13 +59,6 @@ class MusicGate private constructor() : AutoCloseable { if (handle != 0L) MlNative.resetMusicGate(handle) } - /** Free the gate. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyMusicGate(live)- }- override fun toString(): String = "Now Playing music gate (CPU)" /** Front-end timing constants and the in-process factory for [MusicGate]. */
library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.ktindex f456c8df97..6ec2a81688 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt@@ -1,7 +1,5 @@ package com.vayunmathur.library.ml -import android.os.ParcelFileDescriptor-import com.vayunmathur.library.log.Log import java.io.File import java.text.Normalizer @@ -52,25 +50,12 @@ import java.text.Normalizer * concurrent calls would clobber each other's state. A caller must hold a lock across * [translate] and [close]. */-class NllbHandle private constructor(private val directory: File) : AutoCloseable {- private var handle: Long = 0L+class NllbHandle private constructor(private val directory: File) : MlHandle(MlNative::destroyNllb) { init {- handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- create(directory)- } catch (expected: Exception) {- Log.error(TAG, "cannot open the NLLB model in $directory", expected)- 0L- }- }+ handle = load(TAG, "the NLLB model in $directory") { create(directory) } } - /** True if the graph came up and the tokenizer table is the vocabulary the model was built on. */- val isAvailable: Boolean get() = handle != 0L- /** * Translate [text] from the language [sourceToken] names into the language [targetToken] * names, or null on failure.@@ -90,13 +75,6 @@ class NllbHandle private constructor(private val directory: File) : AutoCloseabl return MlNative.translateNllb(handle, normalised, sourceToken, targetToken) } - /** Free the network and close the weights file. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyNllb(live)- }- override fun toString(): String = "NLLB-200 in $directory" /** Model file names and the on-disk factory for [NllbHandle]. */@@ -121,43 +99,9 @@ class NllbHandle private constructor(private val directory: File) : AutoCloseabl */ fun inDirectory(directory: File): NllbHandle = NllbHandle(directory) - /**- * Open the graph, read the tokenizer table, and hand the descriptor over.- *- * The two `finally`s are what make the descriptor safe rather than usually safe. A raw- * descriptor has no destructor, so every path out of here has to close what it opened:- * the outer one covers a missing or unreadable file, and the inner one covers the- * window after the descriptor has been given up but before native has adopted it.- */- private fun create(directory: File): Long {- val graph = File(directory, GRAPH)- require(graph.isFile) { "$GRAPH is missing from $directory" }- val tokenizer = File(directory, TOKENIZER)- require(tokenizer.isFile) { "$TOKENIZER is missing from $directory" }-- // Offset 0 and the whole file: only an asset needs a range, because only an asset- // shares its descriptor with the rest of the APK.- val fd = ParcelFileDescriptor.open(graph, ParcelFileDescriptor.MODE_READ_ONLY)- .use { it.detachFd() }- var handed = false- try {- val handle =- MlNative.createNllb(fd, 0L, graph.length(), tokenizer.readBytes())- handed = true- return handle- } finally {- if (!handed) closeFd(fd)+ private fun create(directory: File): Long =+ createFromFiles(File(directory, GRAPH), File(directory, TOKENIZER)) { fd, len, bytes ->+ MlNative.createNllb(fd, 0L, len, bytes) }- }-- /**- * 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/NnfpHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/NnfpHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/NnfpHandle.ktindex cece2d2e4c..fbdaaa549a 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/NnfpHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/NnfpHandle.kt@@ -1,8 +1,6 @@ package com.vayunmathur.library.ml import android.content.res.AssetManager-import android.os.ParcelFileDescriptor-import com.vayunmathur.library.log.Log /** * On-device audio fingerprinting: the Now Playing embedding network on the Vulkan compute@@ -66,11 +64,7 @@ import com.vayunmathur.library.log.Log * * Not thread-safe. A caller must hold a lock across [embed] and [close]. */-class NnfpHandle 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+class NnfpHandle private constructor(private val source: String) : MlHandle(MlNative::destroyNnfp) { /** * The [EMBEDDING] fingerprint values for one window, or null on failure.@@ -89,13 +83,6 @@ class NnfpHandle private constructor(private val source: String) : AutoCloseable return MlNative.nnfpEmbed(handle, pcm) } - /** Free the network. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyNnfp(live)- }- override fun toString(): String = "Now Playing fingerprinter from $source" /** Front-end window constants for the Now Playing fingerprint network. */@@ -137,52 +124,10 @@ class NnfpHandle private constructor(private val source: String) : AutoCloseable */ fun inAssets(assets: AssetManager, path: String = GRAPH): NnfpHandle { val instance = NnfpHandle("the APK's $path")- instance.handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- create(assets, path)- } catch (expected: Exception) {- Log.error(TAG, "cannot open $path", expected)- 0L- }+ instance.handle = load(TAG, path) {+ createFromAsset(assets, path) { fd, off, len -> MlNative.createNnfp(fd, off, len) } } 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 [MaiaHandle]'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.createNnfp(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/SupertonicSynthesizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.ktindex c1d780b8af..bd7315dddd 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/SupertonicSynthesizer.kt@@ -60,28 +60,15 @@ import java.text.Normalizer class SupertonicSynthesizer private constructor( private val bundle: Bundle, voice: String,-) : AutoCloseable {- private var handle: Long = 0L+) : MlHandle(MlNative::destroySupertonic) { /** Supertonic's output rate, fixed by the vocoder rather than by the voice. */ val sampleRate: Int = SAMPLE_RATE init {- handle = if (!MlNative.isAvailable) {- 0L- } else {- try {- create(bundle, voice)- } catch (expected: Exception) {- Log.error(TAG, "cannot open the Supertonic bundle in $bundle", expected)- 0L- }- }+ handle = load(TAG, "the Supertonic bundle in $bundle") { create(bundle, voice) } } - /** True if all four networks came up, the codepoint table is the right size and a voice read. */- val isAvailable: Boolean get() = handle != 0L- /** * Switch to another voice, returning false if it could not be read. *@@ -120,13 +107,6 @@ class SupertonicSynthesizer private constructor( return MlNative.synthesizeSupertonic(handle, decomposed, language) ?: FloatArray(0) } - /** Free all four networks. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroySupertonic(live)- }- /** * Where a bundle's six files are, abstracted over the APK and the filesystem. *@@ -163,7 +143,7 @@ class SupertonicSynthesizer private constructor( override fun close() { if (!owned) return owned = false- closeFd(fd)+ MlHandle.closeFd(fd) } } @@ -271,22 +251,12 @@ class SupertonicSynthesizer private constructor( handed = true return handle } finally {- if (!handed) fds.forEach { closeFd(it) }+ if (!handed) fds.forEach { MlHandle.closeFd(it) } } } finally { pieces.forEach { it.close() } } } - /**- * Close a bare descriptor.- *- * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from Kotlin.- * Failures are swallowed because every caller is already on an error path and there is- * nothing useful to do about a descriptor that will not close.- */- private fun closeFd(fd: Int) {- runCatching { ParcelFileDescriptor.adoptFd(fd).close() }- } } }
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 b728c9aacd..4c150373cd 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,7 +1,6 @@ package com.vayunmathur.library.ml import android.content.res.AssetManager-import android.os.ParcelFileDescriptor import com.vayunmathur.library.log.Log /**@@ -52,11 +51,7 @@ import com.vayunmathur.library.log.Log * 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]. */-class WhisperHandle private constructor(private val source: String) : AutoCloseable {- private var handle: Long = 0L-- /** True if the graph came up and the ids describe the model it was built from. */- val isAvailable: Boolean get() = handle != 0L+class WhisperHandle private constructor(private val source: String) : MlHandle(MlNative::destroyWhisper) { /** * Transcribe one 30-second log-mel window into token ids, or null on failure.@@ -71,13 +66,6 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea return MlNative.transcribeWhisper(handle, mel, languageToken) } - /** Free the network and close the weights file. Idempotent. */- override fun close() {- val live = handle- handle = 0L- if (live != 0L) MlNative.destroyWhisper(live)- }- override fun toString(): String = "whisper-base from $source" /** Front-end dimensions, model constants and the asset factory for [WhisperHandle]. */@@ -115,69 +103,17 @@ class WhisperHandle private constructor(private val source: String) : AutoClosea path: String = GRAPH, ): WhisperHandle { val instance = WhisperHandle("the APK's $path")- instance.handle = if (!MlNative.isAvailable || special.size != SPECIAL_IDS) {- if (special.size != SPECIAL_IDS) {- Log.error(TAG, "${special.size} special ids, not $SPECIAL_IDS")- }+ instance.handle = if (special.size != SPECIAL_IDS) {+ Log.error(TAG, "${special.size} special ids, not $SPECIAL_IDS") 0L } else {- try {- create(assets, path, special, languages, suppress, suppressAtBegin)- } catch (expected: Exception) {- Log.error(TAG, "cannot open $path", expected)- 0L+ load(TAG, path) {+ createFromAsset(assets, path) { fd, off, len ->+ MlNative.createWhisper(fd, off, len, special, languages, suppress, suppressAtBegin)+ } } } 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)- }- }-- /**- * 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() }- } } }