Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / scripts / ml / fetch_tinyclip.py

fetch_tinyclip.py239 lines · 10.3 KiBRaw
1#!/usr/bin/env python3
2"""Fetch TinyCLIP's fp32 ONNX export and build the `tinyclip.maml` `:photos` bundles.
3
4# Why this exists
5
6TinyCLIP was the **only bundled model in this tree with no pinned upstream SHA-256 and no fetch
7script**. `scripts/ml/fetch_and_convert.sh` lists six models and CLIP was not among them;
8`photos/src/main/assets/clip/README.md` did not exist, and `photos/src/main/assets/README.md`
9punted to `SUPPLY_CHAIN_RISKS.md`, which named an upstream repo in prose and nothing else. Every
10other model here is pinned by revision *and* file digest. This closes that.
11
12# The fp32 export, not the int8 one the app shipped
13
14The asset being replaced is `onnx/model_int8.onnx` from this same repo, and it is **not** what is
15converted. Read rather than assumed, its 80 `MatMulInteger` weights are per-output-channel with
16zero zero-points — but three tensors are not:
17
18* `vision_model.embeddings.patch_embedding.weight_scale` is a **scalar**, so one scale covers a
19 kernel whose per-channel absmax spans 0.0018 to 0.117.
20* `text_model.embeddings.token_embedding` is **uint8 with a zero point of 226**, and
21 `text_model.embeddings.position_embedding` **uint8 with 220**. `conv_int8.comp` computes
22 `scale[o] * sum(int8_w * in)` and has nowhere to put a zero point, which is the same objection
23 `CHECKPOINTS` in `maml_convert.py` records against SMaLL-100's int8 export.
24
25Requantising those per channel would add a second rounding to resolution that is already gone. So
26this reads `onnx/model.onnx`, which is fp32, and `maml_convert.quantise_per_channel` gives all
27three a per-output-channel scale and no zero point. The result is 22.6 MiB against the shipped
2824.3 MB, and the measured worst per-tensor correlation is 0.99986.
29
30`onnx/model.onnx` is a **build-host** dependency only: 94 MB downloaded here, nothing at run time.
31
32# The pins, and what each one catches
33
34* **File SHA-256**, below. Catches an upstream re-export at the same revision, or a truncated
35 download.
36* **`config.json`**, checked against [`ARCHITECTURE`] rather than trusted. `nets::tinyclip`
37 hardcodes 10 vision layers, 3 text layers, width 256, 4 heads and a 1024-wide feed-forward.
38* **The named-parameter inventory** `maml_convert.check_architecture` asserts — every name and
39 every shape, including the `[in, out]` orientation of all 80 projections, which is what catches a
40 transposed read. That mistake is invisible in the shape for the 76 square ones.
41* **The op counts** `maml_convert.EXPECTED_OPS` pins, which only an ONNX graph can give.
42* **The layer table digest** `maml_convert.EXPECTED_DIGEST` pins, over the emitted order.
43
44The int8 fidelity gate in `maml_convert.Fidelity` is the only one of these that looks at the
45numbers, and it only compares the quantisation against the weight it came from.
46`scripts/ml/onnx_parity.py` is what compares the forward pass.
47
48Usage:
49
50 python scripts/ml/fetch_tinyclip.py # verify digests, write the asset
51 python scripts/ml/fetch_tinyclip.py --work DIR # keep the 94 MB export somewhere specific
52 python scripts/ml/fetch_tinyclip.py --print-digests # after an intentional upstream bump
53"""
54
55import argparse
56import hashlib
57import json
58import os
59import subprocess
60import sys
61import tempfile
62
63REPO = "onnx-community/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M-ONNX"
64
65# Pinned to a commit rather than to `main`, for the reason `fetch_and_convert.sh` gives: the
66# digests below would catch a silent upstream change anyway, but a pinned revision tells you the
67# upstream *revision* that moved rather than just that some bytes differ.
68#
69# MIT, and an ONNX export of `wkcn/TinyCLIP-ViT-8M-16-Text-3M-YFCC15M`, which is also MIT.
70REVISION = "9463a9c508a344c837ffefe9d724f3827bf2dc79"
71
72HERE = os.path.dirname(os.path.abspath(__file__))
73ROOT = os.path.dirname(os.path.dirname(HERE))
74
75# A bundled asset, unlike `fetch_small100.py`'s runtime downloads, so this writes straight into the
76# APK's assets directory beside the BPE table the tokenizer reads.
77OUT = os.path.join(ROOT, "photos", "src", "main", "assets", "clip")
78
79MODEL = "onnx/model.onnx"
80CONFIG = "config.json"
81PREPROCESSOR = "preprocessor_config.json"
82
83# SHA-256 of every file this reads, at the pinned revision. Not the whole repo: the seven other
84# quantisations of the same graph say the same thing as the fp32 one, so pinning them would pin
85# something never downloaded.
86DIGESTS = {
87 MODEL: "31d28cb07209533d10fc4fef73ac324ce17de6741a2372e7e1531a4ac8fdaeb2",
88 CONFIG: "0ca46b868f12305e959a1cfa2b8085e7bffd521f68769ec3bf2999986b55bec3",
89 PREPROCESSOR: "5df7e578c37e907a431daf47fd592fc49fa50d23ed4c41285a0a34a58a9d2e06",
90}
91
92# Transcribed from the pinned `config.json`, and asserted against it below rather than trusted.
93# `nets::tinyclip` is written against these; `maml_convert.ARCHITECTURES` restates the subset the
94# tensor table depends on.
95ARCHITECTURE = {
96 "projection_dim": 512,
97 "vision": {
98 "hidden_size": 256,
99 "intermediate_size": 1024,
100 "num_attention_heads": 4,
101 "num_hidden_layers": 10,
102 "patch_size": 16,
103 "hidden_act": "gelu",
104 },
105 "text": {
106 "hidden_size": 256,
107 "intermediate_size": 1024,
108 "num_attention_heads": 4,
109 "num_hidden_layers": 3,
110 "hidden_act": "gelu",
111 },
112}
113
114# From the pinned `preprocessor_config.json`, and the numbers `ClipEmbedder.preprocess` hardcodes.
115# Asserted here so a re-pin that changed the normalisation could not pass silently: a wrong mean or
116# a wrong crop size produces embeddings that are plausible and wrong, and nothing downstream checks
117# them.
118PREPROCESSING = {
119 "size": 224,
120 "crop_size": 224,
121 "image_mean": [0.48145466, 0.4578275, 0.40821073],
122 "image_std": [0.26862954, 0.26130258, 0.27577711],
123}
124
125
126def sha256(path):
127 digest = hashlib.sha256()
128 with open(path, "rb") as handle:
129 for block in iter(lambda: handle.read(1 << 20), b""):
130 digest.update(block)
131 return digest.hexdigest()
132
133
134def convert(script, *args):
135 """Run one of the sibling converters, letting its own output and exit code through.
136
137 `check=True` matters: `maml_convert.py` exits non-zero when a layer table digest does not
138 match, and that is the check that must stop an asset being written from the wrong export.
139 """
140 subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)
141
142
143def check_architecture(path):
144 """Fail if the export's config is not the architecture `nets::tinyclip` is written against."""
145 held = json.load(open(path, encoding="utf-8"))
146 wrong = {}
147 if held.get("projection_dim") != ARCHITECTURE["projection_dim"]:
148 wrong["projection_dim"] = (held.get("projection_dim"), ARCHITECTURE["projection_dim"])
149 for tower in ("vision", "text"):
150 config = held.get(f"{tower}_config", {})
151 for key, want in ARCHITECTURE[tower].items():
152 if config.get(key) != want:
153 wrong[f"{tower}_config.{key}"] = (config.get(key), want)
154 if wrong:
155 lines = "\n".join(f" {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())
156 raise SystemExit(
157 f"{path} is not the architecture the runtime hardcodes:\n{lines}\n"
158 "nets::tinyclip has these baked in, so re-read it before re-pinning."
159 )
160 print("config.json matches the hardcoded architecture of both towers")
161
162
163def check_preprocessing(path):
164 """Fail if the export's preprocessing is not what `ClipEmbedder.preprocess` implements."""
165 held = json.load(open(path, encoding="utf-8"))
166 got = {
167 # Both are `{"shortest_edge": 224}` / `{"height": 224, "width": 224}` dicts upstream, so
168 # the values are pulled out rather than compared as dicts.
169 "size": (held.get("size") or {}).get("shortest_edge"),
170 "crop_size": (held.get("crop_size") or {}).get("height"),
171 "image_mean": held.get("image_mean"),
172 "image_std": held.get("image_std"),
173 }
174 close = all(
175 abs(a - b) < 1e-6
176 for key in ("image_mean", "image_std")
177 for a, b in zip(got[key] or [], PREPROCESSING[key])
178 )
179 sized = got["size"] == PREPROCESSING["size"] and got["crop_size"] == PREPROCESSING["crop_size"]
180 if not (close and sized):
181 raise SystemExit(
182 f"{path} is not the preprocessing ClipEmbedder implements:\n"
183 f" got {got}\n want {PREPROCESSING}\n"
184 "A wrong mean or crop produces embeddings that are plausible and wrong."
185 )
186 print("preprocessor_config.json matches ClipEmbedder.preprocess")
187
188
189def main():
190 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
191 parser.add_argument("--work", help="where to keep the export (default: a temp directory)")
192 parser.add_argument("-o", "--out", default=OUT, help="where to write tinyclip.maml")
193 parser.add_argument(
194 "--print-digests",
195 action="store_true",
196 help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",
197 )
198 args = parser.parse_args()
199
200 try:
201 from huggingface_hub import snapshot_download
202 except ImportError:
203 raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")
204
205 work = args.work or os.path.join(tempfile.gettempdir(), "tinyclip")
206 local = snapshot_download(
207 repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work
208 )
209 print(f"{REPO}@{REVISION[:12]} in {local}")
210
211 if args.print_digests:
212 for name in DIGESTS:
213 print(f' {name}: "{sha256(os.path.join(local, name))}",')
214 return 0
215
216 for name, expected in DIGESTS.items():
217 got = sha256(os.path.join(local, name))
218 if got != expected:
219 raise SystemExit(
220 f"{name}\n sha256 {got}\n pinned {expected}\n"
221 "The upstream export changed. Re-read it, check the Rust forward pass still\n"
222 "matches, then re-pin with --print-digests."
223 )
224 print(f"{len(DIGESTS)} upstream digests match")
225 check_architecture(os.path.join(local, CONFIG))
226 check_preprocessing(os.path.join(local, PREPROCESSOR))
227
228 os.makedirs(args.out, exist_ok=True)
229 asset = os.path.join(args.out, "tinyclip.maml")
230 convert("maml_convert.py", os.path.join(local, MODEL), "--graph", "tinyclip", "-o", asset)
231
232 size = os.path.getsize(asset)
233 print(f"\n{asset}: {size} bytes ({size / (1 << 20):.1f} MiB)")
234 print(f" sha256 {sha256(asset)}")
235 return 0
236
237
238if __name__ == "__main__":
239 raise SystemExit(main())