Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / maia_parity.py
maia_parity.py407 lines · 16.9 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Maia3 parity harness: the PyTorch checkpoint vs the converted `.maml` through the Rust. |
| 3 | |
| 4 | `onnx_parity.py` does not apply — there is no ONNX export of Maia3 at all — so this follows |
| 5 | `nllb_parity.py`'s precedent of a checkpoint-only harness, but goes further: rather than |
| 6 | comparing a NumPy re-implementation, it drives `reference.rs::dump_reference_output`, so the |
| 7 | thing under test is the **actual Rust plan** running the **actual converted weights**. |
| 8 | |
| 9 | Each fixture position goes through both sides and the 4352 move logits are compared: |
| 10 | |
| 11 | * the reference `MAIA3Model` in fp32, built from `maia3-5m.pt` with the architecture in |
| 12 | `maia3/model_registry.py`, encoded by `maia3/dataset.py::tokenize_board`; |
| 13 | * the Rust CPU interpreter running `nets::maia`'s plan over the `.maml`, fed the 12 planes |
| 14 | this script encodes independently. |
| 15 | |
| 16 | # Why this phase is the one that matters |
| 17 | |
| 18 | Every remaining risk in this model is a silent one. Square indexing, the mirror-and-swap for |
| 19 | black, the move vocabulary's ordering, the eight-fold attention-bias replication and the |
| 20 | post-norm block order all fail into logits that are finite, plausibly distributed and |
| 21 | completely wrong — there is no shape, no digest and no fidelity gate that catches any of |
| 22 | them. A wrong board encoding still plays legal chess, just badly. |
| 23 | |
| 24 | So the comparison is on the assembled 4352-vector, not on an intermediate, and the pass bar |
| 25 | is agreement on the **argmax move** as well as the numbers: a correlation of 0.999 with a |
| 26 | different best move is a failure, and it is the failure mode a subtly wrong encoding |
| 27 | produces. |
| 28 | |
| 29 | # The bar |
| 30 | |
| 31 | fp16 rounding plus int8 weight quantisation. `scripts/ml/maia_quant_eval.py` is what |
| 32 | established that int8 is safe here at all — it measures move agreement over hundreds of |
| 33 | positions, where this measures the whole logit vector over a handful of chosen ones. The two |
| 34 | answer different questions and both are needed: that one says the quantisation does not change |
| 35 | the model, this one says the runtime computes the same thing the checkpoint does. |
| 36 | |
| 37 | What is asserted is the correlation, the relative max deviation against the logit range, and |
| 38 | the argmax over the legal moves. |
| 39 | |
| 40 | Needs torch, python-chess and the checkpoint. Run after `fetch_maia.py`: |
| 41 | |
| 42 | python scripts/ml/maia_parity.py \ |
| 43 | --checkpoint ~/.cache/huggingface/.../maia3-5m.pt \ |
| 44 | --maml games/chess/src/main/assets/maia3-5m.maml |
| 45 | """ |
| 46 | |
| 47 | import argparse |
| 48 | import json |
| 49 | import math |
| 50 | import os |
| 51 | import subprocess |
| 52 | import sys |
| 53 | import tempfile |
| 54 | |
| 55 | import numpy as np |
| 56 | |
| 57 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 58 | ROOT = os.path.dirname(os.path.dirname(HERE)) |
| 59 | FIXTURE = os.path.join(HERE, "maia_parity_fixture.json") |
| 60 | |
| 61 | # `maia3/model_registry.py`: BASE_SIZE_CONFIG plus the maia3-5m row of MODEL_SPECS. |
| 62 | CONFIG = { |
| 63 | "history": 8, |
| 64 | "use_padding": True, |
| 65 | "include_time_info": False, |
| 66 | "dim_emb": 128, |
| 67 | "num_blocks": 8, |
| 68 | "mlp_ratio": 2.0, |
| 69 | "dropout": 0.0, |
| 70 | "use_gab": True, |
| 71 | "use_relative_bias": False, |
| 72 | "use_absolute_pe": False, |
| 73 | "use_rms_norm": True, |
| 74 | "omit_qkv_biases": True, |
| 75 | "activation": "gelu", |
| 76 | "dim_vit": 256, |
| 77 | "head_hid_dim": 256, |
| 78 | "num_heads": 8, |
| 79 | "gab_gen_size": 64, |
| 80 | "gab_per_square_dim": 0, |
| 81 | "gab_intermediate_dim": 64, |
| 82 | } |
| 83 | |
| 84 | # `maia3/dataset.py::PIECE_MAP`, as plane indices: white P,N,B,R,Q,K then black P,N,B,R,Q,K. |
| 85 | PIECE_ORDER = "PNBRQK" |
| 86 | |
| 87 | # The bound |
| 88 | # |
| 89 | # Set from measurement against the shipped int8 file, not chosen. The weights are int8 with a |
| 90 | # per-channel scale and the Rust interpreter rounds every intermediate store through fp16, so |
| 91 | # the gap against fp32 is dominated by the quantisation rather than by any one operation. |
| 92 | # |
| 93 | # Measured over the fixture: correlation 0.99978 to 0.99995, deviation 0.5% to 1.4% of the |
| 94 | # logit range. The endgames sit at the loose end of both because their logit range is the |
| 95 | # narrowest — a fixed absolute error is a larger fraction of a 5.7-wide spread than of a |
| 96 | # 14.8-wide one — not because anything is worse about them. |
| 97 | # |
| 98 | # These were 0.9999 and 1% when the file was fp16, where the deviation was 0.12% to 0.25%. |
| 99 | # What is asserted alongside them is the argmax over *legal* moves, and that is the assertion |
| 100 | # that actually protects the model: a bound loose enough to admit a real encoding bug would |
| 101 | # still be caught by the move disagreeing. |
| 102 | MIN_CORRELATION = 0.9997 |
| 103 | |
| 104 | # Max absolute deviation, as a fraction of the reference vector's range. |
| 105 | MAX_RELATIVE_DEVIATION = 0.02 |
| 106 | |
| 107 | |
| 108 | class Spec: |
| 109 | """The dotted-attribute config object `MAIA3Model` expects.""" |
| 110 | |
| 111 | def __init__(self, held): |
| 112 | self.__dict__.update(held) |
| 113 | |
| 114 | |
| 115 | def encode_planes(board): |
| 116 | """The 12 board planes as `[12, 64]` plane-major, mirrored and colour-swapped for black. |
| 117 | |
| 118 | Independent of `maia3.dataset.tokenize_board` on purpose: it is a re-derivation from the |
| 119 | same rules, so agreement means two readings of the encoding agree rather than one |
| 120 | reading agreeing with itself. It is also the reference for the Kotlin encoder, which |
| 121 | cannot import python-chess. |
| 122 | """ |
| 123 | import chess |
| 124 | |
| 125 | if board.turn == chess.BLACK: |
| 126 | board = board.mirror() |
| 127 | planes = np.zeros((12, 64), dtype=np.float32) |
| 128 | for square in chess.SQUARES: |
| 129 | piece = board.piece_at(square) |
| 130 | if piece is None: |
| 131 | continue |
| 132 | plane = PIECE_ORDER.index(piece.symbol().upper()) |
| 133 | if piece.color == chess.BLACK: |
| 134 | plane += 6 |
| 135 | planes[plane][square] = 1.0 |
| 136 | return planes |
| 137 | |
| 138 | |
| 139 | def reference_logits(model, planes, self_elo, oppo_elo): |
| 140 | """The checkpoint's own 4352 move logits for a board, in fp32.""" |
| 141 | import torch |
| 142 | |
| 143 | history = CONFIG["history"] |
| 144 | # `[64, 12]` square-major, repeated across the eight plies. `get_historical_tokens` pads |
| 145 | # a short history by repeating the earliest position, and with `use_uci_history=False` |
| 146 | # the deque holds only the current one — so all eight plies are this board. |
| 147 | squares = torch.from_numpy(planes.T.copy()) |
| 148 | tokens = squares.repeat(1, history) |
| 149 | # `forward` slices to `12 * history`, so the trailing clk_ponder column is not needed — |
| 150 | # but `get_historical_tokens` appends one, so include it and let the slice drop it. |
| 151 | tokens = torch.cat([tokens, torch.zeros(64, 1)], dim=1).unsqueeze(0) |
| 152 | with torch.no_grad(): |
| 153 | move, _value, _ponder = model( |
| 154 | tokens, |
| 155 | torch.tensor([float(self_elo)]), |
| 156 | torch.tensor([float(oppo_elo)]), |
| 157 | ) |
| 158 | return move[0].numpy().astype(np.float32) |
| 159 | |
| 160 | |
| 161 | def move_name(index): |
| 162 | """The vocabulary entry at `index`, as `maia3/utils.py::get_all_possible_moves` names it.""" |
| 163 | if index < 4096: |
| 164 | return f"{square_name(index // 64)}{square_name(index % 64)}" |
| 165 | at = index - 4096 |
| 166 | from_file, rest = divmod(at, 32) |
| 167 | to_file, piece = divmod(rest, 4) |
| 168 | return f"{'abcdefgh'[from_file]}7{'abcdefgh'[to_file]}8{'qrbn'[piece]}" |
| 169 | |
| 170 | |
| 171 | def square_name(square): |
| 172 | return f"{'abcdefgh'[square % 8]}{square // 8 + 1}" |
| 173 | |
| 174 | |
| 175 | def legal_mask(board): |
| 176 | """The vocabulary indices of `board`'s legal moves, mirrored for black as the model sees them. |
| 177 | |
| 178 | `maia3/dataset.py::get_legal_moves_mask`. This is the mask the app applies before it |
| 179 | samples, so it is the mask the comparison has to apply too: the raw 4352-vector scores |
| 180 | every from-to pair on the board, including the ~4000 that are not moves at all, and their |
| 181 | logits are unconstrained. Comparing an unmasked argmax reports a disagreement over two |
| 182 | illegal moves as a failure. |
| 183 | """ |
| 184 | import chess |
| 185 | |
| 186 | vocabulary = {move_name(index): index for index in range(4352)} |
| 187 | indices = [] |
| 188 | for move in board.legal_moves: |
| 189 | uci = move.uci() |
| 190 | if board.turn == chess.BLACK: |
| 191 | uci = mirror_uci(uci) |
| 192 | at = vocabulary.get(uci) |
| 193 | if at is not None: |
| 194 | indices.append(at) |
| 195 | return np.array(sorted(indices), dtype=np.int64) |
| 196 | |
| 197 | |
| 198 | def mirror_uci(uci): |
| 199 | """`maia3/utils.py::mirror_move`: flip both squares' ranks, keep the promotion piece.""" |
| 200 | flip = lambda square: f"{square[0]}{9 - int(square[1])}" # noqa: E731 |
| 201 | return flip(uci[:2]) + flip(uci[2:4]) + uci[4:] |
| 202 | |
| 203 | |
| 204 | def build_reference_binary(): |
| 205 | """Compile the Rust test binary once and return its path. |
| 206 | |
| 207 | One `cargo` invocation for the whole fixture rather than one per position. That is eight |
| 208 | times less process startup, and it also means a tree that is mid-edit somewhere else only |
| 209 | has to be buildable once, at the start, instead of staying buildable for the length of the |
| 210 | run. |
| 211 | """ |
| 212 | import json |
| 213 | |
| 214 | crate = os.path.join(ROOT, "library", "ml", "src", "main", "rust") |
| 215 | finished = subprocess.run( |
| 216 | [ |
| 217 | "cargo", "test", "--release", "-p", "modelrunner", "--lib", |
| 218 | "--no-run", "--message-format=json", |
| 219 | ], |
| 220 | check=True, |
| 221 | cwd=crate, |
| 222 | capture_output=True, |
| 223 | text=True, |
| 224 | ) |
| 225 | for line in finished.stdout.splitlines(): |
| 226 | try: |
| 227 | message = json.loads(line) |
| 228 | except json.JSONDecodeError: |
| 229 | continue |
| 230 | if message.get("reason") == "compiler-artifact" and message.get("executable"): |
| 231 | if message.get("target", {}).get("name") == "modelrunner": |
| 232 | return message["executable"] |
| 233 | raise SystemExit("cargo did not report a test binary for modelrunner") |
| 234 | |
| 235 | |
| 236 | def run_reference(binary, work, maml): |
| 237 | """Drive `dump_reference_output` for whatever is currently in `work/input.f32`. |
| 238 | |
| 239 | The output file is deleted first and its absence is fatal afterwards. That is not |
| 240 | belt-and-braces: the test is `#[ignore]`d and filtered by name, so a filter that matches |
| 241 | nothing exits 0 and leaves the *previous* position's output in place — and comparing every |
| 242 | position against one stale logit vector produces plausible-looking per-position |
| 243 | disagreements, because the legal-move mask still differs. It cost an afternoon once. |
| 244 | """ |
| 245 | written = os.path.join(work, "reference.f32") |
| 246 | if os.path.exists(written): |
| 247 | os.remove(written) |
| 248 | environment = dict( |
| 249 | os.environ, |
| 250 | PARITY_DIR=work, |
| 251 | PARITY_GRAPH="maia", |
| 252 | PARITY_WIDTH="64", |
| 253 | PARITY_MAML=os.path.abspath(maml), |
| 254 | ) |
| 255 | subprocess.run( |
| 256 | [binary, "dump_reference_output", "--ignored", "--nocapture"], |
| 257 | check=True, |
| 258 | env=environment, |
| 259 | ) |
| 260 | if not os.path.exists(written): |
| 261 | raise SystemExit( |
| 262 | f"{binary} ran but wrote no reference.f32 — the test filter matched nothing, " |
| 263 | "or the maia arm of dump_reference_output returned early." |
| 264 | ) |
| 265 | return np.fromfile(written, dtype=np.float32) |
| 266 | |
| 267 | |
| 268 | def main(): |
| 269 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 270 | parser.add_argument("--checkpoint", required=True, help="maia3-5m.pt") |
| 271 | parser.add_argument("--maml", required=True, help="the converted maia3-5m.maml") |
| 272 | parser.add_argument("--fixture", default=FIXTURE) |
| 273 | parser.add_argument("--work", help="keep the intermediates somewhere specific") |
| 274 | args = parser.parse_args() |
| 275 | |
| 276 | try: |
| 277 | import chess # noqa: F401 |
| 278 | import torch |
| 279 | except ImportError as missing: |
| 280 | raise SystemExit(f"needs torch and python-chess: {missing}") |
| 281 | |
| 282 | sys.path.insert(0, os.path.join(ROOT, "build", "maia", "src")) |
| 283 | try: |
| 284 | from maia3_models import MAIA3Model |
| 285 | except ImportError: |
| 286 | raise SystemExit( |
| 287 | "needs CSSLab/maia3's models.py at build/maia/src/maia3_models.py.\n" |
| 288 | "Fetch it with:\n" |
| 289 | " curl -o build/maia/src/maia3_models.py \\\n" |
| 290 | " https://raw.githubusercontent.com/CSSLab/maia3/main/maia3/models.py" |
| 291 | ) |
| 292 | |
| 293 | print("loading the reference model (fp32, CPU)...") |
| 294 | model = MAIA3Model(Spec(CONFIG)) |
| 295 | state = torch.load(args.checkpoint, map_location="cpu", weights_only=True) |
| 296 | # The checkpoint was saved from a build that called the attention bias "smolgen"; the |
| 297 | # module on `main` calls the same parameter `gab`. Renaming rather than loading loosely, |
| 298 | # so a genuinely missing tensor still fails. |
| 299 | renamed = { |
| 300 | name.replace("smolgen_shared_weight", "gab_shared_weight").replace( |
| 301 | "self_attn.smolgen_weight", "self_attn.gab_weight" |
| 302 | ): value |
| 303 | for name, value in state.items() |
| 304 | } |
| 305 | model.load_state_dict(renamed, strict=True) |
| 306 | model.eval() |
| 307 | |
| 308 | fixture = json.load(open(args.fixture, encoding="utf-8"))["positions"] |
| 309 | # Absolute, because the Rust binary is run from elsewhere. |
| 310 | work = os.path.abspath(args.work or tempfile.mkdtemp(prefix="maia_parity_")) |
| 311 | os.makedirs(work, exist_ok=True) |
| 312 | binary = build_reference_binary() |
| 313 | print(f"{len(fixture)} positions, intermediates in {work}\n") |
| 314 | |
| 315 | results = [] |
| 316 | for position in fixture: |
| 317 | import chess |
| 318 | |
| 319 | board = chess.Board(position["fen"]) |
| 320 | planes = encode_planes(board) |
| 321 | want = reference_logits(model, planes, position["self_elo"], position["oppo_elo"]) |
| 322 | |
| 323 | # The Rust side reads the 12 planes then the two elos, and does the history repeat |
| 324 | # and the elo blend itself — so both are inside the comparison rather than beside it. |
| 325 | feed = np.concatenate( |
| 326 | [planes.ravel(), np.array([position["self_elo"], position["oppo_elo"]], np.float32)] |
| 327 | ).astype(np.float32) |
| 328 | feed.tofile(os.path.join(work, "input.f32")) |
| 329 | |
| 330 | got = run_reference(binary, work, args.maml) |
| 331 | if got.size != want.size: |
| 332 | raise SystemExit(f"{position['name']}: torch has {want.size}, the runtime {got.size}") |
| 333 | |
| 334 | deviation = float(np.abs(want - got).max()) |
| 335 | spread = float(want.max() - want.min()) |
| 336 | relative = deviation / spread |
| 337 | correlation = float(np.corrcoef(want, got)[0, 1]) |
| 338 | |
| 339 | # Masked to the legal moves, which is what the app picks from. The unmasked argmax |
| 340 | # is meaningless: 4000-odd of the 4352 entries are not moves in this position and |
| 341 | # their logits are unconstrained, so two runs can disagree about the best illegal |
| 342 | # move while agreeing on every real one. |
| 343 | legal = legal_mask(board) |
| 344 | best_want = int(legal[want[legal].argmax()]) |
| 345 | best_got = int(legal[got[legal].argmax()]) |
| 346 | # How much room the top legal move has. A disagreement under the fp16 deviation is a |
| 347 | # near-tie, not an encoding bug, and this is what tells the two apart. |
| 348 | ranked = np.sort(want[legal])[::-1] |
| 349 | margin = float(ranked[0] - ranked[1]) if ranked.size > 1 else math.inf |
| 350 | results.append((position, correlation, relative, best_want, best_got, margin, deviation)) |
| 351 | |
| 352 | print(f"{position['name']}:") |
| 353 | print(f" {position['why']}") |
| 354 | print( |
| 355 | f" corr {correlation:.8f} max dev {deviation:.5f} " |
| 356 | f"({relative * 100:.3f}% of a {spread:.2f} range)" |
| 357 | ) |
| 358 | print( |
| 359 | f" best of {legal.size} legal: torch {move_name(best_want)} ({best_want}), " |
| 360 | f"runtime {move_name(best_got)} ({best_got}), margin {margin:.4f}\n" |
| 361 | ) |
| 362 | |
| 363 | # The black-to-move mirror is checked as a relation between two positions rather than |
| 364 | # against a number: startpos and startpos-black are the same board from the mover's own |
| 365 | # side, so they must encode identically and so must produce identical logits. |
| 366 | named = {p["name"]: rest for p, *rest in results} |
| 367 | if "startpos" in named and "startpos-black" in named: |
| 368 | same = named["startpos"][2] == named["startpos-black"][2] |
| 369 | print(f"the mirror: startpos and startpos-black agree on the best move: {same}") |
| 370 | if not same: |
| 371 | raise SystemExit( |
| 372 | "startpos and startpos-black chose different moves. They are the same " |
| 373 | "position from the mover's side, so the mirror-and-swap is wrong." |
| 374 | ) |
| 375 | |
| 376 | # The elo input has to reach the model, which the two ends of the range prove. |
| 377 | if "endgame-elo-floor" in named and "endgame-elo-ceiling" in named: |
| 378 | differ = named["endgame-elo-floor"][2] != named["endgame-elo-ceiling"][2] |
| 379 | print(f"the elo blend: floor and ceiling differ on the same board: {differ}") |
| 380 | |
| 381 | failures = [] |
| 382 | for position, correlation, relative, best_want, best_got, margin, deviation in results: |
| 383 | if correlation < MIN_CORRELATION: |
| 384 | failures.append(f"{position['name']}: correlation {correlation:.8f}") |
| 385 | if relative > MAX_RELATIVE_DEVIATION: |
| 386 | failures.append(f"{position['name']}: max deviation {relative * 100:.3f}% of range") |
| 387 | if best_want != best_got: |
| 388 | # A tie inside this position's own deviation is not a disagreement about the |
| 389 | # model, so it is reported and allowed. A clear preference that flipped is an |
| 390 | # encoding bug, and the margin is what tells the two apart. |
| 391 | note = ( |
| 392 | f"{position['name']}: torch plays {move_name(best_want)}, " |
| 393 | f"the runtime {move_name(best_got)} (margin {margin:.4f} against a " |
| 394 | f"{deviation:.4f} deviation)" |
| 395 | ) |
| 396 | if margin > 2.0 * deviation: |
| 397 | failures.append(note) |
| 398 | else: |
| 399 | print(f" tie inside the runtime's own deviation: {note}") |
| 400 | if failures: |
| 401 | raise SystemExit("\nPARITY FAILED\n " + "\n ".join(failures)) |
| 402 | print(f"\nPARITY OK over {len(results)} positions") |
| 403 | return 0 |
| 404 | |
| 405 | |
| 406 | if __name__ == "__main__": |
| 407 | raise SystemExit(main()) |