chess-nets / code /dev /archzoo.py
Asilarkness's picture
dev files: archzoo.py archtour.py tour_all.sh
111b982 verified
Raw History Blame Contribute Delete
16.7 kB
"""archzoo.py: the architecture tournament zoo (archtour.py). Every net maps planes [B, 17, 8, 8] (chessnet.planes, canonical view:
side to move plays up) -> (policy logits [B, 4096] on from*64+to, value logit [B]); a legal-move net also takes the legal slots li [B, K]
(0 = padding; slot 0 = a1a1 is never a legal move) and puts -1e4 on all other slots, so every variant is trained / evaluated by the
same code (training: cross-entropy to the Lc0 T3 policy over the legal moves + BCE to its value W + D/2).
Base A = a T1-class transformer built by us: 64 square tokens (17 input features each), pre-LN blocks of width C, H heads, FFN ff*C with
ReLU^2, "smolgen" (board-dependent attention bias from a compressed summary of the whole board, output projection shared by all layers),
policy = from-to attention (q_from . k_to / 8), value = per-square 32 -> 256 -> 1. NO convolutions, NO relational bias.
Variants (one change from A each, see VARIANTS):
V1 piece tokens: <= 32 piece tokens (type + square embedding) + 1 global token (castling / en passant); empty squares are implicit.
The relational bias replaces smolgen (smolgen needs a fixed 64 x 64 grid); compared with V7 (the same on 64 square tokens).
V7 square tokens, smolgen replaced by the chess relational bias (rel_q[piece on i, relation i-j] + rel_k[piece on j, relation];
the relation knows the line type and the number of blockers between i and j: chessnet.rel_tables)
V2 A + fixed geometric masks on 6 of 8 heads (rook lines / bishop lines / knight / king+pawn neighbourhood), 2 heads global
V3 A + exact features per square at the input: attackers of us / them, x-rays, hanging pieces (6 more planes)
V4 V3 + policy over the LEGAL moves only: logit = q_from . k_to / 8 + MLP(mover, captured piece, attackers of the target square)
V4a A trained with the legal-softmax loss (isolates the loss part of V4; the net is A)
V5 BatchNorm instead of LayerNorm (folds into the Linear layers at inference)
V6 value logit + learned linear function of the material difference (init = classical piece values)
V8 384 x 6 instead of 256 x 10 (a wider, shallower net at about the same time)
N Stockfish-style NNUE (HalfKAv2_hm: 32 king buckets x 11 piece types x 64 squares = 22528 features per perspective, feature
transformer 3072, pairwise-clipped-ReLU product, 8 layer stacks by piece count 3072 -> 15+1 -> 32 -> 1, PSQT skip) plus a
policy head (Linear on the transformed features -> 4096), because MCTS needs priors; value path is the SF one."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from chessnet import rel_tables
def relu2(x):
return F.relu(x) ** 2
class Geo(nn.Module):
"""Piece ids p [B, 64] (0 empty, 1-6 ours PNBRQK, 7-12 theirs), relation code rel [B, 64, 64] (0-11, chessnet.Net.chess) and
attack planes att [B, 4, 64] (our / their attackers, our / their x-ray attackers; 0.5 per attacker)."""
def __init__(self):
super().__init__()
cls, btw, A, X = rel_tables()
for k, t in (("cls", cls), ("btw", btw), ("A", A.view(2, -1)), ("X", X.view(2, -1))):
self.register_buffer(k, t, persistent=False)
def forward(self, x):
pcs = x[:, :12].flatten(2).to(self.btw.dtype)
occ = pcs.sum(1)
p = (pcs.argmax(1) + 1) * (occ > 0)
nb = (occ @ self.btw).round().clamp(max=2).long().view(-1, 64, 64)
c = self.cls.expand_as(nb)
rel = c + ((c == 4) & (nb == 1)) * 4 + ((c == 4) & (nb == 2)) * 5 + ((c == 5) & (nb == 1)) * 5 + ((c == 5) & (nb == 2)) * 6
iq = p[:, :, None] * 12 + rel
att = torch.stack([self.A[0][iq].sum(1), self.A[1][iq].sum(1), self.X[0][iq].sum(1), self.X[1][iq].sum(1)], 1)
return p, rel, 0.5 * att
class Norm(nn.Module):
def __init__(self, C, kind):
super().__init__()
self.bn = kind == "bn"
self.n = nn.BatchNorm1d(C) if self.bn else nn.LayerNorm(C)
def forward(self, x): # [B, T, C]
return self.n(x.transpose(1, 2)).transpose(1, 2) if self.bn else self.n(x)
# head g allows relations GEO_ALLOW[g] (rel codes of Geo): 0 same, 1 orth adjacent, 2 diag fwd, 3 diag back, 4 / 8 / 9 orth line open /
# one blocker / more, 5 / 10 / 11 the same on diagonals, 6 knight, 7 unrelated
GEO_ALLOW = [{0, 1, 4, 8}, {0, 1, 4, 8}, {0, 2, 3, 5, 10}, {0, 2, 3, 5, 10}, {0, 6}, {0, 1, 2, 3}]
class Blk(nn.Module):
def __init__(self, C, H, ff, norm, smol, rel, geo, T):
super().__init__()
self.H, self.smol, self.rel, self.geo = H, smol, rel, geo
self.n1, self.n2 = Norm(C, norm), Norm(C, norm)
self.qkv, self.proj = nn.Linear(C, 3 * C), nn.Linear(C, C)
self.f1, self.f2 = nn.Linear(C, ff * C), nn.Linear(ff * C, C)
if smol:
self.sg1, self.sg2, self.sg3 = nn.Linear(C, 16), nn.Linear(16 * T, 256), nn.Linear(256, H * 256)
if rel:
self.rq, self.rk = nn.Parameter(torch.zeros(13 * 12, H)), nn.Parameter(torch.zeros(13 * 12, H))
for m in (self.proj, self.f2):
nn.init.zeros_(m.weight)
nn.init.zeros_(m.bias)
def forward(self, x, sg_out, ctx):
B, T, C = x.shape
y = self.n1(x)
q, k, v = self.qkv(y).view(B, T, 3, self.H, C // self.H).permute(2, 0, 3, 1, 4)
m = ctx.get("kmask", 0.0)
if self.smol:
m = m + sg_out(self.sg3(F.silu(self.sg2(self.sg1(y).flatten(1)))).view(B, self.H, 256)).view(B, self.H, 64, 64)
if self.rel:
m = m + (F.embedding(ctx["iq"], self.rq) + F.embedding(ctx["ik"], self.rk)).permute(0, 3, 1, 2)
if self.geo:
m = m + ctx["gmask"]
s = (q @ k.transpose(-1, -2)) * (C // self.H) ** -0.5
a = torch.softmax(s + (m.to(s.dtype) if torch.is_tensor(m) else m), -1) @ v
x = x + self.proj(a.transpose(1, 2).reshape(B, T, C))
return x + self.f2(relu2(self.f1(self.n2(x))))
class ZNet(nn.Module):
def __init__(self, C=256, L=10, H=8, ff=2, norm="ln", smol=True, rel=False, geo=False, feat=False, tok=False, legal=False,
mat=False, D=64):
super().__init__()
self.C, self.tok, self.feat, self.legal, self.mat, self.use_geo = C, tok, feat, legal, mat, rel or geo or feat or legal or tok
T = 33 if tok else 64
if self.use_geo:
self.geo = Geo()
if geo:
allow = torch.zeros(H, 12, dtype=torch.bool)
for h in range(H):
for r in (GEO_ALLOW[h] if h < len(GEO_ALLOW) else range(12)):
allow[h, r] = True
self.register_buffer("allow", allow, persistent=False)
if tok:
self.pemb, self.semb = nn.Embedding(13, C), nn.Embedding(64, C)
self.gemb, self.gtok = nn.Linear(4 + 64, C), nn.Parameter(torch.zeros(C))
else:
self.emb = nn.Linear(17 + (6 if feat else 0), C)
self.pos = nn.Parameter(torch.randn(64, C) * 0.02)
self.blocks = nn.ModuleList([Blk(C, H, ff, norm, smol, rel, geo, T) for _ in range(L)])
self.sg_out = nn.Linear(256, 64 * 64, bias=False) if smol else None
self.nf = Norm(C, norm)
self.pq, self.pk = nn.Linear(C, D), nn.Linear(C, D)
self.D = D
if tok:
self.pk_e, self.pg = nn.Parameter(torch.zeros(64, D)), nn.Linear(C, D)
self.v1, self.v2 = nn.Linear(3 * C, 256), nn.Linear(256, 1)
else:
self.vh, self.v1, self.v2 = nn.Linear(C, 32), nn.Linear(32 * 64, 256), nn.Linear(256, 1)
if legal:
self.mv_p, self.mv_c = nn.Embedding(13, 32), nn.Embedding(13, 32)
self.mv_1, self.mv_2 = nn.Linear(64 + 4, 64), nn.Linear(64, 1)
nn.init.zeros_(self.mv_2.weight)
nn.init.zeros_(self.mv_2.bias)
if mat:
self.mw = nn.Linear(5, 1)
with torch.no_grad():
self.mw.weight.copy_(torch.tensor([[0.25, 0.8, 0.8, 1.2, 2.4]]))
self.mw.bias.zero_()
def _context(self, x, p, rel, att, idx=None):
"""Attention context: relational-bias indices, geometric masks, key mask."""
ctx = {}
if self.tok:
B = x.shape[0]
r = rel.gather(1, idx[:, :, None].expand(-1, -1, 64)).gather(2, idx[:, None, :].expand(-1, idx.shape[1], -1)) # [B, 32, 32]
pt = p.gather(1, idx)
r33 = F.pad(r, (1, 0, 1, 0), value=7)
p33 = torch.cat([torch.zeros_like(pt[:, :1]), pt], 1)
rel, p = r33, p33
ctx["iq"] = p[:, :, None] * 12 + rel
ctx["ik"] = p[:, None, :] * 12 + rel
if hasattr(self, "allow"):
ctx["gmask"] = torch.where(self.allow[:, rel].permute(1, 0, 2, 3), 0.0, -1e4) # [B, H, 64, 64]
return ctx
def forward_core(self, x, li=None):
B = x.shape[0]
if self.use_geo:
p, rel, att = self.geo(x)
if self.tok:
occ = x[:, :12].flatten(2).sum(1) # [B, 64]
score = occ * 100 - torch.arange(64, device=x.device).to(occ.dtype)
idx = score.topk(32, dim=1).indices # occupied squares, low index first
valid = occ.gather(1, idx) > 0.5
g = self.gemb(torch.cat([x[:, 12:16, 0, 0], x[:, 16].flatten(1)], 1))[:, None] + self.gtok
t = torch.cat([g, self.pemb(p.gather(1, idx)) + self.semb(idx)], 1) # [B, 33, C]
ctx = self._context(x, p, rel, att, idx)
ctx["kmask"] = torch.cat([torch.ones_like(valid[:, :1]), valid], 1)[:, None, None, :].to(t.dtype).sub(1.0).mul(1e4)
else:
f = x.flatten(2) # [B, 17, 64]
if self.feat:
pu, pt = (p >= 1) & (p <= 6), p >= 7
hu = (pu & (att[:, 1] > 0) & (att[:, 0] == 0)).to(f.dtype)
ht = (pt & (att[:, 0] > 0) & (att[:, 1] == 0)).to(f.dtype)
f = torch.cat([f, att.to(f.dtype), hu[:, None], ht[:, None]], 1)
t = self.emb(f.transpose(1, 2)) + self.pos
ctx = self._context(x, p, rel, att) if self.use_geo and any(b.rel or b.geo for b in self.blocks) else {}
for blk in self.blocks:
t = blk(t, self.sg_out, ctx)
h = self.nf(t)
if self.tok:
ht = h[:, 1:]
q_t, k_t = self.pq(ht), self.pk(ht)
sq = torch.where(valid, idx, torch.full_like(idx, 64))[:, :, None].expand(-1, -1, self.D)
Q = torch.zeros(B, 65, self.D, dtype=q_t.dtype, device=x.device).scatter(1, sq, q_t)[:, :64]
kE = (self.pk_e[None] + self.pg(h[:, 0])[:, None]).to(k_t.dtype)
K = torch.cat([kE, torch.zeros_like(kE[:, :1])], 1).scatter(1, sq, k_t)[:, :64]
vm = valid[:, :, None].to(ht.dtype)
pooled = torch.cat([(ht * vm).sum(1) / vm.sum(1).clamp(min=1), ht.masked_fill(vm == 0, -1e4).max(1).values, h[:, 0]], 1)
val = self.v2(F.relu(self.v1(pooled)))[:, 0]
else:
Q, K = self.pq(h), self.pk(h)
val = self.v2(F.relu(self.v1(F.relu(self.vh(h)).flatten(1))))[:, 0]
if self.mat:
pc = x[:, :12].flatten(2).sum(2)
val = val + self.mw((pc[:, :5] - pc[:, 6:11]).to(val.dtype))[:, 0]
if self.legal and li is not None:
fr, to = li // 64, li % 64
qf = Q.gather(1, fr[:, :, None].expand(-1, -1, self.D))
kt = K.gather(1, to[:, :, None].expand(-1, -1, self.D))
a = att.gather(2, to[:, None, :].expand(-1, 4, -1)).transpose(1, 2) * 2.0 # [B, K, 4]
f = torch.cat([self.mv_p(p.gather(1, fr)), self.mv_c(p.gather(1, to)), a.to(qf.dtype)], -1)
lg = (qf * kt).sum(-1) / 8.0 + self.mv_2(relu2(self.mv_1(f)))[..., 0]
return lg.masked_fill(li == 0, -1e4), val
return torch.einsum("bsd,btd->bst", Q, K).flatten(1) / 8.0, val
def forward(self, x, li=None):
pol, val = self.forward_core(x, li)
if self.legal and li is not None:
pol = torch.full((x.shape[0], 4096), -1e4, dtype=pol.dtype, device=x.device).scatter(1, li, pol)
return pol, val
def _piece_maps():
# plane order: us P N B R Q K, them P N B R Q K -> feature piece index (kings of both sides share one index)
return torch.tensor([0, 1, 2, 3, 4, 10, 5, 6, 7, 8, 9, 10]), torch.tensor([5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 10])
class NNUE(nn.Module):
def __init__(self, FT=3072, L2=15, L3=32, nb=8):
super().__init__()
self.FT, self.L2, self.nb = FT, L2, nb
self.ft, self.ftb = nn.Embedding(22528 + 1, FT, padding_idx=22528), nn.Parameter(torch.zeros(FT))
nn.init.normal_(self.ft.weight, std=0.03)
with torch.no_grad():
self.ft.weight[22528].zero_()
self.psqt = nn.Embedding(22528 + 1, nb, padding_idx=22528)
nn.init.zeros_(self.psqt.weight)
self.l1 = nn.Linear(FT, nb * (L2 + 1))
self.l2w, self.l2b = nn.Parameter(torch.randn(nb, 2 * L2, L3) * 0.2), nn.Parameter(torch.zeros(nb, L3))
self.l3w, self.l3b = nn.Parameter(torch.randn(nb, L3) * 0.2), nn.Parameter(torch.zeros(nb))
self.pol = nn.Linear(FT, 4096)
mu, mt = _piece_maps()
self.register_buffer("mu", mu, persistent=False)
self.register_buffer("mt", mt, persistent=False)
def features(self, x):
"""Active HalfKAv2_hm indices [B, 32] for us and for them (their view: ranks flipped, colours swapped), 22528 = padding."""
B = x.shape[0]
pl = x[:, :12].flatten(1) # [B, 768]
v, j = pl.topk(32, dim=1)
plane, sq = j // 64, j % 64
ok = v > 0.5
out = []
for side in (0, 1):
ks = x[:, 5 + 6 * side].flatten(1).argmax(1)
s = sq
if side: # their view: ranks flipped
ks, s = (7 - ks // 8) * 8 + ks % 8, (7 - s // 8) * 8 + s % 8
mir = (ks % 8) >= 4 # king on files e-h: mirror the files
kf = torch.where(mir, 7 - ks % 8, ks % 8)
bucket = (ks // 8) * 4 + kf
s = torch.where(mir[:, None], s - s % 8 + 7 - s % 8, s)
pidx = (self.mt if side else self.mu)[plane]
idx = bucket[:, None] * 704 + pidx * 64 + s
out.append(torch.where(ok, idx, torch.full_like(idx, 22528)))
return out[0], out[1], ok.sum(1)
def forward(self, x, li=None):
fu, ft, npc = self.features(x)
du, dt = x.dtype, self.ft.weight.dtype
acc_u = self.ft(fu).sum(1) + self.ftb
acc_t = self.ft(ft).sum(1) + self.ftb
ps = (self.psqt(fu).sum(1) - self.psqt(ft).sum(1)) * 0.5 # [B, nb]
def pw(a):
h = a.shape[1] // 2
return a[:, :h].clamp(0, 1) * a[:, h:].clamp(0, 1)
z = torch.cat([pw(acc_u), pw(acc_t)], 1) # [B, FT] after the pairwise product
bk = ((npc - 1) // 4).clamp(0, self.nb - 1).long()
o = self.l1(z).view(-1, self.nb, self.L2 + 1)
o = o.gather(1, bk[:, None, None].expand(-1, 1, self.L2 + 1))[:, 0] # [B, 16]
h1, skip = o[:, :self.L2], o[:, self.L2]
h = torch.cat([h1.clamp(0, 1) ** 2, h1.clamp(0, 1)], 1) # [B, 30]
w2, b2 = self.l2w[bk], self.l2b[bk]
h = (torch.bmm(h[:, None].to(w2.dtype), w2)[:, 0] + b2).clamp(0, 1)
w3, b3 = self.l3w[bk], self.l3b[bk]
val = (h * w3.to(h.dtype)).sum(1) + b3.to(h.dtype) + skip + ps.gather(1, bk[:, None])[:, 0]
return self.pol(z), val
VARIANTS = {
"A": dict(), "A1": dict(), "V1": dict(tok=True, smol=False, rel=True), "V7": dict(smol=False, rel=True), "V2": dict(geo=True),
"V3": dict(feat=True), "V4a": dict(), "V4": dict(feat=True, legal=True), "V5": dict(norm="bn"), "V6": dict(mat=True),
"V8": dict(C=384, L=6), "V46": dict(feat=True, legal=True, mat=True),
}
LEGAL_LOSS = {"V4a"} # trained with the legal-softmax loss (V4's own logits are legal-only already)
NEEDS_LI = {"V4", "V46"}
def base(name):
"""Round-2 runs reuse a variant under another result name: A_r2 = A, V46_r2 = V46, N_r2 = N."""
return name.split("_")[0]
def make(name):
if base(name) == "N":
return NNUE()
return ZNet(**VARIANTS[base(name)])