Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / maia_quant_eval.py
maia_quant_eval.py357 lines · 15.2 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """How far can Maia3-5M be quantised? Measured on move agreement, not on cosine. |
| 3 | |
| 4 | Phase 8 of the Maia port, generalised to answer int4 as well as int8. |
| 5 | |
| 6 | `maml_convert.Fidelity` gates each tensor at cosine 0.999 against its fp32 self, but a cosine |
| 7 | gate says nothing about whether the model still picks the same move, which is the only thing |
| 8 | this model is for. A weight tensor can correlate at 0.99999 and still flip the top of a 40-way |
| 9 | distribution whose top two moves are 0.02 apart, and the endgame positions in |
| 10 | `maia_parity_fixture.json` have margins exactly that small. |
| 11 | |
| 12 | So this quantises the kernels `collect_maia` emits, dequantises them, loads them back into the |
| 13 | reference model, and compares **the move it plays** against fp32 over a few hundred real |
| 14 | positions. |
| 15 | |
| 16 | # The schemes |
| 17 | |
| 18 | `--bits 8` is what this runtime already implements: symmetric absmax, one scale per output |
| 19 | channel, no zero point, scale rounded to fp16. `maml_convert.quantise_per_channel` verbatim. |
| 20 | |
| 21 | `--bits 4` is the same arithmetic at 7 levels instead of 127, and it is only interesting with |
| 22 | `--group`: a whole output row sharing one scale has to represent 352 weights with 15 codes, |
| 23 | which is not enough. Sub-row groups are what llama.cpp's Q4_0 does, and they cost one extra |
| 24 | fp16 scale per group. **Nothing in `:library:ml` can read either grouped or 4-bit weights |
| 25 | today** — this measures whether it would be worth building, not something that exists. |
| 26 | |
| 27 | # What is not measured |
| 28 | |
| 29 | Device fp16 rounding of the *activations*. Both sides here are fp32 activations, so this |
| 30 | isolates weight quantisation. `maia_parity.py` measures the rest, and it is the harness that |
| 31 | would have to be re-run against a real quantised `.maml` before shipping one. |
| 32 | |
| 33 | Run: |
| 34 | |
| 35 | python scripts/ml/maia_quant_eval.py --checkpoint .../maia3-5m.pt --bits 8 |
| 36 | python scripts/ml/maia_quant_eval.py --checkpoint .../maia3-5m.pt --bits 4 --group 32 |
| 37 | """ |
| 38 | |
| 39 | import argparse |
| 40 | import os |
| 41 | import sys |
| 42 | |
| 43 | import numpy as np |
| 44 | |
| 45 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 46 | ROOT = os.path.dirname(os.path.dirname(HERE)) |
| 47 | sys.path.insert(0, HERE) |
| 48 | |
| 49 | import maml_convert # noqa: E402 |
| 50 | from maia_parity import CONFIG, Spec, encode_planes, legal_mask, move_name # noqa: E402 |
| 51 | |
| 52 | # The parameter-name suffixes that become `1x1` convolution kernels in the `.maml`, and so the |
| 53 | # ones a quantising collector would touch. `in_proj_weight` is fused q/k/v and is handled |
| 54 | # separately: the file holds three kernels, so it gets three independent scale vectors. |
| 55 | KERNELS = ( |
| 56 | "token_projection.weight", |
| 57 | "linear1.weight", |
| 58 | "linear2.weight", |
| 59 | "sm2.weight", |
| 60 | "sm3.weight", |
| 61 | "out_proj.weight", |
| 62 | "proj_sq_from.weight", |
| 63 | "proj_sq_to.weight", |
| 64 | "promo_bias_proj.weight", |
| 65 | ) |
| 66 | |
| 67 | |
| 68 | def quantise(weight, bits, group): |
| 69 | """`weight` round-tripped through `bits`-bit symmetric absmax with `group`-wide scales. |
| 70 | |
| 71 | At `bits=8` and `group=0` this is `maml_convert.quantise_per_channel` reproduced: absmax |
| 72 | over the whole output row, `absmax / 127`, round half away from zero, scale stored fp16. |
| 73 | The reproduction is asserted against the real function in [`check_against_converter`], so |
| 74 | the two cannot drift. |
| 75 | |
| 76 | A `group` splits each output row into spans that carry their own scale. That is the only |
| 77 | thing that makes 4 bits usable — 15 codes across a 352-wide row throws away most of the |
| 78 | resolution — and it is what the runtime would have to learn to read. |
| 79 | """ |
| 80 | limit = float(2 ** (bits - 1) - 1) |
| 81 | rows = np.ascontiguousarray(weight, np.float32).reshape(weight.shape[0], -1) |
| 82 | width = rows.shape[1] |
| 83 | span = width if group in (0, None) else min(group, width) |
| 84 | |
| 85 | out = np.empty_like(rows) |
| 86 | scales = 0 |
| 87 | for start in range(0, width, span): |
| 88 | block = rows[:, start:start + span] |
| 89 | absmax = np.abs(block).max(axis=1) |
| 90 | scale = np.where(absmax > 0, absmax / limit, 1.0).astype(np.float32) |
| 91 | # Round half away from zero, as `np.round` does not: it rounds half to even, which |
| 92 | # biases a symmetric weight distribution towards the even codes. |
| 93 | codes = np.floor(np.abs(block) / scale[:, None] + 0.5) * np.sign(block) |
| 94 | codes = np.clip(codes, -limit, limit) |
| 95 | # The scale is stored fp16 beside the weights, so the reconstruction a shader performs |
| 96 | # uses the *rounded* scale. Rounding it here means the error measured is the error the |
| 97 | # device would have, not an optimistic one. |
| 98 | scale = scale.astype(np.float16).astype(np.float32) |
| 99 | out[:, start:start + span] = codes * scale[:, None] |
| 100 | scales += rows.shape[0] |
| 101 | return out.reshape(weight.shape), scales |
| 102 | |
| 103 | |
| 104 | def check_against_converter(): |
| 105 | """Fail unless `quantise(.., 8, 0)` is `maml_convert.quantise_per_channel` exactly. |
| 106 | |
| 107 | The whole comparison rests on this arm being the shipped quantiser rather than a plausible |
| 108 | reimplementation of it, so it is checked rather than commented. |
| 109 | """ |
| 110 | rng = np.random.default_rng(3) |
| 111 | for shape in [(16, 32), (7, 5), (64, 1)]: |
| 112 | weight = rng.standard_normal(shape).astype(np.float32) |
| 113 | codes, scale = maml_convert.quantise_per_channel(weight) |
| 114 | want = codes.astype(np.float32) * scale[:, None] |
| 115 | got, _ = quantise(weight, 8, 0) |
| 116 | if not np.allclose(want, got, atol=0, rtol=0): |
| 117 | raise SystemExit( |
| 118 | f"the 8-bit arm has drifted from maml_convert.quantise_per_channel at {shape}" |
| 119 | ) |
| 120 | |
| 121 | |
| 122 | def quantise_state(state, bits, group): |
| 123 | """A copy of `state` with every convolution kernel round-tripped, and the scale count.""" |
| 124 | import torch |
| 125 | |
| 126 | out = {} |
| 127 | scales = 0 |
| 128 | for name, value in state.items(): |
| 129 | array = value.numpy() |
| 130 | if name.endswith("in_proj_weight"): |
| 131 | # Split, quantise each third, rejoin: the file holds three kernels with three |
| 132 | # independent scale vectors, so quantising the fused tensor would share a scale |
| 133 | # across q, k and v and understate the resolution quantisation actually gets. |
| 134 | third = array.shape[0] // 3 |
| 135 | parts = [] |
| 136 | for index in range(3): |
| 137 | block, count = quantise(array[index * third:(index + 1) * third], bits, group) |
| 138 | parts.append(block) |
| 139 | scales += count |
| 140 | out[name] = torch.from_numpy(np.concatenate(parts, axis=0)) |
| 141 | elif name.endswith("smolgen_shared_weight") or name.endswith("smolgen_weight"): |
| 142 | # One kernel in the file, replicated eight times, so the eight aliases all get the |
| 143 | # same quantisation rather than eight independent ones. |
| 144 | block, count = quantise(array, bits, group) |
| 145 | out[name] = torch.from_numpy(block) |
| 146 | if name.endswith("smolgen_shared_weight"): |
| 147 | # Counted once here and multiplied by the replication in `file_sizes`. |
| 148 | scales += count |
| 149 | elif any(name.endswith(suffix) for suffix in KERNELS): |
| 150 | block, count = quantise(array, bits, group) |
| 151 | out[name] = torch.from_numpy(block) |
| 152 | scales += count |
| 153 | else: |
| 154 | out[name] = value |
| 155 | return out, scales |
| 156 | |
| 157 | |
| 158 | def file_sizes(checkpoint, bits, group): |
| 159 | """`(fp16_bytes, quantised_bytes, kernels)` for the `.maml` a converter would write. |
| 160 | |
| 161 | Measured off `collect_maia`'s own output rather than off the checkpoint, because the two |
| 162 | differ: the attention-bias weight is one parameter in the checkpoint and eight replicated |
| 163 | copies in the file, so it carries eight times its checkpoint weight in the saving. Deriving |
| 164 | it from the checkpoint is how the estimate goes wrong. |
| 165 | """ |
| 166 | import torch |
| 167 | from safetensors.torch import save_file |
| 168 | |
| 169 | repack = os.path.join(ROOT, "build", "maia", "_quant_eval.safetensors") |
| 170 | if not os.path.exists(repack): |
| 171 | os.makedirs(os.path.dirname(repack), exist_ok=True) |
| 172 | state = torch.load(checkpoint, map_location="cpu", weights_only=True) |
| 173 | aliased = [n for n in state if n.endswith("self_attn.smolgen_weight")] |
| 174 | save_file({k: v.clone() for k, v in state.items() if k not in aliased}, repack) |
| 175 | |
| 176 | get, _ = maml_convert.open_checkpoint(repack) |
| 177 | layers, tensors = maml_convert.collect_maia(get, maml_convert.CHECKPOINTS["maia"]) |
| 178 | |
| 179 | quantised_elems = 0 |
| 180 | fp16_elems = 0 |
| 181 | scale_elems = 0 |
| 182 | kernels = 0 |
| 183 | for layer in layers: |
| 184 | for at in range(layer.tensor_count): |
| 185 | array = np.asarray(tensors[layer.first_tensor + at]) |
| 186 | # A kernel is the rank-4 first tensor of a projection; everything else stays fp16. |
| 187 | if layer.op in ("Linear", "Smolgen") and at == 0 and array.ndim == 4: |
| 188 | quantised_elems += array.size |
| 189 | width = array.size // array.shape[0] |
| 190 | spans = 1 if group in (0, None) else -(-width // min(group, width)) |
| 191 | scale_elems += array.shape[0] * spans |
| 192 | kernels += 1 |
| 193 | else: |
| 194 | fp16_elems += array.size |
| 195 | fp16_bytes = (quantised_elems + fp16_elems) * 2 |
| 196 | # 4-bit weights pack two to a byte; a scale is fp16 either way. |
| 197 | per_weight = 1.0 if bits == 8 else bits / 8.0 |
| 198 | packed = int(np.ceil(quantised_elems * per_weight)) |
| 199 | return fp16_bytes, packed + (fp16_elems + scale_elems) * 2, kernels |
| 200 | |
| 201 | |
| 202 | def positions(count, seed): |
| 203 | """`count` positions reached by random legal play, so they are real and varied. |
| 204 | |
| 205 | Random rather than fixture: eight hand-picked positions cannot measure an agreement rate, |
| 206 | and what matters is how often quantisation changes the answer across the distribution of |
| 207 | positions a game actually visits — including the many where the top two moves are close. |
| 208 | """ |
| 209 | import chess |
| 210 | |
| 211 | rng = np.random.default_rng(seed) |
| 212 | out = [] |
| 213 | while len(out) < count: |
| 214 | board = chess.Board() |
| 215 | # A whole game of random play, sampling along the way, so openings, middlegames and |
| 216 | # endgames all appear in roughly the proportion a game spends in them. |
| 217 | for _ in range(rng.integers(20, 120)): |
| 218 | legal = list(board.legal_moves) |
| 219 | if not legal: |
| 220 | break |
| 221 | board.push(legal[rng.integers(len(legal))]) |
| 222 | if board.is_game_over(): |
| 223 | break |
| 224 | out.append(board.copy()) |
| 225 | if len(out) >= count: |
| 226 | break |
| 227 | return out[:count] |
| 228 | |
| 229 | |
| 230 | def best_legal(model, board, elo, torch): |
| 231 | """`(index, margin)` for the model's top legal move, and its lead over the runner-up.""" |
| 232 | planes = encode_planes(board) |
| 233 | squares = torch.from_numpy(planes.T.copy()) |
| 234 | tokens = torch.cat([squares.repeat(1, CONFIG["history"]), torch.zeros(64, 1)], dim=1) |
| 235 | with torch.no_grad(): |
| 236 | move, _value, _ponder = model( |
| 237 | tokens.unsqueeze(0), torch.tensor([float(elo)]), torch.tensor([float(elo)]) |
| 238 | ) |
| 239 | logits = move[0].numpy() |
| 240 | legal = legal_mask(board) |
| 241 | if legal.size == 0: |
| 242 | return None, 0.0 |
| 243 | ranked = np.sort(logits[legal])[::-1] |
| 244 | margin = float(ranked[0] - ranked[1]) if ranked.size > 1 else float("inf") |
| 245 | return int(legal[logits[legal].argmax()]), margin |
| 246 | |
| 247 | |
| 248 | def main(): |
| 249 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 250 | parser.add_argument("--checkpoint", required=True, help="maia3-5m.pt") |
| 251 | parser.add_argument("--bits", type=int, default=8, choices=[2, 3, 4, 5, 6, 8]) |
| 252 | parser.add_argument( |
| 253 | "--group", |
| 254 | type=int, |
| 255 | default=0, |
| 256 | help="weights per scale within an output row; 0 means one scale for the whole row", |
| 257 | ) |
| 258 | parser.add_argument("--positions", type=int, default=400) |
| 259 | parser.add_argument("--elo", type=int, default=1500) |
| 260 | parser.add_argument("--seed", type=int, default=11) |
| 261 | args = parser.parse_args() |
| 262 | |
| 263 | try: |
| 264 | import chess # noqa: F401 |
| 265 | import torch |
| 266 | except ImportError as missing: |
| 267 | raise SystemExit(f"needs torch and python-chess: {missing}") |
| 268 | |
| 269 | sys.path.insert(0, os.path.join(ROOT, "build", "maia", "src")) |
| 270 | try: |
| 271 | from maia3_models import MAIA3Model |
| 272 | except ImportError: |
| 273 | raise SystemExit("needs build/maia/src/maia3_models.py; see maia_parity.py's header") |
| 274 | |
| 275 | check_against_converter() |
| 276 | |
| 277 | state = torch.load(args.checkpoint, map_location="cpu", weights_only=True) |
| 278 | rename = lambda held: { # noqa: E731 |
| 279 | n.replace("smolgen_shared_weight", "gab_shared_weight").replace( |
| 280 | "self_attn.smolgen_weight", "self_attn.gab_weight" |
| 281 | ): v |
| 282 | for n, v in held.items() |
| 283 | } |
| 284 | |
| 285 | reference = MAIA3Model(Spec(CONFIG)) |
| 286 | reference.load_state_dict(rename(state), strict=True) |
| 287 | reference.eval() |
| 288 | |
| 289 | low_state, _ = quantise_state(state, args.bits, args.group) |
| 290 | low = MAIA3Model(Spec(CONFIG)) |
| 291 | low.load_state_dict(rename(low_state), strict=True) |
| 292 | low.eval() |
| 293 | |
| 294 | grouping = "per output channel" if not args.group else f"per {args.group} weights" |
| 295 | fp16_bytes, packed_bytes, kernels = file_sizes(args.checkpoint, args.bits, args.group) |
| 296 | print(f"int{args.bits}, {grouping}, over {kernels} kernels") |
| 297 | print( |
| 298 | f"file: {fp16_bytes / (1 << 20):.1f} MiB fp16 -> {packed_bytes / (1 << 20):.1f} MiB " |
| 299 | f"({100 * (fp16_bytes - packed_bytes) / fp16_bytes:.0f}% saved)" |
| 300 | ) |
| 301 | |
| 302 | # The same gate conversion applies, so a scheme that cannot pass it is reported as such |
| 303 | # rather than only being judged on moves. |
| 304 | worst = 1.0 |
| 305 | worst_name = "" |
| 306 | for name, value in state.items(): |
| 307 | if not (name.endswith(KERNELS) or name.endswith("in_proj_weight")): |
| 308 | continue |
| 309 | if name.endswith("self_attn.smolgen_weight"): |
| 310 | continue |
| 311 | flat = value.numpy().reshape(value.shape[0], -1).ravel() |
| 312 | back = low_state[name].numpy().reshape(value.shape[0], -1).ravel() |
| 313 | cosine = float(np.dot(flat, back) / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30)) |
| 314 | if cosine < worst: |
| 315 | worst, worst_name = cosine, name |
| 316 | verdict = "passes" if worst >= maml_convert.MIN_INT8_COSINE else "FAILS" |
| 317 | print( |
| 318 | f"worst per-tensor cosine {worst:.6f} ({worst_name}) " |
| 319 | f"\u2014 {verdict} the {maml_convert.MIN_INT8_COSINE} gate" |
| 320 | ) |
| 321 | |
| 322 | boards = positions(args.positions, args.seed) |
| 323 | print(f"\n{len(boards)} positions from random legal play, at elo {args.elo}\n") |
| 324 | |
| 325 | agreed = 0 |
| 326 | disagreements = [] |
| 327 | for board in boards: |
| 328 | want, margin = best_legal(reference, board, args.elo, torch) |
| 329 | got, _ = best_legal(low, board, args.elo, torch) |
| 330 | if want is None: |
| 331 | continue |
| 332 | if want == got: |
| 333 | agreed += 1 |
| 334 | else: |
| 335 | disagreements.append((margin, board.fen(), move_name(want), move_name(got))) |
| 336 | |
| 337 | rate = 100.0 * agreed / len(boards) |
| 338 | print(f"move agreement: {agreed}/{len(boards)} = {rate:.1f}%") |
| 339 | if disagreements: |
| 340 | disagreements.sort() |
| 341 | print("\nwhere they differ, closest margin first:") |
| 342 | for margin, fen, want, got in disagreements[:8]: |
| 343 | print(f" margin {margin:.4f} fp32 {want} quantised {got}") |
| 344 | print(f" {fen}") |
| 345 | # 0.1 is comfortably outside the deviation fp16 rounding alone produces, which |
| 346 | # `maia_parity.py` measures at 0.011 to 0.018. A disagreement wider than that is the |
| 347 | # quantisation changing the model's mind, not landing a coin flip the other way. |
| 348 | wide = [d for d in disagreements if d[0] > 0.1] |
| 349 | print( |
| 350 | f"\n{len(disagreements)} disagreements, {len(wide)} of them on a margin over 0.1 " |
| 351 | "(i.e. wider than fp16 rounding alone)" |
| 352 | ) |
| 353 | return 0 |
| 354 | |
| 355 | |
| 356 | if __name__ == "__main__": |
| 357 | raise SystemExit(main()) |