chess-nets / code /dev /chessnet.py
Asilarkness's picture
dev files: chessnet.py trtnet.py gmcts3.py diloco2.py kl_eval.py archzoo.py archtour.py queue_v46.txt scale_boot.sh sims_pre.sh
2153fb2 verified
Raw History Blame Contribute Delete
16.4 kB
"""chessnet.py: board features and the policy+value network.
Canonical view: the side to move always plays "up" as white (python-chess Board.mirror() when black is to move), so
one network serves both colours. A position is 12 bitboards (us P N B R Q K, them P N B R Q K) plus a flags word
(bits 0-3 castling us-K us-Q them-K them-Q, bits 4-7 en-passant file + 1). Moves are from*64 + to in that view
(promotions share the from-to slot; the engine promotes to a queen unless only an under-promotion is legal).
Net: input conv -> NB residual blocks (C channels, squeeze-excitation) -> policy head = attention between squares
(logit[from, to] = q_from . k_to / 8) and value head -> one logit for the side to move's expected score in [0, 1]."""
import chess
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
ATTN_IMPL = os.environ.get("CHESS_ATTN", "sdpa")
PIECES = (chess.PAWN, chess.KNIGHT, chess.BISHOP, chess.ROOK, chess.QUEEN, chess.KING)
N_PLANES = 17
def canon(board):
return board if board.turn == chess.WHITE else board.mirror()
def feats(board):
"""-> (12 bitboards as python ints, flags int) of the canonical board."""
b = canon(board)
bb = [b.pieces_mask(p, chess.WHITE) for p in PIECES] + [b.pieces_mask(p, chess.BLACK) for p in PIECES]
cr = b.castling_rights
fl = (bool(cr & chess.BB_H1) | bool(cr & chess.BB_A1) << 1 | bool(cr & chess.BB_H8) << 2 | bool(cr & chess.BB_A8) << 3)
if b.ep_square is not None:
fl |= (chess.square_file(b.ep_square) + 1) << 4
return bb, fl
def to_int64(bbs):
return np.array(bbs, dtype=np.uint64).view(np.int64)
def move_index(board, move):
"""Index of a move in the canonical from-to space."""
if board.turn == chess.WHITE:
return move.from_square * 64 + move.to_square
return chess.square_mirror(move.from_square) * 64 + chess.square_mirror(move.to_square)
def pack(bb):
"""bb [N, 12] int64 bitboards -> [N, 32] uint8: the piece id 0-12 of every square in 4 bits (square 2k in the low
nibble of byte k, 2k+1 in the high one). 38 bytes per position with flags / value / move instead of 102."""
bb = np.asarray(bb, dtype=np.int64).reshape(-1, 12)
ids = np.zeros((len(bb), 64), np.uint8)
sh = np.arange(64, dtype=np.int64)
for k in range(12):
ids[((bb[:, k:k + 1] >> sh) & 1).astype(bool)] = k + 1
return ids[:, 0::2] | (ids[:, 1::2] << 4)
def planes_packed(pk, fl):
"""pk [B, 32] uint8 (on any device), fl [B] int64 -> [B, 17, 8, 8] float planes, identical to planes()."""
ids = torch.stack([pk & 15, pk >> 4], -1).view(-1, 64).long() # [B, 64] piece id per square
x = F.one_hot(ids, 13)[..., 1:].transpose(1, 2).float() # [B, 12, 64]
return _with_flags(x, fl)
_BITS = {}
def planes(bb, fl):
"""bb [B, 12] int64, fl [B] int64 (on any device) -> [B, 17, 8, 8] float planes."""
dev = bb.device
if dev not in _BITS:
_BITS[dev] = (torch.arange(64, device=dev), torch.arange(4, device=dev))
x = ((bb[:, :, None] >> _BITS[dev][0]) & 1).float() # [B, 12, 64]
return _with_flags(x, fl)
def _with_flags(x, fl):
"""Piece planes [B, 12, 64] + flags -> [B, 17, 8, 8] (4 castling planes, en-passant target plane)."""
dev = x.device
if dev not in _BITS:
_BITS[dev] = (torch.arange(64, device=dev), torch.arange(4, device=dev))
b4 = _BITS[dev][1]
cast = ((fl[:, None] >> b4) & 1).float() # [B, 4]
epf = ((fl >> 4) & 15) - 1 # ep target square is on rank 6
ep = F.one_hot((40 + epf).clamp(min=0), 64).float() * (epf >= 0).float()[:, None] # no sync (no bool indexing)
x = torch.cat([x, cast[:, :, None].expand(-1, -1, 64), ep[:, None]], 1)
return x.view(-1, N_PLANES, 8, 8)
class Block(nn.Module):
def __init__(self, C):
super().__init__()
self.c1, self.b1 = nn.Conv2d(C, C, 3, padding=1, bias=False), nn.BatchNorm2d(C)
self.c2, self.b2 = nn.Conv2d(C, C, 3, padding=1, bias=False), nn.BatchNorm2d(C)
self.se1, self.se2 = nn.Linear(C, C // 4), nn.Linear(C // 4, 2 * C)
def forward(self, x):
h = F.relu(self.b1(self.c1(x)))
h = self.b2(self.c2(h))
w, b = self.se2(F.relu(self.se1(h.mean((2, 3))))).chunk(2, 1)
return F.relu(x + h * torch.sigmoid(w)[:, :, None, None] + b[:, :, None, None])
def rel_tables():
"""Square-pair geometry in the canonical view (us move up the board) and attack rules.
cls[i, j] (static): 0 same square, 1 orthogonally adjacent, 2 diagonally adjacent forward (rank up), 3 diagonally
adjacent backward, 4 same rank/file at distance >= 2, 5 same diagonal at distance >= 2, 6 knight jump, 7 unrelated.
btw[k, i*64 + j] = 1 if square k lies strictly between i and j on their line (classes 4 and 5).
At run time classes 4 / 5 split by the number of pieces in between: 4 / 5 = open line, 8 / 10 = one blocker
(x-ray, pin, discovered attack), 9 / 11 = two or more -> 12 relations.
Pieces: 0 empty, 1-6 our P N B R Q K, 7-12 their P N B R Q K. A[side, piece, rel] = 1 if that piece attacks along
that relation (their pawns attack backward, ours forward); X[side, piece, rel] = x-ray (slider, one blocker)."""
cls = torch.zeros(64, 64, dtype=torch.long)
btw = torch.zeros(64, 64 * 64)
for i in range(64):
ri, fi = divmod(i, 8)
for j in range(64):
rj, fj = divmod(j, 8)
dr, df = rj - ri, fj - fi
adr, adf = abs(dr), abs(df)
if i == j:
c = 0
elif max(adr, adf) == 1:
c = 1 if dr == 0 or df == 0 else (2 if dr > 0 else 3)
elif dr == 0 or df == 0:
c = 4
elif adr == adf:
c = 5
elif {adr, adf} == {1, 2}:
c = 6
else:
c = 7
cls[i, j] = c
if c in (4, 5):
sr, sf = (dr > 0) - (dr < 0), (df > 0) - (df < 0)
for k in range(1, max(adr, adf)):
btw[(ri + sr * k) * 8 + fi + sf * k, i * 64 + j] = 1
A, X = torch.zeros(2, 13, 12), torch.zeros(2, 13, 12)
for side in (0, 1):
P, N, B, R, Q, K = (6 * side + k for k in range(1, 7))
for piece, rels in ((P, [2] if side == 0 else [3]), (N, [6]), (B, [2, 3, 5]), (R, [1, 4]), (Q, [1, 2, 3, 4, 5]),
(K, [1, 2, 3])):
A[side, piece, rels] = 1
for piece, rels in ((B, [10]), (R, [8]), (Q, [8, 10])):
X[side, piece, rels] = 1
return cls, btw, A, X
class AttnBlock(nn.Module):
"""Chess-aware transformer layer over the 64 squares (pre-LayerNorm, H heads, FF of width ff*C).
The attention logit between squares i and j is q_i.k_j / sqrt(d) plus
* a learned bias per head and square pair (fixed geometry),
* a board-dependent bias generated from a compressed summary of the whole board (the "smolgen" idea of Leela
Chess Zero; the last projection `sg_out` is shared by all blocks),
* a relational bias rel_q[piece on i, relation(i, j)] + rel_k[piece on j, relation(i, j)], where the relation
knows the line type and how many pieces stand between i and j (open / x-ray / blocked), so every head sees
who can hit whom through the current blockers, recomputed for each position.
The output projections start at zero, so a new block is the identity until it learns something."""
def __init__(self, C, H=8, ff=2):
super().__init__()
self.H = H
self.ln1, self.ln2 = nn.LayerNorm(C), nn.LayerNorm(C)
self.qkv, self.proj = nn.Linear(C, 3 * C), nn.Linear(C, C)
self.ff1, self.ff2 = nn.Linear(C, ff * C), nn.Linear(ff * C, C)
self.bias = nn.Parameter(torch.zeros(H, 64, 64))
self.rel_q, self.rel_k = nn.Parameter(torch.zeros(H, 13 * 12)), nn.Parameter(torch.zeros(H, 13 * 12))
self.sg1, self.sg2, self.sg3 = nn.Linear(C, 16), nn.Linear(16 * 64, 256), nn.Linear(256, H * 256)
for m in (self.proj, self.ff2):
nn.init.zeros_(m.weight)
nn.init.zeros_(m.bias)
def forward(self, x, sg_out, rb): # x [B, 64, C]; rb [B, H, 64, 64] relational bias
B, T, C = x.shape
y = self.ln1(x)
s = F.silu(self.sg2(self.sg1(y).flatten(1))) # [B, 256] board summary
g = sg_out(self.sg3(s).view(B, self.H, 256)).view(B, self.H, 64, 64)
q, k, v = self.qkv(y).view(B, T, 3, self.H, C // self.H).permute(2, 0, 3, 1, 4)
m = (g + rb + self.bias).to(q.dtype)
if ATTN_IMPL == "manual": # plain softmax attention (T = 64 is tiny)
a = torch.softmax((q @ k.transpose(-1, -2)) * (C // self.H) ** -0.5 + m, -1) @ v
else:
a = F.scaled_dot_product_attention(q, k, v, attn_mask=m)
x = x + self.proj(a.transpose(1, 2).reshape(B, T, C))
return x + self.ff2(F.silu(self.ff1(self.ln2(x))))
def make_net(d):
"""Net of the shape stored in a checkpoint dict (C, NB, optional NA attention blocks, CF chess features);
{"LC0": <onnx path>} = a Leela Chess Zero net behind the same engine interface (lc0net.py)."""
if "LC0" in d:
from lc0net import Lc0Net
return Lc0Net(d)
if d.get("ARCH"): # archzoo.py net (architecture tournament): ZNet(legal=True) also takes the legal slots
from archzoo import make
return make(d["ARCH"])
return Net(d["C"], d["NB"], d.get("NA", 0), d.get("CF", 0), d.get("AUX", 0))
class Net(nn.Module):
"""Input conv -> NB conv residual blocks -> NA chess-aware attention blocks -> policy / value heads.
CF=1 adds exact chess features computed inside the net from the piece planes: 4 more input planes (how many of
our / their pieces attack each square, and x-ray attacks through one blocker) and a relational bias on the policy
logit of each from-to pair (piece on `from` x relation). All additions start at zero (no effect), so a trained
ResNet can be grown into this shape without changing its output (grow.py).
AUX=1 adds two auxiliary policy heads for training only (KataGo-style extra targets): the opponent's reply on
Stockfish's PV (in our view: squares mirrored) and our move after it. forward(x, aux=True) also returns their
[B, 4096] logits; play uses forward(x) -> (policy, value) as before."""
def __init__(self, C=128, NB=10, NA=0, CF=0, AUX=0):
super().__init__()
self.NA, self.CF, self.AUX = NA, CF, AUX
if AUX:
self.aux_q, self.aux_k = nn.Conv2d(C, 2 * 64, 1), nn.Conv2d(C, 2 * 64, 1)
self.inp = nn.Sequential(nn.Conv2d(N_PLANES + (4 if CF else 0), C, 3, padding=1, bias=False),
nn.BatchNorm2d(C), nn.ReLU())
self.blocks = nn.Sequential(*[Block(C) for _ in range(NB)])
if NA:
self.att = nn.ModuleList([AttnBlock(C) for _ in range(NA)])
self.sg_out = nn.Linear(256, 64 * 64, bias=False)
if CF:
self.pol_rel = nn.Parameter(torch.zeros(13 * 12))
if NA or CF:
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)
self.pq, self.pk = nn.Conv2d(C, 64, 1), nn.Conv2d(C, 64, 1)
self.v = nn.Sequential(nn.Conv2d(C, 32, 1), nn.ReLU(), nn.Flatten(), nn.Linear(32 * 64, 256), nn.ReLU(),
nn.Linear(256, 1))
def chess(self, x):
"""Piece planes -> context (piece id p [B,64] 0-12, one-hot relations laid out for the two batched matmuls
OHq [B*64(i), 12, 64(j)] and OHk [B*64(j), 12, 64(i)], 4 attack planes [B,4,8,8])."""
pcs = x[:, :12].flatten(2).to(self.btw.dtype) # [B, 12, 64] (fp32; half in a half net)
occ = pcs.sum(1)
p = (pcs.argmax(1) + 1) * (occ > 0) # [B, 64] piece id 0-12
nb = (occ @ self.btw).round().clamp(max=2).long().view(-1, 64, 64) # pieces strictly between i and j
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 # [B, 64(i), 64(j)] 0-11
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)
B = x.shape[0]
dt = torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled() else x.dtype
oh = F.one_hot(rel, 12).to(dt) # [B, i, j, c]
ohq = oh.permute(0, 1, 3, 2).reshape(B * 64, 12, 64)
ohk = oh.permute(0, 2, 3, 1).reshape(B * 64, 12, 64)
return p, ohq, ohk, (0.5 * att).view(-1, 4, 8, 8)
@staticmethod
def _side(p, tab, oh, dt):
"""tab [K, 13*12] -> out[b, k, s, t] = tab[k, p_s * 12 + rel(s, t)] laid out [B, 64(s), K, 64(t)]: an
embedding of the piece on s (K x 12 numbers) times the one-hot relation of each pair, as one batched matmul,
instead of a gather with 4096 indices per position into a 156-entry table (whose backward sorts them)."""
K = tab.shape[0]
m = F.embedding(p, tab.view(K, 13, 12).permute(1, 0, 2).reshape(13, K * 12)).to(dt) # [B, 64, K*12]
return torch.bmm(m.view(-1, K, 12), oh).view(p.shape[0], 64, K, 64)
def relbias(self, ctx):
"""Relational attention bias of all attention blocks at once: [B, NA*H, 64(i), 64(j)]."""
p, ohq, ohk = ctx[:3]
rq = torch.cat([b.rel_q for b in self.att]) # [NA*H, 156]
rk = torch.cat([b.rel_k for b in self.att])
return self._side(p, rq, ohq, ohq.dtype).permute(0, 2, 1, 3) + self._side(p, rk, ohk, ohk.dtype).permute(0, 2, 3, 1)
def trunk(self, x, ctx=None):
if (self.CF or self.NA) and ctx is None:
ctx = self.chess(x)
if self.CF:
x = torch.cat([x, ctx[3].to(x.dtype)], 1)
h = self.blocks(self.inp(x))
if self.NA:
B, C = h.shape[:2]
rb = self.relbias(ctx)
H = self.att[0].H
t = h.flatten(2).transpose(1, 2) # [B, 64 squares, C]
for n, blk in enumerate(self.att):
t = blk(t, self.sg_out, rb[:, n * H:(n + 1) * H])
h = t.transpose(1, 2).reshape(B, C, 8, 8)
return h
def heads(self, h, ctx=None):
q, k = self.pq(h).flatten(2), self.pk(h).flatten(2) # [B, 64(d), 64(sq)]
pol = torch.einsum("bds,bdt->bst", q, k).flatten(1) / 8.0 # [B, 4096] from*64 + to
if self.CF and ctx is not None:
pol = pol + self._side(ctx[0], self.pol_rel[None], ctx[1], ctx[1].dtype).flatten(1).to(pol.dtype)
return pol, self.v(h)[:, 0] # value logit
def forward(self, x, aux=False):
ctx = self.chess(x) if (self.CF or self.NA) else None
h = self.trunk(x, ctx)
pol, val = self.heads(h, ctx)
if not aux:
return pol, val
q = self.aux_q(h).flatten(2).reshape(h.shape[0], 2, 64, 64) # [B, head, d, sq]
k = self.aux_k(h).flatten(2).reshape(h.shape[0], 2, 64, 64)
a = torch.einsum("bhds,bhdt->bhst", q, k).flatten(2) / 8.0 # [B, 2, 4096]
return pol, val, a[:, 0], a[:, 1]
class ErrHead(nn.Module):
"""On top of the frozen trunk: predicts |net value - deep Stockfish value| (in [-1, 1] units) for a position,
i.e. how much a search would change the net's opinion. Used to decide which nodes are worth expanding."""
def __init__(self, C=128):
super().__init__()
self.f = nn.Sequential(nn.Conv2d(C, 16, 1), nn.ReLU(), nn.Flatten(), nn.Linear(16 * 64, 64), nn.ReLU(),
nn.Linear(64, 1), nn.Softplus())
def forward(self, h):
return self.f(h)[:, 0]