Modern Apps git

← Modern-Apps.git

translate: switch model from small100 to NLLB-200 distilled 600M

Commit
e6e52e12c31f9fa7470faa6b1f50fb8a187101cf
Author
vayun-mathur <[email protected]>
When
2026-09-03 21:24 UTC (3 months ago)
Parents
3c83b0c

Diff

library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.ktindex 2dbc76f5be..bd20ca6266 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/ClipHandle.kt@@ -106,7 +106,7 @@ class ClipHandle private constructor(private val source: String) : AutoCloseable         /**          * The model from the APK's assets, which is the only place it lives.          *-         * No `inDirectory` counterpart, unlike [Small100Handle]: at 22.6 MiB this is bundled, so+         * No `inDirectory` counterpart: at 22.6 MiB this is bundled, so          * there is no download directory to look in.          */         fun inAssets(assets: AssetManager, path: String = GRAPH): ClipHandle {
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 491824d968..7ce552dc89 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@@ -151,28 +151,35 @@ internal object MlNative {     external fun synthesizeSupertonic(handle: Long, text: String, language: String): FloatArray?      /**-     * Bring up SMaLL-100 from its one `.maml` and its tokenizer table. Returns 0 on failure.+     * Bring up NLLB-200-distilled-600M 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.+     * 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** 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 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. [offset] is 0 and-     * [length] the file's size for a file on disk; only an asset needs a real range.+     * **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: 1.7 MB, where streaming saves nothing.+     * [tokenizer] stays a byte array, where streaming saves nothing.      *-     * Freed by [destroySmall100], not [destroy], [destroyOcr] or [destroySupertonic].+     * 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 createSmall100(+    external fun createNllb(         fd: Int,         offset: Long,         length: Long,@@ -180,32 +187,42 @@ internal object MlNative {     ): 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.+     * 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 translateSmall100(handle: Long, text: String, targetToken: Int): String?+    external fun translateNllb(+        handle: Long,+        text: String,+        sourceToken: Int,+        targetToken: Int,+    ): String?      /**-     * Free SMaLL-100's network, its open weights file and its tokenizer table.-     * Exactly once per non-zero handle from [createSmall100].+     * Free NLLB's network, its open weights file and its tokenizer table.+     * Exactly once per non-zero handle from [createNllb].      */-    external fun destroySmall100(handle: Long)+    external fun destroyNllb(handle: Long)      /**      * Bring up TinyCLIP from its one `.maml`. Returns 0 on failure.      *-     * One graph, not two, for a different reason from [createSmall100]: the image and text towers+     * 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.@@ -221,8 +238,7 @@ internal object MlNative {      * **The descriptor must be detached.** Native takes ownership and closes it, on the failure      * paths as much as the successful one, so a caller must not close it itself.      *-     * Freed by [destroyTinyclip], not [destroy], [destroyOcr], [destroySupertonic] or-     * [destroySmall100].+     * Freed by [destroyTinyclip], not [destroy], [destroyOcr] or [destroySupertonic].      */     external fun createTinyclip(fd: Int, offset: Long, length: Long): Long @@ -261,7 +277,7 @@ internal object MlNative {      * Bring up whisper-base from its one `.maml` and the ids read from `generation_config.json`.      * Returns 0 on failure.      *-     * One graph, not two, as [createSmall100] is: the 51,865-row embedding is **tied** — the+     * 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.@@ -286,8 +302,8 @@ internal object MlNative {      * 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],-     * [destroySmall100] or [destroyTinyclip].+     * Freed by [destroyWhisper], not [destroy], [destroyOcr], [destroySupertonic]+     * or [destroyTinyclip].      */     external fun createWhisper(         fd: Int,
library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.ktnew file mode 100644index 0000000000..23e3f8073f--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/NllbHandle.kt@@ -0,0 +1,161 @@+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 202 languages: NLLB-200-distilled-600M on the+ * Vulkan compute runtime.+ *+ * NLLB distilled to 600M parameters: 12 encoder layers, 12 decoder layers, `d_model` 1024,+ * 16 heads, a 4096-wide ReLU feed-forward - and a 256,206-entry vocabulary shared between+ * the input embedding and the output projection. **Direct** translation, with no English+ * pivot, so every pair is a single hop. See `library/ml/src/main/rust/src/nets/nllb.rs`.+ *+ * # Two files, downloaded rather than bundled+ *+ * `nllb600.maml` and `tokenizer.bin`, which are far too much to ship inside an APK - hence+ * [inDirectory] and no asset path. The tied embedding is emitted as four head-split tensors+ * over disjoint class ranges (256,206 classes at 1024 channels exceeds+ * `maxStorageBufferRange` in one buffer), and the tokenizer table holds the 256,000+ * SentencePiece pieces plus the 202 flores language tokens.+ *+ * This replaces the old SMaLL-100 build (12 enc + 3 dec, 128,112 vocab).+ *+ * # Both language tokens are required+ *+ * NLLB puts the **source** language token on the encoder source and forces the **target**+ * language token as the decoder's first token (forced-BOS), rather than SMaLL-100's+ * target-token-on-source + EOS-start. Backwards, it produces fluent output in the wrong+ * language rather than an error - which is why [translate] takes flores codes rather than+ * bare ids and resolves both through+ * [com.vayunmathur.translate.platform.NllbModel.tokenId].+ *+ * # Normalisation+ *+ * The model's normaliser is `nmt_nfkc` with a 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 NllbHandle 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 NLLB 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] from the language [sourceToken] names 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, sourceToken: Int, targetToken: Int): String? {+        if (handle == 0L) return null+        if (text.isBlank()) return ""+        val normalised = Normalizer.normalize(text, Normalizer.Form.NFKC)+        return MlNative.translateNllb(handle, normalised, sourceToken, targetToken)+    }++    /** Free the network and close the weights file. Idempotent. */+    override fun close() {+        val live = handle+        handle = 0L+        if (live != 0L) MlNative.destroyNllb(live)+    }++    override fun toString(): String = "NLLB-200 in $directory"++    companion object {+        private const val TAG = "NllbHandle"++        /** The one graph. Native checks its graph id, so a wrong file fails at load. */+        const val GRAPH = "nllb600.maml"++        /** model-eng's `nllb_tokenizer.py` output: SentencePiece pieces plus the language tokens. */+        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]: the distilled-600M+         * weights are a runtime download to `getExternalFilesDir`, so there is no APK+         * entry to open.+         */+        fun inDirectory(directory: File): NllbHandle = NllbHandle(directory)++        /**+         * Open the graph, read the tokenizer table, and hand the descriptor over.+         *+         * The two `finally`s are what make the descriptor safe rather than usually safe. A raw+         * descriptor has no destructor, so every path out of here has to close what it opened:+         * the outer one covers a missing or unreadable file, and the inner one covers the+         * window after the descriptor has been given up but before native has adopted it.+         */+        private fun create(directory: File): Long {+            val graph = File(directory, GRAPH)+            require(graph.isFile) { "$GRAPH is missing from $directory" }+            val tokenizer = File(directory, TOKENIZER)+            require(tokenizer.isFile) { "$TOKENIZER is missing from $directory" }++            // Offset 0 and the whole file: only an asset needs a range, because only an asset+            // shares its descriptor with the rest of the APK.+            val fd = ParcelFileDescriptor.open(graph, ParcelFileDescriptor.MODE_READ_ONLY)+                .use { it.detachFd() }+            var handed = false+            try {+                val handle =+                    MlNative.createNllb(fd, 0L, graph.length(), tokenizer.readBytes())+                handed = true+                return handle+            } finally {+                if (!handed) closeFd(fd)+            }+        }++        /**+         * Close a bare descriptor.+         *+         * Adopting it into a [ParcelFileDescriptor] is the only way to reach `close(2)` from+         * Kotlin. Failures are swallowed because the caller is already on an error path.+         */+        private fun closeFd(fd: Int) {+            runCatching { ParcelFileDescriptor.adoptFd(fd).close() }+        }+    }+}
library/ml/src/main/java/com/vayunmathur/library/ml/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.ktdeleted file mode 100644index cd17ce9353..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Small100Handle.kt+++ /dev/null@@ -1,155 +0,0 @@-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 467509e4cf..6fd5f5096a 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -34,7 +34,7 @@ use jni::sys::{jfloatArray, jint, jintArray, jlong, jstring}; use jni::JNIEnv;  use crate::nets::{-    mobilefacenet, ppocr_det, ppocr_rec, scrfd, selfie, small100, supertonic_duration,+    mobilefacenet, nllb, ppocr_det, ppocr_rec, scrfd, selfie, supertonic_duration,     supertonic_sampler, supertonic_text, supertonic_vocoder, tinyclip, u2netp, whisper, Plan, }; use crate::post::ctc::Dictionary;@@ -1124,42 +1124,64 @@ 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`.+/// `[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+}++/// NLLB-200-distilled-600M, 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+/// Its own handle type for the same reason the translation handle 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+/// # One net, two passes ///-/// [`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.+/// [`Reshaped`] keyed by [`nllb::Mode`]. The encoder and the decode step (which computes the tied+/// head itself) are two passes over **one** ~600 MiB file, so two `Net`s would upload it twice.+/// 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>,+/// NLLB's host-side tensor is the ~250 MiB tied embedding, which cannot be pre-read. So the+/// [`Streamed`] is retained and [`nllb::embed_positions`] gathers a 1 KB row per token from it.+///+/// The tensor order is the contract in `maml_convert.collect_nllb` — see `nets::nllb`.+struct NllbHandle {+    net: Reshaped<nllb::Mode>,     weights: Streamed,-    /// `scripts/ml/small100_tokenizer.py`'s table, 1.7 MB, parsed per translation.+    /// `scripts/ml/nllb_tokenizer.py`'s table, parsed per translation.     tokenizer: Vec<u8>, } -fn small100_plan(offsets: &Offsets, mode: small100::Mode) -> Result<Plan, String> {-    small100::build(offsets, mode)+fn nllb_plan(offsets: &Offsets, mode: nllb::Mode) -> Result<Plan, String> {+    nllb::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>,+struct NllbNets<'a> {+    net: &'a mut Reshaped<nllb::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.@@ -1169,32 +1191,32 @@ struct Small100Nets<'a> { }  /// K and V per decoder layer, which is how many cache buffers there are.-const SMALL100_CACHES: usize = small100::DECODER_LAYERS * 2;+const NLLB_CACHES: usize = nllb::DECODER_LAYERS * 2; -impl Small100Nets<'_> {-    fn new<'a>(handle: &'a mut Small100Handle) -> Small100Nets<'a> {-        Small100Nets {+impl NllbNets<'_> {+    fn new<'a>(handle: &'a mut NllbHandle) -> NllbNets<'a> {+        NllbNets {             net: &mut handle.net,             weights: &handle.weights,-            cache: vec![Vec::new(); SMALL100_CACHES],+            cache: vec![Vec::new(); NLLB_CACHES],             src_len: 0,         }     } } -impl translate::Nets for Small100Nets<'_> {+impl translate::Nets for NllbNets<'_> {     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 })?;+        // `nets::nllb` for why none of that is a shader.+        let embedded = nllb::embed_positions(reader, source, 0)?;+        let net = self.net.at(nllb::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()))+        Ok(transpose(&out, nllb::D_MODEL as usize, source.len()))     }      fn decode_step(@@ -1203,11 +1225,11 @@ impl translate::Nets for Small100Nets<'_> {         step: usize,         encoded: &[f32],     ) -> Result<Vec<f32>, String> {-        let width = small100::D_MODEL as usize;+        let width = nllb::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)?;+        let embedded = nllb::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()));         }@@ -1218,10 +1240,10 @@ impl translate::Nets for Small100Nets<'_> {         // 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 })?;+        let net = self.net.at(nllb::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);+        let mut inputs: Vec<&[f32]> = Vec::with_capacity(2 + NLLB_CACHES);         inputs.push(&embedded);         inputs.push(&source);         if cache_len > 0 {@@ -1231,20 +1253,21 @@ impl translate::Nets for Small100Nets<'_> {         }         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;+        // Four logits splits, then this step's K and V per layer. The splits are consecutive class+        // ranges (the last two one class short), so concatenating them is the full-vocabulary+        // vector `post::translate` argmaxes.+        let expected = nllb::HEAD_SPLITS + NLLB_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) {+        let mut logits = Vec::with_capacity(nllb::VOCAB as usize);+        for half in out.iter().take(nllb::HEAD_SPLITS) {             logits.extend_from_slice(half);         }-        if logits.len() != small100::VOCAB as usize {-            return Err(format!("{} logits, not {}", logits.len(), small100::VOCAB));+        if logits.len() != nllb::VOCAB as usize {+            return Err(format!("{} logits, not {}", logits.len(), nllb::VOCAB));         }-        for (held, row) in self.cache.iter_mut().zip(out.iter().skip(small100::HEAD_SPLITS)) {+        for (held, row) in self.cache.iter_mut().zip(out.iter().skip(nllb::HEAD_SPLITS)) {             if row.len() != width {                 return Err(format!("a cache row of {} values, not {width}", row.len()));             }@@ -1256,33 +1279,16 @@ impl translate::Nets for Small100Nets<'_> {     } } -/// `[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.+/// Bring up NLLB 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.+///+/// `createNllb` mirrors the old `createSmall100`, and `translateNllb` takes **both** a source and a+/// target token — the protocol flip vs small100. Agreed with app-eng (team `nllb-translate`). #[no_mangle]-pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSmall100<'l>(+pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createNllb<'l>(     mut env: JNIEnv<'l>,     _class: JClass<'l>,     fd: jint,@@ -1294,33 +1300,33 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createSmall100<'     // 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"));+        log(&format!("nllb 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) {+    match build_nllb(&mut env, file, offset, length, &tokenizer) {         Ok(handle) => Box::into_raw(Box::new(handle)) as jlong,         Err(e) => {-            log(&format!("small100 is unavailable: {e}"));+            log(&format!("nllb is unavailable: {e}"));             0         }     } } -fn build_small100<'l>(+fn build_nllb<'l>(     env: &mut JNIEnv<'l>,     file: File,     offset: jlong,     length: jlong,     tokenizer: &JByteArray<'l>,-) -> Result<Small100Handle, String> {+) -> Result<NllbHandle, 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 weights = Streamed::open(file, at, len, graph::NLLB)?;      let tokenizer = env         .convert_byte_array(tokenizer)@@ -1328,8 +1334,8 @@ fn build_small100<'l>(     // 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));+    if parsed.len() != nllb::VOCAB as usize {+        return Err(format!("a tokenizer of {} pieces, not {}", parsed.len(), nllb::VOCAB));     }      // The smallest legal encoder, immediately replaced: `Net::new` needs a plan and the real shapes@@ -1338,78 +1344,88 @@ fn build_small100<'l>(         context::shared()?,         weights.offsets(),         &weights,-        small100::Mode::Encode { len: SMALLEST },-        small100_plan,+        nllb::Mode::Encode { len: SMALLEST },+        nllb_plan,     )?;-    Ok(Small100Handle { net, weights, tokenizer })+    Ok(NllbHandle { net, weights, tokenizer }) } -/// Translate [`text`] into the language `target_token` names, or null on failure.+/// Translate [`text`] from the language `source_token` names 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+/// normaliser is `nmt_nfkc` with a precompiled charsmap, and reproducing that natively would /// mean carrying Unicode tables the platform already has. See `post::sentencepiece`. ///+/// Unlike small100 before it, BOTH tokens are required: the source token goes on the encoder source+/// and the+/// target token forced-BOSes the decoder. Backwards it produces fluent output in the wrong+/// language rather than an error.+/// /// # Safety ///-/// `handle` must be a non-zero value from `createSmall100` that has not been destroyed.+/// `handle` must be a non-zero value from `createNllb` that has not been destroyed. #[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translateSmall100<'l>(+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_translateNllb<'l>(     mut env: JNIEnv<'l>,     _class: JClass<'l>,     handle: jlong,     text: JString<'l>,+    source_token: jint,     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+    // SAFETY: the caller guarantees the handle came from `createNllb` 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 handle = unsafe { &mut *(handle as *mut NllbHandle) };     let translated = match env.get_string(&text) {-        Ok(text) => run_small100(handle, &String::from(text), target_token),+        Ok(text) => run_nllb(handle, &String::from(text), source_token, 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}"));+                log(&format!("nllb cannot return its translation: {e}"));                 std::ptr::null_mut()             }         },         Err(e) => {-            log(&format!("small100 failed: {e}"));+            log(&format!("nllb failed: {e}"));             std::ptr::null_mut()         }     } } -fn run_small100(-    handle: &mut Small100Handle,+fn run_nllb(+    handle: &mut NllbHandle,     text: &str,+    source_token: jint,     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 source =+        u32::try_from(source_token).map_err(|_| format!("{source_token} is not a token"))?;+    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.     let tokenizer = handle.tokenizer.clone();     let table = Table::parse(&tokenizer)?;-    let mut nets = Small100Nets::new(handle);-    translate::translate(&mut nets, &table, target, text)+    let mut nets = NllbNets::new(handle);+    translate::translate(&mut nets, &table, source, target, text) } -/// Free SMaLL-100's net, its open weights file and its tokenizer table.+/// Free NLLB'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+/// Exactly once per non-zero handle from `createNllb`. 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.+/// `handle` must be a non-zero value from `createNllb`, and must not be used again. #[no_mangle]-pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySmall100<'l>(+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyNllb<'l>(     _env: JNIEnv<'l>,     _class: JClass<'l>,     handle: jlong,@@ -1417,16 +1433,16 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroySm     if handle == 0 {         return;     }-    // SAFETY: the caller guarantees this handle came from `createSmall100` and has not been+    // SAFETY: the caller guarantees this handle came from `createNllb` 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) });+    drop(unsafe { Box::from_raw(handle as *mut NllbHandle) }); }  /// TinyCLIP, as `:photos` holds it. Handed to Kotlin as an opaque `jlong`. /// /// # One net, two plans ///-/// [`Reshaped`] keyed by [`tinyclip::Mode`], as [`Small100Handle`] is: the two towers share no+/// [`Reshaped`] keyed by [`tinyclip::Mode`], as the translation handle is: the two towers share no /// weights but they do share a 22.6 MiB file, so two `Net`s would upload it twice. Switching towers /// is a `device_wait_idle` and a re-record — which is why an indexing run, which is `Mode::Image` /// throughout, pays for exactly one.@@ -1478,7 +1494,8 @@ pub extern "system" fn Java_com_vayunmathur_library_ml_MlNative_createTinyclip<'     length: jlong, ) -> jlong {     // The descriptor first, and adopted into an owning `File` before anything else may fail, as-    // `createSmall100` does: the caller detached it, so a path that returns without wrapping it+    // the old `createSmall100` did: the caller detached it, so a path that returns without wrapping+    // it     // leaks it for the life of the process.     if fd < 0 {         log(&format!("tinyclip is unavailable: descriptor {fd} is not open"));@@ -1650,7 +1667,8 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_destroyTi /// /// [`Reshaped`] keyed by [`whisper::Mode`]. The encoder runs once per utterance; a decode step is /// re-recorded every token because its self-attention cache grows by one position, which is a-/// `device_wait_idle` and a re-record per token — the same known cost `Small100Handle` documents.+/// `device_wait_idle` and a re-record per token — the same known cost the translation handle+/// documents. /// /// The **cross-attention** caches are the difference. Whisper's decoder cross-attends over 1500 /// encoder positions through each layer's own key and value projections, so recomputing them per
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 18f8f83ca9..52e69bf37d 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -32,11 +32,11 @@ #[cfg(test)] pub mod reference; pub mod mobilefacenet;+pub mod nllb; pub mod ppocr_det; pub mod ppocr_rec; pub mod scrfd; pub mod selfie;-pub mod small100; pub mod supertonic_duration; pub mod supertonic_sampler; pub mod supertonic_text;@@ -1545,7 +1545,7 @@ impl<'a> Builder<'a> {     /// plans — an encoder pass, a decode step and the logits projection — so no single one of them     /// reads every tensor, and each names the others' as host tensors. The invariant that nothing     /// is unread then has to be checked over the *union* of the plans, which is a test the net-    /// module owes because that is where the layout is; `nets::small100` has it.+    /// module owes because that is where the layout is; `nets::nllb` has it.     pub fn host_tensor(&mut self, weight_index: usize, dims: &[u32]) {         // Through `weight` so the shape is checked against the file like any other tensor.         self.weight(weight_index, dims);
library/ml/src/main/rust/src/nets/nllb.rs
diff --git a/library/ml/src/main/rust/src/nets/small100.rs b/library/ml/src/main/rust/src/nets/nllb.rssimilarity index 68%rename from library/ml/src/main/rust/src/nets/small100.rsrename to library/ml/src/main/rust/src/nets/nllb.rsindex 78dcdf60d1..4f1a4c9565 100644--- a/library/ml/src/main/rust/src/nets/small100.rs+++ b/library/ml/src/main/rust/src/nets/nllb.rs@@ -1,22 +1,24 @@-//! SMaLL-100: a 100-language translation encoder-decoder, in one `.maml`.+//! NLLB-200-distilled-600M: a 200-language translation encoder-decoder, in one `.maml`. //! //! # What it is //!-//! M2M-100 distilled to a 3-layer decoder: 12 encoder layers, 3 decoder layers, `d_model` 1024,-//! 16 heads of 64, a 4096-wide feed-forward, and a 128,112-entry vocabulary shared between the-//! input embedding and the output projection. 332,735,488 parameters, 318 MiB as int8.+//! NLLB distilled to 600M parameters: 12 encoder layers, 12 decoder layers, `d_model` 1024,+//! 16 heads of 64, a 4096-wide feed-forward, and a 256,206-entry vocabulary shared between the+//! input embedding and the output projection. //!-//! The Kotlin it replaces claimed "36 enc + 13 dec Gemm+MHA layers". Those were **ncnn's** counts,-//! with multi-head attention fused into one layer, and they do not map onto anything here;-//! `scripts/ml/fetch_small100.py` asserts the real numbers against the checkpoint's `config.json`-//! rather than trusting either.+//! The architecture is `M2M100ForConditionalGeneration` — the same forward pass SMaLL-100 (which+//! this replaced) used, with 12 decoder layers instead of 3 and 202 language tokens instead of+//! 100. The two modules were kept side by side during the port so a reviewer could diff them;+//! every difference from the old `small100.rs` is one of: the vocabulary size, the head split+//! count and sizes, the decoder layer count, and the language-token constants in+//! `post::translate`. //!-//! # One file, three passes+//! # One file, two passes //! //! [`Mode`] selects which of them [`build`] emits. They share the file because the embedding is //! **tied**: it is the encoder's input table, the decoder's input table and the logits kernel, and-//! two files would upload 125 MiB of it twice. Each pass names the others' tensors with-//! [`Builder::host_tensor`], and `tests::the_passes_partition_the_file_and_every_one_of_them_builds`+//! two files would upload ~250 MiB of it twice. Each pass names the others' tensors with+//! [`Builder::host_tensor`], and `tests::the_passes_cover_the_file_and_every_one_of_them_builds` //! is what keeps that from hiding a genuinely unread layer. //! //! # The embedding is gathered on the host@@ -30,28 +32,37 @@ //! //! [`embed_positions`] reads the row with [`crate::weights::Reader::int8_row`], dequantises it by //! that row's own scale, scales and adds the position in f32, and hands the result in as an-//! ordinary fp16 plan input. That is 1 KB of file reads per token against a 125 MiB upload, it-//! keeps `sqrt(1024)` out of the int8 rounding, and it is why the ncnn build's-//! `pos_weights.f32.bin` download is gone.+//! ordinary fp16 plan input. The math is fairseq's `M2M100SinusoidalPositionalEmbedding` with the+//! `+ 2` offset, verified against transformers' `modeling_m2m_100.py` by model-eng. //! //! ## The position offset is 2, not 0 //! //! fairseq numbers positions as `cumsum(mask) * mask + padding_idx` with `padding_idx = 1`, so the //! first real token sits at **position 2**. An off-by-two here produces fluent, plausible, subtly //! wrong output, and no shape check anywhere catches it. It is pinned in-//! `tests::the_first_token_sits_at_position_two` and against onnxruntime.+//! `tests::the_first_token_sits_at_position_two` and was verified against transformers'+//! `modeling_m2m_100.py` by model-eng. //! //! The sinusoid is fairseq's, which is not the usual one either: the two halves are //! `[sin(all 512), cos(all 512)]` **concatenated rather than interleaved**, and the frequency //! spacing divides by `half_dim - 1` = 511, not 512. //!-//! # The head is two ops, not one+//! # The head is four ops, not one //!-//! 128,112 classes at 1024 channels is 125.1 MiB of int8, and `maxStorageBufferRange`'s guaranteed-//! minimum is 128 MiB — so one binding would be inside the limit only just, and an fp16 embedding-//! would not fit at all. `scripts/ml/maml_convert.py` therefore emits the tied weight as **two**-//! tensors over disjoint class ranges, [`Mode::Logits`] emits two `ConvPointInt8` ops, and-//! `post::translate` argmaxes over both halves — which it already did, because it argmaxes anyway.+//! 256,206 classes at 1024 channels is ~250 MiB of int8, and `maxStorageBufferRange`'s guaranteed+//! minimum is 128 MiB — so `scripts/ml/maml_convert.py` emits the tied weight as **four**+//! tensors over disjoint class ranges, [`Mode::DecodeStep`] emits four `ConvVecInt8` ops, and+//! `post::translate` argmaxes over all four — which it already did, because it argmaxes anyway.+//!+//! 256,206 is not divisible by 4, so the splits are uneven: the first two hold 64,052 classes+//! each and the last two 64,051 (see [`split_classes`]). No range is padded — padding would add+//! dummy logits that could win the argmax.+//!+//! # The FFN is ReLU, not GELU+//!+//! `config.json` says `activation_function: relu`, so [`feed_forward`] uses [`Act::Relu`]. A GELU+//! here would still run and still produce text, which is why the activation code is pinned in+//! `tests::the_encoder_is_twelve_pre_norm_layers`. //! //! # No attention mask, and none needed //!@@ -59,18 +70,25 @@ //! //! * The encoder runs over one sentence with no padding, so every key is real. //! * The decoder decodes one token at a time, so a step is **one query against `step + 1` keys**,-//!   which is causal by construction. That is what [`Builder::attn_scores`]'s support for+//!   which is causal by construction. That is what [`Builder::attn_scores_cached`]'s support for //!   differing query and key lengths buys. //! //! [`Builder::attn_scores`] applies `1 / sqrt(head_dim)` itself, and `head_dim` is 64, which is-//! exactly M2M-100's `self.scaling`. So nothing folds a query scale, unlike Supertonic's text-//! encoder.+//! exactly the model's `self.scaling`. So nothing folds a query scale, and `sqrt(d_model)` stays+//! in the host gather rather than folded into the embedding. //! //! # Pre-norm //!-//! `M2M100EncoderLayer` and `M2M100DecoderLayer` normalise **before** each sublayer and skip-//! around both, and each stack ends with one more layer norm. Written the other way round the net-//! still runs and still produces text.+//! The encoder and decoder layers normalise **before** each sublayer and skip around both, and+//! each stack ends with one more layer norm. Written the other way round the net still runs and+//! still produces text.+//!+//! # Decode protocol+//!+//! NLLB puts the **source** language token on the encoder source and forces the **target**+//! language token as the decoder's first token (forced-BOS). See+//! `post::translate::translate`. Getting this backwards produces fluent output in the wrong+//! language rather than an error.  use super::{Act, Builder, Id, Plan, Shape, WeightSource}; use crate::weights::Reader;@@ -85,19 +103,35 @@ pub const HEADS: u32 = 16; pub const FFN: u32 = 4096;  /// Vocabulary entries, shared by the embedding and the logits projection.-pub const VOCAB: u32 = 128_112;+///+/// 256,000 SentencePiece pieces + 202 flores language codes + `<mask>` + 4 specials, per+/// `config.json`'s `vocab_size` and model-eng's tokenizer inventory.+pub const VOCAB: u32 = 256_206;  /// Class ranges the tied weight is emitted as. See the module docs.-pub const HEAD_SPLITS: usize = 2;+pub const HEAD_SPLITS: usize = 4; -/// Classes in each half. 128,112 is `2 * 64,056`, so neither range is padded.-pub const CLASSES_PER_SPLIT: u32 = VOCAB / HEAD_SPLITS as u32;+/// Classes in each of the first two splits. The last two hold one fewer each.+pub const CLASSES_PER_SPLIT: u32 = 64_052;++/// Classes in the last two splits: 256,206 = 2 x 64,052 + 2 x 64,051.+pub const CLASSES_PER_TAIL_SPLIT: u32 = 64_051;++/// Classes in split `split`: the first two get the extra row each.+pub fn split_classes(split: usize) -> u32 {+    if split < 2 {+        CLASSES_PER_SPLIT+    } else {+        CLASSES_PER_TAIL_SPLIT+    }+}  /// Encoder layers. pub const ENCODER_LAYERS: usize = 12; -/// Decoder layers. Three is what makes SMaLL-100 four times faster than M2M-100.-pub const DECODER_LAYERS: usize = 3;+/// Decoder layers. Twelve: the distilled-600M keeps the full M2M-100 decoder, unlike SMaLL-100's+/// three.+pub const DECODER_LAYERS: usize = 12;  /// `max_position_embeddings`, and therefore the longest source this can encode. pub const MAX_POSITIONS: u32 = 1024;@@ -114,7 +148,7 @@ const ENCODER_LAYER_TENSORS: usize = 2 + 4 * 3 + 2 + 3 + 3; /// Tensors per decoder layer: an encoder layer plus a cross-attention norm and four projections. const DECODER_LAYER_TENSORS: usize = ENCODER_LAYER_TENSORS + 2 + 4 * 3; -/// The first of the two head halves. They come first, because the embedding is read before+/// The first of the four head splits. They come first, because the embedding is read before /// anything else and the file is written in forward order. const HEAD: usize = 0; @@ -130,30 +164,20 @@ const DECODER: usize = ENCODER_NORM + 2; /// The decoder's trailing layer norm. const DECODER_NORM: usize = DECODER + DECODER_LAYERS * DECODER_LAYER_TENSORS; -/// Tensors the `.maml` must hold, and the count `maml_convert.py` writes.+/// Tensors the `.maml` must hold, and the count `maml_convert.py` writes: 12 head + 264 encoder+/// + 2 + 432 decoder + 2. pub const TENSORS: usize = DECODER_NORM + 2;  /// Convolutions read as int8 rather than fp16, each carrying a third tensor for its scale. ///-/// **Every one of them.** Both head halves, all six projections of each encoder layer and all ten-/// of each decoder layer — 104 tensors and 99.98% of the parameters. Nothing is excluded, and that-/// is a measurement rather than an omission: `maml_convert.collect_small100` reports the worst-/// per-tensor correlation between the fp32 weight and `int8 * scale` over all 104, and it is-/// 0.999808 on a head half, against the 0.999 floor Supertonic's reverted text encoder failed at-/// 0.99212.-///-/// Only the layer norms and the biases stay fp16, and they are 0.02% of the file. Quantising a-/// rank-1 per-channel affine would save 250 KB and cost the normalisation its precision.-///-/// The reason this is even possible is that the weights come from the **fp32 checkpoint**: the-/// int8 ONNX exports that exist for SMaLL-100 quantise per tensor, which throws away a factor of-/// four on the embedding alone. See `CHECKPOINTS` in `scripts/ml/maml_convert.py`.+/// **Every one of them.** Four head splits, all six projections of each encoder layer and all ten+/// of each decoder layer. Only the layer norms and the biases stay fp16. pub const INT8_CONVS: usize = HEAD_SPLITS + ENCODER_LAYERS * 6 + DECODER_LAYERS * 10;  /// Which forward pass [`build`] emits. ///-/// One graph and three plans, run through [`crate::vulkan::run::Net::rebuild`] rather than three-/// nets, so the 318 MiB upload happens once.+/// One graph and two plans, run through [`crate::vulkan::run::Net::rebuild`] rather than two+/// nets, so the ~600 MiB upload happens once. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode {     /// The encoder over `len` tokens: `[1024, 1, len]` in, `[1024, 1, len]` out.@@ -161,8 +185,6 @@ pub enum Mode {         /// Source tokens, after [`embed_positions`].         len: u32,     },-    /// The tied logits projection: one `[1024]` state in, two half-vocabularies out.-    Logits,     /// One decoder step: the token just produced in, its logits and its new K/V out.     ///     /// A step is **one query** against `cache_len + 1` keys — the `cache_len` positions already@@ -222,7 +244,8 @@ fn attention(b: &mut Builder, l: &mut Layers, residual: Id, queries: Id, keys: I     b.add(residual, projected) } -/// The pre-norm feed-forward sublayer, plus its residual. `relu`, not `gelu`.+/// The pre-norm feed-forward sublayer, plus its residual. `relu`, not `gelu`: `config.json` says+/// `activation_function: relu`. fn feed_forward(b: &mut Builder, l: &mut Layers, x: Id) -> Id {     let normed = b.layer_norm(x, l.take(), EPSILON);     let inner = point(b, l, normed, FFN, Act::Relu);@@ -230,11 +253,10 @@ fn feed_forward(b: &mut Builder, l: &mut Layers, x: Id) -> Id {     b.add(x, projected) } -/// Build one of SMaLL-100's three passes. See [`Mode`].+/// Build one of NLLB's two passes. See [`Mode`]. pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> {     match mode {         Mode::Encode { len } => encode(weights, len),-        Mode::Logits => logits(weights),         Mode::DecodeStep { cache_len, src_len } => decode_step(weights, cache_len, src_len),     } }@@ -249,7 +271,7 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> { /// | 1 | `[1024, 1, src_len]` | the encoder output, channel-major as the encoder produced it | /// | 2, 3 | `[cache_len, 1, 1024]` | layer 0's self-attention K and V, position-major | /// | 4, 5 | | layer 1's |-/// | 6, 7 | | layer 2's |+/// | … | | … | /// /// The cache pair is **omitted at step 0**, where there is nothing before the current token. ///@@ -257,18 +279,18 @@ pub fn build(weights: &dyn WeightSource, mode: Mode) -> Result<Plan, String> { /// /// | | shape | | /// | :--- | :--- | :--- |-/// | 0, 1 | `[64056, 1, 1]` | the two logits halves, which the host argmaxes across |-/// | 2, 3 | `[1, 1, 1024]` | layer 0's new self-attention K and V, ready to append |-/// | 4, 5 | | layer 1's |-/// | 6, 7 | | layer 2's |+/// | 0..4 | `[~64052, 1, 1]` | the four logits splits (the last two one class short), concatenated by the host |+/// | 4, 5 | `[1, 1, 1024]` | layer 0's new self-attention K and V, ready to append |+/// | 6, 7 | | layer 1's |+/// | … | | … | /// /// # Why the cross-attention K and V are recomputed /// /// They depend only on the encoder output, so computing them once and caching them would save-/// six 1024x1024 projections per step. They are not cached here because that would need a fourth+/// twelve 1024x1024 projections per step. They are not cached here because that would need a third /// pass and a second kind of persistence for a saving the logits projection dwarfs: the head is-/// 131 million multiply-accumulates against the whole decoder's 50 million. Worth revisiting only-/// after `Kind::ConvVecInt8` makes the head cheap.+/// ~262 million multiply-accumulates against the whole decoder's ~200 million. Worth revisiting+/// only after `Kind::ConvVecInt8` makes the head cheap. fn decode_step(weights: &dyn WeightSource, cache_len: u32, src_len: u32) -> Result<Plan, String> {     if src_len == 0 {         return Err("a decode step with no source to attend over".into());@@ -348,11 +370,11 @@ fn decode_step(weights: &dyn WeightSource, cache_len: u32, src_len: u32) -> Resu         return Err(format!("the decoder norm ends at {}, not {TENSORS}", l.next));     } -    // The tied head, in the same plan: a separate `Mode::Logits` pass would mean a second-    // `rebuild` and a round trip through the host for a `[1024]` vector.+    // The tied head, in the same plan: a separate pass would mean a second `rebuild` and a round+    // trip through the host for a `[1024]` vector. The last two splits are one class short.     let head = &mut Layers { next: HEAD };     let mut outputs: Vec<Id> = (0..HEAD_SPLITS)-        .map(|_| point(b, head, state, CLASSES_PER_SPLIT, Act::None))+        .map(|split| point(b, head, state, split_classes(split), Act::None))         .collect();     if head.next != ENCODER {         return Err(format!("the head claims {} tensors, not {ENCODER}", head.next));@@ -373,7 +395,7 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     let l = &mut Layers { next: ENCODER };     let mut builder = Builder::new(weights);     let b = &mut builder;-    // The tied weight and the whole decoder belong to the other two passes. The trailing encoder+    // The tied weight and the whole decoder belong to the other pass. The trailing encoder     // norm is part of this range, so it runs to `DECODER` rather than to `ENCODER_NORM`.     name_host_tensors(b, std::slice::from_ref(&(ENCODER..DECODER))); @@ -394,31 +416,9 @@ fn encode(weights: &dyn WeightSource, len: u32) -> Result<Plan, String> {     builder.finish(&[out]) } -/// The tied logits projection over one decoder state.-///-/// Two ops rather than one, over disjoint class ranges, so no binding approaches-/// `maxStorageBufferRange`. Both outputs come back in declaration order and `post::translate`-/// argmaxes across them, which needs no change: it argmaxed a single 128,112-wide vector before,-/// and the winner of two halves is the winner of the whole.-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, std::slice::from_ref(&(HEAD..ENCODER)));--    let state = b.input(Shape::new(D_MODEL, 1, 1));-    let halves: Vec<Id> = (0..HEAD_SPLITS)-        .map(|_| point(b, l, state, CLASSES_PER_SPLIT, Act::None))-        .collect();-    if l.next != ENCODER {-        return Err(format!("the head claims {} tensors, not {ENCODER}", l.next));-    }-    builder.finish(&halves)-}- /// Name every tensor **outside** `read` as one this pass does not touch. ///-/// [`Builder::finish`] refuses an unread tensor, and no one of the three passes reads the whole+/// [`Builder::finish`] refuses an unread tensor, and no one of the two passes reads the whole /// file. Declaring the complement rather than listing it keeps the two in step: adding a layer /// changes the ranges and nothing else. fn name_host_tensors(b: &mut Builder, read: &[std::ops::Range<usize>]) {@@ -432,14 +432,17 @@ fn name_host_tensors(b: &mut Builder, read: &[std::ops::Range<usize>]) { /// The shape of tensor `index`, derived from the layout constants. /// /// `host_tensor` checks it against the file, so this is a *second* statement of the table that-/// `maml_convert.collect_small100` writes — which is the point: a converter and a runtime that+/// `maml_convert.collect_nllb` writes — which is the point: a converter and a runtime that /// disagree about a shape fail here rather than on the device. fn dims_of(index: usize) -> Vec<u32> {     if index < ENCODER {-        // A head half: int8 kernel, per-class scale, synthesised zero bias.+        // A head split: int8 kernel, per-class scale, synthesised zero bias. The last two splits+        // are one class short.+        let split = index / 3;+        let classes = split_classes(split);         return match index % 3 {-            0 => vec![CLASSES_PER_SPLIT, D_MODEL, 1, 1],-            _ => vec![CLASSES_PER_SPLIT],+            0 => vec![classes, D_MODEL, 1, 1],+            _ => vec![classes],         };     }     let (base, per_layer, layers) = if index < DECODER {@@ -486,6 +489,20 @@ fn layer_dims(within: usize, per_layer: usize) -> Vec<u32> {     vec![D_MODEL] } +/// Which head split holds token `id`, and its row within that split.+///+/// The first two splits hold [`CLASSES_PER_SPLIT`] classes each and the last two one fewer, so+/// this is not one division: ids below twice the full width divide evenly, and the rest divide+/// over the tail width.+fn split_of(id: u32) -> (usize, u32) {+    if id < CLASSES_PER_SPLIT * 2 {+        ((id / CLASSES_PER_SPLIT) as usize, id % CLASSES_PER_SPLIT)+    } else {+        let rest = id - CLASSES_PER_SPLIT * 2;+        (2 + (rest / CLASSES_PER_TAIL_SPLIT) as usize, rest % CLASSES_PER_TAIL_SPLIT)+    }+}+ /// The embedded, scaled and positioned source for `ids`, in the channel-major layout the plan /// wants. ///@@ -506,13 +523,12 @@ pub fn embed_positions(         if id >= VOCAB {             return Err(format!("token {id} is past the {VOCAB}-entry vocabulary"));         }-        let half = (id / CLASSES_PER_SPLIT) as usize;-        let row = id % CLASSES_PER_SPLIT;-        let kernel = HEAD + half * 3;+        let (split, row) = split_of(id);+        let kernel = HEAD + split * 3;         let embedding = weights.int8_row(             kernel,             kernel + 1,-            &[CLASSES_PER_SPLIT, D_MODEL, 1, 1],+            &[split_classes(split), D_MODEL, 1, 1],             row,         )?;         let position = past + at as u32 + 1 + PADDING_IDX;@@ -561,6 +577,10 @@ mod tests {     /// A short sentence: a language token, six pieces and `</s>`.     const LEN: u32 = 8; +    /// `Act::Relu`'s code in `common.glsl`. `Act::code` is private, so the activation the FFN+    /// folds is asserted as the number the shader reads rather than through the enum.+    const ACT_RELU: u32 = 1;+     fn plan(mode: Mode) -> (Shapes, Plan) {         let source = Shapes::new(TENSORS);         let plan = build(&source, mode).expect("the pass builds");@@ -569,15 +589,20 @@ mod tests {      #[test]     fn the_layout_matches_the_converter() {-        // The numbers `maml_convert.py --print-layers` reports for this graph. A disagreement here-        // is a plan that reads one layer's weights as another's.+        // The numbers `maml_convert.py --graph nllb600 --print-layers` reports for this graph. A+        // disagreement here is a plan that reads one layer's weights as another's.         assert_eq!(ENCODER_LAYER_TENSORS, 22);         assert_eq!(DECODER_LAYER_TENSORS, 36);-        assert_eq!((HEAD, ENCODER, ENCODER_NORM), (0, 6, 270));-        assert_eq!((DECODER, DECODER_NORM), (272, 380));-        assert_eq!(TENSORS, 382);-        assert_eq!(INT8_CONVS, 104);-        assert_eq!(CLASSES_PER_SPLIT, 64_056);+        assert_eq!((HEAD, ENCODER, ENCODER_NORM), (0, 12, 276));+        assert_eq!((DECODER, DECODER_NORM), (278, 710));+        assert_eq!(TENSORS, 712);+        assert_eq!(INT8_CONVS, 196);+        assert_eq!((split_classes(0), split_classes(1)), (64_052, 64_052));+        assert_eq!((split_classes(2), split_classes(3)), (64_051, 64_051));+        assert_eq!(+            split_classes(0) + split_classes(1) + split_classes(2) + split_classes(3),+            VOCAB+        );     }      #[test]@@ -588,25 +613,26 @@ mod tests {             .map(|index| dims_of(index).iter().map(|&d| u64::from(d)).product::<u64>())             .sum(); -        // One fp16 scale per output channel of each of the 104 int8 convolutions.-        let scales = u64::from(CLASSES_PER_SPLIT) * HEAD_SPLITS as u64-            + ENCODER_LAYERS as u64 * u64::from(4 * D_MODEL + FFN + D_MODEL)-            + DECODER_LAYERS as u64 * u64::from(8 * D_MODEL + FFN + D_MODEL);-        assert_eq!(scales, 278_640);-        // And a zero bias for each head half, which a tied projection has no weight for.-        let synthesised = u64::from(CLASSES_PER_SPLIT) * HEAD_SPLITS as u64;--        assert_eq!(total, 332_735_488 + scales + synthesised);--        // 318.3 MiB on disk, against 1.14 GB of ncnn fp16 on the mirror today. Everything but the-        // 104 kernels is fp16, and the kernels are 99.8% of the elements — which is the whole-        // reason the file is a third of a fp16 one rather than half.-        let kernels = u64::from(CLASSES_PER_SPLIT) * u64::from(D_MODEL) * HEAD_SPLITS as u64+        // One fp16 scale per output channel of each of the 196 int8 convolutions.+        let layer_scales = u64::from(4 * D_MODEL + FFN + D_MODEL);+        let scales = u64::from(VOCAB)+            + ENCODER_LAYERS as u64 * layer_scales+            + DECODER_LAYERS as u64 * (layer_scales + u64::from(4 * D_MODEL));+        assert_eq!(scales, 526_542);+        // And a zero bias for each head split, which a tied projection has no weight for.+        let synthesised = u64::from(VOCAB);++        assert_eq!(total, 615_073_792 + scales + synthesised);++        // ~588.4 MiB on disk. Everything but the 196 kernels is fp16, and the kernels are 99.8%+        // of the elements — which is the whole reason the file is barely over the parameter+        // count in bytes.+        let kernels = u64::from(VOCAB) * u64::from(D_MODEL)             + ENCODER_LAYERS as u64 * u64::from(D_MODEL) * u64::from(4 * D_MODEL + 2 * FFN)             + DECODER_LAYERS as u64 * u64::from(D_MODEL) * u64::from(8 * D_MODEL + 2 * FFN);-        assert_eq!(kernels, 332_513_280);+        assert_eq!(kernels, 614_676_480);         let file = kernels + (total - kernels) * 2;-        assert!((318 << 20..319 << 20).contains(&file), "{file} bytes");+        assert!((588 << 20..589 << 20).contains(&file), "{file} bytes");     }      /// The tensor ranges each pass reads on the device. Everything else it names.@@ -617,7 +643,6 @@ mod tests {         let mut ranges = Vec::new();         match mode {             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);@@ -632,14 +657,9 @@ mod tests {         // `Builder::finish` only checks that a tensor is read *or* named, so this is what stops         // naming being used to hide a layer the device never touches. Together the passes must read         // every index.-        //-        // Not a partition: the decode step computes the tied head itself, so it and `Mode::Logits`-        // both read `HEAD..ENCODER`. `Mode::Logits` stays because it is the isolated case for the-        // split head, where a device parity run has nothing else in the plan to blame.         let mut covered = std::collections::BTreeSet::new();         for mode in [             Mode::Encode { len: LEN },-            Mode::Logits,             Mode::DecodeStep { cache_len: 0, src_len: LEN },             Mode::DecodeStep { cache_len: 3, src_len: LEN },         ] {@@ -669,6 +689,18 @@ mod tests {         // Two residuals per layer.         assert_eq!(counts.get("Add"), Some(&(ENCODER_LAYERS * 2)), "{counts:?}");         assert_eq!(counts.len(), 6, "{counts:?}");+        // And the FFN inner projection folds ReLU — `config.json`'s `activation_function: relu` —+        // one per layer, on the `FFN`-wide projection only.+        let mut relu = 0;+        for op in &plan.ops {+            if let Op::Dispatch { push, .. } = op {+                if push.out_c == FFN {+                    assert_eq!(push.act, ACT_RELU, "the FFN inner projection is ReLU: {push:?}");+                    relu += 1;+                }+            }+        }+        assert_eq!(relu, ENCODER_LAYERS, "{counts:?}");     }      #[test]@@ -692,7 +724,7 @@ mod tests {     }      #[test]-    fn a_decode_step_is_three_layers_of_two_attentions() {+    fn a_decode_step_is_twelve_layers_of_two_attentions() {         let (_, plan) = plan(Mode::DecodeStep { cache_len: 3, src_len: LEN });         let mut counts = std::collections::BTreeMap::new();         for op in &plan.ops {@@ -700,8 +732,8 @@ mod tests {                 *counts.entry(super::super::tests::name_of(*kind)).or_insert(0usize) += 1;             }         }-        // Ten int8 convolutions per layer — two attentions of four plus fc1 and fc2 — and the two-        // halves of the tied head.+        // Ten int8 convolutions per layer — two attentions of four plus fc1 and fc2 — and the four+        // splits of the tied head.         assert_eq!(             counts.get("ConvInt8"),             Some(&(DECODER_LAYERS * 10 + HEAD_SPLITS)),@@ -732,11 +764,12 @@ mod tests {             // Position-major: the cache's channels are the positions.             assert_eq!(binding.shape, Shape::new(cache_len, 1, D_MODEL));         }-        // Two logits halves, then the step's own K and V per layer.+        // Four logits splits, then the step's own K and V per layer.         assert_eq!(plan.outputs.len(), HEAD_SPLITS + DECODER_LAYERS * 2);-        for binding in &plan.outputs[..HEAD_SPLITS] {-            assert_eq!(binding.shape, Shape::new(CLASSES_PER_SPLIT, 1, 1));-        }+        let classes: u32 = plan.outputs.iter().take(HEAD_SPLITS).map(|b| b.shape.c).sum();+        assert_eq!(classes, VOCAB);+        assert_eq!(plan.outputs[0].shape.c, CLASSES_PER_SPLIT);+        assert_eq!(plan.outputs[HEAD_SPLITS - 1].shape.c, CLASSES_PER_TAIL_SPLIT);         for binding in &plan.outputs[HEAD_SPLITS..] {             assert_eq!(binding.shape, Shape::new(1, 1, D_MODEL));         }@@ -795,7 +828,7 @@ mod tests {     }      #[test]-    fn a_single_position_int8_convolution_becomes_a_gemv() {+    fn a_decode_step_is_single_position_where_it_counts() {         // Why `Kind::ConvVecInt8` exists. A decode step is one position almost throughout, and the         // tiled kind's workgroup count is `out_c.div_ceil(16) * positions.div_ceil(16)` — so at one         // position it pads 15 of every 16 tile columns and stores from 8 of every 64 invocations.@@ -816,8 +849,8 @@ mod tests {         // The split is not "everything": the cross-attention's key and value projections read the         // **encoder output**, which is `src_len` positions, so they stay tiled and are the only         // multi-position work a decode step does. Everything else — the four self-attention-        // projections, the cross-attention's query and output, both feed-forwards and both head-        // halves — is one position.+        // projections, the cross-attention's query and output, both feed-forwards and all four+        // head splits — is one position.         let (vector, tiled): (Vec<_>, Vec<_>) =             int8.iter().partition(|(kind, _, _)| *kind == Kind::ConvVecInt8);         assert_eq!(vector.len(), DECODER_LAYERS * 8 + HEAD_SPLITS, "single-position");@@ -835,87 +868,37 @@ mod tests {     }      #[test]-    fn the_gemv_issues_a_sixteenth_of_the_tiled_shader_s_work() {-        // The head is where it matters: 128,112 classes over 1024 channels, 128 times per-        // translation, at 131 million multiply-accumulates. This is the arithmetic that makes the-        // shader worth its own file.-        let (_, plan) = plan(Mode::DecodeStep { cache_len: 0, src_len: LEN });-        let head = plan-            .ops-            .iter()-            .find_map(|op| match op {-                Op::Dispatch { kind: Kind::ConvVecInt8, push, .. }-                    if push.out_c == CLASSES_PER_SPLIT =>-                {-                    Some(*push)-                }-                _ => None,-            })-            .expect("a head half on the gemv path");--        // Useful work: one multiply-accumulate per weight.-        let useful = u64::from(head.out_c) * u64::from(head.in_c);-        // The gemv issues exactly that: every lane of every workgroup contributes to eight rows.-        let gemv = u64::from(head.count) * 64 * 8 * (u64::from(head.in_c) / 64);-        assert_eq!(gemv, useful);-        // The tiled path issues 64 invocations x a 2x2 register block per k-step, for a tile that-        // is 16 channels by 16 positions of which 15 are padding.-        let tiles = head.out_c.div_ceil(16) * 1u32.div_ceil(16);-        let issued = u64::from(tiles) * 64 * 4 * u64::from(head.in_c);-        assert_eq!(issued / gemv, 16, "{issued} against {gemv}");-    }--    #[test]-    fn the_encoder_stays_on_the_tiled_path() {-        // The gemv shader is for one position only: over a sequence the tiled kind reuses a staged-        // weight tile across 16 positions, which is the whole reason it exists.-        let (_, plan) = plan(Mode::Encode { len: LEN });-        for op in &plan.ops {-            if let Op::Dispatch { kind, push, .. } = op {-                if super::super::tests::name_of(*kind) == "ConvInt8" {-                    assert_eq!(*kind, Kind::ConvPointInt8, "{push:?}");-                }-            }-        }-    }--    #[test]-    fn the_head_is_two_ops_over_disjoint_class_ranges() {-        let (_, plan) = plan(Mode::Logits);-        let dispatches: Vec<_> = plan-            .ops+    fn the_head_is_four_ops_over_disjoint_class_ranges() {+        // Together the four splits are the whole vocabulary, which is what `post::translate`+        // argmaxes. The last two splits are one class short each.+        let source = Shapes::new(TENSORS);+        let plan = build(&source, Mode::DecodeStep { cache_len: 0, src_len: LEN })+            .expect("the step builds");+        let heads: Vec<_> = plan+            .outputs             .iter()-            .filter_map(|op| match op {-                Op::Dispatch { kind, push, .. } => Some((*kind, *push)),-                _ => None,-            })+            .take(HEAD_SPLITS)+            .map(|b| b.shape.c)             .collect();-        assert_eq!(dispatches.len(), HEAD_SPLITS, "{dispatches:?}");-        for (kind, push) in &dispatches {-            assert_eq!(super::super::tests::name_of(*kind), "ConvInt8");-            assert_eq!(push.out_c, CLASSES_PER_SPLIT, "{push:?}");-            assert_eq!(push.in_c, D_MODEL, "{push:?}");-        }-        // Different kernels, which is what "disjoint ranges" means in the file.-        assert_ne!(dispatches[0].1.weight, dispatches[1].1.weight);-        assert_eq!(plan.outputs.len(), HEAD_SPLITS);-        for binding in &plan.outputs {-            assert_eq!(binding.shape, Shape::new(CLASSES_PER_SPLIT, 1, 1));-        }-        // Together they are the whole vocabulary, which is what `post::translate` argmaxes.-        let classes: u32 = plan.outputs.iter().map(|b| b.shape.c).sum();-        assert_eq!(classes, VOCAB);+        assert_eq!(heads, vec![64_052, 64_052, 64_051, 64_051]);+        assert_eq!(heads.iter().sum::<u32>(), VOCAB);     }      #[test]     fn the_head_binds_under_the_guaranteed_range() {-        // Why the split exists: 128,112 x 1024 int8 is 125.1 MiB against a guaranteed 128 MiB, and-        // fp16 would be 250. A half plus its scale and bias is comfortably inside either.+        // Why the split exists and why it is four: the whole 256,206 x 1024 int8 table is ~250+        // MiB against a guaranteed 128 MiB, and two splits would each sit just under it the way+        // the whole small100-era 128k table did — too tight. A quarter plus its scale and bias is+        // comfortably inside.         let whole = u64::from(VOCAB) * u64::from(D_MODEL);-        assert!(whole > 120 << 20, "the whole table is {whole} bytes");-        let half = u64::from(CLASSES_PER_SPLIT) * u64::from(D_MODEL)+        assert!(whole > 250 << 20, "the whole table is {whole} bytes");+        // Two splits would be 128,103 classes each — just under the 128 MiB floor the way the+        // whole small100-era 128k table was. Too tight for a binding plus its scale and bias.+        let half = 128_103u64 * u64::from(D_MODEL);+        assert!(half > 120 << 20, "a half would be {half} bytes: too tight");+        let quarter = u64::from(CLASSES_PER_SPLIT) * u64::from(D_MODEL)             + u64::from(CLASSES_PER_SPLIT) * 4;-        assert!(half < 96 << 20, "a half is {half} bytes");+        assert!(quarter < 96 << 20, "a quarter is {quarter} bytes");     }      #[test]@@ -948,6 +931,40 @@ mod tests {         assert!((sinusoid(1, half - 1) - smallest).abs() < 1e-6, "{}", sinusoid(1, half - 1));     } +    #[test]+    fn split_of_covers_the_whole_vocabulary_without_gaps() {+        // The uneven split is the one place an id could fall between two ranges or land in both.+        // Every id must map to exactly one (split, row), and the row must be inside that split.+        let mut seen = 0u32;+        for split in 0..HEAD_SPLITS {+            for row in 0..split_classes(split) {+                seen += 1;+                let _ = (split, row);+            }+        }+        assert_eq!(seen, VOCAB);+        // The boundaries: the last id of each split and the first of the next.+        assert_eq!(split_of(0), (0, 0));+        assert_eq!(split_of(64_051), (0, 64_051));+        assert_eq!(split_of(64_052), (1, 0));+        assert_eq!(split_of(128_103), (1, 64_051));+        assert_eq!(split_of(128_104), (2, 0));+        assert_eq!(split_of(192_154), (2, 64_050));+        assert_eq!(split_of(192_155), (3, 0));+        assert_eq!(split_of(256_205), (3, 64_050));+        // And the mapping is the identity in order: walking ids walks (split, row) contiguously.+        let mut next = 0u32;+        for split in 0..HEAD_SPLITS {+            let base = HEAD + split * 3;+            let _ = base;+            for row in 0..split_classes(split) {+                assert_eq!(split_of(next), (split, row), "id {next}");+                next += 1;+            }+        }+        assert_eq!(next, VOCAB);+    }+     #[test]     fn a_pass_over_nothing_or_past_the_table_is_refused() {         let source = Shapes::new(TENSORS);@@ -959,85 +976,17 @@ mod tests {         assert!(error.contains("positions the model has"), "{error}");     } -    /// The host embedding gather against the real 318 MiB file.-    ///-    /// Skipped without `SMALL100_MAML`, like the tokenizer's real-vocabulary test: the file is a-    /// runtime download rather than a checked-in asset. `scripts/ml/fetch_small100.py` builds it.-    ///-    /// The pinned numbers came from reading the same file in Python and applying transformers'-    /// `M2M100SinusoidalPositionalEmbedding.get_embedding` verbatim, so this is a cross-check of-    /// three things at once: the int8 row dequantisation, `sqrt(1024)`, and the sinusoid's-    /// concatenated-halves convention at the `+ 2` position.-    #[test]-    fn the_host_gather_agrees_with_the_reference() {-        let Ok(path) = std::env::var("SMALL100_MAML") else {-            return;-        };-        let file = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));-        let len = file.metadata().expect("metadata").len();-        let streamed = crate::weights::Streamed::open(file, 0, len, crate::weights::graph::SMALL100)-            .expect("the real file opens");-        let table = streamed.offsets();-        let reader = Reader::new(&table, &streamed);--        // `__en__`, then the first piece of "Hello, world!", then `</s>` — at positions 2, 3, 4.-        let ids = [128_022u32, 65_761, 2];-        let out = embed_positions(reader, &ids, 0).expect("the gather succeeds");-        assert_eq!(out.len(), D_MODEL as usize * ids.len());--        // Channel-major: `out[c * len + t]`. A position-major layout would put these six values-        // contiguously at the start instead, so this also pins the transpose.-        let at = |channel: usize, token: usize| out[channel * ids.len() + token];-        let want: [(usize, f32); 9] = [-            (0, 8.618_953),-            (1, 2.024_961),-            (2, 1.425_964),-            (3, 0.703_241),-            (4, 0.835_844),-            (5, 0.722_445),-            (511, 0.856_828),-            (512, -1.884_653),-            (1023, 0.020_996),-        ];-        for (channel, expected) in want {-            let got = at(channel, 0);-            assert!(-                (got - expected).abs() < 2e-3,-                "channel {channel}: {got} against {expected}"-            );-        }--        // The same token at two positions must differ by exactly the two sinusoids' difference —-        // the property that fails if the position offset or the layout is wrong, with no fixture.-        let twice = embed_positions(reader, &[7, 7], 0).expect("the gather succeeds");-        for channel in 0..D_MODEL as usize {-            let first = twice[channel * 2];-            let second = twice[channel * 2 + 1];-            let delta = sinusoid(2, channel) - sinusoid(3, channel);-            assert!(-                ((first - second) - delta).abs() < 1e-3,-                "channel {channel}: {first} - {second} against {delta}"-            );-        }--        // `past` shifts the position, which is how a decode step at step `s` lands on `s + 2`.-        let shifted = embed_positions(reader, &[7], 1).expect("the gather succeeds");-        for channel in 0..D_MODEL as usize {-            let expected = twice[channel * 2] - sinusoid(2, channel) + sinusoid(3, channel);-            assert!((shifted[channel] - expected).abs() < 1e-3, "channel {channel}");-        }-    }-     #[test]     fn every_tensor_shape_is_stated_the_same_way_twice() {-        // `dims_of` restates the table `maml_convert.collect_small100` writes, and `Layers` walks+        // `dims_of` restates the table `maml_convert.collect_nllb` writes, and `Layers` walks         // it. This checks the two agree for every index, which is what makes `host_tensor`'s shape         // check meaningful rather than circular.         let mut expected: Vec<Vec<u32>> = Vec::new();-        for _ in 0..HEAD_SPLITS {-            expected.push(vec![CLASSES_PER_SPLIT, D_MODEL, 1, 1]);-            expected.push(vec![CLASSES_PER_SPLIT]);-            expected.push(vec![CLASSES_PER_SPLIT]);+        for split in 0..HEAD_SPLITS {+            let classes = split_classes(split);+            expected.push(vec![classes, D_MODEL, 1, 1]);+            expected.push(vec![classes]);+            expected.push(vec![classes]);         }         let projection = |out: u32, inputs: u32| {             vec![vec![out, inputs, 1, 1], vec![out], vec![out]]
library/ml/src/main/rust/src/post/sentencepiece.rs
diff --git a/library/ml/src/main/rust/src/post/sentencepiece.rs b/library/ml/src/main/rust/src/post/sentencepiece.rsindex a913f07fc0..fd8828fedc 100644--- a/library/ml/src/main/rust/src/post/sentencepiece.rs+++ b/library/ml/src/main/rust/src/post/sentencepiece.rs@@ -1,4 +1,4 @@-//! SMaLL-100's SentencePiece tokenizer: text to token ids and back.+//! NLLB's SentencePiece tokenizer: text to token ids and back. //! //! # What was inside the ncnn AAR //!@@ -7,9 +7,9 @@ //! //! # It is BPE, and the "scores" are merge ranks //!-//! The model file is named `sentencepiece.bpe.model` and its `trainer_spec.model_type` is 2, BPE.-//! Its pieces carry scores of 0, -1, -2, ... which are **negative merge ranks** rather than log-//! probabilities: `,` scores -119149 because it is a very late merge. So encoding is greedy+//! The model file is named `sentencepiece.bpe.model` and its `trainer_spec.model_type` is 2, BPE+//! (verified by model-eng with the existing `read_spm` parser: 256,000 pieces, scores 0..-255996).+//! Its pieces carry **negative merge ranks** rather than log probabilities, so encoding is greedy //! pairwise merging — repeatedly join the adjacent pair whose concatenation is in the vocabulary //! with the highest score, leftmost on a tie — and not the Viterbi a Unigram model would need. //! Reading the scores as log probabilities and running Viterbi produces plausible pieces and the@@ -25,7 +25,7 @@ //! Latin, Cyrillic, Arabic, Devanagari, Han, Kana, Hangul, fullwidth forms and emoji — NFKC plus //! that whitespace handling agrees with `nmt_nfkc` on all of them. //!-//! The table itself is `scripts/ml/small100_tokenizer.py`'s output; see it for the format.+//! The table itself is `scripts/ml/nllb_tokenizer.py`'s output; see it for the format.  use std::collections::HashMap; @@ -292,34 +292,42 @@ mod tests {         assert_eq!(parsed.decode(&[]), "");     } -    /// The real vocabulary, against ids taken from `sentencepiece` itself.+    /// The real vocabulary, against model-eng's verified inventory.     ///     /// Skipped rather than ignored: the table is a runtime download rather than a checked-in-    /// asset, so `SMALL100_TOKENIZER` is how you point at one. `scripts/ml/fetch_small100.py`+    /// asset, so `NLLB_TOKENIZER` is how you point at one. `scripts/ml/fetch_nllb600.py`     /// builds it, and prints the command.+    ///+    /// These assert the *inventory* rather than golden encode ids: golden ids need the reference+    /// `sentencepiece` run, which is model-eng's parity harness. What this catches is a table+    /// built from the wrong files — wrong length, wrong specials, missing language range.     #[test]     fn the_real_vocabulary_agrees_with_sentencepiece() {-        let Ok(path) = std::env::var("SMALL100_TOKENIZER") else {+        let Ok(path) = std::env::var("NLLB_TOKENIZER") else {             return;         };         let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"));         let parsed = Table::parse(&bytes).expect("the real table parses");-        assert_eq!(parsed.len(), 128_112);-        // Every one of these came out of `sentencepiece.SentencePieceProcessor` on the shipped-        // model, mapped through fairseq's vocabulary order.-        let cases: [(&str, &[u32]); 6] = [-            ("Hello, world!", &[65_761, 4, 55_185, 30]),-            ("café naïve", &[40_244, 18, 6_460, 470]),-            ("  multiple   spaces\tand\nnewlines  ", &[119_683, 654, 44_628, 1_019, 19_420, 116_356]),-            ("한국어", &[13_740, 2_254]),-            ("emoji 🙂 done", &[21_761, 720, 6_459, 111_108]),-            // Fullwidth forms, already folded by the caller's NFKC.-            ("Full A", &[26_033, 58]),-        ];-        for (text, want) in cases {-            assert_eq!(parsed.encode(text), want, "encoding {text:?}");+        // 256,000 BPE pieces, then `<pad>`, the 202 flores codes, `<mask>`, two empty pads.+        assert_eq!(parsed.len(), 256_206);+        // fairseq's specials, in fairseq's order — `parse` already checks these, restated here so+        // the failure names the inventory rather than the parser.+        for (id, name) in [(0, "<s>"), (1, "<pad>"), (2, "</s>"), (3, "<unk>")] {+            assert_eq!(parsed.piece(id), Some(name.as_bytes()), "special {id}");+        }+        // The language range: 202 flores codes at 256001..256202, then `<mask>`. Their exact text+        // is model-eng's mapping JSON; what matters here is that they are present, non-empty and+        // distinct — a missing or duplicated code would mistranslate silently.+        let mut seen = std::collections::BTreeSet::new();+        for id in 256_001..=256_202u32 {+            let piece = parsed.piece(id).unwrap_or_else(|| panic!("language token {id} missing"));+            assert!(!piece.is_empty(), "language token {id} is empty");+            assert!(seen.insert(piece.to_vec()), "language token {id} duplicates another");+        }+        assert_eq!(parsed.piece(256_203), Some(b"<mask>".as_slice()), "<mask>");+        // And encoding is non-degenerate on the real table: every id it emits is in range.+        for id in parsed.encode("Hello, world!") {+            assert!(id < 256_206, "id {id} past the vocabulary");         }-        // And a round trip, which is what the decode loop ends with.-        assert_eq!(parsed.decode(&[1_197, 6_308]), "the cat");     } }
library/ml/src/main/rust/src/post/translate.rs
diff --git a/library/ml/src/main/rust/src/post/translate.rs b/library/ml/src/main/rust/src/post/translate.rsindex ebc0fde014..5627892396 100644--- a/library/ml/src/main/rust/src/post/translate.rs+++ b/library/ml/src/main/rust/src/post/translate.rs@@ -1,4 +1,4 @@-//! SMaLL-100's decode loop: source text to translated text, one token at a time.+//! NLLB's decode loop: source text to translated text, one token at a time. //! //! # What was inside the ncnn AAR //!@@ -7,19 +7,24 @@ //! both use — because the order of the special tokens is where the mistakes are and none of them //! needs a device to catch. //!-//! # The target language token goes on the SOURCE side+//! # The source language token goes on the SOURCE side; the decoder starts from </s> //!-//! This is the one thing about SMaLL-100 that is easy to get backwards, and getting it backwards-//! produces fluent output in the wrong language rather than an error. Its distillation gives the-//! *encoder* the target language:+//! This is the one thing about NLLB that is easy to get backwards, and getting it backwards+//! produces fluent output in the wrong language rather than an error: //! //! ```text-//! source  = [target_language_token] ++ tokenizer(text) ++ [</s>]-//! decoder starts from </s> (id 2), not from the language token+//! source  = [source_language_token] ++ tokenizer(text) ++ [</s>]+//! decoder input starts from </s> (id 2); the first *generated* token is forced to the+//! target language token (forced-BOS), then decoding proceeds autoregressively //! ``` //!-//! M2M-100 proper puts a source-language token on the source and a target-language token on the-//! decoder; SMaLL-100 does neither of those. See [`translate`].+//! That forcing is HuggingFace `generate`'s `forced_bos_token_id`: the step-0 logits are+//! overridden, so the model never gets a vote on the first output. Every reference+//! `greedy_output_ids` in `scripts/ml/nllb_parity_fixture.json` is `[2, tgt, content…, 2]`,+//! which is exactly the framing [`translate`] replays.+//!+//! SMaLL-100, which this replaced, did it the other way round: the *target* token on the source+//! and `</s>`-start. See [`translate`]. //! //! # Greedy, not beam //!@@ -30,16 +35,10 @@  use super::sentencepiece::{Table, EOS}; -/// The first of the 100 language tokens, `af`. They are contiguous from here.+/// Decoder start token: `</s>` (id 2), which is also `decoder_start_token_id`. ///-/// Cross-checked against `Small100Model.LANG_ID`'s `FIRST_LANG_ID` and against the export's own-/// `lang_tokens`, whose minimum is this and whose ids have no gaps.-pub const FIRST_LANG_TOKEN: u32 = 128_004;--/// Language tokens the model holds.-pub const LANGUAGES: u32 = 100;--/// What the decoder is primed with, which is `</s>` and not a language token.+/// The decoder input starts here — not at the language token. The language token is *generated*+/// first, forced: step 0 of [`translate`] overrides the logits with the target token. pub const DECODER_START: u32 = EOS;  /// Tokens the loop will emit before giving up.@@ -64,47 +63,83 @@ pub trait Nets {     fn decode_step(&mut self, token: u32, step: usize, encoded: &[f32]) -> Result<Vec<f32>, String>; } -/// Translate `normalised` into the language `target_token` names.+/// Translate `normalised` from the language `source_token` names into the language `target_token`+/// names.+///+/// The first of NLLB's 202 language tokens, `ace_Arab` through `zul_Latn` in flores order.+///+/// Model-eng's tokenizer inventory: the 202 flores codes sit at ids `256001..256202` (after the+/// 256,000 SentencePiece pieces), with `<mask>` at 256203 and fairseq's specials at 0..3.+pub const FIRST_NLLB_LANG_TOKEN: u32 = 256_001;++/// Language tokens NLLB holds: the 202 flores200 codes.+pub const NLLB_LANGUAGES: u32 = 202;++/// Whether `token` is one of NLLB's language tokens.+pub fn is_nllb_lang_token(token: u32) -> bool {+    (FIRST_NLLB_LANG_TOKEN..FIRST_NLLB_LANG_TOKEN + NLLB_LANGUAGES).contains(&token)+}++/// Translate `normalised` from the language `source_token` names into the language `target_token`+/// names, with NLLB's protocol.+///+/// `normalised` must already be NFKC; see [`Table::encode`]. Both tokens are validated here:+/// swapping them produces fluent output in the wrong language rather than an error. ///-/// `normalised` must already be NFKC; see [`Table::encode`]. `target_token` is one of the 100-/// language tokens, which the caller resolves from a language code — the Kotlin side already has-/// that table, and duplicating 100 entries here to look one up would be two places to get wrong.+/// The decoder starts from `</s>` ([`DECODER_START`]) and step 0 is *forced* to `target_token`+/// — HuggingFace's `forced_bos_token_id` — so the step-0 argmax is discarded, the forced token+/// is fed back as step 1's input but never emitted as text, and decoding proceeds greedily from+/// there, stopping at the first `</s>`. /// /// An empty result means the text had nothing to translate, which is not a failure. pub fn translate(     nets: &mut dyn Nets,     table: &Table,+    source_token: u32,     target_token: u32,     normalised: &str, ) -> Result<String, String> {-    if !(FIRST_LANG_TOKEN..FIRST_LANG_TOKEN + LANGUAGES).contains(&target_token) {-        return Err(format!(-            "{target_token} is not one of the {LANGUAGES} language tokens from {FIRST_LANG_TOKEN}"-        ));+    for (what, token) in [("source", source_token), ("target", target_token)] {+        if !is_nllb_lang_token(token) {+            return Err(format!(+                "{what} token {token} is not one of the {NLLB_LANGUAGES} NLLB language tokens \+                 from {FIRST_NLLB_LANG_TOKEN}"+            ));+        }     }     let body = table.encode(normalised);     if body.is_empty() {         return Ok(String::new());     } -    // The language token leads the SOURCE, and the tokenizer's own `</s>` closes it.+    // The SOURCE language token leads the source, and the tokenizer's own `</s>` closes it.     let mut source = Vec::with_capacity(body.len() + 2);-    source.push(target_token);+    source.push(source_token);     source.extend(body);     source.push(EOS);      let encoded = nets.encode(&source)?;      let mut produced: Vec<u32> = Vec::new();+    // The decoder starts from `</s>`, and step 0 is forced to the target language — the+    // `forced_bos_token_id` override. The forced token is fed back as step 1's input but never+    // emitted: it is framing, not translated text.     let mut token = DECODER_START;     for step in 0..MAX_TOKENS {         let logits = nets.decode_step(token, step, &encoded)?;-        let next = argmax(&logits)-            .ok_or_else(|| format!("the decoder returned {} logits at step {step}", logits.len()))?;+        let next = if step == 0 {+            target_token+        } else {+            argmax(&logits).ok_or_else(|| {+                format!("the decoder returned {} logits at step {step}", logits.len())+            })?+        };         if next == EOS {             break;         }-        produced.push(next);+        if step > 0 {+            produced.push(next);+        }         token = next;     }     Ok(table.decode(&produced))@@ -195,30 +230,32 @@ mod tests {     }      #[test]-    fn the_language_token_leads_the_source_and_eos_closes_it() {-        // The trap this module exists to document: SMaLL-100 puts the *target* language on the-        // *source* side, and the decoder starts from `</s>` rather than from that token. Both-        // halves are asserted, because swapping them produces fluent text in the wrong language.+    fn the_forced_bos_frames_the_output_like_the_reference() {+        // The parity fixture's `greedy_output_ids` are `[2, tgt, content…, 2]`; this replays that+        // framing through the loop: step 0 sees `</s>`, is forced to the target, emits it back at+        // step 1 without emitting it as text, then decodes content until `</s>`.         let bytes = table_bytes();         let table = Table::parse(&bytes).expect("parses");-        let mut nets = scripted(&[EOS]);-        let target = FIRST_LANG_TOKEN + 7;-        translate(&mut nets, &table, target, "a b").expect("translates");-        assert_eq!(nets.source.first(), Some(&target));-        assert_eq!(nets.source.last(), Some(&EOS));-        // And the decoder was primed with `</s>`, not with the language token.-        assert_eq!(nets.steps.first(), Some(&(DECODER_START, 0)));+        let source = FIRST_NLLB_LANG_TOKEN;+        let target = FIRST_NLLB_LANG_TOKEN + 1;+        let mut nets = scripted(&[10, 11, EOS]);+        translate(&mut nets, &table, source, target, "a").expect("translates");+        // Step 0's scripted winner (10) is discarded by the forcing; step 1 sees script[1].+        assert_eq!(nets.steps, vec![(DECODER_START, 0), (target, 1), (11, 2)]);     }      #[test]-    fn each_step_feeds_the_previous_token_back() {-        // Greedy decoding is a chain: step n sees what step n-1 chose. Feeding the original-        // start token every time would still terminate and still produce text.+    fn step_zero_forces_the_target_token_regardless_of_the_logits() {+        // `forced_bos_token_id`: the step-0 argmax is discarded even when it has a clear winner,+        // the forced token is fed back but never emitted, and decoding proceeds from there.         let bytes = table_bytes();         let table = Table::parse(&bytes).expect("parses");-        let mut nets = scripted(&[30, 31, 32, EOS]);-        translate(&mut nets, &table, FIRST_LANG_TOKEN, "a").expect("translates");-        assert_eq!(nets.steps, vec![(DECODER_START, 0), (30, 1), (31, 2), (32, 3)]);+        let source = FIRST_NLLB_LANG_TOKEN;+        let target = FIRST_NLLB_LANG_TOKEN + 1;+        // The script's step-0 winner is 30 — it must lose to the forced target.+        let mut nets = scripted(&[30, 31, EOS]);+        translate(&mut nets, &table, source, target, "a").expect("translates");+        assert_eq!(nets.steps, vec![(DECODER_START, 0), (target, 1), (31, 2)]);     }      #[test]@@ -226,9 +263,11 @@ mod tests {         let bytes = table_bytes();         let table = Table::parse(&bytes).expect("parses");         let mut nets = scripted(&[14, 15, EOS, 16]);-        let got = translate(&mut nets, &table, FIRST_LANG_TOKEN, "a").expect("translates");-        // ids 14 and 15 are 'e' and 'f' in the fixture table; 16 is past the `</s>` and unseen.-        assert_eq!(got, "ef");+        let got = translate(&mut nets, &table, FIRST_NLLB_LANG_TOKEN, FIRST_NLLB_LANG_TOKEN + 1, "a")+            .expect("translates");+        // Step 0's scripted winner (14, 'e') is discarded by the forcing, so only 'f' survives;+        // 16 is past the `</s>` and unseen.+        assert_eq!(got, "f");         assert_eq!(nets.steps.len(), 3);     } @@ -241,9 +280,17 @@ mod tests {         // A script of one repeated non-EOS token, longer than the cap.         let script = vec![20u32; MAX_TOKENS + 10];         let mut nets = scripted(&script);-        let got = translate(&mut nets, &table, FIRST_LANG_TOKEN, "a").expect("translates");+        let got = translate(+            &mut nets,+            &table,+            FIRST_NLLB_LANG_TOKEN,+            FIRST_NLLB_LANG_TOKEN + 1,+            "a",+        )+        .expect("translates");         assert_eq!(nets.steps.len(), MAX_TOKENS);-        assert_eq!(got.chars().count(), MAX_TOKENS);+        // Step 0 is the forced target, never emitted, so the cap yields MAX_TOKENS - 1 chars.+        assert_eq!(got.chars().count(), MAX_TOKENS - 1);     }      #[test]@@ -251,7 +298,14 @@ mod tests {         let bytes = table_bytes();         let table = Table::parse(&bytes).expect("parses");         let mut nets = scripted(&[EOS]);-        let got = translate(&mut nets, &table, FIRST_LANG_TOKEN, "   ").expect("translates");+        let got = translate(+            &mut nets,+            &table,+            FIRST_NLLB_LANG_TOKEN,+            FIRST_NLLB_LANG_TOKEN + 1,+            "   ",+        )+        .expect("translates");         assert_eq!(got, "");         assert!(nets.source.is_empty(), "the encoder ran on nothing");         assert!(nets.steps.is_empty(), "the decoder ran on nothing");@@ -259,14 +313,21 @@ mod tests {      #[test]     fn a_token_outside_the_language_range_is_refused() {-        // 128,004 through 128,103. A plain vocabulary id here would be a silent mistranslation.+        // 256,001 through 256,202. A plain vocabulary id in either slot would be a silent+        // mistranslation.         let bytes = table_bytes();         let table = Table::parse(&bytes).expect("parses");         let mut nets = scripted(&[EOS]);-        for wrong in [0, 2, FIRST_LANG_TOKEN - 1, FIRST_LANG_TOKEN + LANGUAGES] {-            let error =-                translate(&mut nets, &table, wrong, "a").expect_err("a non-language token");-            assert!(error.contains("language tokens"), "{error}");+        let good = FIRST_NLLB_LANG_TOKEN;+        for (source, target) in [+            (0, good),+            (good, 2),+            (FIRST_NLLB_LANG_TOKEN - 1, good),+            (good, FIRST_NLLB_LANG_TOKEN + NLLB_LANGUAGES),+        ] {+            let error = translate(&mut nets, &table, source, target, "a")+                .expect_err("a non-language token");+            assert!(error.contains("NLLB language tokens"), "{error}");         }     } @@ -279,4 +340,58 @@ mod tests {         // Negative logits are normal — a softmax was never taken.         assert_eq!(argmax(&[-5.0, -1.0, -9.0]), Some(1));     }++    #[test]+    fn the_loop_replays_the_parity_fixture_framing() {+        // `scripts/ml/nllb_parity_fixture.json`, pair 1 (eng_Latn -> fra_Latn): the reference+        // `greedy_output_ids` are `[2, 256057, content…, 2]`. The script feeds the content back+        // from step 1 on (step 0 is forced); the loop must walk exactly that chain — forced BOS+        // fed back but never emitted, content in order, stop at the trailing `</s>`.+        let bytes = table_bytes();+        let table = Table::parse(&bytes).expect("parses");+        let target = 256_057u32; // fra_Latn+        let content = [17994u32, 141190, 248079, 25358, 123732, 248105, 30213, 385];+        // script[0] is discarded by the forcing; script[1..] answer steps 1... The fixture ids+        // need a full-size vocabulary, which the 200-entry helper cannot hold.+        let mut script = vec![0u32];+        script.extend(content);+        script.push(EOS);+        let mut nets = Scripted {+            script,+            source: Vec::new(),+            steps: Vec::new(),+            vocabulary: 300_000,+        };+        translate(&mut nets, &table, 256_047, target, "a").expect("translates");+        let mut want = vec![(DECODER_START, 0), (target, 1)];+        want.extend(content.iter().enumerate().map(|(i, &id)| (id, i + 2)));+        assert_eq!(nets.steps, want);+        // And the source framing matches the fixture's `encoder_input_ids` convention:+        // source-lang token leads, `</s>` trails.+        assert_eq!(nets.source.first(), Some(&256_047u32));+        assert_eq!(nets.source.last(), Some(&EOS));+    }++    #[test]+    fn the_source_token_leads_the_source_and_eos_starts_the_decoder() {+        // The trap this module exists to document: the SOURCE language leads the source, and the+        // decoder starts from `</s>` with step 0 forced to the TARGET language token. All three+        // are asserted, because swapping source and target produces fluent text in the wrong+        // language.+        let bytes = table_bytes();+        let table = Table::parse(&bytes).expect("parses");+        let mut nets = scripted(&[EOS]);+        let source = FIRST_NLLB_LANG_TOKEN + 3;+        let target = FIRST_NLLB_LANG_TOKEN + 9;+        translate(&mut nets, &table, source, target, "a b").expect("translates");+        assert_eq!(nets.source.first(), Some(&source));+        assert_eq!(nets.source.last(), Some(&EOS));+        // The decoder was primed with `</s>`, not with the language token.+        assert_eq!(nets.steps.first(), Some(&(DECODER_START, 0)));+        // The forced-BOS token is framing, not output: it is fed back at step 1 but never+        // emitted as translated text. The script answers EOS at step 1, so nothing is produced.+        assert_eq!(nets.steps.get(1), Some(&(target, 1)));+        assert!(nets.source.contains(&source));+        assert!(!nets.source.contains(&target), "the target token is not on the source side");+    } }
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex e8b9097291..7cde872d9d 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -70,12 +70,9 @@ pub mod graph {     pub const SUPERTONIC_TTL: u32 = 13;     /// Supertonic 3's flow-matching sampler. See [`crate::nets::supertonic_sampler`].     pub const SUPERTONIC_VE: u32 = 14;-    /// SMaLL-100 translation, encoder and decoder in one file. See `crate::nets::small100`.-    ///-    /// One graph rather than two because the 128,112-row embedding is **tied**: it is the encoder's-    /// input table, the decoder's input table and the logits kernel, and two files would upload-    /// 125 MiB of it twice.-    pub const SMALL100: u32 = 15;+    // 15 was SMaLL-100's graph, deleted when NLLB replaced it. The number is **not** reused: an+    // id identifies a forward pass, and a `.maml` built for the old net must be rejected rather+    // than loaded as whatever took its slot.     /// TinyCLIP-ViT-8M/16 Text-3M, both towers in one file. See [`crate::nets::tinyclip`].     ///     /// One graph rather than two because the towers share a file and a [`super::Weights`] upload,@@ -87,6 +84,17 @@ pub mod graph {     /// One graph rather than two because the 51,865-row embedding is **tied**: it is the decoder's     /// input table and the logits kernel, so two files would upload 26.6 MB of it twice.     pub const WHISPER: u32 = 17;+    /// NLLB-200-distilled-600M translation, encoder and decoder in one file. See+    /// [`crate::nets::nllb`].+    ///+    /// One graph rather than two because the 256,206-row embedding is **tied**: it is the+    /// encoder's input table, the decoder's input table and the logits kernel, and two files would+    /// upload ~250 MiB of it twice.+    ///+    /// Agreed three-ways with model-eng and app-eng (team `nllb-translate`): the next free id+    /// after whisper's 17, with 7..10 staying retired. `maml_convert.py` has `GRAPHS["nllb600"]`+    /// at the same number.+    pub const NLLB: u32 = 18; }  /// One tensor's entry in the table: where it is and what shape it is.@@ -600,12 +608,12 @@ impl<'a> Reader<'a> {     /// One row of an int8 tensor, dequantised by that row's scale.     ///     /// The counterpart of [`Reader::fp16`] for a quantised table, and it exists for one caller:-    /// [`crate::nets::small100`] gathers rows of the tied embedding on the host rather than in a+    /// [`crate::nets::nllb`] gathers rows of the tied embedding on the host rather than in a     /// shader. Doing so removes the need for an int8 `embed.comp`, lets `sqrt(d_model)` and the     /// sinusoidal position be applied in f32 before anything is rounded, and reads 1 KB per token-    /// instead of uploading a 125 MiB table a second time.+    /// instead of uploading a ~250 MiB table a second time.     ///-    /// A row rather than the whole tensor because the whole tensor is 125 MiB. `dims[0]` is the+    /// A row rather than the whole tensor because the whole tensor is ~250 MiB. `dims[0]` is the     /// row count and a row is contiguous, which is a property of the `[out, in, 1, 1]` layout     /// `scripts/ml/maml_convert.py` writes rather than an assumption — and `shaped` checks it.     pub fn int8_row(
metadata_data/translate.md
diff --git a/metadata_data/translate.md b/metadata_data/translate.mdindex 3eeabd00ed..c130a45c63 100644--- a/metadata_data/translate.md+++ b/metadata_data/translate.md@@ -1,10 +1,10 @@ A fully offline translation app with camera OCR  Features:-- Offline neural translation using SMaLL-100 (ncnn)+- Offline neural translation using NLLB-200 (202 languages) - Camera translation with on-device OCR - Translate text from any app via the selection menu-- Supports dozens of languages entirely offline-- Model files (~1.2 GB) fetched once and SHA-256 verified+- Supports 202 languages entirely offline+- Model files fetched once and SHA-256 verified  Internet required only for initial asset downloads
scripts/ml/fetch_nllb600.py
diff --git a/scripts/ml/fetch_nllb600.py b/scripts/ml/fetch_nllb600.pynew file mode 100644index 0000000000..1adabf36de--- /dev/null+++ b/scripts/ml/fetch_nllb600.py@@ -0,0 +1,254 @@+#!/usr/bin/env python3+"""Fetch NLLB-200-distilled-600M's checkpoint and build the files `:translate` downloads.++Mirrors `fetch_small100.py`: pin the HF revision, download + digest-check every input,+assert `config.json` against transcribed architecture constants, assert the four tied+embedding copies byte-identical, build `tokenizer.bin` + `nllb_langs.json` via+`nllb_tokenizer.py`, convert `pytorch_model.bin` (via a local `.safetensors` repack —+`maml_convert.open_checkpoint` reads safetensors) to `nllb600.maml` via+`maml_convert.py --graph nllb600`.++It is not folded into `fetch_and_convert.sh` because these are **runtime downloads**,+not bundled assets: the output goes to a build directory and then to the mirror.++# The decode protocol (contract with rust-eng's `nets::nllb600`, read from transformers)++* **Source side:** NLLB's `NllbTokenizer.set_src_lang_special_tokens` (non-legacy) uses+  `prefix=[src_lang]` + `suffix=[eos]` — i.e. the **source-language** token LEADS the+  source sequence: `[src_lang, pieces..., eos]`. (SMaLL-100/M2M-100 put the *target*+  token on the source side; NLLB puts the *source* token there. Easy to get backwards.)+* **Target side:** the decoder's first input is the **target-language** token as+  forced BOS (`forced_bos_token_id = tgt_lang_id`, `decoder_start_token_id` unused at+  inference): decode step 0 input is `[tgt_lang]`, then autoregressive.+* **Positions:** fairseq sinusoid, first real token at position 2+  (`cumsum(mask)*mask + padding_idx`, padding_idx 1 — `M2M100SinusoidalPositionalEmbedding`+  with `offset=2`). Same math as small100; the Rust reuses it with NLLB's constants.+* **FFN activation:** ReLU (`activation_function: relu` in config.json).+* **Embeddings:** `scale_embedding: true` — host gather multiplies by `sqrt(1024)`.+* **Specials:** BOS 0 (`<s>`), PAD 1, EOS 2 (`</s>`), UNK 3. Lang tokens 256001..256202,+  `<mask>` 256203 (never emitted), 256204..256205 padding.++# The pins, and what each one catches++* **File SHA-256** below. Catches an upstream re-export at the same revision, or a+  truncated download.+* **The parameter inventory** `maml_convert.check_checkpoint` asserts (509 names:+  `model.shared` + 12 enc + 12 dec layers + 2 final norms). Catches a transposed or+  resized checkpoint; `fc1 [4096,1024]` / `fc2 [1024,4096]` is the asymmetric pair.+* **The layer table digest** `maml_convert.EXPECTED_DIGEST["nllb600"]` pins (722 tensors).+* **`config.json`**, fetched and checked but not converted — the ARCHITECTURE constants+  below are transcribed from it and `nets::nllb600` hardcodes them.++Usage:++    python scripts/ml/fetch_nllb600.py                 # verify digests, build the files+    python scripts/ml/fetch_nllb600.py --work DIR      # keep the checkpoint somewhere specific+    python scripts/ml/fetch_nllb600.py --print-digests # after an intentional upstream bump+"""++import argparse+import hashlib+import json+import os+import subprocess+import sys+import tempfile++REPO = "facebook/nllb-200-distilled-600M"++# Pinned commit. Re-pin with --print-digests after an intentional bump (and only then).+REVISION = "f8d333a098d19b4fd9a8b18f94170487ad3f821d"++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(os.path.dirname(HERE))++# Not an assets directory: these files are fetched at run time from+# `data.vayunmathur.com/models/nllb600/`, so the build only has to produce them for upload.+OUT = os.path.join(ROOT, "build", "nllb600")++CHECKPOINT = "pytorch_model.bin"+SPM = "sentencepiece.bpe.model"+TOKENIZER = "tokenizer.json"+CONFIG = "config.json"+GENERATION_CONFIG = "generation_config.json"+SPECIAL_TOKENS = "special_tokens_map.json"++# SHA-256 of every file this reads, at the pinned revision. Fill in with --print-digests+# on the first run (placeholder zeros fail loudly until then); the checkpoint's are the+# 2.46 GB bin plus the small files.+DIGESTS = {+    CHECKPOINT: "c266c2cfd19758b6d09c1fc31ecdf1e485509035f6b51dfe84f1ada83eefcc42",+    SPM: "14bb8dfb35c0ffdea7bc01e56cea38b9e3d5efcdcb9c251d6b40538e1aab555a",+    TOKENIZER: "e316b82de11d0f951f370943b3c438311629547285129b0b81dadabd01bca665",+    CONFIG: "f9b4081d3d108e9d06532ea8d92b932c04ed3a15ff2f87e6982f8e14db51fbc5",+    GENERATION_CONFIG: "0bb604cdb8392649176935a447ce994128f170a6908c135a17d0e3dfb8113cb2",+    SPECIAL_TOKENS: "992bd4ed610d644d6823081937bcc91bb8878dd556cea4ae5327f2480361330e",+}++# Transcribed from the pinned `config.json`, and asserted against it below rather+# than trusted. `nets::nllb600` is written against these.+ARCHITECTURE = {+    "d_model": 1024,+    "encoder_layers": 12,+    "decoder_layers": 12,+    "encoder_attention_heads": 16,+    "decoder_attention_heads": 16,+    "encoder_ffn_dim": 4096,+    "decoder_ffn_dim": 4096,+    "vocab_size": 256_206,+    "max_position_embeddings": 1024,+    "pad_token_id": 1,+    "bos_token_id": 0,+    "eos_token_id": 2,+    "decoder_start_token_id": 2,+    "scale_embedding": True,+    "activation_function": "relu",+    "model_type": "m2m_100",+}++# The four names the tied embedding appears under. Asserted byte-identical before+# conversion; only model.shared.weight is emitted.+TIED_COPIES = [+    "model.shared.weight",+    "model.encoder.embed_tokens.weight",+    "model.decoder.embed_tokens.weight",+    "lm_head.weight",+]+++def sha256(path):+    digest = hashlib.sha256()+    with open(path, "rb") as handle:+        for block in iter(lambda: handle.read(1 << 20), b""):+            digest.update(block)+    return digest.hexdigest()+++def convert(script, *args):+    """Run one of the sibling converters, letting its own output and exit code through."""+    subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)+++def check_architecture(path):+    """Fail if the checkpoint's shape is not the one `nets::nllb600` is written against."""+    held = json.load(open(path, encoding="utf-8"))+    wrong = {k: (held.get(k), v) for k, v in ARCHITECTURE.items() if held.get(k) != v}+    if wrong:+        lines = "\n".join(f"  {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())+        raise SystemExit(+            f"{path} is not the architecture the runtime hardcodes:\n{lines}\n"+            "nets::nllb600 has these baked in, so re-read it before re-pinning."+        )+    print(f"config.json matches {len(ARCHITECTURE)} hardcoded architecture constants")+++def check_tied(checkpoint_path):+    """Fail unless the four tied copies are byte-identical (so emitting one is exact)."""+    import torch++    sd = torch.load(checkpoint_path, map_location="cpu", weights_only=True)+    first = sd[TIED_COPIES[0]]+    for name in TIED_COPIES[1:]:+        other = sd[name]+        if other.shape != first.shape or not bool(torch.equal(first, other)):+            diff = float((first.float() - other.float()).abs().max())+            raise SystemExit(+                f"{name} differs from {TIED_COPIES[0]} (max abs diff {diff}): "+                "the embedding is untied, so emitting one copy is wrong."+            )+    print(f"tied embedding identical under {len(TIED_COPIES)} names {list(first.shape)}")+++def to_safetensors(checkpoint_path, out_path):+    """Repack the `.bin` as `.safetensors` (same bytes, indexed) for `open_checkpoint`."""+    import torch+    from safetensors.torch import save_file++    sd = torch.load(checkpoint_path, map_location="cpu", weights_only=True)+    # The four tied copies share storage (which is itself the proof they are tied);+    # clone so safetensors does not refuse shared memory, and drop the three extras+    # so the repack holds exactly the 509-tensor architecture `check_checkpoint` wants.+    extras = [n for n in TIED_COPIES[1:] if n in sd]+    for name in extras:+        del sd[name]+    sd = {k: v.clone() for k, v in sd.items()}+    save_file(sd, out_path)+    print(f"  (dropped tied extras: {extras})")+    print(f"repacked {len(sd)} tensors -> {os.path.basename(out_path)}")+++def main():+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+    parser.add_argument("--work", help="where to keep the checkpoint (default: a temp directory)")+    parser.add_argument("-o", "--out", default=OUT, help="where to write the files")+    parser.add_argument(+        "--print-digests",+        action="store_true",+        help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",+    )+    parser.add_argument(+        "--local", help="use an already-downloaded snapshot dir instead of downloading"+    )+    args = parser.parse_args()++    try:+        from huggingface_hub import snapshot_download+    except ImportError:+        raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")++    if args.local:+        local = args.local+    else:+        work = args.work or os.path.join(tempfile.gettempdir(), "nllb600")+        local = snapshot_download(+            repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work+        )+    print(f"{REPO}@{REVISION[:12]} in {local}")++    if args.print_digests:+        for name in DIGESTS:+            print(f'    {name}: "{sha256(os.path.join(local, name))}",')+        return 0++    for name, expected in DIGESTS.items():+        got = sha256(os.path.join(local, name))+        if got != expected:+            raise SystemExit(+                f"{name}\n  sha256 {got}\n  pinned {expected}\n"+                "The upstream export changed. Re-read it, check the Rust forward pass still\n"+                "matches, then re-pin with --print-digests."+            )+    print(f"{len(DIGESTS)} upstream digests match")+    check_architecture(os.path.join(local, CONFIG))+    check_tied(os.path.join(local, CHECKPOINT))++    os.makedirs(args.out, exist_ok=True)+    convert(+        "nllb_tokenizer.py",+        "--spm", os.path.join(local, SPM),+        "--tokenizer", os.path.join(local, TOKENIZER),+        "-o", os.path.join(args.out, "tokenizer.bin"),+        "--langs-out", os.path.join(args.out, "nllb_langs.json"),+    )+    safetensors_path = os.path.join(args.out, "_nllb600.safetensors")+    to_safetensors(os.path.join(local, CHECKPOINT), safetensors_path)+    convert(+        "maml_convert.py",+        safetensors_path,+        "--graph", "nllb600",+        "-o", os.path.join(args.out, "nllb600.maml"),+        "--print-digest",+    )+    os.remove(safetensors_path)++    print(f"\n{args.out}")+    for name in sorted(os.listdir(args.out)):+        path = os.path.join(args.out, name)+        if os.path.isfile(path):+            size = os.path.getsize(path)+            print(f"  {name}: {size} bytes ({size / (1 << 20):.1f} MiB) {sha256(path)}")+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())
scripts/ml/fetch_small100.py
diff --git a/scripts/ml/fetch_small100.py b/scripts/ml/fetch_small100.pydeleted file mode 100644index c9755ad6f3..0000000000--- a/scripts/ml/fetch_small100.py+++ /dev/null@@ -1,233 +0,0 @@-#!/usr/bin/env python3-"""Fetch SMaLL-100's checkpoint and build the two files `:translate` downloads.--# Why this exists--SMaLL-100 shipped with the worst provenance of any model in this tree. The ncnn `.param`/`.bin`-pair on the mirror was produced by a chain of hand-run tools that no longer exists, and-`tokenizer.bin` could not be rebuilt at all: `scripts/ml/small100_tokenizer.py` wanted a-`tokenizer_data.json` that is neither in the repo nor anywhere upstream. So the SHA-256 pins in-`translate/.../Small100Model.kt` asserted that six blobs had not changed, without anyone being-able to say where they came from. This closes that, the same way `fetch_supertonic.py` did.--It is not folded into `fetch_and_convert.sh` because these are **runtime downloads**, not bundled-assets: the output goes to a build directory and then to the mirror, so there is nothing for that-script's in-repo digest table to compare against.--# Two repos, and why the fp32 one--`alirezamsh/small100` is the model, MIT-licensed, and supplies the weights and both tokenizer-inputs. `casawolice/small100-onnx` supplies only `lang_tokens.json`, so the 100 `__xx__` ids are-read rather than transcribed a second time - `Small100Model.LANG_ORDER` already transcribes the-codes. Its `sentencepiece.bpe.model` and `vocab.json` are byte-identical to the fp32 repo's, which-is how the two are known to be the same checkpoint.--That repo also has an int8 ONNX export, and it is **not** used. It quantises per tensor rather-than per output channel, and it carries the tied 131M-parameter embedding three times, which is-why its deployment set is 609 MB against the 318 MiB this produces. See `CHECKPOINTS` in-`scripts/ml/maml_convert.py`.--# The pins, and what each one catches--* **File SHA-256**, below. Catches an upstream re-export at the same revision, or a truncated-  download. `sentencepiece.bpe.model`'s digest is the one already pinned in `Small100Model.kt`,-  which is the only thread connecting the mirror's blobs to a named upstream repo.-* **The parameter inventory** `maml_convert.check_checkpoint` asserts - every name and every-  shape. Catches a checkpoint whose *structure* moved, which is what would make the hardcoded-  Rust forward pass in `nets::small100` read the right shapes holding the wrong numbers. It is-  also what catches a transposed projection.-* **The layer table digest** `maml_convert.EXPECTED_DIGEST` pins, over the emitted order.-* **`config.json`**, which is fetched and checked but not converted, because the architecture-  constants below are transcribed from it and `nets::small100` hardcodes them.--The int8 fidelity gate in `maml_convert.collect_small100` is the only one of these that looks at-the numbers, and it only compares the quantisation against the weight it came from.-`scripts/ml/onnx_parity.py` is what compares the forward pass.--Usage:--    python scripts/ml/fetch_small100.py                 # verify digests, build the two files-    python scripts/ml/fetch_small100.py --work DIR      # keep the checkpoint somewhere specific-    python scripts/ml/fetch_small100.py --print-digests # after an intentional upstream bump-"""--import argparse-import hashlib-import json-import os-import subprocess-import sys-import tempfile--REPO = "alirezamsh/small100"--# Pinned to a commit rather than to `main`, for the reason `fetch_and_convert.sh` gives: the-# digests below would catch a silent upstream change anyway, but a pinned revision tells you the-# upstream *revision* that moved rather than just that some bytes differ.-REVISION = "8ab680e26a596d2e3d2d2d17ae0f68df1037328c"--# Only `lang_tokens.json` comes from here. See the module docstring.-LANG_REPO = "casawolice/small100-onnx"-LANG_REVISION = "5c2c73ac70bee9c58f5a7ac5e84a36bee25db8ee"--HERE = os.path.dirname(os.path.abspath(__file__))-ROOT = os.path.dirname(os.path.dirname(HERE))--# 

Diff truncated.