exp: chess contract A, RP vs GRP, history oracle and measured floor
grp - rp_wide -0.0057 +/- 0.0021 (1/8 seeds). The history oracle, which hands the memoryless model each piece's own past, pays +0.0014 +/- 0.0011 on 4/8 seeds -- ambiguous. The constant-displacement floor sits at mse 0.0556 / acc 0.3325 against the arms' 0.0389 / 0.414, so the models do learn from the board; it is the per-entity history specifically that this readout does not use.
This commit is contained in:
1 file changed
+70
-21
+70
-21
@@ -37,6 +37,8 @@ from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
|||||||
|
|
||||||
PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn"
|
PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn"
|
||||||
ATTR_DIM = 8 # piece type (6), colour (1), "this is the one that moves" (1)
|
ATTR_DIM = 8 # piece type (6), colour (1), "this is the one that moves" (1)
|
||||||
|
ORACLES = ("none", "history") # `history` hands each entity its own past, the thing memory
|
||||||
|
# would have to learn to carry. Opt-in, and it only adds columns.
|
||||||
SCALE = 7.0 # file/rank -> [0,1], so a relation lands in [-1,1] like the torus does
|
SCALE = 7.0 # file/rank -> [0,1], so a relation lands in [-1,1] like the torus does
|
||||||
|
|
||||||
|
|
||||||
@@ -54,6 +56,7 @@ class Ply:
|
|||||||
target: np.ndarray # (2,) that piece's displacement
|
target: np.ndarray # (2,) that piece's displacement
|
||||||
dests: np.ndarray # (L, 2) displacement of every legal move from its square
|
dests: np.ndarray # (L, 2) displacement of every legal move from its square
|
||||||
true_dest: int # index into dests
|
true_dest: int # index into dests
|
||||||
|
past: np.ndarray # (N, 2*hist) each entity's previous squares, as displacements
|
||||||
|
|
||||||
|
|
||||||
def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
|
def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
|
||||||
@@ -79,9 +82,10 @@ def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
|
|||||||
id_at[r_to] = id_at.pop(r_from)
|
id_at[r_to] = id_at.pop(r_from)
|
||||||
|
|
||||||
|
|
||||||
def plies(game: chess.pgn.Game) -> list[Ply]:
|
def plies(game: chess.pgn.Game, hist: int = 3) -> list[Ply]:
|
||||||
board = game.board()
|
board = game.board()
|
||||||
id_at = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)}
|
id_at = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)}
|
||||||
|
seen: dict[int, list[int]] = {}
|
||||||
out: list[Ply] = []
|
out: list[Ply] = []
|
||||||
for move in game.mainline_moves():
|
for move in game.mainline_moves():
|
||||||
piece = board.piece_at(move.from_square)
|
piece = board.piece_at(move.from_square)
|
||||||
@@ -101,6 +105,14 @@ def plies(game: chess.pgn.Game) -> list[Ply]:
|
|||||||
mover = squares.index(move.from_square)
|
mover = squares.index(move.from_square)
|
||||||
attrs[mover, 7] = 1.0
|
attrs[mover, 7] = 1.0
|
||||||
|
|
||||||
|
# each entity's own past, relative to where it stands now. Absent history is zero,
|
||||||
|
# which is also "I am where I was" -- the ambiguity costs the oracle, never the model.
|
||||||
|
past = np.zeros((len(squares), 2 * hist), dtype=np.float32)
|
||||||
|
for k, sq in enumerate(squares):
|
||||||
|
for j, old in enumerate(reversed(seen.get(id_at[sq], [])[-hist:])):
|
||||||
|
past[k, 2 * j] = (chess.square_file(old) - chess.square_file(sq)) / SCALE
|
||||||
|
past[k, 2 * j + 1] = (chess.square_rank(old) - chess.square_rank(sq)) / SCALE
|
||||||
|
|
||||||
# every legal destination for that piece, as a displacement; promotions collapse
|
# every legal destination for that piece, as a displacement; promotions collapse
|
||||||
legal = list(dict.fromkeys(m.to_square for m in board.legal_moves
|
legal = list(dict.fromkeys(m.to_square for m in board.legal_moves
|
||||||
if m.from_square == move.from_square))
|
if m.from_square == move.from_square))
|
||||||
@@ -108,28 +120,30 @@ def plies(game: chess.pgn.Game) -> list[Ply]:
|
|||||||
(chess.square_rank(t) - chess.square_rank(move.from_square)) / SCALE]
|
(chess.square_rank(t) - chess.square_rank(move.from_square)) / SCALE]
|
||||||
for t in legal], dtype=np.float32)
|
for t in legal], dtype=np.float32)
|
||||||
j = legal.index(move.to_square)
|
j = legal.index(move.to_square)
|
||||||
out.append(Ply([id_at[sq] for sq in squares], attrs, coords, mover, dests[j], dests, j))
|
out.append(Ply([id_at[sq] for sq in squares], attrs, coords, mover, dests[j], dests, j,
|
||||||
|
past))
|
||||||
|
|
||||||
|
seen.setdefault(id_at[move.from_square], []).append(move.from_square)
|
||||||
advance_ids(board, move, piece, id_at)
|
advance_ids(board, move, piece, id_at)
|
||||||
board.push(move)
|
board.push(move)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
def load(n_games: int, min_plies: int = 20) -> list[list[Ply]]:
|
def load(n_games: int, hist: int = 3, min_plies: int = 20) -> list[list[Ply]]:
|
||||||
games: list[list[Ply]] = []
|
games: list[list[Ply]] = []
|
||||||
with open(PGN, encoding="utf-8", errors="replace") as fh:
|
with open(PGN, encoding="utf-8", errors="replace") as fh:
|
||||||
while len(games) < n_games:
|
while len(games) < n_games:
|
||||||
g = chess.pgn.read_game(fh)
|
g = chess.pgn.read_game(fh)
|
||||||
if g is None:
|
if g is None:
|
||||||
break
|
break
|
||||||
p = plies(g)
|
p = plies(g, hist)
|
||||||
if len(p) >= min_plies:
|
if len(p) >= min_plies:
|
||||||
games.append(p)
|
games.append(p)
|
||||||
return games
|
return games
|
||||||
|
|
||||||
|
|
||||||
def n_params(memory: bool, hidden: int, cppn_hidden: int) -> int:
|
def n_params(memory: bool, hidden: int, cppn_hidden: int, attr_dim: int = ATTR_DIM) -> int:
|
||||||
org = Organism(ATTR_DIM, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden, memory=memory)
|
org = Organism(attr_dim, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden, memory=memory)
|
||||||
return sum(p.numel() for p in org.parameters())
|
return sum(p.numel() for p in org.parameters())
|
||||||
|
|
||||||
|
|
||||||
@@ -145,7 +159,8 @@ def match_width(hidden: int, cppn_hidden: int) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
|
def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
|
||||||
opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool):
|
opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool,
|
||||||
|
oracle: bool):
|
||||||
"""One game as one continuous stream. Memory starts empty: new game, new pieces."""
|
"""One game as one continuous stream. Memory starts empty: new game, new pieces."""
|
||||||
memory: dict[int, torch.Tensor] = {}
|
memory: dict[int, torch.Tensor] = {}
|
||||||
pending: list[torch.Tensor] = []
|
pending: list[torch.Tensor] = []
|
||||||
@@ -153,7 +168,8 @@ def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
|
|||||||
with torch.set_grad_enabled(opt is not None):
|
with torch.set_grad_enabled(opt is not None):
|
||||||
for ply in game:
|
for ply in game:
|
||||||
coords = torch.from_numpy(ply.coords)
|
coords = torch.from_numpy(ply.coords)
|
||||||
pred, memory = org(torch.from_numpy(ply.attrs), flat_diff(coords), ply.ids,
|
attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs
|
||||||
|
pred, memory = org(torch.from_numpy(attrs), flat_diff(coords), ply.ids,
|
||||||
affect.axes, memory)
|
affect.axes, memory)
|
||||||
p = pred[ply.mover]
|
p = pred[ply.mover]
|
||||||
loss = ((p - torch.from_numpy(ply.target)) ** 2).mean() # masked to the mover
|
loss = ((p - torch.from_numpy(ply.target)) ** 2).mean() # masked to the mover
|
||||||
@@ -176,10 +192,32 @@ def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
|
|||||||
return affect, losses, hits, chance
|
return affect, losses, hits, chance
|
||||||
|
|
||||||
|
|
||||||
|
def run_constant(games: list[list[Ply]], seed: int) -> dict:
|
||||||
|
"""The floor: predict the mean displacement, ignore everything else.
|
||||||
|
|
||||||
|
Chance levels are measured here, never assumed. If a trained arm sits on this line it
|
||||||
|
learned nothing about the position and the arms cannot be told apart -- which is a fact
|
||||||
|
about the task, not about any mechanism in it.
|
||||||
|
"""
|
||||||
|
order = np.random.default_rng(seed).permutation(len(games))
|
||||||
|
cut = max(1, len(games) // 4)
|
||||||
|
mean = np.mean([p.target for gi in order[cut:] for p in games[gi]], 0)
|
||||||
|
mse, hits, chance = [], [], []
|
||||||
|
for gi in order[:cut]:
|
||||||
|
for ply in games[gi]:
|
||||||
|
mse.append(float(((mean - ply.target) ** 2).mean()))
|
||||||
|
hits.append(float(int(((ply.dests - mean) ** 2).sum(1).argmin()) == ply.true_dest))
|
||||||
|
chance.append(1.0 / len(ply.dests))
|
||||||
|
return dict(seed=seed, hidden=0, memory=False, oracle=False, params=2, plies=len(mse),
|
||||||
|
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
|
||||||
|
chance=statistics.fmean(chance))
|
||||||
|
|
||||||
|
|
||||||
def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, seed: int,
|
def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, seed: int,
|
||||||
lr: float, bptt: int, kappa: float, use_affect: bool) -> dict:
|
lr: float, bptt: int, kappa: float, use_affect: bool, oracle: bool = False) -> dict:
|
||||||
torch.manual_seed(seed)
|
torch.manual_seed(seed)
|
||||||
org = Organism(ATTR_DIM, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden,
|
attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0)
|
||||||
|
org = Organism(attr_dim, 2, 2, hidden_dim=hidden, cppn_hidden=cppn_hidden,
|
||||||
kappa=kappa, memory=memory)
|
kappa=kappa, memory=memory)
|
||||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
||||||
acfg, affect = AffectConfig(), Affect()
|
acfg, affect = AffectConfig(), Affect()
|
||||||
@@ -188,12 +226,12 @@ def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, see
|
|||||||
order = np.random.default_rng(seed).permutation(len(games))
|
order = np.random.default_rng(seed).permutation(len(games))
|
||||||
cut = max(1, len(games) // 4)
|
cut = max(1, len(games) // 4)
|
||||||
for gi in order[cut:]:
|
for gi in order[cut:]:
|
||||||
affect, *_ = _stream(org, games[gi], affect, acfg, opt, bptt, use_affect)
|
affect, *_ = _stream(org, games[gi], affect, acfg, opt, bptt, use_affect, oracle)
|
||||||
mse, hits, chance = [], [], []
|
mse, hits, chance = [], [], []
|
||||||
for gi in order[:cut]:
|
for gi in order[:cut]:
|
||||||
affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect)
|
affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect, oracle)
|
||||||
mse += l; hits += h; chance += c
|
mse += l; hits += h; chance += c
|
||||||
return dict(seed=seed, hidden=hidden, memory=memory,
|
return dict(seed=seed, hidden=hidden, memory=memory, oracle=oracle,
|
||||||
params=sum(p.numel() for p in org.parameters()), plies=len(mse),
|
params=sum(p.numel() for p in org.parameters()), plies=len(mse),
|
||||||
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
|
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
|
||||||
chance=statistics.fmean(chance))
|
chance=statistics.fmean(chance))
|
||||||
@@ -202,6 +240,7 @@ def run(games: list[list[Ply]], memory: bool, hidden: int, cppn_hidden: int, see
|
|||||||
def main() -> None:
|
def main() -> None:
|
||||||
ap = argparse.ArgumentParser()
|
ap = argparse.ArgumentParser()
|
||||||
ap.add_argument("--games", type=int, default=400)
|
ap.add_argument("--games", type=int, default=400)
|
||||||
|
ap.add_argument("--hist", type=int, default=3, help="past squares the oracle hands over")
|
||||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
||||||
ap.add_argument("--hidden", type=int, default=32)
|
ap.add_argument("--hidden", type=int, default=32)
|
||||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
ap.add_argument("--cppn-hidden", type=int, default=32)
|
||||||
@@ -210,20 +249,28 @@ def main() -> None:
|
|||||||
ap.add_argument("--kappa", type=float, default=0.0)
|
ap.add_argument("--kappa", type=float, default=0.0)
|
||||||
ap.add_argument("--affect", default="neutral", choices=("neutral", "stream"),
|
ap.add_argument("--affect", default="neutral", choices=("neutral", "stream"),
|
||||||
help="neutral holds psi at (0,0); stream runs the real EMA chain")
|
help="neutral holds psi at (0,0); stream runs the real EMA chain")
|
||||||
|
ap.add_argument("--arms", default="rp,grp,rp_wide,rp_oracle")
|
||||||
ap.add_argument("--out", default="results/chess.json")
|
ap.add_argument("--out", default="results/chess.json")
|
||||||
a = ap.parse_args()
|
a = ap.parse_args()
|
||||||
|
|
||||||
games = load(a.games)
|
games = load(a.games, a.hist)
|
||||||
wide = match_width(a.hidden, a.cppn_hidden)
|
wide = match_width(a.hidden, a.cppn_hidden)
|
||||||
arms = {"rp": (False, a.hidden), "grp": (True, a.hidden), "rp_wide": (False, wide)}
|
# rp_oracle is the ceiling, not a competitor: the memoryless model is HANDED each piece's
|
||||||
|
# own past, which is exactly what memory would have to learn to carry. If it does not pay,
|
||||||
|
# a memory null here is about the setup and not about memory.
|
||||||
|
all_arms = {"rp": (False, a.hidden, False), "grp": (True, a.hidden, False),
|
||||||
|
"rp_wide": (False, wide, False), "rp_oracle": (False, wide, True),
|
||||||
|
"constant": (False, 0, False)}
|
||||||
|
arms = {k: all_arms[k] for k in a.arms.split(",")}
|
||||||
print(f"{len(games)} games, {sum(len(g) for g in games)} plies; "
|
print(f"{len(games)} games, {sum(len(g) for g in games)} plies; "
|
||||||
f"width-matched memoryless arm at hidden={wide}\n")
|
f"width-matched memoryless arm at hidden={wide}\n")
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
for name, (mem, h) in arms.items():
|
for name, (mem, h, orc) in arms.items():
|
||||||
for seed in (int(s) for s in a.seeds.split(",")):
|
for seed in (int(s) for s in a.seeds.split(",")):
|
||||||
r = run(games, mem, h, a.cppn_hidden, seed, a.lr, a.bptt, a.kappa,
|
r = (run_constant(games, seed) if name == "constant" else
|
||||||
a.affect == "stream") | {"arm": name}
|
run(games, mem, h, a.cppn_hidden, seed, a.lr, a.bptt, a.kappa,
|
||||||
|
a.affect == "stream", orc)) | {"arm": name}
|
||||||
print(f"{name:<8} seed={seed} params={r['params']:<6} "
|
print(f"{name:<8} seed={seed} params={r['params']:<6} "
|
||||||
f"mse={r['mse']:.5f} acc={r['acc']:.4f}", flush=True)
|
f"mse={r['mse']:.5f} acc={r['acc']:.4f}", flush=True)
|
||||||
results.append(r)
|
results.append(r)
|
||||||
@@ -237,11 +284,13 @@ def main() -> None:
|
|||||||
print(f"{n:<8}{rs[0]['params']:>8}{statistics.fmean(r['mse'] for r in rs):>10.5f}"
|
print(f"{n:<8}{rs[0]['params']:>8}{statistics.fmean(r['mse'] for r in rs):>10.5f}"
|
||||||
f"{statistics.fmean(r['acc'] for r in rs):>9.4f}"
|
f"{statistics.fmean(r['acc'] for r in rs):>9.4f}"
|
||||||
f"{statistics.fmean(r['chance'] for r in rs):>9.4f}")
|
f"{statistics.fmean(r['chance'] for r in rs):>9.4f}")
|
||||||
for base in ("rp", "rp_wide"):
|
for top, base in (("grp", "rp"), ("grp", "rp_wide"), ("rp_oracle", "rp_wide")):
|
||||||
d = [g["acc"] - b["acc"] for g, b in zip(by["grp"], by[base])]
|
if top not in by or base not in by:
|
||||||
|
continue
|
||||||
|
d = [x["acc"] - y["acc"] for x, y in zip(by[top], by[base])]
|
||||||
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
|
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
|
||||||
verdict = "ambiguous" if abs(statistics.fmean(d)) < se else "a direction"
|
verdict = "ambiguous" if abs(statistics.fmean(d)) < se else "a direction"
|
||||||
print(f"\ngrp - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
||||||
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- {verdict}")
|
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- {verdict}")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user