Modern Apps git

← Modern-Apps.git

translate: run SMaLL-100 on the in-house runtime, 7 files to 2

Commit
e785e1f8b649e852ccb0382fdf9ea07ae0cff726
Author
vayun-mathur <[email protected]>
When
2026-08-29 04:03 UTC (3 months ago)
Parents
f68b01c

Diff

library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 5ddd5560ba..8225dc20d1 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -139,6 +139,58 @@ internal object MlNative {      */     external fun synthesizeSupertonic(handle: Long, text: String): FloatArray? +    /**+     * Bring up SMaLL-100 from its one `.maml` and its tokenizer table. Returns 0 on failure.+     *+     * One graph, not two: the 128,112-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 125 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** for the reason [createSupertonic] gives, and more+     * so: at 318 MiB a `ByteArray` would allocate it three times over and be killed for it. 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. [offset] is 0 and+     * [length] the file's size for a file on disk; only an asset needs a real range.+     *+     * [tokenizer] stays a byte array: 1.7 MB, where streaming saves nothing.+     *+     * Freed by [destroySmall100], not [destroy], [destroyOcr] or [destroySupertonic].+     */+    external fun createSmall100(+        fd: Int,+        offset: Long,+        length: Long,+        tokenizer: ByteArray,+    ): Long++    /**+     * Translate [text] 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 237 KB precompiled charsmap, and reproducing that+     * natively would mean carrying Unicode tables the platform already has.+     *+     * [targetToken] goes on the **source** side, which is the one thing about SMaLL-100 that is easy+     * to get backwards: its distillation gives the *encoder* the target language and starts the+     * decoder from `</s>`. Backwards it produces fluent output in the wrong language rather than an+     * error. `Small100Model.LANG_ID` is the table.+     *+     * Greedy decoding, capped at 128 tokens. An empty string means the text had nothing to+     * translate, which is not a failure.+     */+    external fun translateSmall100(handle: Long, text: String, targetToken: Int): String?++    /**+     * Free SMaLL-100's network, its open weights file and its tokenizer table.+     * Exactly once per non-zero handle from [createSmall100].+     */+    external fun destroySmall100(handle: Long)+     /**      * Detect faces in [pixels] and return them flattened, nine floats per face.      *
library/ml/src/main/java/com/vayunmathur/library/ml/Small100Handle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Small100Handle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Small100Handle.ktnew file mode 100644index 0000000000..cd17ce9353--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Small100Handle.kt@@ -0,0 +1,155 @@+package com.vayunmathur.library.ml++import android.os.ParcelFileDescriptor+import android.util.Log+import java.io.File+import java.text.Normalizer++/**+ * On-device translation between any two of 100 languages: SMaLL-100 on the Vulkan compute runtime.+ *+ * M2M-100 distilled to a 3-layer decoder — 12 encoder layers, `d_model` 1024, 16 heads, a 128,112+ * entry vocabulary — at 332.7 million parameters. **Direct** translation, with no English pivot, so+ * every pair is a single hop. See `library/ml/src/main/rust/src/nets/small100.rs`.+ *+ * # Two files, 320 MB, downloaded rather than bundled+ *+ * `small100.maml` is 318.3 MiB and `tokenizer.bin` 1.7 MB, which is far too much to ship inside an+ * APK — hence [inDirectory] and no asset path. Everything but the layer norms and the biases is+ * int8, quantised per output channel from the fp32 checkpoint; the worst per-tensor correlation+ * against fp32 is 0.9998.+ *+ * The ncnn build this replaces downloaded **1.14 GB** across seven files. It was fp16 because ncnn+ * could not quantise the embedding, and an int4 attempt crashed with a tagged-memory fault inside+ * `libncnn_android.so`.+ *+ * # The target language goes on the source side+ *+ * SMaLL-100 does not use `forced_bos_token_id`. The target-language token is prepended to the+ * **source** and the decoder starts from `</s>`. Backwards, it produces fluent output in the wrong+ * language rather than an error — which is why [translate] takes a token rather than a code and+ * leaves the table to the caller that already has it.+ *+ * # Normalisation+ *+ * The model's normaliser is `nmt_nfkc` with a 237 KB precompiled charsmap, so [translate] applies+ * `java.text.Normalizer` **NFKC** first and native does the rest — the same split+ * [SupertonicSynthesizer] uses for NFD.+ *+ * # Availability+ *+ * Construction never throws. [isAvailable] is false when `libmodelrunner.so` is missing for this+ * ABI, when either file is absent or malformed, or when the device cannot give us a Vulkan device+ * with fp16 compute — and then [translate] returns null.+ *+ * # Threading+ *+ * Not thread-safe, and more sharply than the other handles here: a translation re-records the+ * network once per decoded token, so two concurrent calls would interleave recordings of the same+ * command buffer. A caller must hold a lock across [translate] and [close].+ */+class Small100Handle private constructor(private val directory: File) : AutoCloseable {+    private var handle: Long = 0L++    init {+        handle = if (!MlNative.isAvailable) {+            0L+        } else {+            try {+                create(directory)+            } catch (e: Throwable) {+                Log.e(TAG, "cannot open the SMaLL-100 model in $directory", e)+                0L+            }+        }+    }++    /** True if the graph came up and the tokenizer table is the vocabulary the model was built on. */+    val isAvailable: Boolean get() = handle != 0L++    /**+     * Translate [text] into the language [targetToken] names, or null on failure.+     *+     * An empty string means there was nothing to translate, which is not a failure — blank input and+     * input the tokenizer maps to nothing both come back empty. Null means the engine is unavailable+     * or the pass failed, and the reason is in logcat under `ModelRunner`.+     *+     * Long text should be split into sentences first. Nothing refuses a paragraph, but decoding is+     * capped at 128 tokens and every step attends over the whole source.+     */+    fun translate(text: String, targetToken: Int): String? {+        if (handle == 0L) return null+        if (text.isBlank()) return ""+        val normalised = Normalizer.normalize(text, Normalizer.Form.NFKC)+        return MlNative.translateSmall100(handle, normalised, targetToken)+    }++    /** Free the network and close the weights file. Idempotent. */+    override fun close() {+        val live = handle+        handle = 0L+        if (live != 0L) MlNative.destroySmall100(live)+    }++    override fun toString(): String = "SMaLL-100 in $directory"++    companion object {+        private const val TAG = "Small100Handle"++        /** The one graph. Native checks its graph id, so a wrong file fails at load. */+        const val GRAPH = "small100.maml"++        /** `scripts/ml/small100_tokenizer.py`'s output: 128,112 pieces and their merge ranks. */+        const val TOKENIZER = "tokenizer.bin"++        /** The files [inDirectory] needs, for a caller checking a download is complete. */+        val FILES: List<String> = listOf(GRAPH, TOKENIZER)++        /**+         * The model in a folder on disk, which is the only place it lives.+         *+         * No `inAssets` counterpart, unlike [SupertonicSynthesizer]: at 320 MB this is a runtime+         * download to `getExternalFilesDir`, so there is no APK entry to open.+         */+        fun inDirectory(directory: File): Small100Handle = Small100Handle(directory)++        /**+         * Open the graph, read the tokenizer table, and hand the descriptor over.+         *+         * The two `finally`s are what make the descriptor safe rather than usually safe. A raw+         * descriptor has no destructor, so every path out of here has to close what it opened: the+         * outer one covers a missing or unreadable file, and the inner one covers the window after+         * the descriptor has been given up but before native has adopted it.+         */+        private fun create(directory: File): Long {+            val graph = File(directory, GRAPH)+            require(graph.isFile) { "$GRAPH is missing from $directory" }+            val tokenizer = File(directory, TOKENIZER)+            require(tokenizer.isFile) { "$TOKENIZER is missing from $directory" }++            // Offset 0 and the whole file: only an asset needs a range, because only an asset shares+            // its descriptor with the rest of the APK.+            val fd = ParcelFileDescriptor.open(graph, ParcelFileDescriptor.MODE_READ_ONLY)+                .use { it.detachFd() }+            var handed = false+            try {+                val handle =+                    MlNative.createSmall100(fd, 0L, graph.length(), tokenizer.readBytes())+                handed = true+                return handle+            } finally {+                if (!handed) closeFd(fd)+            }+        }++        /**+         * Close a bare descriptor.+         *+         * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from Kotlin.+         * Failures are swallowed because the caller is already on an error path.+         */+        private fun closeFd(fd: Int) {+            runCatching { ParcelFileDescriptor.adoptFd(fd).close() }+        }+    }+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 21ba335609..65280e8a53 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -34,13 +34,15 @@ use jni::sys::{jfloatArray, jint, jlong, jstring}; use jni::JNIEnv;  use crate::nets::{-    mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration, supertonic_sampler,-    supertonic_text, supertonic_vocoder, u2netp, Plan,+    mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, small100, supertonic_duration,+    supertonic_sampler, supertonic_text, supertonic_vocoder, u2netp, Plan, }; use crate::post::ctc::Dictionary; use crate::post::nms::{self, Face, Maps}; use crate::post::ocr::{self, Line};+use crate::post::sentencepiece::Table; use crate::post::supertonic;+use crate::post::translate; use crate::preprocess::{     Letterbox, FACE_EMBED, IMAGENET, PPOCR_DET, PPOCR_REC, RESCALE_ONLY, SCRFD, };@@ -1082,6 +1084,304 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroy<'     drop(unsafe { Box::from_raw(handle as *mut Handle) }); } +/// SMaLL-100, as `:translate` holds it. Handed to Kotlin as an opaque `jlong`.+///+/// Its own handle type for the same reason [`SupertonicHandle`] is: it owns a different set of+/// things, and one `destroy` guessing between them would be type confusion waiting to happen.+///+/// # One net, three plans+///+/// [`Reshaped`] keyed by [`small100::Mode`] rather than by a length. The encoder, the decode step+/// and the logits projection are three passes over **one** 318 MiB file, so three `Net`s would+/// upload it three times; one net rebuilt per pass uploads it once. A rebuild is a+/// `device_wait_idle` and a re-record, and a decode step's cache grows by one position each time,+/// so a translation of `n` tokens costs `n + 1` of them. That is the known cost of holding the KV+/// cache on the host, and it is what a future prefix bound in [`crate::nets::Push`] would remove.+///+/// # The weights file stays open+///+/// Unlike Supertonic, whose host-side tensors are read once into [`supertonic::Conditioning`],+/// SMaLL-100's host-side tensor is the 125 MiB tied embedding, which cannot be pre-read. So the+/// [`Streamed`] is retained and [`small100::embed_positions`] gathers a 1 KB row per token from it.+struct Small100Handle {+    net: Reshaped<small100::Mode>,+    weights: Streamed,+    /// `scripts/ml/small100_tokenizer.py`'s table, 1.7 MB, parsed per translation.+    tokenizer: Vec<u8>,+}++fn small100_plan(offsets: &Offsets, mode: small100::Mode) -> Result<Plan, String> {+    small100::build(offsets, mode)+}++/// The two GPU passes, as [`translate::Nets`] wants them, plus the host-side KV cache.+///+/// Built per translation and dropped with it, so a cache cannot leak into the next sentence — the+/// failure `Net::reset` would otherwise exist to prevent.+struct Small100Nets<'a> {+    net: &'a mut Reshaped<small100::Mode>,+    weights: &'a Streamed,+    /// Per decoder layer, the K then V for every position decoded so far, position-major and+    /// concatenated. `[cache_len * D_MODEL]` each, appended one row at a time.+    cache: Vec<Vec<f32>>,+    /// Source positions, so a decode step records at the length the encoder ran at.+    src_len: u32,+}++/// K and V per decoder layer, which is how many cache buffers there are.+const SMALL100_CACHES: usize = small100::DECODER_LAYERS * 2;++impl Small100Nets<'_> {+    fn new<'a>(handle: &'a mut Small100Handle) -> Small100Nets<'a> {+        Small100Nets {+            net: &mut handle.net,+            weights: &handle.weights,+            cache: vec![Vec::new(); SMALL100_CACHES],+            src_len: 0,+        }+    }+}++impl translate::Nets for Small100Nets<'_> {+    fn encode(&mut self, source: &[u32]) -> Result<Vec<f32>, String> {+        let len = u32::try_from(source.len()).map_err(|_| "a source longer than u32")?;+        let reader = self.weights.reader();+        // The embedding, `sqrt(d_model)` and the sinusoidal positions, all on the host. See+        // `nets::small100` for why none of that is a shader.+        let embedded = small100::embed_positions(reader, source, 0)?;+        let net = self.net.at(small100::Mode::Encode { len })?;+        let out = one_output(net.infer_raw(&embedded)?)?;+        self.src_len = len;+        // The plan produces `[d_model, 1, len]`; the trait's contract is `[len, d_model]`. One+        // transpose here rather than a comment that disagrees with the trait.+        Ok(transpose(&out, small100::D_MODEL as usize, source.len()))+    }++    fn decode_step(+        &mut self,+        token: u32,+        step: usize,+        encoded: &[f32],+    ) -> Result<Vec<f32>, String> {+        let width = small100::D_MODEL as usize;+        let cache_len = u32::try_from(step).map_err(|_| "a step past u32")?;+        let reader = self.weights.reader();+        // `past = step`, which is what puts this token at position `step + 2`.+        let embedded = small100::embed_positions(reader, &[token], cache_len)?;+        if !encoded.len().is_multiple_of(width) {+            return Err(format!("{} encoder values is not a whole number of {width}", encoded.len()));+        }+        let src_len = (encoded.len() / width) as u32;+        if src_len != self.src_len {+            return Err(format!("a step over {src_len} source positions after {}", self.src_len));+        }+        // Back to `[d_model, 1, src_len]`, which is what the cross-attention projections read.+        let source = transpose(encoded, encoded.len() / width, width);++        let net = self.net.at(small100::Mode::DecodeStep { cache_len, src_len })?;+        // Declaration order: the token, the encoder output, then each layer's K and V. The cache+        // pair is absent at step 0, where there is nothing before this token.+        let mut inputs: Vec<&[f32]> = Vec::with_capacity(2 + SMALL100_CACHES);+        inputs.push(&embedded);+        inputs.push(&source);+        if cache_len > 0 {+            for held in &self.cache {+                inputs.push(held);+            }+        }+        let out = net.infer_raw_many(&inputs)?;++        // Two logits halves, then this step's K and V per layer. The halves are consecutive class+        // ranges, so concatenating them is the 128,112-wide vector `post::translate` argmaxes.+        let expected = small100::HEAD_SPLITS + SMALL100_CACHES;+        if out.len() != expected {+            return Err(format!("a decode step returned {} tensors, not {expected}", out.len()));+        }+        let mut logits = Vec::with_capacity(small100::VOCAB as usize);+        for half in out.iter().take(small100::HEAD_SPLITS) {+            logits.extend_from_slice(half);+        }+        if logits.len() != small100::VOCAB as usize {+            return Err(format!("{} logits, not {}", logits.len(), small100::VOCAB));+        }+        for (held, row) in self.cache.iter_mut().zip(out.iter().skip(small100::HEAD_SPLITS)) {+            if row.len() != width {+                return Err(format!("a cache row of {} values, not {width}", row.len()));+            }+            // Position-major, so appending is a plain extend and the plan's own concatenation of+            // it is one contiguous copy.+            held.extend_from_slice(row);+        }+        Ok(logits)+    }+}++/// `[rows, columns]` to `[columns, rows]`.+///+/// The encoder output crosses the `translate::Nets` seam as `[positions, d_model]` and this runtime+/// works in `[d_model, positions]`, so it is transposed once on the way out and once per step on+/// the way back in. Eight kilobytes for a sentence, against a trait whose documented shape would+/// otherwise be wrong.+fn transpose(values: &[f32], rows: usize, columns: usize) -> Vec<f32> {+    let mut out = vec![0.0f32; values.len()];+    for row in 0..rows {+        for column in 0..columns {+            if let (Some(&from), Some(slot)) =+                (values.get(row * columns + column), out.get_mut(column * rows + row))+            {+                *slot = from;+            }+        }+    }+    out+}++/// Bring up SMaLL-100 from its one `.maml` and its tokenizer table. Returns 0 on failure.+///+/// # Safety+///+/// Called only by the JVM, with a valid `env`, arrays it owns, and a descriptor nothing else holds.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSmall100<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    fd: jint,+    offset: jlong,+    length: jlong,+    tokenizer: JByteArray<'l>,+) -> jlong {+    // The descriptor first, and adopted into an owning `File` before anything else may fail: the+    // caller detached it, so a path that returns without wrapping it leaks it for the life of the+    // process. Every check below the adoption is therefore free to fail; nothing above it is.+    if fd < 0 {+        log(&format!("small100 is unavailable: descriptor {fd} is not open"));+        return 0;+    }+    // SAFETY: the caller detached the descriptor, so nothing else owns it, and `File` closes it on+    // drop — including on every failure path below.+    let file = unsafe { File::from_raw_fd(fd) };+    match build_small100(&mut env, file, offset, length, &tokenizer) {+        Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,+        Err(e) => {+            log(&format!("small100 is unavailable: {e}"));+            0+        }+    }+}++fn build_small100<'l>(+    env: &mut JNIEnv<'l>,+    file: File,+    offset: jlong,+    length: jlong,+    tokenizer: &JByteArray<'l>,+) -> Result<Small100Handle, String> {+    let (at, len) = match (u64::try_from(offset), u64::try_from(length)) {+        (Ok(at), Ok(len)) => (at, len),+        _ => return Err(format!("the graph spans {offset}+{length}")),+    };+    let weights = Streamed::open(file, at, len, graph::SMALL100)?;++    let tokenizer = env+        .convert_byte_array(tokenizer)+        .map_err(|e| format!("cannot read the tokenizer table: {e}"))?;+    // Parsed once here purely to refuse a bad table at construction rather than at the first+    // translation, when the UI has already committed to having a working engine.+    let parsed = Table::parse(&tokenizer)?;+    if parsed.len() != small100::VOCAB as usize {+        return Err(format!("a tokenizer of {} pieces, not {}", parsed.len(), small100::VOCAB));+    }++    // The smallest legal encoder, immediately replaced: `Net::new` needs a plan and the real shapes+    // are not known until a sentence arrives. `Net::rebuild` only ever grows the arena.+    let net = Reshaped::streamed(+        context::shared()?,+        weights.offsets(),+        &weights,+        small100::Mode::Encode { len: SMALLEST },+        small100_plan,+    )?;+    Ok(Small100Handle { net, weights, tokenizer })+}++/// Translate [`text`] into the language `target_token` names, or null on failure.+///+/// `text` must already be NFKC — `java.text.Normalizer.normalize(text, Form.NFKC)`. The model's+/// normaliser is `nmt_nfkc` with a 237 KB precompiled charsmap, and reproducing that natively would+/// mean carrying Unicode tables the platform already has. See `post::sentencepiece`.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createSmall100` that has not been destroyed.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translateSmall100<'l>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+    text: JString<'l>,+    target_token: jint,+) -> jstring {+    if handle == 0 {+        return std::ptr::null_mut();+    }+    // SAFETY: the caller guarantees the handle came from `createSmall100` and is still live. It is+    // `&mut` because a decode step re-records the net, and Kotlin serialises calls on one handle.+    let handle = unsafe { &mut *(handle as *mut Small100Handle) };+    let translated = match env.get_string(&text) {+        Ok(text) => run_small100(handle, &String::from(text), target_token),+        Err(e) => Err(format!("cannot read the source text: {e}")),+    };+    match translated {+        Ok(out) => match env.new_string(&out) {+            Ok(string) => string.into_raw(),+            Err(e) => {+                log(&format!("small100 cannot return its translation: {e}"));+                std::ptr::null_mut()+            }+        },+        Err(e) => {+            log(&format!("small100 failed: {e}"));+            std::ptr::null_mut()+        }+    }+}++fn run_small100(+    handle: &mut Small100Handle,+    text: &str,+    target_token: jint,+) -> Result<String, String> {+    let target = u32::try_from(target_token).map_err(|_| format!("{target_token} is not a token"))?;+    // Cloned so the table can borrow it while the nets borrow the handle mutably. 1.7 MB against a+    // translation that uploads nothing and reads a 318 MiB file.+    let tokenizer = handle.tokenizer.clone();+    let table = Table::parse(&tokenizer)?;+    let mut nets = Small100Nets::new(handle);+    translate::translate(&mut nets, &table, target, text)+}++/// Free SMaLL-100's net, its open weights file and its tokenizer table.+///+/// Exactly once per non-zero handle from `createSmall100`. When it is the last user of the shared+/// `VkDevice`, the device goes away with it.+///+/// # Safety+///+/// `handle` must be a non-zero value from `createSmall100`, and must not be used again.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySmall100<'l>(+    _env: JNIEnv<'l>,+    _class: JClass<'l>,+    handle: jlong,+) {+    if handle == 0 {+        return;+    }+    // SAFETY: the caller guarantees this handle came from `createSmall100` and has not been+    // destroyed. `Net`'s Drop waits for the device to go idle before freeing.+    drop(unsafe { Box::from_raw(handle as *mut Small100Handle) });+}+ fn new_float_array(env: &mut JNIEnv, values: &[f32]) -> Result<jfloatArray, String> {     let array: JFloatArray = env         .new_float_array(values.len() as jint)
library/ml/src/main/rust/src/nets/small100.rs
diff --git a/library/ml/src/main/rust/src/nets/small100.rs b/library/ml/src/main/rust/src/nets/small100.rsindex 561e4a7872..6b583a5413 100644--- a/library/ml/src/main/rust/src/nets/small100.rs+++ b/library/ml/src/main/rust/src/nets/small100.rs@@ -375,7 +375,7 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     let b = &mut builder;     // The tied weight and the whole decoder belong to the other two passes. The trailing encoder     // norm is part of this range, so it runs to `DECODER` rather than to `ENCODER_NORM`.-    name_host_tensors(b, &[ENCODER..DECODER]);+    name_host_tensors(b, std::slice::from_ref(&(ENCODER..DECODER)));      let x = b.input(Shape::new(D_MODEL, 1, len));     let mut x = x;@@ -404,7 +404,7 @@ fn logits(weights: &dyn WeightSource) -> Result<Plan, String> {     let l = &mut Layers { next: HEAD };     let mut builder = Builder::new(weights);     let b = &mut builder;-    name_host_tensors(b, &[HEAD..ENCODER]);+    name_host_tensors(b, std::slice::from_ref(&(HEAD..ENCODER)));      let state = b.input(Shape::new(D_MODEL, 1, 1));     let halves: Vec<Id> = (0..HEAD_SPLITS)@@ -614,11 +614,17 @@ mod tests {     /// Stated here rather than returned by [`build`] because it is the thing under test: a pass     /// that read the wrong range would name the right one and still be wrong.     fn read_by(mode: Mode) -> Vec<std::ops::Range<usize>> {+        let mut ranges = Vec::new();         match mode {-            Mode::Encode { .. } => vec![ENCODER..DECODER],-            Mode::Logits => vec![HEAD..ENCODER],-            Mode::DecodeStep { .. } => vec![HEAD..ENCODER, DECODER..TENSORS],+            Mode::Encode { .. } => ranges.push(ENCODER..DECODER),+            Mode::Logits => ranges.push(HEAD..ENCODER),+            Mode::DecodeStep { .. } => {+                // The decode step computes the tied head itself, so it reads both ends of the file.+                ranges.push(HEAD..ENCODER);+                ranges.push(DECODER..TENSORS);+            }         }+        ranges     }      #[test]
translate/build.gradle.kts
diff --git a/translate/build.gradle.kts b/translate/build.gradle.ktsindex 90e924b3bc..5e000e57dc 100644--- a/translate/build.gradle.kts+++ b/translate/build.gradle.kts@@ -17,9 +17,9 @@ android { }  dependencies {-    // On-device translation runs entirely in the ncnn AAR (SMaLL-100 via the-    // Small100 class); the model files are downloaded at runtime from the mirror.-    implementation(libs.ncnn.android)+    // On-device translation runs on `:library:ml`'s own Vulkan compute runtime (SMaLL-100 via+    // `Small100Handle`); the two model files are downloaded at runtime from the mirror.+    implementation(project(":library:ml"))     implementation(project(":library:downloadservice"))     implementation(project(":library:ocr"))     implementation(project(":library:network"))
translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.kt b/translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.ktindex 589e6480df..5f3fed3723 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/Small100Model.kt@@ -3,49 +3,69 @@ package com.vayunmathur.translate.platform import android.content.Context import com.vayunmathur.library.downloadservice.ModelDownloadItem import com.vayunmathur.library.downloadservice.downloadModels+import com.vayunmathur.library.ml.Small100Handle import com.vayunmathur.library.util.DataStoreUtils import java.io.File  /**- * Runtime-download config for the on-device **SMaLL-100** translation model- * (converted to ncnn). Quantization attempt:- * - int4 weight-only block quant via ncnnllm (mseclip b64) produced 680 MB vs- *   1.14 GB fp16 (36 enc + 13 dec Gemm+MHA layers, term 401), Embed stays fp16- *   (262 MB ×2 floor).- * - **CRASH**: int4 MHA `forward_weight_block_quantize` triggered MTE- *   SEGV_MTESERR in `libncnn_android.so` at `multiheadattention.cpp:793`- *   (Pixel 9 Pro XL, Android 17, OpenMP worker). Tombstone 28:- *   `pc 0x490224 -> forward_weight_block_quantize (.omp_outlined_debug__.33)`.- *   Root cause: ncnn int4 block-quant MHA not MTE-clean (packed int4 unpack may- *   read out-of-tag). Roll back to fp16 stable; alternative path: Gemm-only- *   int4 or classic Embed int8 via ncnn2int8.+ * Runtime-download config for the on-device **SMaLL-100** translation model.  *- * Files are fetched mirror-only from `data.vayunmathur.com/models/small100/`- * with SHA-256 pinning via [downloadModels]. Auto-install via- * `InitialModelDownloadChecker` in MainActivity (like OpenAssistant).+ * Two files, 320 MB: `small100.maml` and `tokenizer.bin`. Rebuild both byte for byte with+ * `python scripts/ml/fetch_small100.py`, which pins `alirezamsh/small100` by revision and per-file+ * SHA-256 and prints the digests below.+ *+ * # It used to be 1.14 GB across seven files+ *+ * The previous build was ncnn, and fp16, because ncnn could not quantise the 131M-parameter+ * embedding — 262 MB of fp16 per net, twice over. An int4 weight-block attempt to fix that crashed:+ * `forward_weight_block_quantize` triggered a tagged-memory fault, `SEGV_MTESERR` in+ * `libncnn_android.so` at `multiheadattention.cpp:793`, on a Pixel 9 Pro XL. So the size and the+ * only two MTE faults this tree has seen had the same cause, and both are gone with the dependency:+ * the model now runs on `:library:ml`'s own Vulkan runtime, quantised int8 per output channel.+ *+ * Files are fetched mirror-only from `data.vayunmathur.com/models/small100/` with SHA-256 pinning+ * via [downloadModels]. Auto-install via `InitialModelDownloadChecker` in MainActivity.  */ object Small100Model {     private const val BASE = "https://data.vayunmathur.com/models/small100/"     const val DIR = "small100" -    /** The 7 runtime files — fp16 stable (int4 MHA crashes on Pixel 9 MTE, see above). */+    /** The 2 runtime files. Names and order come from [Small100Handle.FILES]. */     val FILES: List<ModelDownloadItem> = listOf(-        item("encoder.ncnn.param", "4c86bc19318933169474ddab957c7031cbce48d95c06d3159d487e6a941959c8"),-        item("encoder.ncnn.bin", "06d34fe528960b8f5246592d99b4bfaf27b164fc4a49bd5a13d95eadb87d13a2"),-        item("decoder.ncnn.param", "e3fd9b9be770d93a022d98c8b29f5ed603e08b04be424da8480cacfce00467bf"),-        item("decoder.ncnn.bin", "2bedd93dc073cb1840c563acfa5e70816893c6fbf678a538fdad68f90325ec70"),-        item("sentencepiece.bpe.model", "d8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a"),-        item("vocab.txt", "84733eadc2b3f2a21c55687336ca538e55650233bcc729650cd53c2d2fc77319"),-        item("pos_weights.f32.bin", "254e2cf622a8e498df8600c5052ec492129b5ca8932ada1e514a091c26f9dd80"),+        item(+            Small100Handle.GRAPH,+            "0c7f64de141874d062d25043f9391c669d6fef62cd2763220f2c6eb50e68fa47",+        ),+        item(+            Small100Handle.TOKENIZER,+            "b6556bd9f5db3b08977e4db430d3d5fc8301891f74e58018da637ba6068a4b16",+        ),+    )++    /**+     * The seven ncnn files, deleted from an existing install the first time this runs.+     *+     * Without this an upgrade leaves 1.14 GB of unreachable weights in the app's external files+     * directory, which nothing else will ever remove. Kept as names rather than a wildcard so a+     * future file of ours cannot be caught by it.+     */+    private val RETIRED = listOf(+        "encoder.ncnn.param",+        "encoder.ncnn.bin",+        "decoder.ncnn.param",+        "decoder.ncnn.bin",+        "sentencepiece.bpe.model",+        "vocab.txt",+        "pos_weights.f32.bin",     )      private fun item(name: String, sha256: String) =         ModelDownloadItem("$BASE$name", "$DIR/$name", "SMaLL-100 $name", sha256) -    /** Directory the ncnn `Small100` loads from. */+    /** Directory [Small100Handle.inDirectory] loads from. */     fun modelDir(context: Context): File = File(context.getExternalFilesDir(null), DIR) -    /** True once every model file is present on disk. */+    /** True once both model files are present on disk. */     fun isDownloaded(context: Context): Boolean {         val root = context.getExternalFilesDir(null) ?: return false         return FILES.all { File(root, it.fileName).exists() }@@ -58,6 +78,24 @@ object Small100Model {     fun progress(ds: DataStoreUtils): Float =         (FILES.map { ds.getDouble("progress_${it.fileName}") ?: 0.0 }.average()).toFloat() +    /**+     * Delete the ncnn model an earlier version downloaded, returning the bytes reclaimed.+     *+     * Safe to call at any time and cheap when there is nothing to do, which is every run after the+     * first. See [RETIRED].+     */+    fun deleteRetired(context: Context): Long {+        val directory = modelDir(context)+        var reclaimed = 0L+        for (name in RETIRED) {+            val file = File(directory, name)+            if (!file.isFile) continue+            val size = file.length()+            if (file.delete()) reclaimed += size+        }+        return reclaimed+    }+     /**      * The 100 languages SMaLL-100 was trained on, in fairseq dictionary order (which is      * plain lexicographic order of these codes). `ast`, `ceb`, `ilo` and `ns` are@@ -82,9 +120,10 @@ object Small100Model {      /**      * SMaLL-100 target-language token ids (`128004 + fairseq index`). SMaLL-100 needs-     * only the target language (it's prepended to the source), so no source id is-     * required. Derived from [LANG_ORDER] rather than transcribed; the values match-     * `lang_tokens` in the model's upstream `mobile_manifest.json`.+     * only the target language — it is prepended to the **source**, not forced on the+     * decoder — so no source id is required. Derived from [LANG_ORDER] rather than+     * transcribed; the values match `lang_tokens.json` in the upstream export, and+     * `post::translate::FIRST_LANG_TOKEN` asserts the same base natively.      */     val LANG_ID: Map<String, Int> =         LANG_ORDER.withIndex().associate { (index, code) -> code to FIRST_LANG_ID + index }
translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.kt b/translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.ktindex 71454c90a9..f2b11a67c8 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/Small100Translator.kt@@ -1,30 +1,37 @@ package com.vayunmathur.translate.platform -import com.vayunmathur.translate.domain.TranslationEngine- import android.content.Context import android.util.Log-import com.vayunmathur.ncnn.Small100+import com.vayunmathur.library.ml.Small100Handle+import com.vayunmathur.translate.domain.TranslationEngine import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext  /**- * [TranslationEngine] backed by the ncnn AAR's [Small100] (on-device SMaLL-100).- * The model is loaded lazily from [Small100Model.modelDir] the first time it's- * needed and only if the files have been downloaded; until then [isAvailable] is- * false and the UI shows a download prompt. Language detection is unnecessary —- * SMaLL-100 only needs the target language — so [detectLanguage] returns null.+ * [TranslationEngine] backed by [Small100Handle] — SMaLL-100 on `:library:ml`'s Vulkan runtime.+ *+ * The model is loaded lazily from [Small100Model.modelDir] the first time it is needed, and only if+ * the two files have been downloaded; until then [isAvailable] is false and the UI shows a download+ * prompt. Language detection is unnecessary — SMaLL-100 needs only the target language — so+ * [detectLanguage] returns null.+ *+ * # The lock is not only for the handle+ *+ * A translation re-records the network once per decoded token, so two concurrent calls would+ * interleave recordings of the same command buffer. The mutex therefore covers the whole of+ * [translate] rather than just the load, and [close] too.  */ class Small100Translator(private val context: Context) : TranslationEngine {      private val lock = Mutex()-    private var model: Small100? = null-    private var loadFailed = false+    private var model: Small100Handle? = null+    private var attempts = 0+    private var closed = false      override suspend fun isAvailable(): Boolean = withContext(Dispatchers.Default) {-        lock.withLock { ensure() }+        lock.withLock { ensure() != null }     }      override suspend fun detectLanguage(text: String): String? = null@@ -32,11 +39,11 @@ class Small100Translator(private val context: Context) : TranslationEngine {     override suspend fun translate(text: String, from: String?, to: String): String? =         withContext(Dispatchers.Default) {             if (text.isBlank()) return@withContext ""-            val tgtId = Small100Model.LANG_ID[to] ?: return@withContext null+            val target = Small100Model.LANG_ID[to] ?: return@withContext null             lock.withLock {-                if (!ensure()) return@withContext null+                val handle = ensure() ?: return@withContext null                 try {-                    model?.translate(text, tgtId)?.ifBlank { null }+                    handle.translate(text, target)?.ifBlank { null }                 } catch (t: Throwable) {                     Log.e(TAG, "translate failed", t)                     null@@ -45,36 +52,51 @@ class Small100Translator(private val context: Context) : TranslationEngine {         }      /** Call after a successful model download so the next use loads it. */-    suspend fun reset() = lock.withLock { loadFailed = false }+    suspend fun reset() = lock.withLock { attempts = 0 } +    /**+     * Free the model. Terminal: nothing loads again afterwards, and it is idempotent.+     *+     * Deliberately **not** `suspend`, because the only caller is `ViewModel.onCleared`, which is+     * not. That means it does not take [lock], so it must not run while a translation is in flight —+     * which `onCleared` guarantees: `viewModelScope` is cancelled before it runs and the UI cannot+     * ask for another translation once the view model is cleared.+     */     fun close() {+        closed = true         model?.close()         model = null     } -    /** Load the ncnn model once, if the files are present. Returns whether it's ready. */-    private fun ensure(): Boolean {-        model?.let { return true }-        if (loadFailed) return false-        if (!Small100Model.isDownloaded(context)) return false-        return try {-            val m = Small100(Small100Model.modelDir(context).absolutePath)-            if (m.isAvailable) {-                model = m-                true-            } else {-                m.close()-                loadFailed = true-                false-            }-        } catch (t: Throwable) {-            Log.e(TAG, "Small100 load failed", t)-            loadFailed = true-            false+    /**+     * The loaded model, loading it if the files are present.+     *+     * Retries are capped at [MAX_ATTEMPTS] rather than latched on the first failure, because the+     * one recoverable cause — a download that finished between two calls — is exactly the case a+     * latch would make permanent. Anything else fails twice and stays failed.+     */+    private fun ensure(): Small100Handle? {+        model?.let { return it }+        if (closed || attempts >= MAX_ATTEMPTS) return null+        if (!Small100Model.isDownloaded(context)) return null+        attempts+++        val reclaimed = Small100Model.deleteRetired(context)+        if (reclaimed > 0) {+            Log.i(TAG, "reclaimed $reclaimed bytes of retired ncnn weights")+        }+        val handle = Small100Handle.inDirectory(Small100Model.modelDir(context))+        if (!handle.isAvailable) {+            handle.close()+            return null         }+        model = handle+        return handle     }      companion object {         private const val TAG = "Small100Translator"++        /** One retry, for a download that completed between two calls. See `ensure`. */+        private const val MAX_ATTEMPTS = 2     } }