Modern Apps git

← Modern-Apps.git

translate: pin SMaLL-100 provenance, rebuild tokenizer.bin from upstream

Commit
c78a4f6dbd41d017c2a2375a7804c56a2d0f3142
Author
vayun-mathur <[email protected]>
When
2026-08-29 02:20 UTC (3 months ago)
Parents
d69004d

Diff

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 7f07e5e715..a913f07fc0 100644--- a/library/ml/src/main/rust/src/post/sentencepiece.rs+++ b/library/ml/src/main/rust/src/post/sentencepiece.rs@@ -294,11 +294,10 @@ mod tests {      /// The real vocabulary, against ids taken from `sentencepiece` itself.     ///-    /// Ignored because the table is a runtime download rather than a checked-in asset, like the-    /// parity probes in `nets::reference`. Run it with-    /// `SMALL100_TOKENIZER=<path> cargo test -p modelrunner --lib -- --ignored real_vocabulary`.+    /// 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`+    /// builds it, and prints the command.     #[test]-    #[ignore = "needs SMALL100_TOKENIZER pointing at a converted tokenizer.bin"]     fn the_real_vocabulary_agrees_with_sentencepiece() {         let Ok(path) = std::env::var("SMALL100_TOKENIZER") else {             return;
scripts/ml/fetch_small100.py
diff --git a/scripts/ml/fetch_small100.py b/scripts/ml/fetch_small100.pynew file mode 100644index 0000000000..bfb7676ac7--- /dev/null+++ b/scripts/ml/fetch_small100.py@@ -0,0 +1,205 @@+#!/usr/bin/env python3+"""Fetch SMaLL-100's int8 ONNX export 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.++# 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 layer table digest** `maml_convert.EXPECTED_DIGEST` pins. Catches an export whose+  *structure* moved, which is what would make the hardcoded Rust forward pass in+  `nets::small100` read the right shapes holding the wrong numbers.+* **`config.json`**, which is fetched and checked but not converted, because the architecture+  constants below are transcribed from it and `nets::small100` hardcodes them.++None of the three checks the numbers. `scripts/ml/onnx_parity.py` does.++# The export is already int8++Upstream ran `onnxruntime.quantization.quantize_dynamic(weight_type=QInt8)`, so every `MatMul`+is a `MatMulInteger` and the 131M-parameter embedding `Gather` is int8 too. That is the whole+reason this port is worth doing: ncnn could not quantise the embedding, which is why the model on+the mirror is 1.14 GB. See `scripts/ml/maml_convert.py` for what the converter does with it.++Usage:++    python scripts/ml/fetch_small100.py                 # verify digests, build the two files+    python scripts/ml/fetch_small100.py --work DIR      # keep the ONNX 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 = "casawolice/small100-onnx"++# 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 = "5c2c73ac70bee9c58f5a7ac5e84a36bee25db8ee"++HERE = os.path.dirname(os.path.abspath(__file__))+ROOT = os.path.dirname(os.path.dirname(HERE))++# Not an assets directory: these two files are fetched at run time from+# `data.vayunmathur.com/models/small100/`, so the build only has to produce them for upload.+# `build/` is already gitignored.+OUT = os.path.join(ROOT, "build", "small100")++ENCODER = "onnx/encoder_model.onnx"+DECODER = "onnx/decoder_model_merged.onnx"++# The three files the tokenizer table is built from. `vocab.json` decides ids because it is the+# fairseq order; the `.bpe.model` supplies merge ranks; `lang_tokens.json` supplies the 100+# `__xx__` ids so they are read rather than transcribed.+SPM = "sentencepiece.bpe.model"+VOCAB = "vocab.json"+LANGS = "lang_tokens.json"+CONFIG = "config.json"++# SHA-256 of every file this reads, at REVISION. Not the whole repo: the sample code,+# `tokenizer.json` and the 3.7 MB `added_tokens.json` are not fetched, so pinning them would pin+# something never downloaded.+DIGESTS = {+    ENCODER: "a130f553106646e56c1908094074f354353c45d86b3e8d222b037784035e6dcd",+    DECODER: "f966ce4f1f484c2307dc007ef0beadc3a1651220c1ff9b33ea8dddbce468a4b0",+    SPM: "d8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a",+    VOCAB: "b6e77e474aeea8f441363aca7614317c06381f3eacfe10fb9856d5081d1074cc",+    LANGS: "c638e65941c57577fff6321d5be72b2b25afc39fde7d6a48adecd2e44b504ddf",+    CONFIG: "4ba2f8f7c5ec286bdb2088ac3b8d0ca3b8b19eb4f107c7c3a44205ba15873bb2",+}++WANTED = list(DIGESTS)++# Transcribed from the pinned `config.json`, and asserted against it below rather than trusted.+# `Small100Model.kt` claimed "36 enc + 13 dec" layers, which were ncnn's fused counts and do not+# map onto anything here; `nets::small100` is written against these.+ARCHITECTURE = {+    "d_model": 1024,+    "encoder_layers": 12,+    "decoder_layers": 3,+    "encoder_attention_heads": 16,+    "decoder_attention_heads": 16,+    "encoder_ffn_dim": 4096,+    "decoder_ffn_dim": 4096,+    "vocab_size": 128_112,+    "max_position_embeddings": 1024,+    "pad_token_id": 1,+    "decoder_start_token_id": 2,+    "scale_embedding": True,+    "activation_function": "relu",+}+++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.++    `check=True` matters: `maml_convert.py` exits non-zero when a layer table digest does not+    match, and that is the check that must stop an upload being built from the wrong export.+    """+    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::small100` 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::small100 has these baked in, so re-read it before re-pinning."+        )+    print(f"config.json matches {len(ARCHITECTURE)} hardcoded architecture constants")+++def main():+    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+    parser.add_argument("--work", help="where to keep the ONNX (default: a temp directory)")+    parser.add_argument("-o", "--out", default=OUT, help="where to write the two 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",+    )+    args = parser.parse_args()++    try:+        from huggingface_hub import snapshot_download+    except ImportError:+        raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")++    work = args.work or os.path.join(tempfile.gettempdir(), "small100-onnx")+    local = snapshot_download(+        repo_id=REPO, revision=REVISION, allow_patterns=WANTED, local_dir=work+    )+    print(f"{REPO}@{REVISION[:12]} in {local}")++    if args.print_digests:+        for name in WANTED:+            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))++    os.makedirs(args.out, exist_ok=True)+    tokenizer = os.path.join(args.out, "tokenizer.bin")+    convert(+        "small100_tokenizer.py",+        "--spm", os.path.join(local, SPM),+        "--vocab", os.path.join(local, VOCAB),+        "--langs", os.path.join(local, LANGS),+        "-o", tokenizer,+    )++    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)}")+    print(+        "\nThe digests above are what `Small100Model.FILES` pins. To check the table against"+        "\nthe real `sentencepiece`:\n  SMALL100_TOKENIZER="+        f"{tokenizer} cargo test -p modelrunner --lib -- real_vocabulary"+    )+    return 0+++if __name__ == "__main__":+    raise SystemExit(main())
scripts/ml/small100_tokenizer.py
diff --git a/scripts/ml/small100_tokenizer.py b/scripts/ml/small100_tokenizer.pyindex 2a2befec22..5ffa9f5ccd 100644--- a/scripts/ml/small100_tokenizer.py+++ b/scripts/ml/small100_tokenizer.py@@ -9,10 +9,32 @@ probability - `,` scores -119149 because it is a very late merge, which looks li know the convention. Encoding is therefore greedy pairwise merging by highest score, leftmost on a tie, and not the Viterbi a Unigram model would need. +# Two inputs, because only one of them can be fetched+ `tokenizer_data.json` from the reference export is enough on its own: its `vocab` is 128,112-`[piece, score]` pairs in **fairseq** id order (which differs from the .model's), and its scores-are byte-identical to the .model's for all 127,610 shared pieces. So no protobuf is parsed here or-anywhere else.+`[piece, score]` pairs in **fairseq** id order and its scores are the .model's. But that file is+not in the repo and is not among the pinned upstream downloads, so a fresh checkout cannot+reproduce the table from it. `--spm` rebuilds the same table from the three files that *are*+pinned - `sentencepiece.bpe.model`, `vocab.json` and `lang_tokens.json` - and is the path+`fetch_small100.py` drives.++The two sources are not interchangeable views of one list, because the .model and fairseq+disagree about both order and inventory:++* **Order.** The .model is `<unk> <s> </s>` then merges; fairseq is `<s> <pad> </s> <unk>` then+  merges. `vocab.json` *is* the fairseq order, so it decides ids and the .model only supplies+  scores.+* **Inventory.** 127,610 pieces are shared. 394 are in `vocab.json` only (`<pad>`, runs of NUL,+  a few hundred CJK characters) and 390 are in the .model only. The 390 cannot be represented -+  the table is indexed by id and those have none - and the real tokenizer maps them to `<unk>`+  anyway, since it segments with the .model and then looks the piece up in `vocab.json`.++# Scores the .model does not supply++502 of the 128,112 entries have no .model score: the 394 above, the 100 `__xx__` language tokens+and the 8 `madeupword` slots. They all get one below the lowest real rank, so a merge only ever+reaches them when no genuine merge applies. Giving them 0 instead - the *highest* rank, since+these are negative - would make `__en__` the first merge in any text containing it.  # Normalisation happens in Kotlin @@ -37,6 +59,8 @@ records rather than skipped, so ids stay aligned.  Usage:     ./scripts/ml/small100_tokenizer.py tokenizer_data.json -o out/tokenizer.bin+    ./scripts/ml/small100_tokenizer.py --spm sentencepiece.bpe.model \+        --vocab vocab.json --langs lang_tokens.json -o out/tokenizer.bin """  import argparse@@ -50,8 +74,137 @@ MAGIC = b"SPM1" SPECIALS = {"bos": 0, "pad": 1, "eos": 2, "unk": 3} METASPACE = "\u2581" +# `SMALL100Tokenizer.vocab_size` is `len(vocab.json) + 100 languages + num_madeup_words`, and the+# embedding the converter reads is this wide. A mismatch means the checkpoint moved.+VOCAB_SIZE = 128_112+MADEUP_WORDS = 8++# `trainer_spec.model_type`, from sentencepiece's ModelType enum. Encoding is greedy pairwise+# merging only because this is BPE; a Unigram model would need Viterbi over the same table.+MODEL_TYPE_BPE = 2+++def read_varint(blob, at):+    """One protobuf varint, returning the value and the offset past it."""+    value = 0+    shift = 0+    while True:+        if at >= len(blob):+            raise SystemExit("a varint runs off the end of the model")+        byte = blob[at]+        at += 1+        value |= (byte & 0x7F) << shift+        if not byte & 0x80:+            return value, at+        shift += 7+++def fields(blob):+    """Every top-level protobuf field as `(number, wire_type, payload)`.++    Hand-decoded rather than generated, because the alternative is depending on the+    `sentencepiece` wheel to read three fields out of a file we already have. Only the two wire+    types this model uses are handled; anything else is a format change worth stopping on.+    """+    at = 0+    while at < len(blob):+        tag, at = read_varint(blob, at)+        number, wire = tag >> 3, tag & 7+        if wire == 2:+            length, at = read_varint(blob, at)+            yield number, wire, blob[at : at + length]+            at += length+        elif wire == 5:+            yield number, wire, blob[at : at + 4]+            at += 4+        elif wire == 0:+            value, at = read_varint(blob, at)+            yield number, wire, value+        else:+            raise SystemExit(f"unhandled protobuf wire type {wire} in the model") -def build(path):++def read_spm(path):+    """`piece -> merge rank` from a `sentencepiece.bpe.model`, asserting it is the BPE we expect.++    `ModelProto` numbers `pieces` 1, `trainer_spec` 2 and `normalizer_spec` 3; inside a piece,+    `piece` is 1 and `score` is 2 as a fixed32 float. Scores are whole numbers because they are+    ranks, and that is asserted rather than rounded - a fractional score would mean the file is+    Unigram after all, and the Rust merge loop would be the wrong algorithm.+    """+    blob = open(path, "rb").read()+    scores = {}+    checked_type = False+    for number, _, payload in fields(blob):+        if number == 1:+            piece, score = None, 0.0+            for inner, wire, value in fields(payload):+                if inner == 1:+                    piece = value.decode("utf-8")+                elif inner == 2 and wire == 5:+                    score = struct.unpack("<f", value)[0]+            if piece is None:+                raise SystemExit(f"{path}: a piece with no `piece` field")+            if score != int(score):+                raise SystemExit(f"{path}: {piece!r} scores {score}, which is not a merge rank")+            scores.setdefault(piece, int(score))+        elif number == 2:+            for inner, _, value in fields(payload):+                if inner == 3:+                    checked_type = True+                    if value != MODEL_TYPE_BPE:+                        raise SystemExit(+                            f"{path}: trainer_spec.model_type is {value}, not BPE"+                            f" ({MODEL_TYPE_BPE}); the merge loop in post::sentencepiece only"+                            " applies to BPE"+                        )+        elif number == 3:+            for inner, _, value in fields(payload):+                if inner == 1 and value.decode("utf-8") != "nmt_nfkc":+                    raise SystemExit(+                        f"{path}: normalizer is {value.decode('utf-8')!r}, not nmt_nfkc;"+                        " the Kotlin caller normalises with Form.NFKC"+                    )+    if not checked_type:+        raise SystemExit(f"{path}: no trainer_spec.model_type, so this may not be BPE")+    return scores+++def build_from_spm(spm_path, vocab_path, langs_path):+    """The table from the three pinned upstream files. See the module docstring."""+    scores = read_spm(spm_path)+    encoder = json.load(open(vocab_path, encoding="utf-8"))+    langs = json.load(open(langs_path, encoding="utf-8"))["lang_to_id"]++    by_id = {}+    for piece, id_ in encoder.items():+        if id_ in by_id:+            raise SystemExit(f"{vocab_path}: id {id_} is both {by_id[id_]!r} and {piece!r}")+        by_id[id_] = piece+    if sorted(by_id) != list(range(len(by_id))):+        raise SystemExit(f"{vocab_path}: ids are not 0..{len(by_id) - 1}")+    base = len(by_id)+    for code, id_ in sorted(langs.items(), key=lambda pair: pair[1]):+        if id_ != len(by_id):+            raise SystemExit(f"{langs_path}: {code} is {id_}, not {len(by_id)}")+        by_id[id_] = f"__{code}__"+    for id_ in range(len(by_id), len(by_id) + MADEUP_WORDS):+        by_id[id_] = ""+    if len(by_id) != VOCAB_SIZE:+        raise SystemExit(+            f"{len(by_id)} ids from {base} vocab + {len(langs)} languages + {MADEUP_WORDS}"+            f" madeupwords, against config.json's vocab_size {VOCAB_SIZE}"+        )++    # One below the lowest real rank, so these lose every merge they are in.+    floor = min(scores.values()) - 1+    shared = sum(1 for piece in by_id.values() if piece in scores)+    vocab = [(by_id[id_], scores.get(by_id[id_], floor)) for id_ in range(len(by_id))]+    return vocab, shared+++def build_from_json(path):+    """The table from `tokenizer_data.json`, which a fresh checkout cannot fetch."""     held = json.load(open(path, encoding="utf-8"))     if held.get("metaspace") != METASPACE:         raise SystemExit(f"{path}: metaspace is {held.get('metaspace')!r}, not U+2581")@@ -60,7 +213,14 @@ def build(path):     vocab = held["vocab"]     if len(vocab) != held["vocab_size"]:         raise SystemExit(f"{path}: {len(vocab)} entries against vocab_size {held['vocab_size']}")+    return [(piece, score) for piece, score in vocab] ++def pack(vocab):+    """The `SPM1` blob for `[(piece, score)]` in id order."""+    names = [piece for piece, _ in vocab[:4]]+    if names != ["<s>", "<pad>", "</s>", "<unk>"]:+        raise SystemExit(f"ids 0..3 are {names}, not fairseq's specials in fairseq's order")     out = bytearray(MAGIC)     out += struct.pack("<I", len(vocab))     empty = 0@@ -78,16 +238,30 @@ def build(path):  def main():     parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])-    parser.add_argument("tokenizer_data")+    parser.add_argument("tokenizer_data", nargs="?")+    parser.add_argument("--spm", help="sentencepiece.bpe.model, in place of tokenizer_data")+    parser.add_argument("--vocab", help="vocab.json, the fairseq id order; required with --spm")+    parser.add_argument("--langs", help="lang_tokens.json; required with --spm")     parser.add_argument("-o", "--out", required=True)     args = parser.parse_args() -    blob, count, empty = build(args.tokenizer_data)+    if args.spm:+        if not (args.vocab and args.langs):+            parser.error("--spm needs --vocab and --langs")+        vocab, shared = build_from_spm(args.spm, args.vocab, args.langs)+        note = f", {shared} scores from the .model"+    elif args.tokenizer_data:+        vocab = build_from_json(args.tokenizer_data)+        note = ""+    else:+        parser.error("pass either tokenizer_data or --spm")++    blob, count, empty = pack(vocab)     directory = os.path.dirname(os.path.abspath(args.out))     os.makedirs(directory, exist_ok=True)     with open(args.out, "wb") as f:         f.write(blob)-    print(f"{os.path.basename(args.out)}: {count} pieces ({empty} empty), {len(blob)} bytes")+    print(f"{os.path.basename(args.out)}: {count} pieces ({empty} empty), {len(blob)} bytes{note}")   if __name__ == "__main__":