Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / fetch_nllb600.py
fetch_nllb600.py254 lines · 10.5 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Fetch NLLB-200-distilled-600M's checkpoint and build the files `:translate` downloads. |
| 3 | |
| 4 | Mirrors `fetch_small100.py`: pin the HF revision, download + digest-check every input, |
| 5 | assert `config.json` against transcribed architecture constants, assert the four tied |
| 6 | embedding copies byte-identical, build `tokenizer.bin` + `nllb_langs.json` via |
| 7 | `nllb_tokenizer.py`, convert `pytorch_model.bin` (via a local `.safetensors` repack — |
| 8 | `maml_convert.open_checkpoint` reads safetensors) to `nllb600.maml` via |
| 9 | `maml_convert.py --graph nllb600`. |
| 10 | |
| 11 | It is not folded into `fetch_and_convert.sh` because these are **runtime downloads**, |
| 12 | not bundled assets: the output goes to a build directory and then to the mirror. |
| 13 | |
| 14 | # The decode protocol (contract with rust-eng's `nets::nllb600`, read from transformers) |
| 15 | |
| 16 | * **Source side:** NLLB's `NllbTokenizer.set_src_lang_special_tokens` (non-legacy) uses |
| 17 | `prefix=[src_lang]` + `suffix=[eos]` — i.e. the **source-language** token LEADS the |
| 18 | source sequence: `[src_lang, pieces..., eos]`. (SMaLL-100/M2M-100 put the *target* |
| 19 | token on the source side; NLLB puts the *source* token there. Easy to get backwards.) |
| 20 | * **Target side:** the decoder's first input is the **target-language** token as |
| 21 | forced BOS (`forced_bos_token_id = tgt_lang_id`, `decoder_start_token_id` unused at |
| 22 | inference): decode step 0 input is `[tgt_lang]`, then autoregressive. |
| 23 | * **Positions:** fairseq sinusoid, first real token at position 2 |
| 24 | (`cumsum(mask)*mask + padding_idx`, padding_idx 1 — `M2M100SinusoidalPositionalEmbedding` |
| 25 | with `offset=2`). Same math as small100; the Rust reuses it with NLLB's constants. |
| 26 | * **FFN activation:** ReLU (`activation_function: relu` in config.json). |
| 27 | * **Embeddings:** `scale_embedding: true` — host gather multiplies by `sqrt(1024)`. |
| 28 | * **Specials:** BOS 0 (`<s>`), PAD 1, EOS 2 (`</s>`), UNK 3. Lang tokens 256001..256202, |
| 29 | `<mask>` 256203 (never emitted), 256204..256205 padding. |
| 30 | |
| 31 | # The pins, and what each one catches |
| 32 | |
| 33 | * **File SHA-256** below. Catches an upstream re-export at the same revision, or a |
| 34 | truncated download. |
| 35 | * **The parameter inventory** `maml_convert.check_checkpoint` asserts (509 names: |
| 36 | `model.shared` + 12 enc + 12 dec layers + 2 final norms). Catches a transposed or |
| 37 | resized checkpoint; `fc1 [4096,1024]` / `fc2 [1024,4096]` is the asymmetric pair. |
| 38 | * **The layer table digest** `maml_convert.EXPECTED_DIGEST["nllb600"]` pins (722 tensors). |
| 39 | * **`config.json`**, fetched and checked but not converted — the ARCHITECTURE constants |
| 40 | below are transcribed from it and `nets::nllb600` hardcodes them. |
| 41 | |
| 42 | Usage: |
| 43 | |
| 44 | python scripts/ml/fetch_nllb600.py # verify digests, build the files |
| 45 | python scripts/ml/fetch_nllb600.py --work DIR # keep the checkpoint somewhere specific |
| 46 | python scripts/ml/fetch_nllb600.py --print-digests # after an intentional upstream bump |
| 47 | """ |
| 48 | |
| 49 | import argparse |
| 50 | import hashlib |
| 51 | import json |
| 52 | import os |
| 53 | import subprocess |
| 54 | import sys |
| 55 | import tempfile |
| 56 | |
| 57 | REPO = "facebook/nllb-200-distilled-600M" |
| 58 | |
| 59 | # Pinned commit. Re-pin with --print-digests after an intentional bump (and only then). |
| 60 | REVISION = "f8d333a098d19b4fd9a8b18f94170487ad3f821d" |
| 61 | |
| 62 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 63 | ROOT = os.path.dirname(os.path.dirname(HERE)) |
| 64 | |
| 65 | # Not an assets directory: these files are fetched at run time from |
| 66 | # `data.maproj.org/models/nllb600/`, so the build only has to produce them for upload. |
| 67 | OUT = os.path.join(ROOT, "build", "nllb600") |
| 68 | |
| 69 | CHECKPOINT = "pytorch_model.bin" |
| 70 | SPM = "sentencepiece.bpe.model" |
| 71 | TOKENIZER = "tokenizer.json" |
| 72 | CONFIG = "config.json" |
| 73 | GENERATION_CONFIG = "generation_config.json" |
| 74 | SPECIAL_TOKENS = "special_tokens_map.json" |
| 75 | |
| 76 | # SHA-256 of every file this reads, at the pinned revision. Fill in with --print-digests |
| 77 | # on the first run (placeholder zeros fail loudly until then); the checkpoint's are the |
| 78 | # 2.46 GB bin plus the small files. |
| 79 | DIGESTS = { |
| 80 | CHECKPOINT: "c266c2cfd19758b6d09c1fc31ecdf1e485509035f6b51dfe84f1ada83eefcc42", |
| 81 | SPM: "14bb8dfb35c0ffdea7bc01e56cea38b9e3d5efcdcb9c251d6b40538e1aab555a", |
| 82 | TOKENIZER: "e316b82de11d0f951f370943b3c438311629547285129b0b81dadabd01bca665", |
| 83 | CONFIG: "f9b4081d3d108e9d06532ea8d92b932c04ed3a15ff2f87e6982f8e14db51fbc5", |
| 84 | GENERATION_CONFIG: "0bb604cdb8392649176935a447ce994128f170a6908c135a17d0e3dfb8113cb2", |
| 85 | SPECIAL_TOKENS: "992bd4ed610d644d6823081937bcc91bb8878dd556cea4ae5327f2480361330e", |
| 86 | } |
| 87 | |
| 88 | # Transcribed from the pinned `config.json`, and asserted against it below rather |
| 89 | # than trusted. `nets::nllb600` is written against these. |
| 90 | ARCHITECTURE = { |
| 91 | "d_model": 1024, |
| 92 | "encoder_layers": 12, |
| 93 | "decoder_layers": 12, |
| 94 | "encoder_attention_heads": 16, |
| 95 | "decoder_attention_heads": 16, |
| 96 | "encoder_ffn_dim": 4096, |
| 97 | "decoder_ffn_dim": 4096, |
| 98 | "vocab_size": 256_206, |
| 99 | "max_position_embeddings": 1024, |
| 100 | "pad_token_id": 1, |
| 101 | "bos_token_id": 0, |
| 102 | "eos_token_id": 2, |
| 103 | "decoder_start_token_id": 2, |
| 104 | "scale_embedding": True, |
| 105 | "activation_function": "relu", |
| 106 | "model_type": "m2m_100", |
| 107 | } |
| 108 | |
| 109 | # The four names the tied embedding appears under. Asserted byte-identical before |
| 110 | # conversion; only model.shared.weight is emitted. |
| 111 | TIED_COPIES = [ |
| 112 | "model.shared.weight", |
| 113 | "model.encoder.embed_tokens.weight", |
| 114 | "model.decoder.embed_tokens.weight", |
| 115 | "lm_head.weight", |
| 116 | ] |
| 117 | |
| 118 | |
| 119 | def sha256(path): |
| 120 | digest = hashlib.sha256() |
| 121 | with open(path, "rb") as handle: |
| 122 | for block in iter(lambda: handle.read(1 << 20), b""): |
| 123 | digest.update(block) |
| 124 | return digest.hexdigest() |
| 125 | |
| 126 | |
| 127 | def convert(script, *args): |
| 128 | """Run one of the sibling converters, letting its own output and exit code through.""" |
| 129 | subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT) |
| 130 | |
| 131 | |
| 132 | def check_architecture(path): |
| 133 | """Fail if the checkpoint's shape is not the one `nets::nllb600` is written against.""" |
| 134 | held = json.load(open(path, encoding="utf-8")) |
| 135 | wrong = {k: (held.get(k), v) for k, v in ARCHITECTURE.items() if held.get(k) != v} |
| 136 | if wrong: |
| 137 | lines = "\n".join(f" {k}: {got!r} against {want!r}" for k, (got, want) in wrong.items()) |
| 138 | raise SystemExit( |
| 139 | f"{path} is not the architecture the runtime hardcodes:\n{lines}\n" |
| 140 | "nets::nllb600 has these baked in, so re-read it before re-pinning." |
| 141 | ) |
| 142 | print(f"config.json matches {len(ARCHITECTURE)} hardcoded architecture constants") |
| 143 | |
| 144 | |
| 145 | def check_tied(checkpoint_path): |
| 146 | """Fail unless the four tied copies are byte-identical (so emitting one is exact).""" |
| 147 | import torch |
| 148 | |
| 149 | sd = torch.load(checkpoint_path, map_location="cpu", weights_only=True) |
| 150 | first = sd[TIED_COPIES[0]] |
| 151 | for name in TIED_COPIES[1:]: |
| 152 | other = sd[name] |
| 153 | if other.shape != first.shape or not bool(torch.equal(first, other)): |
| 154 | diff = float((first.float() - other.float()).abs().max()) |
| 155 | raise SystemExit( |
| 156 | f"{name} differs from {TIED_COPIES[0]} (max abs diff {diff}): " |
| 157 | "the embedding is untied, so emitting one copy is wrong." |
| 158 | ) |
| 159 | print(f"tied embedding identical under {len(TIED_COPIES)} names {list(first.shape)}") |
| 160 | |
| 161 | |
| 162 | def to_safetensors(checkpoint_path, out_path): |
| 163 | """Repack the `.bin` as `.safetensors` (same bytes, indexed) for `open_checkpoint`.""" |
| 164 | import torch |
| 165 | from safetensors.torch import save_file |
| 166 | |
| 167 | sd = torch.load(checkpoint_path, map_location="cpu", weights_only=True) |
| 168 | # The four tied copies share storage (which is itself the proof they are tied); |
| 169 | # clone so safetensors does not refuse shared memory, and drop the three extras |
| 170 | # so the repack holds exactly the 509-tensor architecture `check_checkpoint` wants. |
| 171 | extras = [n for n in TIED_COPIES[1:] if n in sd] |
| 172 | for name in extras: |
| 173 | del sd[name] |
| 174 | sd = {k: v.clone() for k, v in sd.items()} |
| 175 | save_file(sd, out_path) |
| 176 | print(f" (dropped tied extras: {extras})") |
| 177 | print(f"repacked {len(sd)} tensors -> {os.path.basename(out_path)}") |
| 178 | |
| 179 | |
| 180 | def main(): |
| 181 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 182 | parser.add_argument("--work", help="where to keep the checkpoint (default: a temp directory)") |
| 183 | parser.add_argument("-o", "--out", default=OUT, help="where to write the files") |
| 184 | parser.add_argument( |
| 185 | "--print-digests", |
| 186 | action="store_true", |
| 187 | help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump", |
| 188 | ) |
| 189 | parser.add_argument( |
| 190 | "--local", help="use an already-downloaded snapshot dir instead of downloading" |
| 191 | ) |
| 192 | args = parser.parse_args() |
| 193 | |
| 194 | try: |
| 195 | from huggingface_hub import snapshot_download |
| 196 | except ImportError: |
| 197 | raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub") |
| 198 | |
| 199 | if args.local: |
| 200 | local = args.local |
| 201 | else: |
| 202 | work = args.work or os.path.join(tempfile.gettempdir(), "nllb600") |
| 203 | local = snapshot_download( |
| 204 | repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work |
| 205 | ) |
| 206 | print(f"{REPO}@{REVISION[:12]} in {local}") |
| 207 | |
| 208 | if args.print_digests: |
| 209 | for name in DIGESTS: |
| 210 | print(f' {name}: "{sha256(os.path.join(local, name))}",') |
| 211 | return 0 |
| 212 | |
| 213 | for name, expected in DIGESTS.items(): |
| 214 | got = sha256(os.path.join(local, name)) |
| 215 | if got != expected: |
| 216 | raise SystemExit( |
| 217 | f"{name}\n sha256 {got}\n pinned {expected}\n" |
| 218 | "The upstream export changed. Re-read it, check the Rust forward pass still\n" |
| 219 | "matches, then re-pin with --print-digests." |
| 220 | ) |
| 221 | print(f"{len(DIGESTS)} upstream digests match") |
| 222 | check_architecture(os.path.join(local, CONFIG)) |
| 223 | check_tied(os.path.join(local, CHECKPOINT)) |
| 224 | |
| 225 | os.makedirs(args.out, exist_ok=True) |
| 226 | convert( |
| 227 | "nllb_tokenizer.py", |
| 228 | "--spm", os.path.join(local, SPM), |
| 229 | "--tokenizer", os.path.join(local, TOKENIZER), |
| 230 | "-o", os.path.join(args.out, "tokenizer.bin"), |
| 231 | "--langs-out", os.path.join(args.out, "nllb_langs.json"), |
| 232 | ) |
| 233 | safetensors_path = os.path.join(args.out, "_nllb600.safetensors") |
| 234 | to_safetensors(os.path.join(local, CHECKPOINT), safetensors_path) |
| 235 | convert( |
| 236 | "maml_convert.py", |
| 237 | safetensors_path, |
| 238 | "--graph", "nllb600", |
| 239 | "-o", os.path.join(args.out, "nllb600.maml"), |
| 240 | "--print-digest", |
| 241 | ) |
| 242 | os.remove(safetensors_path) |
| 243 | |
| 244 | print(f"\n{args.out}") |
| 245 | for name in sorted(os.listdir(args.out)): |
| 246 | path = os.path.join(args.out, name) |
| 247 | if os.path.isfile(path): |
| 248 | size = os.path.getsize(path) |
| 249 | print(f" {name}: {size} bytes ({size / (1 << 20):.1f} MiB) {sha256(path)}") |
| 250 | return 0 |
| 251 | |
| 252 | |
| 253 | if __name__ == "__main__": |
| 254 | raise SystemExit(main()) |