Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / maia_to_onnx.py
maia_to_onnx.py137 lines · 4.3 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """Export Maia3-5M to ONNX for the `:games:chess` ORT port. |
| 3 | |
| 4 | Reads the pinned `maia3-5m.pt` checkpoint through CSSLab/maia3's own `MAIA3Model` |
| 5 | (`build/maia/src/maia3_models.py`), renames the checkpoint's `smolgen_*` names to the |
| 6 | module's `gab_*` names (as `maia_parity.py` does), and exports a single static graph: |
| 7 | |
| 8 | tokens float32 [1, 64, 97] square-major planes x8 plies + clk column |
| 9 | self_elo float32 [1] 0..5000 |
| 10 | oppo_elo float32 [1] 0..5000 |
| 11 | -> moves float32 [1, 4352] from*64+to, then file-promotion head |
| 12 | |
| 13 | Only the move head is exported: value/ponder never leave the engine. Dropout is disabled |
| 14 | by `eval()` + `torch.no_grad()`; the export is fp32 (the app quantises nothing — the old |
| 15 | `.maml` was int8, the ONNX runs fp32 at 5.2M params, ~21 MB). |
| 16 | |
| 17 | Usage: |
| 18 | python scripts/ml/maia_to_onnx.py --checkpoint build/maia/ckpt/maia3-5m.pt \ |
| 19 | -o analysis/onnx_work/maia/maia3-5m.onnx |
| 20 | """ |
| 21 | |
| 22 | import argparse |
| 23 | import os |
| 24 | import sys |
| 25 | |
| 26 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 27 | ROOT = os.path.dirname(os.path.dirname(HERE)) |
| 28 | |
| 29 | CONFIG = { |
| 30 | "history": 8, |
| 31 | "use_padding": True, |
| 32 | "include_time_info": False, |
| 33 | "dim_emb": 128, |
| 34 | "num_blocks": 8, |
| 35 | "mlp_ratio": 2.0, |
| 36 | "dropout": 0.0, |
| 37 | "use_gab": True, |
| 38 | "use_relative_bias": False, |
| 39 | "use_absolute_pe": False, |
| 40 | "use_rms_norm": True, |
| 41 | "omit_qkv_biases": True, |
| 42 | "activation": "gelu", |
| 43 | "dim_vit": 256, |
| 44 | "head_hid_dim": 256, |
| 45 | "num_heads": 8, |
| 46 | "gab_gen_size": 64, |
| 47 | "gab_per_square_dim": 0, |
| 48 | "gab_intermediate_dim": 64, |
| 49 | } |
| 50 | |
| 51 | |
| 52 | class Spec: |
| 53 | def __init__(self, held): |
| 54 | self.__dict__.update(held) |
| 55 | |
| 56 | |
| 57 | def main(): |
| 58 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 59 | parser.add_argument("--checkpoint", required=True) |
| 60 | parser.add_argument("-o", "--out", required=True) |
| 61 | args = parser.parse_args() |
| 62 | |
| 63 | import torch |
| 64 | import torch.nn as nn |
| 65 | |
| 66 | sys.path.insert(0, os.path.join(ROOT, "build", "maia", "src")) |
| 67 | from maia3_models import MAIA3Model |
| 68 | |
| 69 | model = MAIA3Model(Spec(CONFIG)) |
| 70 | state = torch.load(args.checkpoint, map_location="cpu", weights_only=True) |
| 71 | renamed = { |
| 72 | name.replace("smolgen_shared_weight", "gab_shared_weight").replace( |
| 73 | "self_attn.smolgen_weight", "self_attn.gab_weight" |
| 74 | ): value |
| 75 | for name, value in state.items() |
| 76 | } |
| 77 | model.load_state_dict(renamed, strict=True) |
| 78 | model.eval() |
| 79 | |
| 80 | # The TorchScript exporter has no `aten::rms_norm` symbol. Replace every RMSNorm with |
| 81 | # the same math spelled out of portable ops (weight * x / sqrt(mean(x^2) + eps)). |
| 82 | class ManualRMSNorm(nn.Module): |
| 83 | def __init__(self, rms): |
| 84 | super().__init__() |
| 85 | self.weight = rms.weight |
| 86 | # `eps=None` means torch's default: float32 eps (2^-23), matching nets::maia. |
| 87 | self.eps = float(rms.eps) if rms.eps is not None else 1.1920929e-7 |
| 88 | |
| 89 | def forward(self, x): |
| 90 | mean_square = x.pow(2).mean(dim=-1, keepdim=True) |
| 91 | normalized = x * torch.rsqrt(mean_square + self.eps) |
| 92 | return normalized * self.weight |
| 93 | |
| 94 | def swap_rms(module): |
| 95 | for name, child in list(module.named_children()): |
| 96 | if isinstance(child, nn.RMSNorm): |
| 97 | module.add_module(name, ManualRMSNorm(child)) |
| 98 | else: |
| 99 | swap_rms(child) |
| 100 | |
| 101 | swap_rms(model) |
| 102 | |
| 103 | tokens = torch.zeros(1, 64, 97) |
| 104 | self_elo = torch.tensor([1500.0]) |
| 105 | oppo_elo = torch.tensor([1500.0]) |
| 106 | |
| 107 | class MoveHead(torch.nn.Module): |
| 108 | def __init__(self, base): |
| 109 | super().__init__() |
| 110 | self.base = base |
| 111 | |
| 112 | def forward(self, tokens, self_elos, oppo_elos): |
| 113 | move, _value, _ponder = self.base(tokens, self_elos, oppo_elos) |
| 114 | return move |
| 115 | |
| 116 | wrapped = MoveHead(model) |
| 117 | os.makedirs(os.path.dirname(os.path.abspath(args.out)), exist_ok=True) |
| 118 | torch.onnx.export( |
| 119 | wrapped, |
| 120 | (tokens, self_elo, oppo_elo), |
| 121 | args.out, |
| 122 | input_names=["tokens", "self_elo", "oppo_elo"], |
| 123 | output_names=["moves"], |
| 124 | dynamic_axes={ |
| 125 | "tokens": {0: "batch"}, |
| 126 | "self_elo": {0: "batch"}, |
| 127 | "oppo_elo": {0: "batch"}, |
| 128 | "moves": {0: "batch"}, |
| 129 | }, |
| 130 | opset_version=17, |
| 131 | dynamo=False, |
| 132 | ) |
| 133 | print(f"wrote {args.out}") |
| 134 | |
| 135 | |
| 136 | if __name__ == "__main__": |
| 137 | raise SystemExit(main()) |