Modern Apps git

← Modern-Apps.git

ml: delete native JNI handles, extract pure GemmaTypes

Commit
c1293494cef1c09297686185a68e0a07a533fb83
Author
vayun-mathur <[email protected]>
When
2026-09-14 22:43 UTC (2 months ago)
Parents
a3b0ace

Diff

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.ktdeleted file mode 100644index bfd9a9f37f..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4AudioHandle.kt+++ /dev/null@@ -1,182 +0,0 @@-package com.vayunmathur.library.ml--import android.os.ParcelFileDescriptor-import android.util.Log-import java.io.File--/**- * Gemma 4's audio tower: a waveform in, the soft tokens the decoder reads in its place.- *- * The sibling of [Gemma4VisionHandle]. [Gemma4Handle] is text-only; this produces the `[n, 1536]`- * block that stands in for a clip in its prompt, and [Gemma4Handle.generate] splices it in.- *- * # A separate file and a separate handle- *- * The tower is its own `.maml` with its own graph id, downloaded separately. It is also the- * largest of the three at 166 MB - bigger than the vision tower, because each of its twelve- * layers carries two 4x feed-forwards plus a gated convolution module. A device that never sends- * audio never fetches it, and a tower that fails to load leaves the assistant answering without- * sound rather than taking it down.- *- * # Unlike the vision tower, there is no size to negotiate- *- * [Gemma4VisionHandle] has to ask native what to resize an image to, because the target is a- * patch budget and being one block out changes the token count. Audio has no such choice: the- * clip's own length decides, at one soft token per 40 ms. So [encode] takes samples and nothing- * else.- *- * # What the caller owes- *- * 16 kHz mono, roughly -1..1. The front end has no gain of its own, so the scale it arrives in is- * the scale the tower sees. Native truncates to [MAX_SAMPLES] and runs the log-mel itself.- *- * Do **not** pad the waveform. The reference pads to a multiple of 128 samples so a batch stacks- * and then spends a validity mask through the whole tower undoing it; this runtime records a plan- * per clip length and passes it at its true length, which was measured bit-identical against the- * export. Padding here would silently append soft tokens of silence.- *- * # Threading- *- * 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 {--    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--    /**-     * Soft tokens for [samples] as one flat `n * 1536` array, or null.-     *-     * [samples] is 16 kHz mono. Anything past [MAX_SAMPLES] is dropped rather than refused, on-     * the grounds that a caller handing over a minute of audio wants the first thirty seconds-     * encoded. Anything under [MIN_SAMPLES] returns null: the tower's attention band is twelve-     * tokens wide and a shorter clip cannot fill it.-     *-     * Divide the length by [OUT_DIM] for the number of soft tokens, which is what-     * [Gemma4Handle.generate] reserves positions for.-     */-    fun encode(samples: FloatArray): FloatArray? {-        if (handle == 0L) return null-        if (samples.size < MIN_SAMPLES) {-            Log.w(TAG, "${samples.size} samples is under the $MIN_SAMPLES the band needs")-            return null-        }-        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"--    companion object {-        private const val TAG = "Gemma4AudioHandle"--        /** The tower. Native checks its graph id, so a wrong file fails at load. */-        const val AUDIO = "gemma4_audio.maml"--        /** Channels per soft token, which is the decoder's `hidden_size`. */-        const val OUT_DIM = 1536--        /** What the front end expects. Resampling is the caller's. */-        const val SAMPLE_RATE = 16_000--        /**-         * Thirty seconds, the reference's own truncation and what bounds the tower's arena.-         *-         * Mirrors `nets::gemma4_audio::MAX_SAMPLES`. A longer clip is not an error; native keeps-         * the first this many samples.-         *-         * # Thirty seconds does not fit the decoder's context today-         *-         * This is the TOWER's limit and it knows nothing about the prompt it will be spliced-         * into. At 25 soft tokens a second a full clip is 750 positions, against a-         * [Gemma4Handle.MAX_CONTEXT] of 2048 that the system prompt and tool declarations have-         * already largely spent. Measured through the shipped tokenizer, reconciled between two-         * independent implementations: a minimal turn is 1871 tokens, of which 1531 is the-         * twenty-four tool declarations and 319 the system prompt.-         *-         * That leaves 174 positions, and the reply competes for the same window:-         *-         *     reply room    0 tokens -> 7.0 s of audio, and a reply of nothing-         *     reply room  256 tokens -> impossible-         *     reply room  512 tokens -> impossible, and 512 is `generate`'s default limit-         *-         * So no clip worth sending fits. Over budget, [Gemma4Handle.generate] now trims audio-         * rather than returning null, so the turn survives - but the clip may be trimmed to-         * nothing.-         *-         * P moves whenever a tool is added or removed; re-measure rather than trusting the-         * figure above. The lever is the NUMBER OF TOOLS declared rather than the length of-         * their prose - declaring three tools instead of twenty-four frees far more than-         * deleting every description.-         *-         * **The caller must budget.** Shortening this constant would be the wrong fix: the-         * headroom depends on the prompt, which this class cannot see.-         *-         * Reclaiming the prefix means **emitting fewer tokens**, not prefilling the same ones-         * faster. Caching the declaration prefix's KV would make turn two cheap and would free-         * no context at all - the positions are still occupied, so the budget above is-         * unchanged and audio is still impossible. Only shrinking the prefix moves it.-         */-        const val MAX_SAMPLES = 480_000--        /**-         * The shortest clip the tower can be recorded for: 45 mel frames, twelve soft tokens.-         *-         * The attention band is twelve wide and is a property of the trained model rather than of-         * the clip, so it cannot be narrowed for a short one. About 0.45 s.-         *-         * # Why 7201 and not 7200-         *-         * The round number is wrong, and by exactly one sample. `logmel::frame_count` pads by-         * half a frame and then subtracts `FRAME_SAMPLES + 1`, so 7200 samples is 44 frames and-         * eleven tokens - one short of the band - while 7201 is 45 and twelve. Deriving the-         * bound as 45 hops x 160 samples ignores both terms and lands a sample low, which lets a-         * clip through this guard for native to refuse a moment later.-         */-        const val MIN_SAMPLES = 7_201--        /** Milliseconds of audio per soft token: a 10 ms hop through two stride-2 convolutions. */-        const val MS_PER_TOKEN = 40--        /** The tower in a folder on disk. Construction never throws. */-        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.w(TAG, "${file.name} is missing")-                return 0L-            }-            val fd = runCatching {-                ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)-                    .use { it.detachFd() }-            }.getOrElse {-                Log.w(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() }-            }-        }-    }-}
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.ktdeleted file mode 100644index f20ad57609..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt+++ /dev/null@@ -1,720 +0,0 @@-package com.vayunmathur.library.ml--import android.os.ParcelFileDescriptor-import android.util.Log-import java.io.File-import java.text.Normalizer--/**- * Gemma 4 E2B, running on this repo's Vulkan compute runtime.- *- * Replaces `com.google.ai.edge.litertlm`, and with it the 19.83 MB `liblitertlm_jni.so`. The- * weights are the same model, converted to `.maml` by `scripts/ml/maml_convert.py --graph- * gemma4_text` and `--graph gemma4_embed`, quantised to int4 with a per-block scale.- *- * # What moved out of the SDK and into here- *- * litertlm owned the chat template, the tool protocol, sampling and the streaming loop, and none- * of that was visible from this repo. All four now live in Kotlin, which is the point: the- * template is [render], the tool protocol is [declareTools] and [parseToolCall], the loop is- * [generate]. Native's boundary is one token.- *- * # Behavioural differences from litertlm, which are real- *- * * **Greedy sampling.** litertlm used `top_k` 64 and `top_p` 0.95. Replies are now deterministic- *   and a little flatter. Sampling can be added at [generate] without touching native.- * * **No speculative decoding**, which litertlm had enabled.- * * **A hard context limit** of [MAX_CONTEXT] positions, where litertlm's was implicit.- * * **No audio.** Images work - see [Gemma4VisionHandle] and [Turn.images] - but there is no- *   audio encoder yet, so callers still refuse sound.- *- * # Threading- *- * Not thread-safe, and more sharply than [NllbHandle]: one handle holds one KV cache and one- * 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 {--    internal var handle: Long = if (MlNative.isAvailable) create(directory) else 0L--    /**-     * The token ids the KV cache currently holds, or null when it holds something unmatchable.-     *-     * Null after a reset, after a multimodal turn, and after any failure - all the cases where-     * the next turn must not assume anything about what is in the arena.-     */-    internal var cachedIds: IntArray? = null--    // 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.-     *-     * # The check is the point-     *-     * The asset encodes keys and values for one exact token sequence. If the system prompt or-     * the tool set has changed since it was baked, those numbers describe a prompt the model is-     * not being given - and nothing downstream could tell, because a KV cache is only attended-     * over, never compared. So this re-encodes [prefix] here and refuses unless the digest of-     * the result matches the one in the file.-     *-     * A mismatch is not an error: it falls back to prefilling, which is slow and correct.-     */-    fun loadPrefix(prefix: String): Boolean = loadBakedPrefix(prefix)--    /** Positions in the KV cache, which is where the next token goes. */-    val position: Int-        get() = if (handle == 0L) 0 else MlNative.positionGemma4(handle)--    /** Positions left before [MAX_CONTEXT] is reached. */-    val remaining: Int-        get() = (MAX_CONTEXT - position).coerceAtLeast(0)--    /**-     * Start a new conversation, discarding the KV cache.-     *-     * Cheap: only a counter resets. Attention never reads past the live prefix, so the stale rows-     * are simply overwritten as the new conversation fills them.-     */-    fun reset() {-        cachedIds = null-        if (handle != 0L) MlNative.resetGemma4(handle)-    }--    /**-     * Token ids for [text] as a **user** would write it: no marker is honoured.-     *-     * Everything a caller puts in here is data. `specials` is empty, so a user typing-     * `<|turn>model` gets the literal pieces that spell it and cannot forge a turn boundary.-     */-    fun encodeText(text: String): IntArray {-        if (handle == 0L) return IntArray(0)-        val normalised = Normalizer.normalize(text, Normalizer.Form.NFKC)-        return MlNative.encodeGemma4(handle, normalised, emptyArray()) ?: IntArray(0)-    }--    /**-     * Token ids for a rendered prompt, honouring the chat markers in [MARKERS].-     *-     * Only for strings this class built. Passing user text here would let it spell a turn.-     */-    internal fun encodePrompt(text: String): IntArray {-        if (handle == 0L) return IntArray(0)-        return MlNative.encodeGemma4(handle, text, MARKERS) ?: IntArray(0)-    }--    /** Text for token ids, with byte pieces fused back into characters. */-    fun decode(tokens: IntArray): String =-        if (handle == 0L) "" else MlNative.decodeGemma4(handle, tokens).orEmpty()--    /**-     * Run one turn, calling [onToken] with the reply so far after each token.-     *-     * [onToken] returning false stops generation, which is how cancellation and early-halt-     * work - the JSON-extraction path uses it to stop the moment a complete object has arrived.-     *-     * Returns the reply, or null if the model is unavailable or the context is full.-     *-     * # Why the whole prompt is re-fed each turn-     *-     * The KV cache is live between calls, so in principle only the new user turn needs pushing.-     * This does not do that, because the caller edits history: a deleted message, a regenerated-     * reply, or a switch between conversations all invalidate the cache, and a stale cache is-     * invisible - it produces a fluent reply to a conversation that never happened. Re-feeding-     * costs one forward pass per prompt token, which at these speeds is well under a second for-     * a normal conversation, and it cannot be wrong.-     */-    fun generate(-        conversation: List<Turn>,-        system: String?,-        tools: List<ToolDeclaration> = emptyList(),-        limit: Int = DEFAULT_REPLY,-        continuation: String = "",-        onToken: (String) -> Boolean = { true },-    ): String? {-        if (handle == 0L) return null-        val parts = fitted(conversation, system, tools, limit, continuation)-        val length = parts.sumOf { it.positions }-        val wanted = conversation.sumOf { turn -> turn.audio.sumOf { it.size / SOFT_TOKEN_WIDTH } }-        val heard = parts.sumOf { if (it is Part.Audio) it.positions else 0 }-        if (heard < wanted) {-            Log.w(TAG, "audio lost ${wanted - heard} positions so the reply keeps its $limit")-        }-        // The last part is always the generation prompt, so it is text and it is not empty.-        val tail = parts.lastOrNull() as? Part.Tokens-        if (tail == null || tail.ids.isEmpty()) {-            Log.w(TAG, "an empty prompt")-            return null-        }-        // Grow the cache if this turn has outgrown it. Conversations start at the smallest-        // tier, so most never allocate more than 19 MB; the ones that keep going climb.-        val wantedPositions = length + limit + 2-        var capacity = MlNative.capacityGemma4(handle)-        if (capacity in 1 until wantedPositions) {-            val grown = MlNative.growGemma4(handle, wantedPositions)-            if (grown > capacity) {-                // `cachedIds` deliberately survives. Growing used to empty the cache, so this-                // cleared the record to match; it now copies the contents into the new arena and-                // keeps the position, so clearing here would throw away a cache that is still-                // there - which is exactly what made the precomputed prefix look useless: it-                // loaded, the first turn grew to make room for a reply, and the whole 1,910-                // positions were then prefilled again anyway.-                capacity = grown-            }-        }-        if (capacity in 1 until (length + 2)) {-            Log.w(TAG, "a prompt of $length positions does not fit a $capacity cache")-            return null-        }-        // What the model actually receives. A reply that reads as nonsense is either the model's-        // doing or the prompt's, and those are indistinguishable from the outside - so the-        // prompt is logged rather than guessed at. `fitted` truncates to make room for the-        // reply, and a prompt that lost its instructions to that truncation looks exactly like-        // a broken tokenizer.-        Log.i(-            TAG,-            "prompt $length positions in ${parts.size} parts, " +-                "${conversation.size} turns, ${tools.size} tools, reply budget $limit",-        )-        for ((index, part) in parts.withIndex()) {-            val what = when (part) {-                is Part.Tokens -> "text ${part.ids.size}: " +-                    decode(part.ids.take(40).toIntArray()).replace("\n", "\\n").take(160)-                is Part.Image -> "image ${part.positions}"-                is Part.Audio -> "audio ${part.positions}"-                // Untokenised text should never survive `fitted`, so seeing one here is itself-                // the bug rather than a case to render nicely.-                is Part.Text -> "UNTOKENISED ${part.text.take(80)}"-            }-            Log.i(TAG, "  part $index  $what")-        }--        // Reuse whatever of the cache this prompt shares with the last one.-        //-        // A turn's prompt is nearly all of the previous turn's: the same system block, the same-        // tool declarations, the same history. Only the tail differs - the new user turn and the-        // generation prompt. The KV cache for the shared part is still in the arena and still-        // correct, because the tokens that produced it have not changed.-        //-        // Text-only prompts only. An image or audio part contributes soft tokens rather than-        // ids, so deciding whether two of them are "the same" means comparing megabytes of-        // floats - and getting that wrong does not fail, it answers a conversation that never-        // happened. The multimodal path re-feeds, exactly as it did before.-        val flat = if (parts.all { it is Part.Tokens }) {-            IntArray(length).also { out ->-                var at = 0-                for (part in parts) {-                    val ids = (part as Part.Tokens).ids-                    ids.copyInto(out, at)-                    at += ids.size-                }-            }-        } else {-            null-        }-        var reused = 0-        val prior = cachedIds-        if (flat != null && prior != null) {-            // Never reuse the final token: its logits are the prediction this turn needs, so it-            // has to be fed through `stepGemma4` rather than sat in the cache.-            val ceiling = minOf(prior.size, flat.size - 1)-            while (reused < ceiling && prior[reused] == flat[reused]) reused++-        }-        if (reused > 0 && MlNative.seekGemma4(handle, reused) == reused) {-            Log.i(TAG, "reused $reused of $length positions, feeding ${length - reused}")-        } else {-            reused = 0-            reset()-        }-        cachedIds = null--        // Everything but the very last token only fills the cache; its logits would be discarded.-        if (flat != null) {-            val feed = flat.copyOfRange(reused, flat.size - 1)-            if (feed.isNotEmpty() && MlNative.pushGemma4(handle, feed) < 0) return null-            // What the cache holds now. The reply's own tokens are appended as they are-            // generated, so the next turn matches against the whole exchange.-            cachedIds = flat.copyOfRange(0, flat.size - 1)-        } else {-        for ((index, part) in parts.withIndex()) {-            val fed = when (part) {-                is Part.Image -> MlNative.pushSoftGemma4(handle, part.soft)-                is Part.Audio -> MlNative.pushSoftGemma4(handle, part.soft)-                is Part.Tokens -> {-                    val ids = if (index == parts.lastIndex) part.ids.dropLast(1).toIntArray()-                    else part.ids-                    if (ids.isEmpty()) 0 else MlNative.pushGemma4(handle, ids)-                }-                is Part.Text -> -1-            }-            if (fed < 0) return null-        }-        }--        val produced = ArrayList<Int>(limit)-        var next = tail.ids.last()-        val room = minOf(limit, remaining - 1)-        for (step in 0 until room) {-            val token = MlNative.stepGemma4(handle, next)-            if (token < 0) break-            if (token in STOP) break-            produced.add(token)-            next = token-            if (!onToken(decode(produced.toIntArray()))) break-        }-        // The fed token and everything generated after it are in the cache too, so record them-        // and the next turn starts from the end of this reply rather than the start of the-        // conversation.-        cachedIds = cachedIds?.let { it + tail.ids.last() + produced.toIntArray() }-        return decode(produced.toIntArray())-    }--    /**-     * A prompt is not one string once an image is in it.-     *-     * An image has no token id to encode, so it cannot be spelled into the prompt and tokenised-     * with the rest. It arrives as the vision tower's `[n, 1536]` block and is pushed as an-     * embedding, which means the prompt has to be fed in order as a sequence of parts rather than-     * as one array.-     */-    internal sealed interface Part {-        /** How many positions in the KV cache this part occupies. */-        val positions: Int--        /** Text, before it has been tokenised. */-        data class Text(val text: String) : Part {-            override val positions: Int get() = 0-        }--        /** Text, tokenised. */-        data class Tokens(val ids: IntArray) : Part {-            override val positions: Int get() = ids.size--            override fun equals(other: Any?): Boolean =-                this === other || (other is Tokens && ids.contentEquals(other.ids))--            override fun hashCode(): Int = ids.contentHashCode()-        }--        /** One image's soft tokens, `n * 1536` from [Gemma4VisionHandle.encode]. */-        data class Image(val soft: FloatArray) : Part {-            override val positions: Int get() = soft.size / SOFT_TOKEN_WIDTH--            override fun equals(other: Any?): Boolean =-                this === other || (other is Image && soft.contentEquals(other.soft))--            override fun hashCode(): Int = soft.contentHashCode()-        }--        /**-         * One clip's soft tokens, `n * 1536` from [Gemma4AudioHandle.encode].-         *-         * Distinct from [Image] despite carrying the same shape and being pushed the same way,-         * because the two are bracketed by different markers and a clip in an image's brackets-         * is a prompt the model was never trained on. Collapsing them into one variant would-         * make that a one-character mistake.-         */-        data class Audio(val soft: FloatArray) : Part {-            override val positions: Int get() = soft.size / SOFT_TOKEN_WIDTH--            override fun equals(other: Any?): Boolean =-                this === other || (other is Audio && soft.contentEquals(other.soft))--            override fun hashCode(): Int = soft.contentHashCode()-        }-    }--    /**-     * [render]'s output, cut at every image and every clip.-     *-     * Media sits at the head of the turn that carries it, bracketed by [BOI]/[EOI] or-     * [BOA]/[EOA] the way the reference processor's `replace_image_token` and-     * `replace_audio_token` bracket their runs of placeholders. The placeholders themselves are-     * not emitted: their whole purpose is to reserve positions for the tower's rows, and the-     * rows are pushed directly.-     *-     * Images come before audio within a turn, which is the reference processor's own order.-     */-    private fun renderParts(-        conversation: List<Turn>,-        system: String?,-        tools: List<ToolDeclaration>,-        continuation: String = "",-    ): List<Part> {-        val parts = ArrayList<Part>()-        val text = StringBuilder()-        fun flush() {-            if (text.isNotEmpty()) {-                parts.add(Part.Text(text.toString()))-                text.clear()-            }-        }-        text.append("<bos>")-        val declared = declareTools(tools)-        if (!system.isNullOrBlank() || declared.isNotEmpty()) {-            text.append("<|turn>system\n")-            if (!system.isNullOrBlank()) text.append(system)-            text.append(declared)-            text.append("<turn|>\n")-        }-        for (turn in conversation) {-            text.append("<|turn>").append(turn.role.marker).append('\n')-            for (image in turn.images) {-                if (image.isEmpty() || image.size % SOFT_TOKEN_WIDTH != 0) continue-                parts.add(Part.Text(text.toString() + BOI_MARKER))-                text.clear()-                parts.add(Part.Image(image))-                text.append(EOI_MARKER)-            }-            for (clip in turn.audio) {-                if (clip.isEmpty() || clip.size % SOFT_TOKEN_WIDTH != 0) continue-                parts.add(Part.Text(text.toString() + BOA_MARKER))-                text.clear()-                parts.add(Part.Audio(clip))-                text.append(EOA_MARKER)-            }-            text.append(turn.text)-            text.append("<turn|>\n")-        }-        text.append("<|turn>model\n")-        // A tool call and its result belong **inside** the open model turn. Appending them as a-        // finished turn instead - `<|turn>model ... <turn|>` then a fresh `<|turn>model` - made-        // the model see its own turn ended and a new one begin, which reads as the start of a-        // conversation: it greeted instead of answering. Only the first message showed it,-        // because that is the one the system prompt forces a tool call on.-        text.append(continuation)-        flush()-        return parts-    }--    override fun close() {-        val live = handle-        handle = 0L-        if (live != 0L) MlNative.destroyGemma4(live)-    }--    override fun toString(): String = "Gemma 4 E2B in $directory"--    /**-     * One message in a conversation.-     *-     * [images] are [Gemma4VisionHandle.encode]'s output and [audio] is-     * [Gemma4AudioHandle.encode]'s, one entry per item, each occupying `size / 1536` positions at-     * the head of the turn. Pass them unscaled - the reference scatters both towers' rows into-     * the decoder's embeddings as they are.-     */-    data class Turn(-        val role: Role,-        val text: String,-        val images: List<FloatArray> = emptyList(),-        val audio: List<FloatArray> = emptyList(),-    )--    /** Who spoke. Gemma's own names, not OpenAI's: the model turn is `model`, not `assistant`. */-    enum class Role(internal val marker: String) {-        USER("user"),-        MODEL("model"),-    }--    /** A tool the model may call, in the shape [declareTools] serialises. */-    data class ToolDeclaration(-        val name: String,-        val description: String,-        val parameters: List<Parameter>,-    ) {-        /** One argument. [type] is Gemma's spelling: `STRING`, `NUMBER`, `BOOLEAN`. */-        data class Parameter(-            val name: String,-            val description: String,-            val type: String,-            val required: Boolean = true,-        )-    }--    /**-     * The prompt [generate] would build, with audio already fitted into what the reply leaves.-     *-     * One budget for the window, computed once, with the reply reserve and the audio trim both-     * reading from it - so the two cannot each reserve the space the other reserved.-     *-     * The reply is reserved here rather than left to `remaining - 1` in [generate]. That-     * expression hands the reply every position the prompt did not use, so a turn that spends its-     * budget leaves nothing for the turn after it and the conversation dies.-     *-     * Derived from the prompt in hand on every call, never from a constant: the fixed cost is-     * dominated by the tool declarations and moves whenever those do.-     */-    private fun fitted(-        conversation: List<Turn>,-        system: String?,-        tools: List<ToolDeclaration>,-        limit: Int,-        continuation: String = "",-    ): List<Part> {-        val rendered = renderParts(conversation, system, tools, continuation).map { part ->-            when (part) {-                is Part.Text -> Part.Tokens(encodePrompt(part.text))-                is Part.Image, is Part.Audio, is Part.Tokens -> part-            }-        }-        val fixed = rendered.sumOf { if (it is Part.Audio) 0 else it.positions }-        return fitAudio(rendered, promptCeiling(limit) - fixed)-    }--    /**-     * Positions the prompt for [conversation] would occupy, so a caller can drop history before-     * [generate] refuses it.-     *-     * Exists because [generate] cannot fix an over-long conversation itself: trimming audio is a-     * decision about one attachment, but deciding which turns a user may lose is the caller's.-     * This is the same arithmetic [generate] performs, so the two cannot disagree about whether-     * something fits - compare it against [promptCeiling] with the same `limit`.-     *-     * Zero when the model is unavailable, which reads as "fits" rather than stranding a caller-     * in a loop dropping turns that would never have been sent.-     */-    fun positionsFor(-        conversation: List<Turn>,-        system: String?,-        tools: List<ToolDeclaration> = emptyList(),-        limit: Int = DEFAULT_REPLY,-    ): Int {-        if (handle == 0L) return 0-        return fitted(conversation, system, tools, limit).sumOf { it.positions }-    }--    /** A call the model asked for, as [parseToolCall] found it. */-    data class ToolCall(val name: String, val arguments: Map<String, String>)--    companion object {-        internal const val TAG = "Gemma4Handle"--        /**-         * Reply positions [generate] reserves unless a caller says otherwise.-         *-         * One constant so the reserve and anything measuring against it cannot drift apart.-         */-        const val DEFAULT_REPLY = 512--        /**-         * The most positions a prompt may occupy while still leaving [limit] for the reply.-         *-         * The guard's own bound and the reply reserve are not additive - they compete for the-         * same tail of the window, so the binding constraint is the larger of the two. `maxOf`-         * says that directly; subtracting both would give back one position fewer than the model-         * could have used, at every limit.-         */-        fun promptCeiling(limit: Int = DEFAULT_REPLY): Int = MAX_CONTEXT - maxOf(limit, 3)--        /**-         * [parts] with its audio trimmed to at most [budget] positions in total.-         *-         * A clip is trimmed from its end, so the model hears the start of a recording rather-         * than a window out of the middle of it, and earlier clips are served before later ones.-         *-         * A clip trimmed to nothing is dropped. The `<|audio>` brackets [renderParts] put around-         * it stay, because they are already tokenised into the neighbouring text by the time this-         * runs and two positions do not justify a second tokenisation pass to reclaim.-         *-         * Returns [parts] itself when there is no audio, so a text turn is untouched by all of-         * this - the budget can only ever take positions away from a clip, never from the prompt.-         *-         * Pure, and `internal` rather than private, so the unit tests can show the trim actually-         * firing. A guard that cannot fire is worse than no guard, and this one is invisible from-         * outside. The caller does the logging: keeping `android.util.Log` out of here is what-         * lets it be tested on the JVM at all.-         */-        internal fun fitAudio(parts: List<Part>, budget: Int): List<Part> {-            if (parts.none { it is Part.Audio }) return parts-            var left = budget.coerceAtLeast(0)-            val out = ArrayList<Part>(parts.size)-            for (part in parts) {-                if (part !is Part.Audio) {-                    out.add(part)-                    continue-                }-                val want = part.positions-                val keep = want.coerceAtMost(left)-                left -= keep-                when {-                    keep == want -> out.add(part)-                    keep > 0 -> out.add(Part.Audio(part.soft.copyOf(keep * SOFT_TOKEN_WIDTH)))-                }-            }-            return out-        }--        /** The decoder. Native checks its graph id, so a wrong file fails at load. */-        const val TEXT = "gemma4_text.maml"--        /** The two embedding tables, host-gathered. */-        const val EMBED = "gemma4_embed.maml"--        /** `scripts/ml/gemma4_tokenizer.py`'s output. */-        const val TOKENIZER = "gemma4_tokenizer.spm1"--        /** The files [inDirectory] needs, for a caller checking a download is complete. */-        val FILES: List<String> = listOf(TEXT, EMBED, TOKENIZER)--        /** Positions the runtime offers. Mirrors `nets::gemma4::MAX_CONTEXT`. */-        const val MAX_CONTEXT = 16384--        /** Channels in one soft token, which is the decoder's `hidden_size`. */-        const val SOFT_TOKEN_WIDTH = 1536--        /**-         * The marker that opens an image, `boi_token` in the checkpoint's tokenizer config.-         *-         * The run of `<|image|>` placeholders the reference puts between this and [EOI_MARKER] is-         * **not** emitted here. Those exist to reserve positions for the tower's rows, and this-         * pushes the rows themselves - so spelling the placeholders as well would double every-         * image's cost in context and feed the model a run of embeddings it was never shown.-         */-        const val BOI_MARKER = "<|image>"--        /** The marker that closes an image, `eoi_token`. See [BOI_MARKER]. */-        const val EOI_MARKER = "<image|>"--        /**-         * The marker that opens a clip, `boa_token`, id 256000.-         *-         * Read off the tokenizer rather than assumed to mirror [BOI_MARKER]: the two families do-         * turn out to share a shape, `<|x>` opening and `<x|>` closing, but they interleave in-         * id order - image 255999, audio 256000, then `<|image|>` 258880, `<|audio|>` 258881,-         * `<image|>` 258882, `<audio|>` 258883 - so neither pair can be derived from the other.-         *-         * As with images, the `<|audio|>` placeholders the reference emits between these are-         * **not** written here: they exist to reserve positions for the tower's rows, and this-         * pushes the rows themselves.-         */-        const val BOA_MARKER = "<|audio>"--        /** The marker that closes a clip, `eoa_token`. See [BOA_MARKER]. */-        const val EOA_MARKER = "<audio|>"--        /**-         * Ids that end a reply, from the checkpoint's `generation_config.json`.-         *-         * Three, not one. `<eos>` is 1, but an instruction-tuned Gemma ends its reply with-         * `<turn|>` (106) and `<eos>` almost never appears - stopping only on 1 would let the-         * model run on emitting turn markers until the token budget stopped it instead.-         */-        val STOP = intArrayOf(1, 106, 50)--        /**-         * The markers [encodePrompt] honours, and which user text therefore cannot spell.-         *-         * Read off the checkpoint's `chat_template.jinja`, plus the image and audio brackets,-         * which are markers for the same reason the turn tags are: a user who could spell-         * [BOI_MARKER] could claim to have sent a picture.-         *-         * **Every marker [renderParts] emits must be in here.** A marker that is emitted but not-         * declared is encoded as literal characters instead of its own id, which is not an error-         * anywhere - the prompt still tokenises, the turn still runs, and the decoder simply-         * never sees the `boa` 256000 or `eoa` 258883 it was trained to bracket soft tokens-         * with. The audio pair was emitted for some hours before it was declared here.-         *-         * `internal` rather than private so `Gemma4MarkersTest` can enforce that coupling, which-         * nothing else does.-         */-        internal val MARKERS = arrayOf(-            "<bos>", "<eos>", "<|turn>", "<turn|>",-            "<|tool>", "<tool|>", "<|tool_call>", "<tool_call|>",-            "<|tool_response>", "<tool_response|>", "<|\"|>",-            BOI_MARKER, EOI_MARKER, BOA_MARKER, EOA_MARKER,-        )--        /**-         * A conversation as the prompt string Gemma was trained on.-         *-         * Ported from `chat_template.jinja` by rendering it and matching the output exactly.-         * The implementation lives in [renderGemma4Prompt]; this wrapper keeps existing-         * call sites working.-         */-        fun render(-            conversation: List<Turn>,-            system: String?,-            tools: List<ToolDeclaration> = emptyList(),-            continuation: String = "",-        ): String = renderGemma4Prompt(conversation, system, tools, continuation)--        /**-         * Tool declarations in the template's own syntax. Implemented in-         * [declareGemma4Tools]; this wrapper keeps existing call sites working.-         */-        fun declareTools(tools: List<ToolDeclaration>): String = declareGemma4Tools(tools)--        /**-         * The tool call in [reply], or null if there is not a complete one.-         * Implemented in [parseGemma4ToolCall]; this wrapper keeps existing call sites working.-         */-        fun parseToolCall(reply: String): ToolCall? = parseGemma4ToolCall(reply)--        /** A tool's result, in the shape the model expects to read back. */-        fun renderToolResponse(name: String, value: String): String =-            renderGemma4ToolResponse(name, value)--        /** Gemma's value delimiter, which is a token rather than a quotation mark. */-        private const val QUOTE = "<|\"|>"--        private fun quoted(value: String): String = QUOTE + value + QUOTE--        /**-         * The model in a folder on disk, which is the only place it lives.-         *-         * Construction never throws: a missing file or an unsupported device leaves-         * [isAvailable] false and the assistant simply off.-         */-        fun inDirectory(directory: File): Gemma4Handle = Gemma4Handle(directory)--        // Native handle construction (create, fd close, cache budget) lives in Gemma4Prefix.kt.-        private fun create(directory: File): Long = createGemma4Handle(directory)--        /** The baked prefix cache, beside the weights. Optional. */-        const val PREFIX_CACHE = "gemma4_prefix.kv"--        /** `GKV1` + positions + stride + a 32-byte digest. */-        internal const val HEADER = 4 + 4 + 4 + 32--        internal fun readInt(bytes: ByteArray, at: Int): Int =-            (bytes[at].toInt() and 0xFF) or-                ((bytes[at + 1].toInt() and 0xFF) shl 8) or-                ((bytes[at + 2].toInt() and 0xFF) shl 16) or-                ((bytes[at + 3].toInt() and 0xFF) shl 24)--        /**-         * The digest `bake_gemma4_prefix` writes: FNV-1a over the token bytes, four times with-         * different seeds to fill 32 bytes.-         *-         * Not cryptographic, and does not need to be: it guards against a stale asset after-         * someone edits the prompt, not against an adversary who could replace the weights too.-         */-        internal fun digest(tokens: IntArray): ByteArray {-            val out = ByteArray(32)-            for (lane in 0 until 4) {-                // `0x9e3779b9`, the **32-bit** golden ratio, because that is what-                // `bake_gemma4_prefix` seeds with. The 64-bit one was here first and matched on-                // lane 0 only - so the digest disagreed while the token count agreed, and a-                // perfectly good cache was rejected as "baked for a different prompt".-                var hash = -0x340d631b7bdddcdbL xor (lane.toLong() * 0x9e3779b9L)-                for (token in tokens) {-                    for (shift in 0 until 4) {-                        hash = hash xor ((token ushr (shift * 8)).toLong() and 0xFF)-                        hash *= 0x100000001b3L-                    }-                }-                for (byte in 0 until 8) {-                    out[lane * 8 + byte] = (hash ushr (byte * 8)).toByte()-                }-            }-            return out-        }--    }-}
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.ktdeleted file mode 100644index 648dc7be4e..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prefix.kt+++ /dev/null@@ -1,188 +0,0 @@-package com.vayunmathur.library.ml--import android.os.ParcelFileDescriptor-import android.util.Log-import java.io.File--/**- * The baked prefix-cache half of [Gemma4Handle] (plus the one-shot benchmark),- * as `internal` extensions so Gemma4Handle.kt stays under the FileLength limit.- * The public entry points stay on the handle and delegate here.- */--/**- * Time the model once, so the log says where its time goes.- *- * Runs three passes each way and keeps the best, which costs a couple of seconds the first- * time a conversation starts and answers a question that guesswork has repeatedly got wrong.- */-internal fun Gemma4Handle.runBenchmark() {-    if (handle != 0L) {-        MlNative.capabilitiesGemma4()-        MlNative.imageProbeGemma4()-        MlNative.benchmarkGemma4(handle)-    }-}--/**- * Load the baked cache for [prefix], if it is present and matches. Returns whether it did.- *- * # The check is the point- *- * The asset encodes keys and values for one exact token sequence. If the system prompt or- * the tool set has changed since it was baked, those numbers describe a prompt the model is- * not being given - and nothing downstream could tell, because a KV cache is only attended- * over, never compared. So this re-encodes [prefix] here and refuses unless the digest of- * the result matches the one in the file.- *- * A mismatch is not an error: it falls back to prefilling, which is slow and correct.- */-internal fun Gemma4Handle.loadBakedPrefix(prefix: String): Boolean {-    if (handle == 0L) return false-    val file = java.io.File(directory, Gemma4Handle.PREFIX_CACHE)-    if (!file.isFile) return false-    val tokens = encodePrompt(prefix)-    if (tokens.isEmpty()) return false-    val blob = runCatching { file.readBytes() }.getOrNull() ?: return false-    if (blob.size < Gemma4Handle.HEADER || String(blob, 0, 4, Charsets.US_ASCII) != "GKV1") {-        Log.w(Gemma4Handle.TAG, "${Gemma4Handle.PREFIX_CACHE} is not a baked cache")-        return false-    }-    val positions = Gemma4Handle.readInt(blob, 4)-    // The size check stays enforced even though the digest does not: `positions` decides-    // where the next token goes and how many ids are recorded as cached, so a wrong count-    // corrupts the bookkeeping rather than merely the contents.-    if (positions != tokens.size) {-        Log.i(Gemma4Handle.TAG, "${Gemma4Handle.PREFIX_CACHE} is $positions positions, this prefix is ${tokens.size}")-        return false-    }-    // The digest is reported, not enforced.-    //-    // It says whether these keys and values were computed from *these* tokens, and a-    // mismatch means the model is about to attend over a prompt it was not given. Refusing-    // is the safe behaviour and what this did first. It is advisory while the prefix is-    // still being iterated on, because a stale cache should slow the work down rather than-    // stop it - but a mismatch here is a real defect, not noise, and the loud log is the-    // only thing standing between it and a plausible wrong answer.-    if (!Gemma4Handle.digest(tokens).contentEquals(blob.copyOfRange(12, 12 + 32))) {-        Log.w(Gemma4Handle.TAG, "${Gemma4Handle.PREFIX_CACHE} DIGEST MISMATCH - using it anyway; replies may be wrong")-    }-    // The cache starts at the smallest tier and this prefix is larger than it. Growing first-    // is not optional: `loadPrefixGemma4` refuses a prefix bigger than the cache rather than-    // truncating it, because half a prefix is keys for a prompt nobody sent.-    if (MlNative.capacityGemma4(handle) < positions) {-        val grown = MlNative.growGemma4(handle, positions + 2)-        if (grown < positions) {-            Log.i(Gemma4Handle.TAG, "a $positions-position prefix does not fit this device; prefilling")-            return false-        }-    }-    val loaded = MlNative.loadPrefixGemma4(handle, positions, blob.copyOfRange(Gemma4Handle.HEADER, blob.size))-    if (loaded != positions) return false-    // The cache now holds exactly these tokens, so the next turn matches against them and-    // feeds only what follows.-    cachedIds = tokens-    Log.i(Gemma4Handle.TAG, "loaded a $positions-position prefix cache, skipping its prefill")-    return true-}--/**- * Open both graphs, read the tokenizer, and hand the descriptors over.- *- * Two descriptors rather than one, so the `finally` dance is doubled. Native adopts both- * and closes both on every path including failure, so [handed] guards the window between- * detaching and native taking ownership - and both must be closed here if the call is- * never made.- */-internal fun createGemma4Handle(directory: File): Long {-    val text = File(directory, Gemma4Handle.TEXT)-    val embed = File(directory, Gemma4Handle.EMBED)-    val tokenizer = File(directory, Gemma4Handle.TOKENIZER)-    for (file in listOf(text, embed, tokenizer)) {-        if (!file.isFile) {-            Log.w(Gemma4Handle.TAG, "${file.name} is missing from $directory")-            return 0L-        }-    }-    val table = runCatching { tokenizer.readBytes() }.getOrElse {-        Log.w(Gemma4Handle.TAG, "cannot read ${Gemma4Handle.TOKENIZER}: $it")-        return 0L-    }-    val textFd = runCatching {-        ParcelFileDescriptor.open(text, ParcelFileDescriptor.MODE_READ_ONLY)-            .use { it.detachFd() }-    }.getOrElse {-        Log.w(Gemma4Handle.TAG, "cannot open ${Gemma4Handle.TEXT}: $it")-        return 0L-    }-    val embedFd = runCatching {-        ParcelFileDescriptor.open(embed, ParcelFileDescriptor.MODE_READ_ONLY)-            .use { it.detachFd() }-    }.getOrElse {-        closeGemma4Fd(textFd)-        Log.w(Gemma4Handle.TAG, "cannot open ${Gemma4Handle.EMBED}: $it")-        return 0L-    }-    var handed = false-    try {-        val live = MlNative.createGemma4(-            textFd, 0L, text.length(),-            embedFd, 0L, embed.length(),-            table,-            gemma4CacheBudget(),-        )-        handed = true-        return live-    } finally {-        if (!handed) {-            closeGemma4Fd(textFd)-            closeGemma4Fd(embedFd)-        }-    }-}--/**- * 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.- *- * # Why it is a fraction of *total* rather than available memory- *- * Available memory is whatever the rest of the system happens to be doing when the- * assistant starts, so sizing against it makes the conversation length depend on what- * else was open - and shrinks it exactly when the user has been busy. Total memory is a- * property of the device, which is what the tier should track.- *- * A twentieth is deliberately conservative. The weights are already ~2.9 GB of mapped- * file and the tower allocations sit on top, so the cache is not the only claim on the- * budget - and an allocation failure here is a model that will not start at all.- *- *   4 GB  ->  200 MB  ->  8,192 positions- *   8 GB  ->  400 MB  -> 16,384 positions- *  16 GB  ->  800 MB  -> 16,384 positions, the top tier- */-private fun gemma4CacheBudget(): Long {-    // `/proc/meminfo` rather than `ActivityManager`, because this class is constructed-    // from a directory and has no `Context` - and adding one to the signature to read a-    // single number would push Android into an API that is otherwise platform-free.-    val total = runCatching {-        File("/proc/meminfo").useLines { lines ->-            lines.firstOrNull { it.startsWith("MemTotal:") }-                ?.filter(Char::isDigit)-                ?.toLongOrNull()-                ?.times(1024) ?: 0L-        }-    }.getOrDefault(0L)-    // A device that will not say gets the smallest tier, which always fits, rather than-    // an optimistic guess that fails to allocate and leaves the assistant dead.-    if (total <= 0L) return 0L-    return total / 20-}
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prompt.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prompt.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prompt.ktdeleted file mode 100644index b1f1d4b8c3..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Prompt.kt+++ /dev/null@@ -1,136 +0,0 @@-package com.vayunmathur.library.ml--/**- * Gemma's chat template and tool protocol, as pure functions over- * [Gemma4Handle.Turn] and [Gemma4Handle.ToolDeclaration].- *- * Split out of [Gemma4Handle]'s companion so the handle file stays under the- * FileLength limit. The companion keeps thin delegating wrappers, so every- * existing `Gemma4Handle.render(...)` / `declareTools(...)` /- * `parseToolCall(...)` / `renderToolResponse(...)` call site keeps working.- */--/**- * A conversation as the prompt string Gemma was trained on.- *- * Ported from `chat_template.jinja` by rendering it and matching the output exactly,- * rather than by reading the Jinja - the macros are dense and the quoting is unusual, and- * a template that is nearly right degrades quality without failing. The shape is:- *- * ```text- * <bos><|turn>system\n{system}{tools}<turn|>\n<|turn>user\n{text}<turn|>\n<|turn>model\n- * ```- *- * The system turn is emitted only when there is a system prompt or a tool to declare,- * matching the template's own conditional.- */-fun renderGemma4Prompt(-    conversation: List<Gemma4Handle.Turn>,-    system: String?,-    tools: List<Gemma4Handle.ToolDeclaration> = emptyList(),-    continuation: String = "",-): String = buildString {-    append("<bos>")-    val declared = declareGemma4Tools(tools)-    if (!system.isNullOrBlank() || declared.isNotEmpty()) {-        append("<|turn>system\n")-        if (!system.isNullOrBlank()) append(system)-        append(declared)-        append("<turn|>\n")-    }-    for (turn in conversation) {-        append("<|turn>").append(turn.role.marker).append('\n')-        append(turn.text)-        append("<turn|>\n")-    }-    // The generation prompt: an open model turn for the model to complete.-    append("<|turn>model\n")-    // A tool call and its result belong **inside** that turn, not before it.-    //-    // Appending them as a finished model turn instead - `<|turn>model ... <turn|>` and-    // then a fresh `<|turn>model` - was a real bug and a subtle one: the model saw its-    // own turn ended and a new one beginning, which from its point of view is the start-    // of a conversation, so it opened with a greeting instead of answering. It only-    // showed on the first message, because that is the one the system prompt forces a-    // tool call on.-    append(continuation)-}--/**- * Tool declarations in the template's own syntax.- *- * Not JSON. Gemma's template writes `<|tool>declaration:name{...}<tool|>` with values- * wrapped in the `<|"|>` marker rather than in quotation marks, so that a description- * containing a quote cannot break the parse. Reproduced exactly, including the- * alphabetical ordering of parameters that `dictsort` imposes - the model saw them in- * that order during training.- */-fun declareGemma4Tools(tools: List<Gemma4Handle.ToolDeclaration>): String = buildString {-    for (tool in tools) {-        append("<|tool>declaration:").append(tool.name).append('{')-        append("description:").append(quotedGemma4(tool.description))-        append(",parameters:{properties:{")-        val sorted = tool.parameters.sortedBy { it.name }-        for ((index, parameter) in sorted.withIndex()) {-            if (index > 0) append(',')-            append(parameter.name).append(":{description:")-            append(quotedGemma4(parameter.description))-            append(",type:").append(quotedGemma4(parameter.type.uppercase()))-            append('}')-        }-        append("}")-        val required = sorted.filter { it.required }-        if (required.isNotEmpty()) {-            append(",required:[")-            append(required.joinToString(",") { quotedGemma4(it.name) })-            append(']')-        }-        append(",type:").append(quotedGemma4("OBJECT"))-        append("}}<tool|>")-    }-}--/**- * The tool call in [reply], or null if there is not a complete one.- *- * The model emits `<|tool_call>call:name{arg:<|"|>value<|"|>}<tool_call|>`. Parsed rather- * than pattern-matched loosely because a half-written call arrives during streaming and- * must not be acted on: this returns null until the closing marker is present.- */-fun parseGemma4ToolCall(reply: String): Gemma4Handle.ToolCall? {-    val open = reply.indexOf("<|tool_call>call:")-    if (open < 0) return null-    val close = reply.indexOf("<tool_call|>", open)-    if (close < 0) return null-    val body = reply.substring(open + "<|tool_call>call:".length, close)-    val brace = body.indexOf('{')-    if (brace < 0) return null-    val name = body.substring(0, brace).trim()-    if (name.isEmpty()) return null-    val arguments = LinkedHashMap<String, String>()-    var at = brace + 1-    while (at < body.length) {-        val colon = body.indexOf(':', at)-        if (colon < 0) break-        val key = body.substring(at, colon).trim().trim(',', '{', '}')-        val valueStart = body.indexOf(GEMMA4_QUOTE, colon)-        if (valueStart < 0) break-        val valueEnd = body.indexOf(GEMMA4_QUOTE, valueStart + GEMMA4_QUOTE.length)-        if (valueEnd < 0) break-        if (key.isNotEmpty()) {-            arguments[key] = body.substring(valueStart + GEMMA4_QUOTE.length, valueEnd)-        }-        at = valueEnd + GEMMA4_QUOTE.length-        if (at < body.length && body[at] == ',') at++-    }-    return Gemma4Handle.ToolCall(name, arguments)-}--/** A tool's result, in the shape the model expects to read back. */-fun renderGemma4ToolResponse(name: String, value: String): String =-    "<|tool_response>response:$name{value:${quotedGemma4(value)}}<tool_response|>"--/** Gemma's value delimiter, which is a token rather than a quotation mark. */-internal const val GEMMA4_QUOTE = "<|\"|>"--internal fun quotedGemma4(value: String): String = GEMMA4_QUOTE + value + GEMMA4_QUOTE
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.ktdeleted file mode 100644index 13890c6a37..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4VisionHandle.kt+++ /dev/null@@ -1,136 +0,0 @@-package com.vayunmathur.library.ml--import android.graphics.Bitmap-import android.os.ParcelFileDescriptor-import android.util.Log-import androidx.core.graphics.scale-import java.io.File--/**- * Gemma 4's vision tower: an image in, the soft tokens the decoder reads in its place.- *- * Restores the image input that `com.google.ai.edge.litertlm` used to provide. [Gemma4Handle] is- * text-only; this produces the `[n, 1536]` block that stands in for an image in its prompt, and- * [Gemma4Handle.generate] splices it in.- *- * # A separate file and a separate handle- *- * The tower is its own `.maml` with its own graph id, downloaded separately. A device that never- * sends an image never fetches it, and a tower that fails to load leaves the assistant answering- * text rather than taking it down.- *- * # The resize is here, the size is not- *- * Bitmap work belongs on the platform, as it does for `ClipEmbedder`. But the target size is the- * reference preprocessor's aspect-ratio-preserving fit to a patch budget, and being one 48-pixel- * block out changes how many soft tokens come back - so [MlNative.gemma4VisionSize] decides and- * [encode] obeys.- *- * # Threading- *- * 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 {--    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--    /**-     * Soft tokens for [image] as one flat `n * 1536` array, or null.-     *-     * [softTokens] is the patch budget, and the cost is quadratic in it: at [SOFT_TOKENS_DEFAULT]-     * a square image is a 48x48 patch grid whose two attention score maps alone are 254 MB of-     * scratch. The smaller budgets in [SOFT_TOKEN_BUDGETS] trade detail for that.-     *-     * Divide the length by [OUT_DIM] for the number of soft tokens, which varies with the-     * image's aspect ratio and is what [Gemma4Handle.generate] must reserve placeholders for.-     */-    fun encode(image: Bitmap, softTokens: Int = SOFT_TOKENS_DEFAULT): FloatArray? {-        if (handle == 0L) return null-        val size = MlNative.gemma4VisionSize(image.width, image.height, softTokens)-        if (size == null || size.size != 2) {-            Log.w(TAG, "no vision grid for ${image.width}x${image.height} at $softTokens")-            return null-        }-        val (width, height) = size-        // ARGB_8888 because `getPixels` needs a readable config, and a HARDWARE bitmap is not.-        val scaled = runCatching {-            image.scale(width, height).copy(Bitmap.Config.ARGB_8888, false)-        }.getOrElse {-            Log.w(TAG, "cannot resize to ${width}x$height: $it")-            return null-        }-        val pixels = IntArray(width * height)-        scaled.getPixels(pixels, 0, width, 0, 0, width, height)-        if (scaled !== image) scaled.recycle()-        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"--    companion object {-        private const val TAG = "Gemma4VisionHandle"--        /** The tower. Native checks its graph id, so a wrong file fails at load. */-        const val VISION = "gemma4_vision.maml"--        /** Channels per soft token, which is the decoder's `hidden_size`. */-        const val OUT_DIM = 1536--        /**-         * Patch budgets the reference processor accepts. Mirrors-         * `nets::gemma4_vision::SOFT_TOKEN_BUDGETS`.-         */-        val SOFT_TOKEN_BUDGETS = intArrayOf(70, 140, 280, 560, 1120)--        /**-         * The budget to use unless a caller says otherwise, which is the reference's own default.-         *-         * A square image becomes a 48x48 patch grid and 256 soft tokens. That is the faithful-         * choice and the expensive one - see [encode].-         */-        const val SOFT_TOKENS_DEFAULT = 280--        /** The tower in a folder on disk. Construction never throws. */-        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.w(TAG, "${file.name} is missing")-                return 0L-            }-            val fd = runCatching {-                ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)-                    .use { it.detachFd() }-            }.getOrElse {-                Log.w(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() }-            }-        }-    }-}
library/ml/src/main/java/com/vayunmathur/library/ml/GemmaOnnxHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaOnnxHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaOnnxHandle.ktindex 8a52d7947a..e04cefecc5 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaOnnxHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaOnnxHandle.kt@@ -70,7 +70,7 @@ class GemmaOnnxHandle private constructor(private val directory: File) : AutoClo      */     fun generate(         parts: List<PromptPart>,-        limit: Int = Gemma4Handle.DEFAULT_REPLY,+        limit: Int = GEMMA_DEFAULT_REPLY,         onPiece: (String) -> Boolean = { true },     ): String? {         if (!ensure(requireTowers = parts.any { it is PromptPart.Media })) return null@@ -113,6 +113,10 @@ class GemmaOnnxHandle private constructor(private val directory: File) : AutoClo     fun encodeText(text: String): IntArray =         tokenizer?.encode(text) ?: IntArray(0) +    /** Token ids for a rendered prompt, honouring the chat markers. */+    fun encodePrompt(text: String): IntArray =+        tokenizer?.encodePrompt(text) ?: IntArray(0)+     /** Text for token ids. */     fun decode(ids: IntArray): String =         tokenizer?.decode(ids).orEmpty()
library/ml/src/main/java/com/vayunmathur/library/ml/GemmaTypes.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaTypes.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaTypes.ktnew file mode 100644index 0000000000..ca17432369--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/GemmaTypes.kt@@ -0,0 +1,274 @@+package com.vayunmathur.library.ml++/**+ * Gemma 4's chat types, prompt template and tool protocol — pure Kotlin, no native code.+ *+ * Split out of the old Vulkan `Gemma4Handle` so the ONNX path (`GemmaOnnxHandle`,+ * `Gemma4Engine`) keeps the conversation model, the template, the tool syntax and the+ * window budget without the JNI handle. Everything here is exercised by the unit tests and+ * by `:openassistant`; nothing here touches a model file.+ */++/**+ * One message in a conversation.+ *+ * [images] are soft tokens (`n * 1536` floats) at the head of the turn, [audio] likewise+ * for clips. Pass them unscaled.+ */+data class GemmaTurn(+    val role: GemmaRole,+    val text: String,+    val images: List<FloatArray> = emptyList(),+    val audio: List<FloatArray> = emptyList(),+)++/** Who spoke. Gemma's own names, not OpenAI's: the model turn is `model`, not `assistant`. */+enum class GemmaRole(internal val marker: String) {+    USER("user"),+    MODEL("model"),+}++/** A tool the model may call, in the shape [declareGemmaTools] serialises. */+data class GemmaToolDeclaration(+    val name: String,+    val description: String,+    val parameters: List<Parameter>,+) {+    /** One argument. [type] is Gemma's spelling: `STRING`, `NUMBER`, `BOOLEAN`. */+    data class Parameter(+        val name: String,+        val description: String,+        val type: String,+        val required: Boolean = true,+    )+}++/** A call the model asked for, as [parseGemmaToolCall] found it. */+data class GemmaToolCall(val name: String, val arguments: Map<String, String>)++/**+ * A prompt segment: tokenised text, or soft tokens for one image or clip.+ *+ * Media sits at the head of the turn that carries it, bracketed by [BOI_MARKER]/[EOI_MARKER]+ * or [BOA_MARKER]/[EOA_MARKER] the way the reference processor's `replace_image_token` and+ * `replace_audio_token` bracket their runs of placeholders.+ */+sealed interface GemmaPart {+    /** How many positions in the context window this part occupies. */+    val positions: Int++    /** Text, tokenised. */+    data class Tokens(val ids: IntArray) : GemmaPart {+        override val positions: Int get() = ids.size++        override fun equals(other: Any?): Boolean =+            this === other || (other is Tokens && ids.contentEquals(other.ids))++        override fun hashCode(): Int = ids.contentHashCode()+    }++    /** One image's soft tokens, `n * 1536`. */+    data class Image(val soft: FloatArray) : GemmaPart {+        override val positions: Int get() = soft.size / GEMMA_SOFT_TOKEN_WIDTH++        override fun equals(other: Any?): Boolean =+            this === other || (other is Image && soft.contentEquals(other.soft))++        override fun hashCode(): Int = soft.contentHashCode()+    }++    /**+     * One clip's soft tokens, `n * 1536`.+     *+     * Distinct from [Image] despite carrying the same shape, because the two are bracketed+     * by different markers and a clip in an image's brackets is a prompt the model was never+     * trained on.+     */+    data class Audio(val soft: FloatArray) : GemmaPart {+        override val positions: Int get() = soft.size / GEMMA_SOFT_TOKEN_WIDTH++        override fun equals(other: Any?): Boolean =+            this === other || (other is Audio && soft.contentEquals(other.soft))++        override fun hashCode(): Int = soft.contentHashCode()+    }+}++/** Reply positions `generate` reserves unless a caller says otherwise. */+const val GEMMA_DEFAULT_REPLY = 512++/** Positions the runtime offers. */+const val GEMMA_MAX_CONTEXT = 16384++/** Channels in one soft token, which is the decoder's `hidden_size`. */+const val GEMMA_SOFT_TOKEN_WIDTH = 1536++/**+ * The most positions a prompt may occupy while still leaving [limit] for the reply.+ *+ * The guard's own bound and the reply reserve are not additive - they compete for the+ * same tail of the window, so the binding constraint is the larger of the two.+ */+fun gemmaPromptCeiling(limit: Int = GEMMA_DEFAULT_REPLY): Int =+    GEMMA_MAX_CONTEXT - maxOf(limit, 3)++/**+ * [parts] with its audio trimmed to at most [budget] positions in total.+ *+ * A clip is trimmed from its end, so the model hears the start of a recording rather+ * than a window out of the middle of it, and earlier clips are served before later ones.+ * A clip trimmed to nothing is dropped. Returns [parts] itself when there is no audio.+ */+fun fitGemmaAudio(parts: List<GemmaPart>, budget: Int): List<GemmaPart> {+    if (parts.none { it is GemmaPart.Audio }) return parts+    var left = budget.coerceAtLeast(0)+    val out = ArrayList<GemmaPart>(parts.size)+    for (part in parts) {+        if (part !is GemmaPart.Audio) {+            out.add(part)+            continue+        }+        val want = part.positions+        val keep = want.coerceAtMost(left)+        left -= keep+        when {+            keep == want -> out.add(part)+            keep > 0 -> out.add(GemmaPart.Audio(part.soft.copyOf(keep * GEMMA_SOFT_TOKEN_WIDTH)))+        }+    }+    return out+}++/** The marker that opens an image, `boi_token` in the checkpoint's tokenizer config. */+const val GEMMA_BOI_MARKER = "<|image>"++/** The marker that closes an image, `eoi_token`. */+const val GEMMA_EOI_MARKER = "<image|>"++/** The marker that opens a clip, `boa_token`, id 256000. */+const val GEMMA_BOA_MARKER = "<|audio>"++/** The marker that closes a clip, `eoa_token`. */+const val GEMMA_EOA_MARKER = "<audio|>"++/** Ids that end a reply: `<eos>` 1, `<turn|>` 106, double-newline 50. */+val GEMMA_STOP = intArrayOf(1, 106, 50)++/**+ * The markers prompt encoding honours, and which user text therefore cannot spell.+ *+ * **Every marker the renderer emits must be in here.** A marker that is emitted but not+ * declared encodes as literal characters instead of its own id, which is not an error+ * anywhere - and the decoder simply never sees the delimiter it was trained on.+ */+val GEMMA_MARKERS = arrayOf(+    "<bos>", "<eos>", "<|turn>", "<turn|>",+    "<|tool>", "<tool|>", "<|tool_call>", "<tool_call|>",+    "<|tool_response>", "<tool_response|>", "<|\"|>",+    GEMMA_BOI_MARKER, GEMMA_EOI_MARKER, GEMMA_BOA_MARKER, GEMMA_EOA_MARKER,+)++/**+ * A conversation as the prompt string Gemma was trained on.+ *+ * Ported from `chat_template.jinja` by rendering it and matching the output exactly:+ * `<bos><|turn>system\n{system}{tools}<turn|>\n<|turn>user\n{text}<turn|>\n<|turn>model\n`.+ * The system turn is emitted only when there is a system prompt or a tool to declare.+ */+fun renderGemmaPrompt(+    conversation: List<GemmaTurn>,+    system: String?,+    tools: List<GemmaToolDeclaration> = emptyList(),+    continuation: String = "",+): String = buildString {+    append("<bos>")+    val declared = declareGemmaTools(tools)+    if (!system.isNullOrBlank() || declared.isNotEmpty()) {+        append("<|turn>system\n")+        if (!system.isNullOrBlank()) append(system)+        append(declared)+        append("<turn|>\n")+    }+    for (turn in conversation) {+        append("<|turn>").append(turn.role.marker).append('\n')+        append(turn.text)+        append("<turn|>\n")+    }+    // A tool call and its result belong **inside** the open model turn, not before it.+    append("<|turn>model\n")+    append(continuation)+}++/**+ * Tool declarations in the template's own syntax: `<|tool>declaration:name{...}<tool|>`+ * with values wrapped in the `<|"|>` marker, parameters in alphabetical order.+ */+fun declareGemmaTools(tools: List<GemmaToolDeclaration>): String = buildString {+    for (tool in tools) {+        append("<|tool>declaration:").append(tool.name).append('{')+        append("description:").append(quotedGemma(tool.description))+        append(",parameters:{properties:{")+        val sorted = tool.parameters.sortedBy { it.name }+        for ((index, parameter) in sorted.withIndex()) {+            if (index > 0) append(',')+            append(parameter.name).append(":{description:")+            append(quotedGemma(parameter.description))+            append(",type:").append(quotedGemma(parameter.type.uppercase()))+            append('}')+        }+        append("}")+        val required = sorted.filter { it.required }+        if (required.isNotEmpty()) {+            append(",required:[")+            append(required.joinToString(",") { quotedGemma(it.name) })+            append(']')+        }+        append(",type:").append(quotedGemma("OBJECT"))+        append("}}<tool|>")+    }+}++/**+ * The tool call in [reply], or null if there is not a complete one.+ *+ * The model emits `<|tool_call>call:name{arg:<|"|>value<|"|>}<tool_call|>`. Returns null+ * until the closing marker is present, so a half-written call during streaming is never+ * acted on.+ */+fun parseGemmaToolCall(reply: String): GemmaToolCall? {+    val open = reply.indexOf("<|tool_call>call:")+    if (open < 0) return null+    val close = reply.indexOf("<tool_call|>", open)+    if (close < 0) return null+    val body = reply.substring(open + "<|tool_call>call:".length, close)+    val brace = body.indexOf('{')+    if (brace < 0) return null+    val name = body.substring(0, brace).trim()+    if (name.isEmpty()) return null+    val arguments = LinkedHashMap<String, String>()+    var at = brace + 1+    while (at < body.length) {+        val colon = body.indexOf(':', at)+        if (colon < 0) break+        val key = body.substring(at, colon).trim().trim(',', '{', '}')+        val valueStart = body.indexOf(GEMMA_QUOTE, colon)+        if (valueStart < 0) break+        val valueEnd = body.indexOf(GEMMA_QUOTE, valueStart + GEMMA_QUOTE.length)+        if (valueEnd < 0) break+        if (key.isNotEmpty()) {+            arguments[key] = body.substring(valueStart + GEMMA_QUOTE.length, valueEnd)+        }+        at = valueEnd + GEMMA_QUOTE.length+        if (at < body.length && body[at] == ',') at+++    }+    return GemmaToolCall(name, arguments)+}++/** A tool's result, in the shape the model expects to read back. */+fun renderGemmaToolResponse(name: String, value: String): String =+    "<|tool_response>response:$name{value:${quotedGemma(value)}}<tool_response|>"++/** Gemma's value delimiter, which is a token rather than a quotation mark. */+internal const val GEMMA_QUOTE = "<|\"|>"++internal fun quotedGemma(value: String): String = GEMMA_QUOTE + value + GEMMA_QUOTE
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktdeleted file mode 100644index ead1a34ada..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ /dev/null@@ -1,735 +0,0 @@-package com.vayunmathur.library.ml--/**- * The JNI surface of the Vulkan compute runtime in `library/ml/src/main/rust`.- *- * Deliberately narrow: create a network from its weights, hand it a bitmap's pixels, get- * a mask back, destroy it. Preprocessing, the whole forward pass and the readback happen- * on the native side, so the boundary is crossed three times per inference rather than- * once per pixel.- *- * [handle] values are opaque pointers owned by the native side. Every method tolerates- * `0`, which is what the create functions return on failure — so a device without Vulkan- * fp16 compute degrades to a disabled feature rather than a crash. See [isAvailable].- *- * Nothing here is thread-safe. Callers hold a lock across [segment] and [destroy]; see- * [SelfieSegmenter] and [SubjectSegmenter], which do.- */-internal object MlNative {--    /**-     * Whether `libmodelrunner.so` loaded.-     *-     * False on a device whose ABI we did not build for. It says nothing about whether-     * Vulkan or fp16 is available — that is only known once a create call is attempted,-     * because it needs a `VkDevice` to ask.-     */-    val isAvailable: Boolean = try {-        System.loadLibrary("modelrunner")-        true-    } catch (_: Throwable) {-        false-    }--    /**-     * Bring up MediaPipe Selfie Segmentation from a `.maml` blob. Returns 0 on failure.-     *-     * Failure is expected and normal on a device without `VK_KHR_shader_float16_int8`,-     * which is a Vulkan 1.2 promotion and so optional at the 1.1 floor minSdk 31-     * guarantees. The reason is written to logcat under the `ModelRunner` tag.-     */-    external fun createSelfie(weights: ByteArray): Long--    /** Bring up U²-Net portable. Returns 0 on failure, as [createSelfie]. */-    external fun createU2netp(weights: ByteArray): Long--    /** Bring up SCRFD 500M face detection. Returns 0 on failure, as [createSelfie]. */-    external fun createScrfd(weights: ByteArray): Long--    /** Bring up MobileFaceNet face embedding. Returns 0 on failure, as [createSelfie]. */-    external fun createMobilefacenet(weights: ByteArray): Long-    /**-     * Bring up both PP-OCRv5 networks and the character table. Returns 0 on failure.-     *-     * Three assets because they are three files: DBNet detection, CTC recognition, and the-     * 836-line dictionary the labels index. Detection runs at a fixed 960x960 square and-     * recognition at a fixed 48x320, so each records its command buffer once.-     *-     * The returned handle is **not** interchangeable with the others: it is freed by-     * [destroyOcr], not [destroy].-     */-    external fun createPpocr(detection: ByteArray, recognition: ByteArray, keys: String): Long-    /**-     * Recognise every line in [pixels] and return them tab-separated, or null on failure.-     *-     * One region per line of the result: the text, then eight quad coordinates in-     * source-bitmap pixels, then the confidence, then `1` or `0` for vertical - ten-     * tab-separated fields after the text.-     *-     * Detection, the rotated crops, recognition of each, the CTC collapse and reading-     * order all happen natively, so this crosses the boundary once per bitmap rather than-     * once per line. An empty string means no text, which is not a failure.-     *-     * Packing text and geometry into one string is safe rather than lucky: the dictionary-     * holds 836 single non-whitespace characters plus a space, so no decoded line can-     * contain a tab or a newline.-     */-    external fun recognizeText(-        handle: Long,-        pixels: IntArray,-        width: Int,-        height: Int,-    ): String?--    /**-     * Bring up Supertonic 3 from its four `.maml` files, the codepoint table and one voice.-     * Returns 0 on failure.-     *-     * No shape arguments: every Supertonic plan is utterance-shaped, so each net is re-recorded per-     * sentence rather than compiled once at a padded width. There is also no phoneme dictionary --     * phoneme dictionary - the front end is [indexer], a flat 65,536-entry codepoint table, which is-     * why [synthesizeSupertonic] insists on NFKD.-     *-     * The four plans arrive as **file descriptors** rather than byte arrays. A `ByteArray` would-     * allocate the model three times over - the Java array, the `Vec<u8>` JNI hands Rust, and the-     * reader's own copy of the data section - which for a ~105 MB bundle is ~300 MB of transient-     * heap and an out-of-memory kill rather than a slow load. Native reads the header and tensor-     * table only, then streams the weights into the GPU through a fixed-size staging buffer.-     *-     * [fds], [offsets] and [lengths] are parallel and in a fixed order: duration predictor, text-     * encoder, sampler, vocoder. All three are needed because an `AssetFileDescriptor` describes a-     * *range of the APK* rather than a file of its own; for a file on disk the offset is 0 and the-     * length is the file's size.-     *-     * **Each descriptor must be detached.** Native takes ownership and closes it, on the failure-     * paths as much as the successful one, so a caller must not close them itself. An asset also has-     * to be stored uncompressed for `openFd` to work at all - `noCompress += "maml"`.-     *-     * [indexer] and [style] stay byte arrays: 128 KB and 25 KB, where streaming saves nothing.-     * [style] is separate from the plans and swappable through [setSupertonicVoice].-     *-     * Freed by [destroySupertonic], not [destroy] or [destroyOcr].-     */-    external fun createSupertonic(-        fds: IntArray,-        offsets: LongArray,-        lengths: LongArray,-        indexer: ByteArray,-        style: ByteArray,-    ): Long--    /**-     * Point a live handle at another voice, returning false on failure.-     *-     * Cheap, and the reason a voice change does not mean a new handle: the four networks stay-     * uploaded and only the two style tensors are replaced.-     */-    external fun setSupertonicVoice(handle: Long, style: ByteArray): Boolean--    /**-     * Synthesise [text] in [language] and return mono samples in `-1..1` at 44,100 Hz, or null on-     * failure.-     *-     * [text] **must already be NFKD**-decomposed - use `java.text.Normalizer.normalize(text,-     * Form.NFKD)`. The model has no precomposed accents: `é` is unmapped while `e` and the-     * combining acute are both first-class tokens, so precomposed text silently loses-     * characters. Doing the decomposition natively would mean carrying Unicode tables in the-     * APK when the platform already has them.-     *-     * NFKD is the only preparation the caller owes. Everything the upstream SDK does after it --     * folding curly quotes and dashes, dropping emoji, expanding `e.g.,`, ending an-     * unpunctuated sentence - happens natively, so the host tests and this call see one front-     * end rather than two.-     *-     * [language] is the ISO-639-1 code, or `na` for one the model does not list. It is not a-     * hint. Supertonic 3 is the multilingual model and was trained with every utterance wrapped-     * in a `<en>...</en>` tag, so the wrong code reads the text in the wrong language and no-     * code at all produces fluent-sounding non-words rather than an error.-     *-     * Two calls with the same text differ, as flow matching starts from a sampled latent.-     */-    external fun synthesizeSupertonic(handle: Long, text: String, language: String): FloatArray?--    /**-     * Bring up NLLB-200-distilled-600M from its one `.maml` and its tokenizer table.-     * Returns 0 on failure.-     *-     * One graph, not two: the 256,206-row-     * embedding is **tied** - it is the encoder's input table, the decoder's input-     * table and the logits kernel - so an encoder file and a decoder file would upload-     * ~250 MiB of it twice. Native selects between the encoder pass, the decode step-     * and the logits projection by re-recording one net.-     *-     * The plan arrives as a **file descriptor** because it is a downloaded file, not a-     * bundled asset: [offset] is 0 and [length] the file's size; only an asset needs a-     * real range. Native reads the header and tensor table only, then streams the-     * weights into the GPU. It also keeps the descriptor open for the life of the-     * handle, because the tied embedding is gathered a row at a time on the host-     * rather than uploaded a second time.-     *-     * **The descriptor must be detached.** Native takes ownership and closes it, on the-     * failure paths as much as the successful one, so a caller must not close it-     * itself.-     *-     * [tokenizer] stays a byte array, where streaming saves nothing.-     *-     * [cacheBudgetBytes] is how much memory this device will spend on the KV cache. Native turns-     * it into positions - one costs 18 KB - and picks the largest tier that fits, so a 4 GB phone-     * holds a short conversation instead of failing to allocate a long one.-     *-     * The maml's graph id is 18 (`graph::NLLB`), agreed three-ways with model-eng-     * and rust-eng - native rejects any other file at load.-     *-     * Freed by [destroyNllb], not [destroy], [destroyOcr], [destroySupertonic]-     * or [destroyTinyclip].-     */-    external fun createNllb(-        fd: Int,-        offset: Long,-        length: Long,-        tokenizer: ByteArray,-    ): Long--    /**-     * Translate [text] from the language [sourceToken] names into the language-     * [targetToken] names, or null on failure.-     *-     * [text] **must already be NFKC** - use `java.text.Normalizer.normalize(text,-     * Form.NFKC)`. The model's normaliser is `nmt_nfkc` with a precompiled charsmap,-     * and reproducing that natively would mean carrying Unicode tables the platform-     * already has.-     *-     * BOTH tokens are required, which is the protocol flip vs the old SMaLL-100-     * target-only call:-     * the source token goes on the **source** side (`pieces + [EOS]`), and the target-     * token forced-BOSes the **decoder** rather than starting from `</s>`. Backwards-     * it produces fluent output in the wrong language rather than an error.-     * `NllbModel.tokenId` is the table: the 202 flores200 codes at 256001..256202,-     * which native validates in `post::translate::is_nllb_lang_token`.-     *-     * Greedy decoding, capped at 128 tokens. An empty string means the text had-     * nothing to translate, which is not a failure.-     */-    external fun translateNllb(-        handle: Long,-        text: String,-        sourceToken: Int,-        targetToken: Int,-    ): String?--    /**-     * Free NLLB's network, its open weights file and its tokenizer table.-     * Exactly once per non-zero handle from [createNllb].-     */-    external fun destroyNllb(handle: Long)--    /**-     * Bring up TinyCLIP from its one `.maml`. Returns 0 on failure.-     *-     * One graph, not two: the image and text towers-     * share **no weights at all**, but they do share a 22.6 MiB file, so two handles would upload it-     * twice. Native selects between them by re-recording one net, which costs a `device_wait_idle` —-     * and an indexing run is the image tower throughout, so it pays for exactly one.-     *-     * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and [length]-     * are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather than a file of-     * its own. `AssetManager.openFd` throws for a deflated entry, which is what `noCompress +=-     * "maml"` in `photos/build.gradle.kts` is for.-     *-     * Native keeps the descriptor open for the life of the handle, because the 12.6 MiB token-     * embedding is gathered a row at a time on the host rather than read from the upload.-     *-     * **The descriptor must be detached.** Native takes ownership and closes it, on the failure-     * paths as much as the successful one, so a caller must not close it itself.-     *-     * Freed by [destroyTinyclip], not [destroy], [destroyOcr] or [destroySupertonic].-     */-    external fun createTinyclip(fd: Int, offset: Long, length: Long): Long--    /**-     * The 512-d image embedding for [pixels], or null on failure.-     *-     * [pixels] is `3 * 224 * 224` floats, NCHW and RGB, already resized to the shortest edge,-     * centre-cropped and normalised by CLIP's mean and standard deviation. That work stays in-     * Kotlin — see `ClipEmbedder.preprocess` — because it is bitmap handling the platform does-     * better.-     *-     * **Not L2-normalised.** `ClipEmbedder.l2Normalize` does that for both towers, so the stored-     * vector format is decided in one place.-     */-    external fun tinyclipImage(handle: Long, pixels: FloatArray): FloatArray?--    /**-     * The 512-d text embedding for [ids], or null on failure.-     *-     * [ids] must be the query's tokens **up to and including `<|endoftext|>`**, with the tokenizer's-     * padding trimmed off. CLIP pools at the end-of-text position, so the trim is what decides which-     * position is pooled — and because the tower is causal, the trimmed sequence gives the identical-     * vector to the padded 77 for a fraction of the work.-     *-     * Not L2-normalised, as [tinyclipImage] is not.-     */-    external fun tinyclipText(handle: Long, ids: IntArray): FloatArray?--    /**-     * Free TinyCLIP's network and its open weights file.-     * Exactly once per non-zero handle from [createTinyclip].-     */-    external fun destroyTinyclip(handle: Long)--    /**-     * Bring up Maia3-5M from its one bundled `.maml`. Returns 0 on failure.-     *-     * One forward pass per move and no search, so unlike [createTinyclip] there is only ever-     * one plan and native never re-records.-     *-     * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and-     * [length] are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather-     * than a file of its own. `AssetManager.openFd` throws for a deflated entry, which is what-     * `noCompress += "maml"` in `games/chess/build.gradle.kts` is for.-     *-     * Native keeps the descriptor open for the life of the handle, because the two elo-     * embeddings are blended on the host — the blend weight is an input, so it cannot be-     * folded into the upload.-     *-     * **The descriptor must be detached.** Native takes ownership and closes it, on the failure-     * paths as much as the successful one, so a caller must not close it itself.-     *-     * Freed by [destroyMaia], not [destroy], [destroyOcr] or [destroySupertonic].-     */-    external fun createMaia(fd: Int, offset: Long, length: Long): Long--    /**-     * The 4352 move logits for a board, or null on failure.-     *-     * [planes] is `12 * 64` floats, plane-major, with square `rank * 8 + file` so a1 is 0 and-     * h8 is 63. The planes are white P, N, B, R, Q, K then black P, N, B, R, Q, K.-     *-     * **The board must already be from the mover's side.** When black is to move the caller-     * mirrors it vertically and swaps the colours, and un-mirrors the move it picks. The model-     * was trained that way and the move vocabulary has no black promotions at all, so passing-     * an unmirrored black position produces legal-looking nonsense rather than an error.-     *-     * [selfElo] and [oppoElo] are 0..5000 and are clamped, not rejected. They are what makes-     * one weights file cover every difficulty.-     *-     * The logits are **raw**: indices 0..4095 are `from * 64 + to` and 4096..4351 are-     * `4096 + fromFile * 32 + toFile * 4 + piece` for q, r, b, n. Legal masking, temperature-     * and sampling all need the caller's move list and stay in Kotlin.-     */-    external fun maiaLogits(-        handle: Long,-        planes: FloatArray,-        selfElo: Int,-        oppoElo: Int,-    ): FloatArray?--    /**-     * Free Maia3's network and its open weights file.-     * Exactly once per non-zero handle from [createMaia].-     */-    external fun destroyMaia(handle: Long)--    /**-     * Bring up the Now Playing audio fingerprinter from its one bundled `.maml`. Returns 0 on-     * failure.-     *-     * One forward pass per window and no state, so like [createMaia] there is only ever one-     * plan and native never re-records.-     *-     * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and-     * [length] are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather-     * than a file of its own. `AssetManager.openFd` throws for a deflated entry, which is what-     * `noCompress += "maml"` in the app's `build.gradle.kts` is for.-     *-     * Unlike [createMaia] native does **not** keep the descriptor open: nothing in this network-     * is read on the host, so the whole file goes to the device at construction and the-     * descriptor is closed there and then.-     *-     * **The descriptor must be detached.** Native takes ownership and closes it, on the failure-     * paths as much as the successful one, so a caller must not close it itself.-     *-     * Freed by [destroyNnfp], not [destroy], [destroyOcr] or [destroySupertonic].-     */-    external fun createNnfp(fd: Int, offset: Long, length: Long): Long--    /**-     * The 64-value fingerprint for one window of audio, or null on failure.-     *-     * [pcm] is exactly [NnfpHandle.WINDOW_SAMPLES] mono 16-bit samples at 16 kHz — 415 ms, the-     * network's whole receptive field. `ShortArray` rather than `FloatArray` because that is-     * what `AudioRecord.read` produces and what the fixed-point log-mel front end wants;-     * routing it through float would cost precision for nothing. A wrong length is an error-     * rather than a pad or a truncate.-     *-     * Native runs the front end itself, so there is no separate feature step to keep in sync.-     * Two calls with the same samples give the same answer: the streaming graph's circular-     * buffers are unrolled into the fixed window, so there is no carried state and no warm-up.-     *-     * The embedding is **not** normalised — whether the descriptor is matched by cosine, by L2-     * or through a product quantiser could not be recovered from the model, so that is the-     * caller's decision rather than an invented convention.-     */-    external fun nnfpEmbed(handle: Long, pcm: ShortArray): FloatArray?--    /**-     * Free the fingerprinter's network.-     * Exactly once per non-zero handle from [createNnfp].-     */-    external fun destroyNnfp(handle: Long)--    /**-     * The music gate, Now Playing's always-on "is this music?" classifier.-     *-     * Never returns 0 in practice: there is no device, no plan and no asset behind this-     * one - the 8,200 int8 parameters are in the binary and it runs on the CPU. A 0 means-     * the native library is a build that does not have it.-     *-     * Freed by [destroyMusicGate], not [destroyNnfp] or any other destroy.-     */-    external fun createMusicGate(): Long--    /**-     * Feed [count] mono 16 kHz samples from the front of [pcm] and get one music-     * probability per completed 10 ms hop, oldest first.-     *-     * Empty rather than null when a call completes no hop or the gate is still inside its-     * 230 ms warm-up; both are ordinary. Null means the call actually failed. The gate is-     * stateful across calls - [resetMusicGate] starts a fresh session.-     */-    external fun musicGatePush(handle: Long, pcm: ShortArray, count: Int): FloatArray?--    /** Discard the gate's streaming state. */-    external fun resetMusicGate(handle: Long)--    /** Free the gate. Exactly once per non-zero handle from [createMusicGate]. */-    external fun destroyMusicGate(handle: Long)--    /**-     * Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`.-     * Returns 0 on failure.-     *-     * One graph, not two: the 51,865-row embedding is **tied** — the-     * decoder's input table and the logits kernel — so an encoder file and a decoder file would-     * upload 26.6 MB of it twice. Native selects between the encoder pass and a decode step by-     * re-recording one net.-     *-     * The plan arrives as a **file descriptor** because it is a bundled asset: [offset] and [length]-     * are the `AssetFileDescriptor`'s, since an asset is a *range of the APK* rather than a file of-     * its own. `AssetManager.openFd` throws for a deflated entry, which is what `noCompress +=-     * "maml"` in `speech/build.gradle.kts` is for. Native keeps the descriptor open for the life of-     * the handle, because the tied embedding is gathered a row at a time on the host.-     *-     * **The descriptor must be detached.** Native takes ownership and closes it, on the failure-     * paths as much as the successful one.-     *-     * The four id arrays come straight out of `generation_config.json`, because that file is the-     * model's and hardcoding its ids here would be a second place to get them wrong:-     * - [special] is exactly five values: `decoder_start_token_id`, `eos_token_id`,-     *   `task_to_id.transcribe`, `no_timestamps_token_id`, `max_length`.-     * - [languages] is the 99 `<|xx|>` ids from `lang_to_id`, used to detect a language when none is-     *   named. The **code to id** mapping stays in Kotlin.-     * - [suppress] is `suppress_tokens` and [suppressAtBegin] is `begin_suppress_tokens`.-     *-     * All four are validated here rather than per transcription, so a broken asset reports an-     * unavailable recogniser instead of producing wrong text.-     *-     * Freed by [destroyWhisper], not [destroy], [destroyOcr], [destroySupertonic]-     * or [destroyTinyclip].-     */-    external fun createWhisper(-        fd: Int,-        offset: Long,-        length: Long,-        special: IntArray,-        languages: IntArray,-        suppress: IntArray,-        suppressAtBegin: IntArray,-    ): Long--    /**-     * Transcribe one log-mel window into token ids, or null on failure.-     *-     * [mel] is `80 * 3000` floats row-major, from `WhisperFeatures.logMel` — 30 seconds at a-     * 160-sample hop, padded or truncated. [languageToken] is a `<|xx|>` id the caller resolved from-     * a code, or **negative** to let the model detect it.-     *-     * The ids come back **raw**, including any special or timestamp token the model emitted:-     * `WhisperTokenizer` is what skips the ids at or above 50,257 that have no text form. An empty-     * array means the window held nothing to transcribe, which is not a failure.-     *-     * Greedy decoding, capped at 224 tokens. Every step re-records the network, so this is slow-     * relative to a single forward pass and must not be called concurrently on one handle.-     */-    external fun transcribeWhisper(handle: Long, mel: FloatArray, languageToken: Int): IntArray?--    /**-     * Free whisper's network, its open weights file and both of its caches.-     * Exactly once per non-zero handle from [createWhisper].-     */-    external fun destroyWhisper(handle: Long)--    /**-     * Detect faces in [pixels] and return them flattened, nine floats per face.-     *-     * The layout per face is `left, top, right, bottom, leftEyeX, leftEyeY, rightEyeX,-     * rightEyeY, score`, every coordinate a fraction of the bitmap. Letterboxing, the-     * forward pass, the anchor decode and non-maximum suppression all happen natively, so-     * this crosses the boundary once per bitmap rather than once per proposal.-     *-     * An empty array means no faces — the common case, and not a failure. Null is a-     * failure.-     */-    external fun detectFaces(-        handle: Long,-        pixels: IntArray,-        width: Int,-        height: Int,-    ): FloatArray?--    /**-     * Run the network over [pixels] and return the mask, or null on failure.-     *-     * [pixels] is `ARGB_8888` as `Bitmap.getPixels` produces it, [width] × [height] long.-     * The bitmap is resized and normalised natively, so any size is accepted; the-     * returned mask is always [maskWidth] × [maskHeight], row-major, in `0..1`.-     */-    external fun segment(handle: Long, pixels: IntArray, width: Int, height: Int): FloatArray?--    /** The mask's width, so callers need not know either network's input size. */-    external fun maskWidth(handle: Long): Int--    /** The mask's height. */-    external fun maskHeight(handle: Long): Int--    /**-     * Free everything the handle owns, after waiting for the GPU to go idle.-     *-     * Exactly once per non-zero handle. When it is the last live network the shared-     * `VkDevice` is destroyed with it, so nothing stays resident once the feature is-     * closed.-     */-    external fun destroy(handle: Long)-    /**-     * Free both PP-OCRv5 networks and the dictionary. Exactly once per non-zero handle-     * from [createPpocr].-     *-     * Separate from [destroy] because the handle is a different native type. Passing one to-     * the other is undefined, which is why there are two functions rather than one that-     * guesses.-     */-    external fun destroyOcr(handle: Long)--    /**-     * Free Supertonic's four networks, its conditioning, its codepoint table and its voice.-     * Exactly once per non-zero handle from [createSupertonic].-     *-     * A third destroy function rather than one that guesses: the handle types own different things-     * and passing one to the wrong destroy is undefined.-     */-    external fun destroySupertonic(handle: Long)--    /**-     * Bring up Gemma 4 E2B from its two `.maml`s and its tokenizer table. Returns 0 on failure.-     *-     * # Two descriptors, both consumed-     *-     * The text decoder and the embedding are separate files with separate graph ids (20 and 21).-     * Native adopts **both** and closes them on every path, including failure - so the caller-     * must detach both and must not close either afterwards. There is no partial-success case:-     * either the handle is non-zero and owns them, or it is 0 and they are already closed.-     *-     * They are separate because nothing on the device reads the embedding. A decode step needs-     * one row of a 262144-row table, so it is gathered on the host and streamed, exactly as-     * NLLB's tied embedding is. Splitting also lets the decoder load while the embedding is-     * still downloading.-     *-     * [tokenizer] stays a byte array, where streaming saves nothing.-     *-     * Freed by [destroyGemma4], not [destroy], [destroyOcr], [destroySupertonic],-     * [destroyTinyclip] or [destroyNllb].-     */-    external fun createGemma4(-        textFd: Int,-        textOffset: Long,-        textLength: Long,-        embedFd: Int,-        embedOffset: Long,-        embedLength: Long,-        tokenizer: ByteArray,-        cacheBudgetBytes: Long,-    ): Long--    /**-     * Token ids for [text], with [specials] matched literally rather than merged into.-     *-     * [specials] are the chat markers a template inserts - `<bos>`, the turn tags, the tool tags.-     * They are passed rather than hardcoded native-side because which markers a prompt may-     * contain is a policy question: a model that let a user's text spell a turn boundary would-     * let them forge one, so the *caller* decides, and user text is encoded with an empty list.-     *-     * Null on failure.-     */-    external fun encodeGemma4(handle: Long, text: String, specials: Array<String>): IntArray?--    /** Text for a run of token ids, fusing byte pieces back into characters. Null on failure. */-    external fun decodeGemma4(handle: Long, tokens: IntArray): String?--    /**-     * Feed [tokens] into the KV cache without generating. Returns the new position, or -1.-     *-     * The prompt path. Every token but the last only fills the cache, so this keeps a 500-token-     * prompt to one JNI crossing instead of 500.-     */-    external fun pushGemma4(handle: Long, tokens: IntArray): Int--    /**-     * Feed one token and return the most likely next one. -1 on failure.-     *-     * Greedy, with no sampling: replies are deterministic. litertlm sampled at `top_k` 64 and-     * `top_p` 0.95, so this is a real behavioural change and not only an implementation one.-     */-    external fun stepGemma4(handle: Long, token: Int): Int--    /** Positions currently in the KV cache, or -1. */-    external fun positionGemma4(handle: Long): Int--    /**-     * Start a new conversation on the same handle.-     *-     * Only the position resets. Attention reads `[windowStart, prefix]`, so cache rows past the-     * new prefix are never read again - clearing them would be a gigabyte of pointless writes-     * between turns.-     */-    external fun resetGemma4(handle: Long)--    /**-     * Rewind the cache to [position], keeping everything below it. Returns it, or -1.-     *-     * The other half of [pushGemma4]. A turn's prompt is almost all of the previous turn's-     * prompt, and the cache for that prefix is still correct - so the caller seeks to the length-     * of the unchanged part and pushes only what is new.-     *-     * **The caller is responsible for the prefix actually being unchanged.** Native cannot check-     * it, and a wrong seek does not fail: the model answers a conversation that never happened.-     * Seeking forward is refused, because those rows hold whatever the arena last put there.-     */-    external fun seekGemma4(handle: Long, position: Int): Int--    /**-     * Time a decode pass with and without the logits head, and log both.-     *-     * The head is 4 of the pass's 1,094 dispatches but 402 MB of its 1.30 GB of weights, so the-     * gap between the two says whether this runtime is limited by memory or by dispatch count --     * which decides whether the work is better kernels or fewer of them.-     */-    external fun benchmarkGemma4(handle: Long): Int--    /**-     * Load a precomputed KV cache for the fixed prompt prefix. Returns the positions, or -1.-     *-     * The caller must have the tokens that produced [cache] and record them as the cache's-     * contents, or the next turn re-feeds the prefix and the saving is lost. Native checks only-     * the byte count - it cannot know which tokens these keys and values came from.-     */-    external fun loadPrefixGemma4(handle: Long, positions: Int, cache: ByteArray): Int--    /** Log a storage-buffer read against a texel-buffer read of the same bytes. */-    external fun imageProbeGemma4(): Int--    /** Log how a gemv's achieved bandwidth varies with the size of the dispatch. */-    external fun scalingGemma4(): Int--    /** Log which GPU features this device offers that the shaders do not yet use. */-    external fun capabilitiesGemma4(): Int--    /** Positions the KV cache currently holds, or -1. */-    external fun capacityGemma4(handle: Long): Int--    /**-     * Grow the cache so [needed] positions fit. Returns the new capacity, or -1 if the device-     * cannot afford it.-     *-     * **This empties the cache.** A larger arena is a different allocation and nothing is copied-     * into it, so the caller must feed its whole prompt again and discard any record of what the-     * cache held. Tiers double, so a long conversation pays this a handful of times rather than-     * on every message.-     */-    external fun growGemma4(handle: Long, needed: Int): Int--    /** Release a [createGemma4] handle. */-    external fun destroyGemma4(handle: Long)--    /**-     * Feed soft tokens - an encoder's output - into the KV cache. Returns how many, or -1.-     *-     * [embeddings] is `n * 1536` floats, one row per soft token, and the position advances by-     * `n`. This is how an image reaches a decoder that is otherwise text-only: there is no token-     * id to gather an embedding for, so the vision tower's rows are pushed as the embedding.-     *-     * Pass [Gemma4VisionHandle.encode]'s output unchanged. It is deliberately not scaled.-     */-    external fun pushSoftGemma4(handle: Long, embeddings: FloatArray): Int--    /**-     * Bring up Gemma 4's vision tower from its own `.maml`. 0 on failure.-     *-     * A third file and a third graph id, separate from [createGemma4] because it is optional: a-     * device that never sends an image never downloads it, and a tower that fails to load leaves-     * the assistant answering text.-     *-     * Freed by [destroyGemma4Vision].-     */-    external fun createGemma4Vision(fd: Int, offset: Long, length: Long): Long--    /**-     * The `[width, height]` in pixels an image of [width] x [height] must be resized to. Null if-     * there is no grid for it.-     *-     * The resize itself is Kotlin's, but the size is not a free choice: it is the reference-     * preprocessor's aspect-ratio-preserving fit to a patch budget, and being one 48-pixel block-     * out changes the number of soft tokens the tower emits. [softTokens] must be one of 70, 140,-     * 280, 560 or 1120.-     */-    external fun gemma4VisionSize(width: Int, height: Int, softTokens: Int): IntArray?--    /**-     * Encode one image to soft tokens: `n * 1536` floats, or null.-     *-     * [pixels] is ARGB_8888 at exactly the size [gemma4VisionSize] returned.-     */-    external fun encodeImageGemma4(-        handle: Long,-        pixels: IntArray,-        width: Int,-        height: Int,-    ): FloatArray?--    /** Release a [createGemma4Vision] handle. */-    external fun destroyGemma4Vision(handle: Long)--    /**-     * Bring up Gemma 4's audio tower from its own `.maml`. 0 on failure.-     *-     * A fourth file and a fourth graph id, optional on the same terms as [createGemma4Vision]: a-     * device that never sends audio never downloads its 166 MB, and a tower that fails to load-     * leaves the assistant answering without sound.-     *-     * Freed by [destroyGemma4Audio].-     */-    external fun createGemma4Audio(fd: Int, offset: Long, length: Long): Long--    /**-     * Encode one clip to soft tokens: `n * 1536` floats, or null.-     *-     * [samples] is 16 kHz mono in roughly -1..1. Native runs the log-mel front end, truncates to-     * thirty seconds, and returns one row per 40 ms of audio. Unlike [encodeImageGemma4] there is-     * no size to negotiate first: the clip's own length decides the token count.-     *-     * Null when the clip is too short for the tower's 12-wide attention band - about 0.45 s.-     */-    external fun encodeAudioGemma4(handle: Long, samples: FloatArray): FloatArray?--    /** Release a [createGemma4Audio] handle. */-    external fun destroyGemma4Audio(handle: Long)-}
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 103742e250..c7efa20a5a 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@@ -1,21 +1,19 @@ package com.vayunmathur.library.ml  /**- * Google's always-on music gate, ported to the CPU.+ * Google's always-on music gate.  *  * The cheap half of Now Playing. Feed it microphone PCM and it answers "is this music?"  * once every 10 ms, from 8,200 int8 parameters. [NnfpHandle] is the other half - the  * expensive fingerprinter you only run once this has said yes - and the two are different  * networks with different shapes, not two entry points to one model.  *- * # Not on the GPU, unlike everything else here+ * # Backend deferred  *- * Every other handle in this package dispatches Vulkan compute. This does not, and so it- * has no asset, no file descriptor and no device: [inProcess] cannot fail for want of- * hardware. At 100 Hz over ~8,200 multiply-accumulates the arithmetic is microseconds,- * while a GPU dispatch would be 100 submit/fence/readback round trips a second on a- * workload whose whole point is being cheap enough to leave running. Google ships it on a- * DSP for the same reason.+ * The gate ran on the CPU half of the deleted Vulkan crate (`gate.rs`). Until it is ported+ * (pure integer arithmetic — no model file, no GPU), this handle is always unavailable:+ * construction succeeds, [isAvailable] is false, and [push] returns null so callers degrade.+ * The API is unchanged so the port drops in without touching callers.  *  * # Streaming, and the warm-up  *@@ -28,46 +26,30 @@ package com.vayunmathur.library.ml  * # Not thread-safe  *  * One [push] at a time, and no [push] concurrent with [close]. Hold a lock across both.- *- * # What this is not- *- * It is not a reproduction of Google's shipped behaviour. The network and its- * quantization are recovered exactly, but two links in the chain are inferences - the- * sigmoid reading of the model's int16 score, and the smoothing inside the latching- * classifier - and the runtime threshold overrides in `music_detector.descriptor` are- * unrecoverable, because that file is a symbol and byte-offset table with no values in- * 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+    /** Always false until the CPU port lands. See the class docs. */+    val isAvailable: Boolean get() = false      /**      * Feed [count] samples from the front of [pcm] and collect one probability in `0f..1f`      * per completed hop, oldest first.      *-     * Empty when the call completed no hop or the gate is still warming up. Null only when-     * the gate is unavailable or [count] does not fit [pcm].+     * Currently always null: the backend is deferred.      */     fun push(pcm: ShortArray, count: Int = pcm.size): FloatArray? {-        if (handle == 0L) return null         if (count < 0 || count > pcm.size) return null-        return MlNative.musicGatePush(handle, pcm, count)+        return null     }      /** Discard the streaming state so the next [push] starts a fresh session. */     fun reset() {-        if (handle != 0L) MlNative.resetMusicGate(handle)+        // Nothing held.     }      /** Free the gate. Idempotent. */     override fun close() {-        val live = handle-        handle = 0L-        if (live != 0L) MlNative.destroyMusicGate(live)+        // Nothing held.     }      override fun toString(): String = "Now Playing music gate (CPU)"@@ -93,10 +75,6 @@ class MusicGate private constructor() : AutoCloseable {          * Named for the fact that there is nothing to open - no asset, no descriptor - to          * distinguish it from [NnfpHandle.inAssets], which does have a file behind it.          */-        fun inProcess(): MusicGate {-            val instance = MusicGate()-            instance.handle = if (MlNative.isAvailable) MlNative.createMusicGate() else 0L-            return instance-        }+        fun inProcess(): MusicGate = MusicGate()     } }
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 8624f3c10e..5355a428ae 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,99 +1,53 @@ package com.vayunmathur.library.ml  import android.content.res.AssetManager-import android.os.ParcelFileDescriptor import android.util.Log  /**- * On-device audio fingerprinting: the Now Playing embedding network on the Vulkan compute- * runtime.+ * On-device audio fingerprinting: the Now Playing embedding network.  *  * Ten alternating frequency and time convolutions over a 32-bin log-mel spectrogram, then a  * depthwise head, at 172,576 parameters. [embed] turns 4.8 seconds of microphone audio into 64- * numbers that identify what is playing. See `library/ml/src/main/rust/src/nets/nnfp.rs`.+ * numbers that identify what is playing.+ *+ * # Backend deferred+ *+ * The model ships as TFLite (`music_detector.sound_model_2`, recovered from an APK, with+ * custom `CIRCULAR_BUFFER` ops no stock runtime executes), and the Vulkan `.maml` path that+ * served it is deleted. Until the TFLite→ONNX export lands, this handle is always+ * unavailable: construction succeeds, [isAvailable] is false, and [embed] returns null so+ * callers degrade. The API (constants, [inAssets], [embed]) is unchanged so the port drops+ * in without touching callers.  *  * # It describes, it does not decide  *  * The embedding is a *descriptor*, not an answer. Matching it against a song database, deciding  * whether the match is good enough, and pooling several windows into one query are all the  * caller's, because none of them are in the model. In particular the vector is **not- * normalised**: whether to compare by cosine, by L2 or through a product quantiser could not be- * recovered from the model, so this does not invent a convention.- *- * # The front end is native too- *- * [embed] takes raw PCM, not features. The log-mel front end — a periodic Hann window, a- * 512-point transform, a 32-channel mel bank over 60–3800 Hz — runs inside the same call, so- * there is no feature-extraction step in Kotlin to keep in sync with the network it feeds. See- * `library/ml/src/main/rust/src/microfrontend.rs`, which is written against a config rather- * than against this model, so another audio net can reuse it.- *- * # No state, so no warm-up- *- * The model was exported as a *streaming* graph, evaluated once per 10 ms with six circular- * buffers carrying state between calls. That is unrolled here into a fixed [WINDOW_SAMPLES]- * window, which is the whole receptive field. So [embed] is a pure function: two calls with the- * same samples give the same 64 numbers, there is nothing to prime, and dropping a window- * corrupts nothing.- *- * Callers step a ring buffer forward by whatever hop they like, but note the window is 4.8 s:- * advancing by one 10 ms frame gives a 99.8% overlapping window and almost the same embedding.- * Something on the order of half a second to a second is the useful range.- *- * # Fidelity- *- * The weights are dequantised from the export's int8 to fp16, because at this size int8 would- * save nine kilobytes and cost accuracy. The consequence worth knowing: this is a float- * evaluation of a network trained quantisation-aware, and it has **not** been compared against- * the original runtime — only against an independently computed reference for the front end.- * Treat embeddings as self-consistent within this implementation rather than interchangeable- * with any produced elsewhere.- *- * # One bundled asset, 340 KiB- *- * `nnfp.maml` ships inside the APK, so this has an [inAssets] and no download. 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 the app's `build.gradle.kts` is for.- *- * # 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 [embed] returns null. Gate the feature on it- * rather than offering recognition that cannot run.+ * normalised**.  *  * # Threading  *  * 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+    /** Always false until the ONNX port lands. See the class docs. */+    val isAvailable: Boolean get() = false      /**      * The [EMBEDDING] fingerprint values for one window, or null on failure.      *      * [pcm] must be exactly [WINDOW_SAMPLES] mono 16-bit samples at [SAMPLE_RATE] — 4.8-     * seconds. A wrong length returns null rather than padding or truncating, because either-     * would silently describe audio that was not recorded.-     *-     * `ShortArray` because that is what `AudioRecord.read` produces and what the fixed-point-     * front end wants. There is no `FloatArray` overload: the conversion would be lossy in one-     * direction and pointless in the other.+     * seconds. Currently always null: the backend is deferred.      */     fun embed(pcm: ShortArray): FloatArray? {-        if (handle == 0L) return null         if (pcm.size != WINDOW_SAMPLES) return null-        return MlNative.nnfpEmbed(handle, pcm)+        return null     }      /** Free the network. Idempotent. */     override fun close() {-        val live = handle-        handle = 0L-        if (live != 0L) MlNative.destroyNnfp(live)+        // Nothing held.     }      override fun toString(): String = "Now Playing fingerprinter from $source"@@ -115,73 +69,26 @@ class NnfpHandle private constructor(private val source: String) : AutoCloseable          /**          * Samples [embed] requires: `FRAME_SAMPLES + HOP_SAMPLES * (WINDOW_FRAMES - 1)`, or-         * 4.795 s. Longer than [WINDOW_FRAMES] hops because the first frame needs a whole-         * window before the hops start.-         *-         * As `ShortArray` that is 153 KiB, which is the size a caller's ring buffer has to be.+         * 4.795 s.          */         const val WINDOW_SAMPLES = FRAME_SAMPLES + HOP_SAMPLES * (WINDOW_FRAMES - 1)          /** Values in one fingerprint. */         const val EMBEDDING = 64 -        /** The one graph. Native checks its graph id, so a wrong file fails at load. */-        const val GRAPH = "nnfp.maml"+        /** The future ONNX graph. */+        const val GRAPH = "nnfp.onnx"          /**-         * The model from the APK's assets, which is the only place it lives.+         * The model from the APK's assets, which is the only place it will live.          *-         * No `inDirectory` counterpart: at 340 KiB this is bundled, so there is no download-         * directory to look in.+         * Currently always unavailable; see the class docs.          */         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 (e: Throwable) {-                    Log.e(TAG, "cannot open $path", e)-                    0L-                }+            if (!runCatching { assets.open(path).close() }.isSuccess) {+                Log.w(TAG, "$path is missing")             }-            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() }+            return NnfpHandle("the APK's $path")         }     } }
library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.ktdeleted file mode 100644index 86b9e54e9e..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Segmentation.kt+++ /dev/null@@ -1,122 +0,0 @@-package com.vayunmathur.library.ml--import android.content.Context-import android.graphics.Bitmap-import android.util.Log--/** A segmentation mask: [width] × [height] probabilities in `0..1`, row-major. */-class SegmentationMask(-    /** Columns. Fixed per network, and independent of the input bitmap's size. */-    val width: Int,-    /** Rows. */-    val height: Int,-    /**-     * Foreground probability per pixel.-     *-     * A fresh array each call — the caller owns it and both call sites blend or threshold-     * it in place.-     */-    val mask: FloatArray,-)--/**- * The safe half of the JNI surface: a network handle with a lifetime.- *- * `internal`, and held by composition rather than inherited from, so the public API of- * this module is exactly [SelfieSegmenter] and [SubjectSegmenter] with three members each- * — Kotlin would otherwise force this type public to let a public class extend it.- *- * # Failure is a state, not an exception- *- * The constructor never throws. If `libmodelrunner.so` is missing, or the device has no- * Vulkan fp16 compute, or the asset will not parse, [isAvailable] is false and [segment]- * returns null — the graceful-degradation shape `GpuStitcher` uses in `:camera`. That is- * the GPU-only decision made visible: there is no CPU fallback, so the feature turns off- * and the caller keeps whatever it had.- *- * # Not thread-safe, on purpose- *- * [segment] and [close] must not overlap. `BokehAnalyzer` holds `synchronized(lock)`- * across the whole native call for exactly this reason — its comments record a real- * `SEGV_MTESERR` use-after-free where `close` destroyed the net while worker threads were- * still reading it. A `VkDevice` handle has the identical hazard, so putting a lock in- * here as well would be a second, redundant one; the discipline stays where the threading- * actually is.- */-internal class NativeSegmenter(-    context: Context,-    assetName: String,-    tag: String,-    create: (ByteArray) -> Long,-) : AutoCloseable {--    /**-     * `@Volatile` because it is the one field whose staleness would be a use-after-free.-     *-     * Callers do establish happens-before via their own locks, so this is belt and braces-     * — but the cost is nothing and the failure mode is a native crash.-     */-    @Volatile private var handle: Long = if (!MlNative.isAvailable) {-        0L-    } else {-        try {-            // `.maml` is `noCompress` in both apps, so this is a straight copy out of the-            // mapped APK rather than an inflate into a second buffer.-            create(context.assets.open(assetName).use { it.readBytes() })-        } catch (e: Throwable) {-            Log.e(tag, "cannot load $assetName", e)-            0L-        }-    }--    /** Whether the network came up. False means the feature is off on this device. */-    val isAvailable: Boolean get() = handle != 0L--    /**-     * Run the network over [bitmap] and return the mask, or null if it is unavailable or-     * the inference failed.-     *-     * [bitmap] may be any size: it is resized and normalised natively. The returned mask-     * is the network's own resolution, which the caller upsamples.-     */-    fun segment(bitmap: Bitmap): SegmentationMask? {-        if (handle == 0L) return null-        // `getPixels` cannot read a HARDWARE bitmap, and a null config means an unknown-        // one. Copying is the only option, and doing it here keeps both call sites from-        // each having to remember.-        val readable = if (bitmap.config == Bitmap.Config.HARDWARE || bitmap.config == null) {-            bitmap.copy(Bitmap.Config.ARGB_8888, false)-        } else {-            bitmap-        } ?: return null--        return try {-            val count = readable.width * readable.height-            var buffer = pixels-            if (buffer == null || buffer.size != count) {-                buffer = IntArray(count)-                pixels = buffer-            }-            readable.getPixels(buffer, 0, readable.width, 0, 0, readable.width, readable.height)-            val values = MlNative.segment(handle, buffer, readable.width, readable.height)-                ?: return null-            SegmentationMask(MlNative.maskWidth(handle), MlNative.maskHeight(handle), values)-        } finally {-            if (readable !== bitmap) readable.recycle()-        }-    }--    /**-     * Reused across calls so the ~15 fps preview path does not allocate a megabyte of-     * `int[]` per second.-     */-    private var pixels: IntArray? = null--    /** Free the network. Idempotent, and safe to call from a `DisposableEffect`. */-    override fun close() {-        val toDestroy = handle-        handle = 0L-        pixels = null-        if (toDestroy != 0L) MlNative.destroy(toDestroy)-    }-}
a/library/ml/src/main/java
diff --git a/library/ml/src/main/java

Diff truncated.