maia: the Maia-3 network in plain Rust (human-like moves by rating)

The 5M model (8 transformer blocks with generated attention bias) computed with
plain f32 loops: no ML runtime, no Python. Weights in a small own format (f16,
10 MB) written by scripts/maia-convert.py from the published checkpoint; the
shared bias tensor is kept once. Agrees with the original PyTorch model to four
decimals on the reference positions (tests/reference.json, an ignored test that
needs the weights); about 85 ms per position on one CPU core. Also the
analyst's research for playing against it (docs/research/play-mode.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-25 03:56:45 +03:00
parent 4d3db2799a
commit 8b468f99a7
11 changed files with 1553 additions and 0 deletions

65
scripts/maia-convert.py Executable file
View file

@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Reads a PyTorch .pt (zip + pickle) without torch and writes our weights file:
magic b'MAIA3W02', u32 count, then per tensor: u16 name len, name, u8 ndim, u32 dims..., u64 offset;
then aligned f16 little-endian data. Usage: convert.py in.pt out.bin"""
import pickle, struct, sys, zipfile, collections
src, dst = sys.argv[1], sys.argv[2]
z = zipfile.ZipFile(src)
root = z.namelist()[0].split('/')[0]
pkl = z.read(f'{root}/data.pkl')
class Storage:
def __init__(self, key, dtype): self.key, self.dtype = key, dtype
def rebuild(storage, offset, size, stride, *rest):
return ('T', storage, offset, tuple(size), tuple(stride))
class U(pickle.Unpickler):
def find_class(self, mod, name):
if mod == 'torch._utils' and name == '_rebuild_tensor_v2': return rebuild
if mod == 'torch' and name.endswith('Storage'): return name
if mod == 'collections' and name == 'OrderedDict': return collections.OrderedDict
if mod == 'torch._utils' and name == '_rebuild_parameter':
return lambda t, *a: t
raise pickle.UnpicklingError(f'refused {mod}.{name}')
def persistent_load(self, pid):
_, dtype, key, loc, numel = pid
return Storage(key, dtype)
obj = U(__import__('io').BytesIO(pkl)).load()
sd = obj['model_state_dict'] if isinstance(obj, dict) and 'model_state_dict' in obj else obj
out = []
for name, t in sd.items():
if not (isinstance(t, tuple) and t and t[0] == 'T'): continue
_, st, off, size, stride = t
assert st.dtype == 'FloatStorage', (name, st.dtype)
raw = z.read(f'{root}/data/{st.key}')
n = 1
for d in size: n *= d
# contiguous check
exp = []; acc = 1
for d in reversed(size): exp.append(acc); acc *= d
assert tuple(reversed(exp)) == stride or n <= 1, (name, size, stride)
data = raw[off*4:(off+n)*4]
vals = struct.unpack(f'<{n}f', data)
data = struct.pack(f'<{n}e', *vals)
name = name.replace('smolgen', 'gab')
# The attention-bias weight is one tensor shared by all the layers: kept once.
if '.self_attn.gab_weight' in name: continue
out.append((name, size, data))
with open(dst, 'wb') as f:
f.write(b'MAIA3W02'); f.write(struct.pack('<I', len(out)))
header_len = 8 + 4 + sum(2 + len(n.encode()) + 1 + 4*len(s) + 8 for n, s, _ in out)
off = (header_len + 63) // 64 * 64
offs = []
for n, s, d in out:
offs.append(off); off += (len(d) + 63) // 64 * 64
for (n, s, d), o in zip(out, offs):
nb = n.encode(); f.write(struct.pack('<H', len(nb))); f.write(nb)
f.write(struct.pack('<B', len(s)))
for x in s: f.write(struct.pack('<I', x))
f.write(struct.pack('<Q', o))
for (n, s, d), o in zip(out, offs):
f.write(b'\0' * (o - f.tell())); f.write(d)
for n, s, _ in out: print(n, s)

53
scripts/maia-reference.py Executable file
View file

@ -0,0 +1,53 @@
#!/usr/bin/env python3
# Writes crates/maia/tests/reference.json from the original Maia-3 code and weights:
# python3 -m venv v && v/bin/pip install torch chess --index-url ... ; git clone https://github.com/CSSLab/maia3
# v/bin/python scripts/maia-reference.py maia3/ maia3-5m.pt crates/maia/tests/reference.json
import sys, json, types
sys.path.insert(0, sys.argv[1])
import torch, chess
from collections import deque
from maia3.models import MAIA3Model
from maia3.dataset import tokenize_board, get_legal_moves_mask, get_historical_tokens
from maia3.utils import get_all_possible_moves, mirror_move
from maia3.model_registry import resolve_model_spec, BASE_SIZE_CONFIG
spec = resolve_model_spec('maia3-5m')
cfg = types.SimpleNamespace(**spec.config); cfg.device='cpu'
cfg.include_time_info=False
model = MAIA3Model(cfg)
sd = torch.load(sys.argv[2], map_location='cpu', weights_only=True)
sd = sd.get('model_state_dict', sd)
model.load_state_dict({k.replace('smolgen','gab'):v for k,v in sd.items()}, strict=False)
model.eval()
moves = get_all_possible_moves(); idx = {m:i for i,m in enumerate(moves)}
cases = [
('startpos', [], 1500, 1500),
('startpos', ['e2e4'], 1100, 1900),
('startpos', ['e2e4','c7c5','g1f3','d7d6','d2d4','c5d4','f3d4','g8f6','b1c3'], 2200, 2200),
('fen 8/P7/8/8/8/8/k6K/8 w - - 0 1', [], 1500, 1500),
('fen r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1', [], 800, 2500),
]
out = []
for start, mv, se, oe in cases:
b = chess.Board() if start == 'startpos' else chess.Board(start[4:])
hist = deque(maxlen=8); hist.append(tokenize_board(b))
for m in mv:
b.push(chess.Move.from_uci(m)); hist.append(tokenize_board(b))
for use_hist in (False, True):
h = hist if use_hist else deque([tokenize_board(b)], maxlen=8)
t = get_historical_tokens(h, cfg, 0,0,0,0).unsqueeze(0)
with torch.no_grad():
lm, lv, _ = model(t, torch.tensor([se]), torch.tensor([oe]))
mask = get_legal_moves_mask(b, idx)
lg = lm[0].masked_fill(~mask, float('-inf'))
p = torch.softmax(lg, -1)
top = torch.topk(p, 5)
res = []
for pr, i in zip(top.values.tolist(), top.indices.tolist()):
u = moves[i]
if b.turn == chess.BLACK: u = mirror_move(u)
res.append([u, pr])
out.append({'start': start, 'moves': mv, 'self': se, 'oppo': oe, 'history': use_hist,
'top': res, 'value': torch.softmax(lv[0],-1).tolist(),
'raw0': lm[0][:8].tolist()})
json.dump(out, open(sys.argv[3],'w'), indent=1)
for o in out: print(o['start'][:20], len(o['moves']), o['history'], o['top'][:3], [round(v,3) for v in o['value']])