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

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

fetch_madlad400.py354 lines · 14.7 KiBRaw
1#!/usr/bin/env python3
2"""Fetch MADLAD400-3B-MT's checkpoint and build the files `:translate` downloads.
3
4Mirrors `fetch_nllb600.py`: pin the HF revision, download + digest-check every input,
5assert `config.json` against transcribed architecture constants, assert the embedding
6is untied (shared vs lm_head differ, so emit both), build Unigram `tokenizer.bin`
7from `spiece.model`, convert `model.safetensors` (fp32) to `madlad400.maml` via
8`maml_convert.py --graph madlad400`.
9
10It is not folded into `fetch_and_convert.sh` because these are **runtime downloads**,
11not bundled assets: the output goes to a build directory and then to the mirror.
12
13# The decode protocol (contract with rust-eng's `nets::madlad`, read from transformers)
14
15* **Source side:** the target-language tag LEADS the source sequence:
16 `[<2tgt>, pieces..., </s>]`. MADLAD is trained with the target tag as a source
17 prefix, unlike NLLB's source-lang token. Easy to get backwards.
18* **Target side:** the decoder's first input is `decoder_start_token_id` = 0
19 (`<unk>`, which doubles as the start token). Decode step 0 input is `[0]`,
20 then autoregressive. No forced-BOS override.
21* **Positions:** none learned and none sinusoidal. T5 uses relative position
22 biases computed on the host (`nets::madlad::relative_bias`) and added to the
23 score maps as plan inputs. The embedding is gathered with NO scale.
24* **FFN activation:** gated-gelu (`feed_forward_proj: gated-gelu` in config.json):
25 `wo(GELU(wi_0(x)) * wi_1(x))`, via the fused `GatedActivate` op with `Act::Gelu`.
26* **Norms:** RMSNorm (`T5LayerNorm`, gamma only, eps 1e-6), pre-norm like NLLB.
27* **Embeddings:** untied (`tie_word_embeddings: false`) — `shared.weight` is the
28 encoder/decoder input table and `lm_head.weight` the logits kernel, emitted as
29 two separate 4-way head splits.
30* **Specials:** UNK 0 (`<unk>`), PAD 1 (`<s>`), EOS 2 (`</s>`). The tokenizer is
31 Unigram (type 1): Viterbi over log-probabilities, NOT greedy BPE merging.
32
33# The pins, and what each one catches
34
35* **File SHA-256** below. Catches an upstream re-export at the same revision, or a
36 truncated download.
37* **The parameter inventory** `maml_convert.check_checkpoint` asserts (encoder 32 +
38 decoder 32 layers + norms + untied head). Catches a transposed or resized
39 checkpoint; `wi_0 [10240, 1024]` / `wo [1024, 8192]` is the asymmetric set.
40* **The layer table digest** `maml_convert.EXPECTED_DIGEST["madlad400"]` pins the
41 emission order.
42* **`config.json`**, fetched and checked but not converted — the ARCHITECTURE constants
43 below are transcribed from it and `nets::madlad` hardcodes them.
44
45Usage:
46
47 python scripts/ml/fetch_madlad400.py # verify digests, build the files
48 python scripts/ml/fetch_madlad400.py --work DIR # keep the checkpoint somewhere specific
49 python scripts/ml/fetch_madlad400.py --print-digests # after an intentional upstream bump
50"""
51
52import argparse
53import hashlib
54import json
55import os
56import struct
57import subprocess
58import sys
59import tempfile
60
61REPO = "google/madlad400-3b-mt"
62
63# Pinned commit. Re-pin with --print-digests after an intentional bump (and only then).
64REVISION = "fa184c675da0b5c9e1c8694fccd4e12e2d422094"
65
66HERE = os.path.dirname(os.path.abspath(__file__))
67ROOT = os.path.dirname(os.path.dirname(HERE))
68
69# Not an assets directory: these files are fetched at run time from
70# `data.maproj.org/models/madlad400/`, so the build only has to produce them for upload.
71OUT = os.path.join(ROOT, "build", "madlad400")
72
73CHECKPOINT = "model.safetensors"
74SPM = "spiece.model"
75TOKENIZER = "tokenizer.json"
76CONFIG = "config.json"
77GENERATION_CONFIG = "generation_config.json"
78SPECIAL_TOKENS = "special_tokens_map.json"
79TOKENIZER_CONFIG = "tokenizer_config.json"
80
81# SHA-256 of every file this reads, at the pinned revision. Fill in with --print-digests
82# on the first run (placeholder zeros fail loudly until then).
83DIGESTS = {
84 CHECKPOINT: "66ff5f8fcaf92291da486fdfbd4d5233cec90e1359348a56e3172c978b3a76d4",
85 SPM: "ef11ac9a22c7503492f56d48dce53be20e339b63605983e9f27d2cd0e0f3922c",
86 TOKENIZER: "a2799ccc696b752ba00c34f58726bfe253a04921ceb6cfc620400f560474790b",
87 CONFIG: "cad399cab799b99409a6ec2d90d72552257c2bb752861261d2016691e0643e7c",
88 GENERATION_CONFIG: "0849b38987568ccfe4ebefc22bbda1cec4bee01c345e93bfab207d4692b0a1d5",
89 SPECIAL_TOKENS: "7f79f1d5063d56c4b980eec0692f3c7429bdef335071d34e566bd00fd4b5e3e0",
90 TOKENIZER_CONFIG: "641fc660745306dfb935f666a68f8bc10a44c39241cfb357be518fda8c09662d",
91}
92
93# Transcribed from the pinned `config.json`, and asserted against it below rather
94# than trusted. `nets::madlad` is written against these.
95ARCHITECTURE = {
96 "d_model": 1024,
97 "d_kv": 128,
98 "num_heads": 16,
99 "num_layers": 32,
100 "num_decoder_layers": 32,
101 "d_ff": 8192,
102 "vocab_size": 256_000,
103 "feed_forward_proj": "gated-gelu",
104 "tie_word_embeddings": False,
105 "relative_attention_num_buckets": 32,
106 "relative_attention_max_distance": 128,
107 "layer_norm_epsilon": 1e-06,
108 "pad_token_id": 1,
109 "eos_token_id": 2,
110 "decoder_start_token_id": 0,
111 "model_type": "t5",
112}
113
114
115def sha256(path):
116 digest = hashlib.sha256()
117 with open(path, "rb") as handle:
118 for block in iter(lambda: handle.read(1 << 20), b""):
119 digest.update(block)
120 return digest.hexdigest()
121
122
123def convert(script, *args):
124 """Run one of the sibling converters, letting its own output and exit code through."""
125 subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)
126
127
128def check_architecture(path):
129 """Fail if the checkpoint's config is not the one `nets::madlad` is written against."""
130 held = json.load(open(path, encoding="utf-8"))
131 wrong = {k: (held.get(k), v) for k, v in ARCHITECTURE.items() if held.get(k) != v}
132 if wrong:
133 lines = "\n".join(f" {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items())
134 raise SystemExit(
135 f"{path} is not the architecture the runtime hardcodes:\n{lines}\n"
136 "nets::madlad has these baked in, so re-read it before re-pinning."
137 )
138 print(f"config.json matches {len(ARCHITECTURE)} hardcoded architecture constants")
139
140
141def check_untied(checkpoint_path):
142 """Fail unless the input and output tables differ (so emitting both is correct).
143
144 The mirror of `fetch_nllb600.check_tied`: NLLB asserts its four copies are
145 byte-identical and emits one; MADLAD's `tie_word_embeddings` is false, so the
146 input table (`decoder.embed_tokens.weight` — this export materialised only the
147 decoder clone, not `shared.weight`) and `lm_head.weight` must differ and the
148 converter emits both. If they ever matched, emitting both would put ~250 MiB
149 back into the download for nothing.
150 """
151 from safetensors import safe_open
152
153 handle = safe_open(checkpoint_path, framework="np")
154 shared = handle.get_tensor("decoder.embed_tokens.weight")
155 head = handle.get_tensor("lm_head.weight")
156 if shared.shape != head.shape or bool((shared == head).all()):
157 raise SystemExit(
158 "decoder.embed_tokens.weight and lm_head.weight are identical: the embedding "
159 "is tied, so emitting both copies is wrong. Re-read nets::madlad's head handling."
160 )
161 print(f"untied embedding confirmed: decoder.embed_tokens {list(shared.shape)} != lm_head (values differ)")
162
163
164def read_varint(blob, at):
165 value = 0
166 shift = 0
167 while True:
168 if at >= len(blob):
169 raise SystemExit("a varint runs off the end of the model")
170 byte = blob[at]
171 at += 1
172 value |= (byte & 0x7F) << shift
173 if not byte & 0x80:
174 return value, at
175 shift += 7
176
177
178def proto_fields(blob):
179 at = 0
180 while at < len(blob):
181 tag, at = read_varint(blob, at)
182 number, wire = tag >> 3, tag & 7
183 if wire == 2:
184 length, at = read_varint(blob, at)
185 yield number, wire, blob[at : at + length]
186 at += length
187 elif wire == 5:
188 yield number, wire, blob[at : at + 4]
189 at += 4
190 elif wire == 0:
191 value, at = read_varint(blob, at)
192 yield number, wire, value
193 else:
194 raise SystemExit(f"unhandled protobuf wire type {wire} in the model")
195
196
197# `trainer_spec.model_type`, from sentencepiece's ModelType enum. Unigram, not BPE:
198# encoding is Viterbi over log-probabilities, and the Rust merge loop would be wrong.
199MODEL_TYPE_UNIGRAM = 1
200
201
202def read_unigram(spm_path):
203 """`[(piece, score)]` in id order from `spiece.model`, asserting Unigram + identity norm.
204
205 Scores are log-probabilities (negative floats, NOT merge ranks). The Rust
206 `Table::encode_unigram` runs Viterbi over them.
207 """
208 import re
209
210 blob = open(spm_path, "rb").read()
211 pieces = []
212 checked_type = False
213 for number, wire, payload in proto_fields(blob):
214 if number == 1:
215 piece, score = None, 0.0
216 for inner, w, value in proto_fields(payload):
217 if inner == 1:
218 piece = value
219 elif inner == 2 and w == 5:
220 score = struct.unpack("<f", value)[0]
221 if piece is None:
222 raise SystemExit(f"{spm_path}: a piece with no `piece` field")
223 pieces.append((piece, score))
224 elif number == 2:
225 for inner, _, value in proto_fields(payload):
226 if inner == 3:
227 checked_type = True
228 if value != MODEL_TYPE_UNIGRAM:
229 raise SystemExit(
230 f"{spm_path}: trainer_spec.model_type is {value}, not Unigram"
231 f" ({MODEL_TYPE_UNIGRAM}); the Viterbi path in post::sentencepiece only"
232 " applies to Unigram"
233 )
234 elif number == 3:
235 for inner, _, value in proto_fields(payload):
236 if inner == 1 and value.decode("utf-8") != "identity":
237 raise SystemExit(
238 f"{spm_path}: normalizer is {value.decode('utf-8')!r}, not identity;"
239 " the Kotlin caller must not NFKC-normalise"
240 )
241 if not checked_type:
242 raise SystemExit(f"{spm_path}: no trainer_spec.model_type, so this may not be Unigram")
243 if len(pieces) != 256_000:
244 raise SystemExit(f"{spm_path}: {len(pieces)} pieces, not the 256000 the runtime hardcodes")
245 # T5 specials, in T5's order — the Rust `Flavour::T5` checks these, restated here so
246 # a re-export that moved them fails at fetch rather than at inference.
247 names = [pieces[i][0].decode("utf-8") for i in range(3)]
248 if names != ["<unk>", "<s>", "</s>"]:
249 raise SystemExit(f"{spm_path}: ids 0..2 are {names}, not T5's <unk> <s> </s>")
250 # Byte fallback must be complete: 256 `<0xNN>` pieces, or uncovered bytes are lost.
251 have = {p.decode("utf-8") for p, _ in pieces}
252 missing = [f"<0x{b:02X}>" for b in range(256) if f"<0x{b:02X}>" not in have]
253 if missing:
254 raise SystemExit(f"{spm_path}: byte fallback incomplete, missing {missing[:4]}...")
255 print(
256 f"{os.path.basename(spm_path)}: {len(pieces)} Unigram pieces, identity normalizer, "
257 "byte fallback complete"
258 )
259 return pieces
260
261
262def write_tokenizer(pieces, out_path):
263 """The `SPM1` blob for Unigram `[(piece, score)]` in id order.
264
265 Same container as `nllb_tokenizer.pack`: magic, count, then `(score i32, len u16,
266 bytes)` per id. Unigram log-probabilities are floats, so they are stored as
267 score * 1e6 rounded to an i32 — exact to 1e-6, far below fp16 resolution, and
268 it keeps the table format (and its parser) shared between the two models.
269 """
270 out = bytearray(b"SPM1")
271 out += struct.pack("<I", len(pieces))
272 for piece, score in pieces:
273 if len(piece) > 0xFFFF:
274 raise SystemExit(f"a piece of {len(piece)} bytes does not fit a u16 length")
275 quantised = int(round(score * 1_000_000))
276 out += struct.pack("<iH", quantised, len(piece))
277 out += piece
278 with open(out_path, "wb") as f:
279 f.write(bytes(out))
280 print(f"{os.path.basename(out_path)}: {len(pieces)} pieces, {len(out)} bytes")
281
282
283def main():
284 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
285 parser.add_argument("--work", help="where to keep the checkpoint (default: a temp directory)")
286 parser.add_argument("-o", "--out", default=OUT, help="where to write the files")
287 parser.add_argument(
288 "--print-digests",
289 action="store_true",
290 help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",
291 )
292 parser.add_argument(
293 "--local", help="use an already-downloaded snapshot dir instead of downloading"
294 )
295 args = parser.parse_args()
296
297 try:
298 from huggingface_hub import snapshot_download
299 except ImportError:
300 raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")
301
302 if args.local:
303 local = args.local
304 else:
305 work = args.work or os.path.join(tempfile.gettempdir(), "madlad400")
306 local = snapshot_download(
307 repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work
308 )
309 print(f"{REPO}@{REVISION[:12]} in {local}")
310
311 if args.print_digests:
312 for name in DIGESTS:
313 print(f' {name}: "{sha256(os.path.join(local, name))}",')
314 return 0
315
316 for name, expected in DIGESTS.items():
317 if expected.startswith("0000"):
318 raise SystemExit(
319 f"{name}: no pinned digest yet. Run with --print-digests once the files "
320 "are downloaded, verify the revision, and pin them here."
321 )
322 got = sha256(os.path.join(local, name))
323 if got != expected:
324 raise SystemExit(
325 f"{name}\n sha256 {got}\n pinned {expected}\n"
326 "The upstream export changed. Re-read it, check the Rust forward pass still\n"
327 "matches, then re-pin with --print-digests."
328 )
329 print(f"{len(DIGESTS)} upstream digests match")
330 check_architecture(os.path.join(local, CONFIG))
331 check_untied(os.path.join(local, CHECKPOINT))
332
333 os.makedirs(args.out, exist_ok=True)
334 pieces = read_unigram(os.path.join(local, SPM))
335 write_tokenizer(pieces, os.path.join(args.out, "tokenizer.bin"))
336 convert(
337 "maml_convert.py",
338 os.path.join(local, CHECKPOINT),
339 "--graph", "madlad400",
340 "-o", os.path.join(args.out, "madlad400.maml"),
341 "--print-digest",
342 )
343
344 print(f"\n{args.out}")
345 for name in sorted(os.listdir(args.out)):
346 path = os.path.join(args.out, name)
347 if os.path.isfile(path):
348 size = os.path.getsize(path)
349 print(f" {name}: {size} bytes ({size / (1 << 20):.1f} MiB) {sha256(path)}")
350 return 0
351
352
353if __name__ == "__main__":
354 raise SystemExit(main())