translate: convert SMaLL-100's fp32 checkpoint to one int8 small100.maml
- Commit
2ae5869fd780c0221e7933823fa8fae76afa48fd- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 02:44 UTC (3 months ago)
- Parents
c78a4f6
Diff
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 a15d8df60f..11b79f8099 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -70,6 +70,12 @@ 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; } /// One tensor's entry in the table: where it is and what shape it is.
scripts/ml/fetch_small100.py
diff --git a/scripts/ml/fetch_small100.py b/scripts/ml/fetch_small100.pyindex bfb7676ac7..c9755ad6f3 100644--- a/scripts/ml/fetch_small100.py+++ b/scripts/ml/fetch_small100.py@@ -1,5 +1,5 @@ #!/usr/bin/env python3-"""Fetch SMaLL-100's int8 ONNX export and build the two files `:translate` downloads.+"""Fetch SMaLL-100's checkpoint and build the two files `:translate` downloads. # Why this exists @@ -14,30 +14,40 @@ It is not folded into `fetch_and_convert.sh` because these are **runtime downloa 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 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.+* **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. -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.+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 ONNX somewhere specific+ 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 """ @@ -49,12 +59,16 @@ import subprocess import sys import tempfile -REPO = "casawolice/small100-onnx"+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 = "5c2c73ac70bee9c58f5a7ac5e84a36bee25db8ee"+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))@@ -64,8 +78,7 @@ ROOT = os.path.dirname(os.path.dirname(HERE)) # `build/` is already gitignored. OUT = os.path.join(ROOT, "build", "small100") -ENCODER = "onnx/encoder_model.onnx"-DECODER = "onnx/decoder_model_merged.onnx"+CHECKPOINT = "model.safetensors" # 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@@ -75,20 +88,19 @@ 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.+# SHA-256 of every file this reads, at the pinned revisions. Not the whole repo: the 1.86 GB+# `model.onnx` and the 1.33 GB `pytorch_model.bin` say the same thing as the checkpoint below, so+# pinning them would pin something never downloaded. DIGESTS = {- ENCODER: "a130f553106646e56c1908094074f354353c45d86b3e8d222b037784035e6dcd",- DECODER: "f966ce4f1f484c2307dc007ef0beadc3a1651220c1ff9b33ea8dddbce468a4b0",+ CHECKPOINT: "dd3b845a36ea4ed90437fd0b9b477e30c21f144d3658679fd5c945e3c96b0fbc", SPM: "d8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a", VOCAB: "b6e77e474aeea8f441363aca7614317c06381f3eacfe10fb9856d5081d1074cc",+ CONFIG: "26fd3989cea6037d432c480f5181d05c088a613394d0361edc6605a6a1058715",+}+LANG_DIGESTS = { 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.@@ -141,7 +153,7 @@ def check_architecture(path): 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("--work", help="where to keep the checkpoint (default: a temp directory)") parser.add_argument("-o", "--out", default=OUT, help="where to write the two files") parser.add_argument( "--print-digests",@@ -155,26 +167,36 @@ def main(): except ImportError: raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub") - work = args.work or os.path.join(tempfile.gettempdir(), "small100-onnx")+ work = args.work or os.path.join(tempfile.gettempdir(), "small100") local = snapshot_download(- repo_id=REPO, revision=REVISION, allow_patterns=WANTED, local_dir=work+ repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work+ )+ langs = snapshot_download(+ repo_id=LANG_REPO,+ revision=LANG_REVISION,+ allow_patterns=list(LANG_DIGESTS),+ local_dir=work + "-langs", ) print(f"{REPO}@{REVISION[:12]} in {local}")+ print(f"{LANG_REPO}@{LANG_REVISION[:12]} in {langs}") + found = [(local, DIGESTS), (langs, LANG_DIGESTS)] if args.print_digests:- for name in WANTED:- print(f' {name}: "{sha256(os.path.join(local, name))}",')+ for root, pins in found:+ for name in pins:+ print(f' {name}: "{sha256(os.path.join(root, 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")+ for root, pins in found:+ for name, expected in pins.items():+ got = sha256(os.path.join(root, 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) + len(LANG_DIGESTS)} upstream digests match") check_architecture(os.path.join(local, CONFIG)) os.makedirs(args.out, exist_ok=True)@@ -183,9 +205,15 @@ def main(): "small100_tokenizer.py", "--spm", os.path.join(local, SPM), "--vocab", os.path.join(local, VOCAB),- "--langs", os.path.join(local, LANGS),+ "--langs", os.path.join(langs, LANGS), "-o", tokenizer, )+ convert(+ "maml_convert.py",+ os.path.join(local, CHECKPOINT),+ "--graph", "small100",+ "-o", os.path.join(args.out, "small100.maml"),+ ) print(f"\n{args.out}") for name in sorted(os.listdir(args.out)):
scripts/ml/maml_convert.py
diff --git a/scripts/ml/maml_convert.py b/scripts/ml/maml_convert.pyindex eb79854bc2..3be8f653da 100644--- a/scripts/ml/maml_convert.py+++ b/scripts/ml/maml_convert.py@@ -39,14 +39,20 @@ byte layout). ONNX tensor layout is preserved verbatim โ `[M, C/group, kH, kW] `Conv`, `[C, M/group, kH, kW]` for `ConvTranspose` โ so nothing here has to agree with the shaders about a transpose. +One graph does not come from an ONNX export at all. SMaLL-100 is read from its PyTorch+`.safetensors` and quantised to int8 here, because the only ONNX exports that exist for it are+already int8 and quantised per *tensor*; see [`CHECKPOINTS`] for why that is not usable.+ ./scripts/ml/maml_convert.py --check model.onnx --graph u2netp ./scripts/ml/maml_convert.py model.onnx --graph u2netp -o out.maml ./scripts/ml/maml_convert.py model.onnx --graph u2netp --print-layers+ ./scripts/ml/maml_convert.py model.safetensors --graph small100 -o out.maml """ import argparse import hashlib import math+import os import struct import sys @@ -64,7 +70,7 @@ from onnx import numpy_helper, shape_inference # 4 4 u32 format version # 8 4 u32 graph id โ the runtime rejects a file built for another net # 12 4 u32 tensor count-# 16 32 source ONNX SHA-256, so a shipped asset traces to its upstream+# 16 32 source SHA-256 of the ONNX or checkpoint, so a shipped asset traces upstream # 48 4 u32 offset of the data section # 52 4 u32 length of the data section # 56 8 reserved, zero@@ -97,6 +103,11 @@ ALIGNMENT = 16 SPEC = __doc__ +# The floor for `cosine(fp32 weight, int8 * scale)` per tensor. Supertonic's text encoder was+# reverted to fp16 at 0.99212 while its sampler shipped at 0.99997, so this is set where a layer+# that quantises this badly is worth looking at rather than shipping.+MIN_INT8_COSINE = 0.999+ # Graph ids. Shared with `library/ml/src/main/rust/src/weights.rs`; changing one # without the other is what the id exists to catch. GRAPHS = {@@ -115,6 +126,8 @@ GRAPHS = { "supertonic_dp": 12, "supertonic_ttl": 13, "supertonic_ve": 14,+ # Read from a PyTorch checkpoint rather than an ONNX graph; see [`CHECKPOINTS`].+ "small100": 15, } # SHA-256 over the ordered layer table (see `layer_table_digest`). Regenerate with@@ -130,6 +143,7 @@ EXPECTED_DIGEST = { "supertonic_dp": "d9a548e1f1ed908a3b0ad27ab543dd7521858f9110b426edb1ed64ba1f1a13e4", "supertonic_ttl": "92d0fa8ae73d4a8a223c77fb4230e390df580744014a3fcf3211ab72a988c020", "supertonic_ve": "48ab5789e8839507ff93e099dc0f61940f25da9ba6201651784f6e68598199e2",+ "small100": "c9f05f2fb686aa53137ca06b521baf6d7a00f32cfb4ea42bd14a5c3e7cf6c086", } # Graphs that are one **module** of a larger export, keyed by the node-name prefix that@@ -202,6 +216,43 @@ EXPECTED_OPS = { }, } +# Graphs read from a **PyTorch checkpoint** rather than an ONNX graph, keyed by graph id name.+#+# Every other net here converts from a frozen ONNX export, and for good reason: the graph records+# the shapes and the op inventory, so `check_graph` can refuse an export whose structure moved+# without anyone transcribing anything. A checkpoint has neither. It is used anyway for SMaLL-100,+# because the only ONNX exports that exist for it are already int8:+#+# * `casawolice/small100-onnx` quantises **per tensor**, not per output channel. Its embedding's+# row absmax spans 0.258 to 1.740, so one scale for the whole table costs a factor of four in+# resolution against the per-row scale `quantise_per_channel` produces, and up to 6.7x on the+# quietest rows. That resolution cannot be recovered by requantising: it is already gone.+# * It carries the 131M-parameter embedding **three times** - `embed_tokens.weight` in the+# encoder, `model.shared.weight` in the decoder and a separately quantised `[1024, 128112]`+# `lm_head` - which is why that deployment set is 609 MB rather than 333 MB. In the checkpoint+# the weight is tied and appears exactly once, so the tied head costs nothing.+# * Its two embedding copies are **uint8 with a zero point of 159**. `conv_point_int8.comp`+# computes `scale[o] * sum(int8_w * in)` and has nowhere to put a zero point.+#+# What is checked instead is the **exact parameter inventory** - every name and every shape,+# derived from the constants below rather than listed - which is a stricter guard than the op+# counts an ONNX graph gets, because it fails on a renamed or resized parameter as well as on a+# missing one. The layer table digest still covers the order.+CHECKPOINTS = {+ "small100": {+ "d_model": 1024,+ "encoder_layers": 12,+ "decoder_layers": 3,+ "ffn": 4096,+ "vocab": 128_112,+ # The tied embedding is 125.1 MiB of int8, and `maxStorageBufferRange`'s guaranteed+ # minimum is 128 MiB. Emitting it as two tensors over disjoint class ranges keeps every+ # binding comfortably under that floor and gives `nets::small100` its two logits ops for+ # free; 128,112 is 2 x 64,056, so the halves are equal and no range is padded.+ "head_splits": 2,+ },+}+ class Layer: """One weighted node, as the Rust forward pass needs to see it."""@@ -570,80 +621,218 @@ def check_graph(model, graph_id_name): raise SystemExit(f"op counts differ: got {only_got}, expected {only_want}") -def quantised_linear(node, held, array, following_bias):- """An int8 `MatMulInteger` as a `1 x 1` convolution, plus its scale and bias.+def open_checkpoint(path):+ """`(name -> ndarray, {name: shape})` for a `.safetensors` file, read one tensor at a time. - Returns `(tensors, key)` or `None` if this is not one of the shapes we lower.+ Lazily, because the checkpoint is 1.33 GB of fp32 and every tensor is quantised to int8 or+ rounded to fp16 the moment it is read - so holding the whole thing costs 1.3 GB of resident+ host memory for nothing.+ """+ try:+ from safetensors import safe_open+ except ImportError:+ raise SystemExit("needs safetensors: python -m pip install safetensors")+ handle = safe_open(path, framework="np")+ shapes = {name: list(handle.get_slice(name).get_shape()) for name in handle.keys()}+ return handle.get_tensor, shapes+++def small100_inventory(spec):+ """`{name: shape}` the checkpoint must hold exactly, derived from [`CHECKPOINTS`].++ Derived rather than transcribed: a list of 275 names would be checked against itself.+ """+ d, ffn = spec["d_model"], spec["ffn"]+ want = {"model.shared.weight": [spec["vocab"], d]}+ for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):+ want[f"model.{side}.layer_norm.weight"] = [d]+ want[f"model.{side}.layer_norm.bias"] = [d]+ for index in range(count):+ at = f"model.{side}.layers.{index}"+ attentions = ["self_attn"] + (["encoder_attn"] if side == "decoder" else [])+ for attention in attentions:+ want[f"{at}.{attention}_layer_norm.weight"] = [d]+ want[f"{at}.{attention}_layer_norm.bias"] = [d]+ for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):+ want[f"{at}.{attention}.{projection}.weight"] = [d, d]+ want[f"{at}.{attention}.{projection}.bias"] = [d]+ want[f"{at}.final_layer_norm.weight"] = [d]+ want[f"{at}.final_layer_norm.bias"] = [d]+ want[f"{at}.fc1.weight"] = [ffn, d]+ want[f"{at}.fc1.bias"] = [ffn]+ want[f"{at}.fc2.weight"] = [d, ffn]+ want[f"{at}.fc2.bias"] = [d]+ return want+++def check_checkpoint(shapes, graph_id_name):+ """Refuse a checkpoint that is not the architecture the Rust forward pass hardcodes. # The transpose that would otherwise be silent - ONNX `MatMul` computes `x @ W`, so its weight is **`[in, out]`**. This runtime indexes a- kernel as `[out, in, kh, kw]`. SMaLL-100's attention projections are all 1024 x 1024, so a- missed transpose would produce a tensor of exactly the right shape holding exactly the- wrong numbers, and the parameter-count check every other net leans on would pass. `fc1` is- `[1024, 4096]`, which is the one that would fail loudly - so the transpose is asserted- against a non-square layer in the tests rather than trusted here.-- # What the export carries, and what is dropped-- Read from `casawolice/small100-onnx` rather than assumed:-- * The weight zero point is a **per-column vector and every entry is 0**, so the quantisation- is symmetric and a value is `int8 * scale`. A non-zero one is refused rather than ignored.- * The weight scale is **per output column** - a `[1024, 4096]` weight carries a `[4096]`- scale. It still multiplies the finished accumulator rather than every tap, so- `conv_int8.comp` costs the same as the fp16 path; it just indexes the scale by output- channel. A scalar is accepted too, broadcast to one per column, so a per-tensor quantiser- also converts.- * The *activation* scale and zero point come from a `DynamicQuantizeLinear` at runtime.- Both are dropped: activations stay fp16 here, which is simpler than reproducing dynamic- quantisation and strictly more accurate, and costs nothing because the weights are what- take the space.+ A `torch.nn.Linear`'s weight is **`[out, in]`**, and this runtime indexes a kernel as+ `[out, in, kh, kw]`, so a projection needs a reshape and no transpose. ONNX `MatMul` is the+ other way round - `x @ W` with a `[in, out]` weight - and every attention projection here is+ square 1024 x 1024, so reading one convention as the other yields a tensor of exactly the+ right shape holding exactly the wrong numbers, and a parameter count that still adds up.++ `fc1` is `[4096, 1024]` and `fc2` is `[1024, 4096]`, so the shape check below is what makes+ that mistake loud: a transposed checkpoint fails on those four numbers before anything is+ written. That is the whole reason this asserts shapes rather than just names. """- if node.op_type != "MatMulInteger" or len(node.input) < 4:- return None- weight_name, zero_name = node.input[1], node.input[3]- if not held(weight_name) or not held(zero_name):- return None- weight = array(weight_name)- if weight.dtype != np.int8 or weight.ndim != 2:- return None- zero = np.array(array(zero_name)).flatten()- if np.any(zero != 0):+ want = small100_inventory(CHECKPOINTS[graph_id_name])+ missing = sorted(set(want) - set(shapes))+ extra = sorted(set(shapes) - set(want))+ shared = sorted(set(want) & set(shapes))+ wrong = {n: (shapes[n], want[n]) for n in shared if shapes[n] != want[n]}+ if missing or extra or wrong:+ lines = []+ if missing:+ lines.append(f" absent: {missing[:6]}{' ...' if len(missing) > 6 else ''}")+ if extra:+ lines.append(f" unexpected: {extra[:6]}{' ...' if len(extra) > 6 else ''}")+ for name, (got, expect) in list(wrong.items())[:6]:+ lines.append(f" {name}: {got} against {expect}") raise SystemExit(- f"{node.output[0]}: weight zero point {zero[zero != 0][:4].tolist()} is not 0, so "- "the quantisation is not symmetric and `conv_int8.comp` would be wrong"+ f"{graph_id_name}: the checkpoint is not the architecture nets/{graph_id_name}.rs\n"+ "hardcodes. A wrong shape here is a wrong forward pass, not a load failure:\n"+ + "\n".join(lines) )- scale_name = weight_name.removesuffix("_quantized") + "_scale"- if not held(scale_name):- raise SystemExit(f"{node.output[0]}: no {scale_name} beside its weight")- scale = np.array(array(scale_name)).flatten()- inputs, outputs = weight.shape- if scale.size == 1:- # A per-tensor quantiser. Broadcast rather than special-case it, so the `.maml` layout is- # the same either way and the shader has one path.- scale = np.repeat(scale, outputs)- if scale.size != outputs:- raise SystemExit(- f"{node.output[0]}: a {scale.size}-element scale for {outputs} output columns; "- "`conv_int8.comp` reads one per output channel"+++def collect_small100(get, spec):+ """SMaLL-100's checkpoint as the ordered tensor table `nets::small100` indexes.++ Order is the contract, and it is:++ the tied embedding, as `head_splits` disjoint class ranges+ each encoder layer, in forward order+ the encoder's final layer norm+ each decoder layer, in forward order+ the decoder's final layer norm++ The **tied embedding comes first and appears once**, because it has two roles and neither+ wants a second copy. `nets::small100` gathers row `t` of it on the host to build the encoder+ and decoder inputs - the rows are contiguous, and each carries its own scale, which is exactly+ what a per-output-channel quantiser produces - and binds the same tensors as the kernel of the+ logits projection. Splitting it by class range is what keeps that binding under+ `maxStorageBufferRange`; see [`CHECKPOINTS`].++ # What is folded, and what is not++ * `sqrt(d_model)` is **not** folded into the embedding here, unlike the fp16 `Gather` arm in+ [`collect_layers`]. The host gather applies it while it is still fp32, which is one rounding+ fewer than scaling an int8 code by its scale and then by `sqrt(1024)`.+ * The attention query scale is **not** folded into `q_proj`. M2M-100 scales the query by+ `head_dim ** -0.5` and `head_dim` is 64, which is the `1 / sqrt(head_dim)` `attn_scores`+ already applies. Folding it would apply it twice.+ * Sinusoidal positions are not in the checkpoint and are not emitted. They are static, so+ `nets::small100` computes them and adds them to the gathered rows in fp32, which also+ removes the `pos_weights.f32.bin` the ncnn build had to download.+ """+ layers = []+ tensors = []+ # Worst per-tensor cosine between the fp32 weight and `int8 * scale`, which is the numbers+ # the device will read. This is the only check that the quantisation itself is usable; the+ # shape assertions in [`check_checkpoint`] are what catch a transpose, since a cosine is+ # computed against whatever was read and a transposed read agrees with itself perfectly.+ fidelity = []++ def quantise(name, weight):+ kernel, scale = quantise_per_channel(weight)+ back = kernel.astype(np.float32).reshape(weight.shape[0], -1) * scale[:, None]+ flat = weight.reshape(weight.shape[0], -1)+ cosine = float(+ np.dot(flat.ravel(), back.ravel())+ / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)+ )+ fidelity.append((cosine, name))+ return kernel, scale++ def emit(op, name, key, added):+ layers.append(Layer(len(layers), op, name, key, len(tensors) - added, added))++ def linear(name):+ """An int8 kernel as `[out, in, 1, 1]`, its per-output-channel scale, and its bias."""+ weight = get(f"{name}.weight")+ bias = get(f"{name}.bias")+ outputs, inputs = weight.shape+ kernel, scale = quantise(name, weight.reshape(outputs, inputs, 1, 1))+ tensors.extend([kernel, scale, bias])+ emit(+ "Linear8",+ name,+ f"Linear8 w={list(kernel.shape)} scale={[outputs]} b={list(bias.shape)} "+ "zp=0 dtype=int8",+ 3,+ )++ def layer_norm(name):+ gamma = get(f"{name}.weight")+ beta = get(f"{name}.bias")+ tensors.extend([gamma, beta])+ emit("LayerNorm", name, f"LayerNorm g={list(gamma.shape)} b={list(beta.shape)}", 2)++ embedding = get("model.shared.weight")+ splits = spec["head_splits"]+ classes, width = embedding.shape+ if classes % splits:+ raise SystemExit(f"{classes} classes do not divide into {splits} equal ranges")+ step = classes // splits+ for part in range(splits):+ lo = part * step+ rows = embedding[lo : lo + step]+ name = f"model.shared.weight[{lo}:{lo + step}]"+ kernel, scale = quantise(name, rows.reshape(step, width, 1, 1))+ # `Builder::conv_int8` reads a bias after the scale, and a tied head has none. Zeros are+ # exact, and recording it in the key means a checkpoint that grows one is not mistaken for+ # this table.+ tensors.extend([kernel, scale, np.zeros(step, dtype=np.float32)])+ emit(+ "Head",+ name,+ f"Head w={list(kernel.shape)} scale={[step]} b={[step]} "+ f"classes={lo}..{lo + step} zp=0 dtype=int8 b0=synthesised",+ 3, )- # `[in, out]` to `[out, in, 1, 1]`.- kernel = np.ascontiguousarray(weight.T).reshape(outputs, inputs, 1, 1)- bias = following_bias(node, outputs)- key = (- f"MatMulInteger w={list(kernel.shape)} scale={[outputs]} b={[outputs]} "- f"zp=0 dtype=int8"- )- return [kernel, scale.astype(np.float32), bias], key++ for side, count in (("encoder", spec["encoder_layers"]), ("decoder", spec["decoder_layers"])):+ for index in range(count):+ at = f"model.{side}.layers.{index}"+ # Pre-norm, as `M2M100EncoderLayer` and `M2M100DecoderLayer` are: the norm comes+ # before the sublayer it feeds and the residual skips both. Emitting in forward order+ # is what lets the Rust walk the table without an index table.+ layer_norm(f"{at}.self_attn_layer_norm")+ for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):+ linear(f"{at}.self_attn.{projection}")+ if side == "decoder":+ layer_norm(f"{at}.encoder_attn_layer_norm")+ for projection in ("q_proj", "k_proj", "v_proj", "out_proj"):+ linear(f"{at}.encoder_attn.{projection}")+ layer_norm(f"{at}.final_layer_norm")+ linear(f"{at}.fc1")+ linear(f"{at}.fc2")+ layer_norm(f"model.{side}.layer_norm")++ fidelity.sort()+ for cosine, name in fidelity[:3]:+ if cosine < MIN_INT8_COSINE:+ raise SystemExit(+ f"{name}: int8 * scale correlates {cosine:.6f} with the fp32 weight, under"+ f" {MIN_INT8_COSINE}.\nQuantising this layer costs too much; exclude it and store"+ " it fp16 instead."+ )+ worst = ", ".join(f"{name} {cosine:.6f}" for cosine, name in fidelity[:3])+ print(f"int8 fidelity over {len(fidelity)} tensors, worst three: {worst}")+ return layers, tensors def quantise_per_channel(kernel): """An fp32 kernel as `(int8, scale)`, symmetric and absmax, one scale per output channel. - The counterpart of [`quantised_linear`], which only ever *validated* an export that had- already been quantised by onnxruntime. Supertonic's exports are fp32, so quantising them is- something this script has to do rather than read off.+ Every int8 tensor in this tree goes through here. Nothing reads a pre-quantised export:+ Supertonic's are fp32, and SMaLL-100's only int8 export quantises per tensor, which throws+ away the resolution this recovers - see [`CHECKPOINTS`]. # Symmetric, with no zero point @@ -738,7 +927,7 @@ def build(layers, tensors, graph_id, onnx_sha256): def main(): parser = argparse.ArgumentParser(description=SPEC.splitlines()[0])- parser.add_argument("onnx")+ parser.add_argument("model", help="an ONNX export, or a .safetensors for a CHECKPOINTS graph") parser.add_argument("--graph", required=True, choices=sorted(GRAPHS)) parser.add_argument("-o", "--out", help="where to write the .maml") parser.add_argument("--check", action="store_true", help="validate only")@@ -746,13 +935,20 @@ def main(): parser.add_argument("--print-digest", action="store_true") args = parser.parse_args() - with open(args.onnx, "rb") as f:- raw = f.read()- onnx_sha256 = hashlib.sha256(raw).digest()-- model = onnx.load(args.onnx)- check_graph(model, args.graph)- layers, tensors = collect_layers(model, MODULES.get(args.graph))+ source_sha256 = hashlib.sha256()+ with open(args.model, "rb") as f:+ for block in iter(lambda: f.read(1 << 20), b""):+ source_sha256.update(block)+ source_size = os.path.getsize(args.model)++ if args.graph in CHECKPOINTS:+ get, shapes = open_checkpoint(args.model)+ check_checkpoint(shapes, args.graph)+ layers, tensors = collect_small100(get, CHECKPOINTS[args.graph])+ else:+ model = onnx.load(args.model)+ check_graph(model, args.graph)+ layers, tensors = collect_layers(model, MODULES.get(args.graph)) digest = layer_table_digest(layers) if args.print_digest:@@ -775,13 +971,13 @@ def main(): for layer in layers: print(f"{layer.index:4d} t{layer.first_tensor:<4d} {layer.key()} # {layer.name}") - blob, count = build(layers, tensors, GRAPHS[args.graph], onnx_sha256)+ blob, count = build(layers, tensors, GRAPHS[args.graph], source_sha256.digest()) if args.out: with open(args.out, "wb") as f: f.write(blob) print( f"{args.graph}: {count} layers, {len(tensors)} tensors, "- f"{len(blob)} bytes ({len(raw)} fp32 in)"+ f"{len(blob)} bytes ({source_size} fp32 in)" )
scripts/ml/test/test_small100.py
diff --git a/scripts/ml/test/test_small100.py b/scripts/ml/test/test_small100.pynew file mode 100644index 0000000000..aa4cd51dcc--- /dev/null+++ b/scripts/ml/test/test_small100.py@@ -0,0 +1,231 @@+#!/usr/bin/env python3+"""test_small100.py - unit test for `maml_convert`'s SMaLL-100 checkpoint path.++`collect_small100` is the one converter arm with no ONNX graph behind it, so nothing about its+input records the architecture: `check_checkpoint` is the whole guard, and `collect_small100`'s+emission *order* is the whole contract with `nets::small100`. Both are checked here against a+toy model of the same shape rather than the real 1.33 GB checkpoint, so this runs in a second and+needs no download.++What each check is defending against:++* **The transpose.** A `torch.nn.Linear` weight is `[out, in]` and a 1x1 kernel is+ `[out, in, 1, 1]`, so a projection is a reshape. ONNX `MatMul` is `[in, out]`, and every+ attention projection here is square, so reading one convention as the other gives the right+ shape holding the wrong numbers. `fc1` and `fc2` are the asymmetric pair that makes it loud, and+ the test asserts a transposed checkpoint is *rejected* rather than trusting a comment.+* **The order.** `nets::small100` walks the tensor table positionally. A layer emitted out of+ order loads cleanly and infers nonsense.+* **The tied head appearing once.** Emitting the embedding twice would put 125 MiB back into the+ download, which is most of the reason for the port.+* **The int8 triple.** `Builder::conv_int8` reads kernel, then per-output-channel scale, then+ bias. A pair, or the scale after the bias, is a silent misread.++Run:+ python3 scripts/ml/test/test_small100.py++Exit code 0 = all assertions passed.+"""++from __future__ import annotations++import os+import sys++import numpy as np++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import maml_convert # noqa: E402 (needs the path above)++# The real architecture with every dimension shrunk, so the table has the same *structure* -+# two head halves, encoder layers, an encoder norm, decoder layers, a decoder norm - at a size+# that fits in memory. `head_splits` stays 2 because that is what the Rust reads.+TOY = {+ "d_model": 8,+ "encoder_layers": 2,+ "decoder_layers": 1,+ "ffn": 16,+ "vocab": 6,+ "head_splits": 2,+}++passed = 0+failed = 0+++def check(what: str, ok: bool) -> None:+ global passed, failed+ if ok:+ passed += 1+ print(f" ok {what}")+ else:+ failed += 1+ print(f" FAIL {what}")+++def toy_checkpoint(spec, transpose_projections: bool = False):+ """`(get, shapes)` for a checkpoint of `spec`'s shape, filled with distinguishable values."""+ rng = np.random.default_rng(7)+ held = {}+ for name, shape in maml_convert.small100_inventory(spec).items():+ if transpose_projections and name.endswith(".weight") and len(shape) == 2:+ shape = list(reversed(shape))+ held[name] = rng.standard_normal(shape).astype(np.float32)+ return held.__getitem__, {name: list(v.shape) for name, v in held.items()}+++def test_the_inventory_is_the_real_architecture() -> None:+ print("inventory:")+ want = maml_convert.small100_inventory(maml_convert.CHECKPOINTS["small100"])+ # 275 is what `alirezamsh/small100` holds; a derived list that disagrees is derived wrong.+ check("275 parameters", len(want) == 275)+ check("the embedding is [vocab, d_model]", want["model.shared.weight"] == [128_112, 1024])+ # The pair a transpose would swap.+ check("fc1 is [ffn, d_model]", want["model.encoder.layers.0.fc1.weight"] == [4096, 1024])+ check("fc2 is [d_model, ffn]", want["model.encoder.layers.0.fc2.weight"] == [1024, 4096])+ check(+ "the decoder has cross-attention",+ "model.decoder.layers.0.encoder_attn.q_proj.weight" in want,+ )+ check(+ "the encoder has none",+ "model.encoder.layers.0.encoder_attn.q_proj.weight" not in want,+ )+ total = sum(int(np.prod(shape)) for shape in want.values())+ check(f"332,735,488 parameters, got {total}", total == 332_735_488)+++def test_a_transposed_checkpoint_is_refused() -> None:+ print("the transpose:")+ _, shapes = toy_checkpoint(TOY)+ try:+ maml_convert.check_checkpoint(shapes, "small100")+ refused = False+ except SystemExit:+ refused = True+ # The toy is not the real architecture, so it must fail; the point is *which* checks fire.+ check("a toy checkpoint is refused against the real spec", refused)++ real = maml_convert.small100_inventory(maml_convert.CHECKPOINTS["small100"])+ flipped = {+ name: (list(reversed(shape)) if name.endswith(".weight") and len(shape) == 2 else shape)+ for name, shape in real.items()+ }+ try:+ maml_convert.check_checkpoint(flipped, "small100")+ caught = ""+ except SystemExit as exit:+ caught = str(exit)+ check("a transposed checkpoint is refused", bool(caught))+ check("and fc1 is named in the message", "fc1" in caught)+ maml_convert.check_checkpoint(real, "small100")+ check("the real inventory is accepted", True)+++def test_the_table_order_is_the_contract() -> None:+ print("order:")+ get, _ = toy_checkpoint(TOY)+ layers, tensors = maml_convert.collect_small100(get, TOY)+ ops = [layer.op for layer in layers]++ heads = [i for i, op in enumerate(ops) if op == "Head"]+ check("both head halves come first", heads == [0, 1])+ check("the embedding is emitted once, as two ranges", len(heads) == TOY["head_splits"])++ # One encoder layer: norm, q, k, v, out, norm, fc1, fc2.+ encoder = ops[2:2 + 8]+ check(+ "an encoder layer is norm, four projections, norm, fc1, fc2",+ encoder == ["LayerNorm", "Linear8", "Linear8", "Linear8", "Linear8",+ "LayerNorm", "Linear8", "Linear8"],+ )+ per_encoder = 8+ at = 2 + TOY["encoder_layers"] * per_encoder+ check("the encoder's final norm follows its layers", ops[at] == "LayerNorm")+ # One decoder layer adds a cross-attention norm and four more projections.+ decoder = ops[at + 1: at + 1 + 13]+ check(+ "a decoder layer has two attentions",+ decoder == ["LayerNorm"] + ["Linear8"] * 4 + ["LayerNorm"] + ["Linear8"] * 4+ + ["LayerNorm", "Linear8", "Linear8"],+ )+ check("the decoder's final norm is last", ops[-1] == "LayerNorm")++ names = [layer.name for layer in layers]+ check(+ "the layers are named after the checkpoint",+ names[2] == "model.encoder.layers.0.self_attn_layer_norm",+ )+ check("a head half names its class range", names[0].endswith("[0:3]"))++ # Every layer's tensors are contiguous and in order, which is how the Rust indexes them.+ at = 0+ contiguous = True+ for layer in layers:+ contiguous = contiguous and layer.first_tensor == at+ at += layer.tensor_count+ check("layer tensor ranges tile the table", contiguous and at == len(tensors))+++def test_an_int8_layer_is_kernel_then_scale_then_bias() -> None:+ print("the int8 triple:")+ get, _ = toy_checkpoint(TOY)+ layers, tensors = maml_convert.collect_small100(get, TOY)++ head = layers[0]+ check("a head half emits three tensors", head.tensor_count == 3)+ kernel, scale, bias = tensors[head.first_tensor: head.first_tensor + 3]+ rows = TOY["vocab"] // TOY["head_splits"]+ check("the kernel is int8", kernel.dtype == np.int8)+ check(+ f"shaped [{rows}, {TOY['d_model']}, 1, 1]",+ list(kernel.shape) == [rows, TOY["d_model"], 1, 1],+ )+ check("one scale per class", scale.shape == (rows,) and scale.dtype != np.int8)+ check("a tied head's bias is zero", bias.shape == (rows,) and not bias.any())++ ffn = next(layer for layer in layers if layer.name.endswith("fc1"))+ kernel, scale, bias = tensors[ffn.first_tensor: ffn.first_tensor + 3]+ check(+ f"fc1's kernel is [{TOY['ffn']}, {TOY['d_model']}, 1, 1]",+ list(kernel.shape) == [TOY["ffn"], TOY["d_model"], 1, 1],+ )+ check("with one scale per output channel", scale.shape == (TOY["ffn"],))+ check("and the checkpoint's own bias", bias.shape == (TOY["ffn"],) and bias.any())++ norm = next(layer for layer in layers if layer.name.endswith("self_attn_layer_norm"))+ check("a layer norm emits two", norm.tensor_count == 2)+ gamma, beta = tensors[norm.first_tensor: norm.first_tensor + 2]+ check("both fp32, so `build` rounds them to fp16", gamma.dtype != np.int8)+ check("both [d_model]", gamma.shape == beta.shape == (TOY["d_model"],))+++def test_the_digest_covers_the_order() -> None:+ print("the digest:")+ get, _ = toy_checkpoint(TOY)+ layers, _ = maml_convert.collect_small100(get, TOY)+ before = maml_convert.layer_table_digest(layers)+ # A key is what the Rust hardcodes about a layer, not its name, so the pair swapped here has+ # to differ in shape. Two `[d_model]` layer norms have the same key and are interchangeable in+ # the digest, which is correct: swapping them changes nothing the forward pass can observe.+ q_proj = next(i for i, layer in enumerate(layers) if layer.name.endswith("q_proj"))+ fc1 = next(i for i, layer in enumerate(layers) if layer.name.endswith("fc1"))+ swapped = list(layers)+ swapped[q_proj], swapped[fc1] = swapped[fc1], swapped[q_proj]+ check("a reordered pair changes it", maml_convert.layer_table_digest(swapped) != before)+ check("the same table does not", maml_convert.layer_table_digest(list(layers)) == before)+++def main() -> int:+ test_the_inventory_is_the_real_architecture()+ test_a_transposed_checkpoint_is_refused()+ test_the_table_order_is_the_contract()+ test_an_int8_layer_is_kernel_then_scale_then_bias()+ test_the_digest_covers_the_order()+ print(f"\n{passed} passed, {failed} failed")+ return 1 if failed else 0+++if __name__ == "__main__":+ raise SystemExit(main())