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

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

fetch_maia.py282 lines · 11.5 KiBRaw
1#!/usr/bin/env python3
2"""Fetch Maia3-5M's checkpoint and build the `.maml` `:games:chess` bundles.
3
4Mirrors `fetch_nllb600.py`'s `.pt` handling and `fetch_tinyclip.py`'s output path: pin the
5HF revision, digest-check the download, assert the parameter inventory, repack the pickle
6as `.safetensors` (`maml_convert.open_checkpoint` reads safetensors and there is no
7`torch.load` in it), then convert to `maia3-5m.maml` in the app's assets directory.
8
9Unlike NLLB this is a **bundled asset**, not a runtime download: 14 MiB is small enough to
10ship, and the chess AI has to work offline. It replaces the 86 MB
11`nn-71d6d32cb962.nnue` Stockfish read.
12
13# The three pins, and what each one catches
14
15* **The checkpoint SHA-256** below. Catches an upstream re-upload at the same revision, or
16 a truncated download.
17* **The parameter inventory** `maml_convert.check_checkpoint` asserts (148 names after the
18 repack). Catches a transposed or resized checkpoint; `linear1 [512, 256]` against
19 `linear2 [256, 512]` is the asymmetric pair.
20* **The layer table digest** `maml_convert.EXPECTED_DIGEST["maia"]` pins (190 tensors).
21
22# The shared attention-bias weight
23
24`smolgen_shared_weight` is one parameter registered under nine names: itself, and
25`transformer.layers.N.self_attn.smolgen_weight` for all eight blocks. `CustomTransformerEncoder`
26assigns the same `nn.Parameter` into every block, so all nine entries alias one storage.
27
28[`check_shared`] asserts that — byte-identical *and* the same `data_ptr` — and the repack
29drops the eight extras, the way `fetch_nllb600.py` drops NLLB's three tied copies. If a
30future checkpoint gives each block its own bias weight the drop would silently discard
31seven real tensors, so it fails instead.
32
33# Elo, and what it means for the app
34
35Strength is a model **input** (`SelfElo` / `OppoElo`, 0..5000), not a search handicap, so
36this one file covers every difficulty. See `games/chess/.../MaiaEngine.kt` for the mapping.
37
38Usage:
39
40 python scripts/ml/fetch_maia.py # verify digests, build the .maml
41 python scripts/ml/fetch_maia.py --work DIR # keep the checkpoint somewhere specific
42 python scripts/ml/fetch_maia.py --print-digests # after an intentional upstream bump
43"""
44
45import argparse
46import hashlib
47import os
48import subprocess
49import sys
50import tempfile
51
52REPO = "UofTCSSLab/Maia3-5M"
53
54# Pinned commit. Re-pin with --print-digests after an intentional bump (and only then).
55REVISION = "b6559de2398d7140b985f28fd2c19fb5e47ddabe"
56
57HERE = os.path.dirname(os.path.abspath(__file__))
58ROOT = os.path.dirname(os.path.dirname(HERE))
59
60# A bundled asset, beside the app's other assets. `noCompress += "maml"` in
61# `games/chess/build.gradle.kts` keeps it page-aligned so `MaiaHandle` can open it as a
62# file descriptor and read it in place rather than copying it to internal storage.
63OUT = os.path.join(ROOT, "games", "chess", "src", "main", "assets")
64
65CHECKPOINT = "maia3-5m.pt"
66
67# SHA-256 of every file this reads, at the pinned revision.
68DIGESTS = {
69 CHECKPOINT: "ba14208b2992d85502f5fb501934abf6aaaeb355e9f3fdf90e326911f562524f",
70}
71
72# Transcribed from `maia3/model_registry.py`'s `BASE_SIZE_CONFIG` plus the `maia3-5m` row of
73# `MODEL_SPECS`, and asserted against the checkpoint's shapes below rather than trusted.
74# `nets::maia` is written against these.
75ARCHITECTURE = {
76 "dim_vit": 256,
77 "head_hid_dim": 256,
78 "num_heads": 8,
79 "num_blocks": 8,
80 "mlp_ratio": 2.0,
81 "history": 8,
82 "dim_emb": 128,
83 "gab_gen_size": 64,
84 "gab_intermediate_dim": 64,
85 # `gab_per_square_dim == 0` is what makes the bias generator pool the squares with a
86 # mean rather than running a per-square projection first — so there is no `sm1`, and
87 # `nets::maia::attention_bias` starts with a `global_avg_pool`.
88 "gab_per_square_dim": 0,
89 "use_gab": True,
90 "use_relative_bias": False,
91 "use_absolute_pe": False,
92 "use_rms_norm": True,
93 "omit_qkv_biases": True,
94 "include_time_info": False,
95 "activation": "gelu",
96}
97
98# Total parameters after the repack drops the eight aliased copies: 7,327,236 in the
99# checkpoint, minus 8 x 262,144.
100PARAMETERS = 5_230_084
101
102# The nine names the attention-bias weight appears under. Asserted to alias one storage
103# before conversion; only `smolgen_shared_weight` survives the repack.
104SHARED_COPIES = ["smolgen_shared_weight"] + [
105 f"transformer.layers.{index}.self_attn.smolgen_weight" for index in range(8)
106]
107
108
109def sha256(path):
110 digest = hashlib.sha256()
111 with open(path, "rb") as handle:
112 for block in iter(lambda: handle.read(1 << 20), b""):
113 digest.update(block)
114 return digest.hexdigest()
115
116
117def convert(script, *args):
118 """Run one of the sibling converters, letting its own output and exit code through."""
119 subprocess.run([sys.executable, os.path.join(HERE, script), *args], check=True, cwd=ROOT)
120
121
122def load(checkpoint_path):
123 import torch
124
125 return torch.load(checkpoint_path, map_location="cpu", weights_only=True)
126
127
128def check_shared(state):
129 """Fail unless all nine attention-bias names are one storage (so dropping eight is exact)."""
130 import torch
131
132 first = state[SHARED_COPIES[0]]
133 for name in SHARED_COPIES[1:]:
134 other = state[name]
135 if other.shape != first.shape or not bool(torch.equal(first, other)):
136 raise SystemExit(
137 f"{name} differs from {SHARED_COPIES[0]}: the blocks no longer share one "
138 "attention-bias weight, so dropping the per-block copies would lose seven "
139 "real tensors. nets::maia assumes one shared weight."
140 )
141 if other.data_ptr() != first.data_ptr():
142 raise SystemExit(
143 f"{name} is equal to {SHARED_COPIES[0]} but is a separate tensor. Equal by "
144 "coincidence is not shared; re-read the checkpoint before re-pinning."
145 )
146 print(f"attention-bias weight shared under {len(SHARED_COPIES)} names {list(first.shape)}")
147
148
149def check_architecture(state):
150 """Fail if the checkpoint's shapes are not the ones `nets::maia` hardcodes.
151
152 There is no `config.json` in this repo — the architecture lives in `model_registry.py`
153 on the Python side and in `nets::maia`'s constants on ours — so the shapes *are* the
154 config, and this reads them back out of the checkpoint.
155 """
156 dim = ARCHITECTURE["dim_vit"]
157 ffn = int(dim * ARCHITECTURE["mlp_ratio"])
158 heads, gen = ARCHITECTURE["num_heads"], ARCHITECTURE["gab_gen_size"]
159 want = {
160 "smolgen_shared_weight": (64 * 64, gen),
161 "elo_embedding_low.weight": (1, ARCHITECTURE["dim_emb"]),
162 "token_projection.weight": (dim, 12 * ARCHITECTURE["history"] + 2 * ARCHITECTURE["dim_emb"]),
163 "transformer.layers.0.self_attn.mha.in_proj_weight": (3 * dim, dim),
164 "transformer.layers.0.self_attn.sm2.weight": (ARCHITECTURE["gab_intermediate_dim"], dim),
165 "transformer.layers.0.self_attn.sm3.weight": (heads * gen, ARCHITECTURE["gab_intermediate_dim"]),
166 "transformer.layers.0.linear1.weight": (ffn, dim),
167 "transformer.layers.0.linear2.weight": (dim, ffn),
168 "promo_bias_proj.weight": (4, ARCHITECTURE["head_hid_dim"]),
169 }
170 wrong = {
171 name: (tuple(state[name].shape) if name in state else None, shape)
172 for name, shape in want.items()
173 if name not in state or tuple(state[name].shape) != shape
174 }
175 if wrong:
176 lines = "\n".join(f" {k}: {got} against {exp}" for k, (got, exp) in wrong.items())
177 raise SystemExit(
178 f"the checkpoint is not the architecture the runtime hardcodes:\n{lines}\n"
179 "nets::maia has these baked in, so re-read it before re-pinning."
180 )
181
182 # `omit_qkv_biases` and `use_rms_norm` are absences, so they are checked as absences.
183 for name in (
184 "transformer.layers.0.self_attn.mha.in_proj_bias",
185 "transformer.layers.0.self_attn.mha.out_proj.bias",
186 "transformer.layers.0.norm1.bias",
187 ):
188 if name in state:
189 raise SystemExit(
190 f"{name} is present, so this checkpoint is not omit_qkv_biases=True with "
191 "RMSNorm blocks. nets::maia synthesises zero biases and reads no beta."
192 )
193
194 total = sum(state[name].numel() for name in state if name not in SHARED_COPIES[1:])
195 if total != PARAMETERS:
196 raise SystemExit(f"{total} parameters after de-aliasing, not the pinned {PARAMETERS}")
197 print(f"{len(want)} shapes and {total} parameters match the hardcoded architecture")
198
199
200def to_safetensors(state, out_path):
201 """Repack as `.safetensors` (same values, indexed) for `open_checkpoint`."""
202 from safetensors.torch import save_file
203
204 # The eight per-block copies share storage with the shared weight (which is itself the
205 # proof they are shared), and safetensors refuses shared memory. Drop them, then clone
206 # so nothing else in the file is a view.
207 kept = {k: v.clone() for k, v in state.items() if k not in SHARED_COPIES[1:]}
208 save_file(kept, out_path)
209 print(f" (dropped {len(SHARED_COPIES) - 1} aliased attention-bias copies)")
210 print(f"repacked {len(kept)} tensors -> {os.path.basename(out_path)}")
211
212
213def main():
214 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
215 parser.add_argument("--work", help="where to keep the checkpoint (default: a temp directory)")
216 parser.add_argument("-o", "--out", default=OUT, help="where to write the .maml")
217 parser.add_argument(
218 "--print-digests",
219 action="store_true",
220 help="print the fetched files' SHA-256 instead of checking them, to re-pin after a bump",
221 )
222 parser.add_argument(
223 "--local", help="use an already-downloaded snapshot dir instead of downloading"
224 )
225 args = parser.parse_args()
226
227 try:
228 from huggingface_hub import snapshot_download
229 except ImportError:
230 raise SystemExit("needs huggingface_hub: python -m pip install huggingface_hub")
231 try:
232 import torch # noqa: F401
233 except ImportError:
234 raise SystemExit("needs torch to read the .pt: python -m pip install torch")
235
236 if args.local:
237 local = args.local
238 else:
239 work = args.work or os.path.join(tempfile.gettempdir(), "maia3-5m")
240 local = snapshot_download(
241 repo_id=REPO, revision=REVISION, allow_patterns=list(DIGESTS), local_dir=work
242 )
243 print(f"{REPO}@{REVISION[:12]} in {local}")
244
245 if args.print_digests:
246 for name in DIGESTS:
247 print(f' {name}: "{sha256(os.path.join(local, name))}",')
248 return 0
249
250 for name, expected in DIGESTS.items():
251 got = sha256(os.path.join(local, name))
252 if got != expected:
253 raise SystemExit(
254 f"{name}\n sha256 {got}\n pinned {expected}\n"
255 "The upstream checkpoint changed. Re-read it, check the Rust forward pass\n"
256 "still matches, then re-pin with --print-digests."
257 )
258 print(f"{len(DIGESTS)} upstream digests match")
259
260 state = load(os.path.join(local, CHECKPOINT))
261 check_shared(state)
262 check_architecture(state)
263
264 os.makedirs(args.out, exist_ok=True)
265 safetensors_path = os.path.join(args.out, "_maia3-5m.safetensors")
266 to_safetensors(state, safetensors_path)
267 convert(
268 "maml_convert.py",
269 safetensors_path,
270 "--graph", "maia",
271 "-o", os.path.join(args.out, "maia3-5m.maml"),
272 )
273 os.remove(safetensors_path)
274
275 built = os.path.join(args.out, "maia3-5m.maml")
276 size = os.path.getsize(built)
277 print(f"\n{built}: {size} bytes ({size / (1 << 20):.1f} MiB) {sha256(built)}")
278 return 0
279
280
281if __name__ == "__main__":
282 raise SystemExit(main())