Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70ddc7a856 | ||
|
|
cde475016f | ||
|
|
2470370a4e | ||
|
|
6e3326426e | ||
|
|
e7737b8138 | ||
|
|
f49840f73d | ||
|
|
f89472dca3 | ||
|
|
2b11e2acd2 | ||
|
|
1c28987649 | ||
|
|
8ea61f9617 | ||
|
|
ceb98ce33c |
No files matched your search
@@ -39,6 +39,14 @@ directory.
|
||||
5602. A number comparing them is confounded 3.9x and is not a memory result. See
|
||||
`results/frozen.md` §1d, which also records why "capacity" was the wrong word for that
|
||||
margin in the first place.
|
||||
- **Verify the model can represent the domain before asking what memory adds.** Every chess
|
||||
null before `results/chess_reach.md` was measured on a kernel that could not tell a knight
|
||||
from a bishop — the type was in `attrs`, so it could only *scale* one shared geometry, and
|
||||
the knight's L scored exactly zero on 8/8 seeds. Those nulls are facts about that setup and
|
||||
not about memory. Before a mechanism comparison, measure whether the model has learned the
|
||||
domain's own structure; a null on a model that has not is uninterpretable. This is the
|
||||
sibling of the oracle rule: the oracle asks whether the information pays, this asks whether
|
||||
the architecture can hold it.
|
||||
- **Pre-register when the result could be argued either way.** State the success criterion,
|
||||
the seed count, and what counts as failure, in `.sdd/progress.md`, before the run. Then
|
||||
accept what comes back. No re-running with adjusted criteria.
|
||||
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
"""Move prediction as a distribution over legal destinations, not a regression to their mean.
|
||||
|
||||
`results/chess_move.md` measured the mismatch this file exists to remove. MSE on a displacement
|
||||
vector fits the CONDITIONAL MEAN of the destinations: a knight with five legal squares has a
|
||||
mean pointing at none of them. History shifts the distribution over destinations -- that is what
|
||||
`chess_history.md` measured, +0.034 with a non-linear decoder -- and barely moves the mean, so
|
||||
an MSE readout discards the shape of information history carries. The evidence is direct:
|
||||
putting the piece type into the kernel improved MSE 0.03888 -> 0.03547 and made accuracy
|
||||
*worse*, 0.4144 -> 0.3998. Objective and question pointed in opposite directions.
|
||||
|
||||
So: change the metric, not the baseline. Same target, same chance level (0.3618, uniform among
|
||||
legal), same conditioning. Only the readout changes -- logits over the 15x15 grid of relative
|
||||
offsets, cross-entropy restricted to the legal ones. Still contract A: supervised, no opponent,
|
||||
no reward.
|
||||
|
||||
Offsets rather than absolute squares for the reason `chess_reach.md` gives: the CPPN sees only
|
||||
r_ij, so an entity's representation is translation-invariant and an absolute target is
|
||||
unanswerable by construction.
|
||||
|
||||
`rp_oracle` is the gate, as in every configuration before this one. If handing the model each
|
||||
piece's own past does not pay here either, per-entity history has no job under contract A and
|
||||
the line closes with a number.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from ailed import Affect, Organism, detach_memory
|
||||
from chess_domain import ATTR_DIM, flat_diff, load
|
||||
from chess_reach import GRID
|
||||
|
||||
|
||||
def n_params(memory: bool, hidden: int, cppn_hidden: int, n_edge: int) -> int:
|
||||
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=n_edge, hidden_dim=hidden,
|
||||
cppn_hidden=cppn_hidden, memory=memory)
|
||||
return sum(q.numel() for q in org.parameters())
|
||||
|
||||
|
||||
def match_width(hidden: int, cppn_hidden: int, n_edge: int) -> int:
|
||||
"""The memoryless width matching the gated model's parameter count, AT THIS TARGET DIM.
|
||||
|
||||
With 225 outputs the readout dominates, so a width matched at target_dim=2 is wrong by
|
||||
several times over. `frozen.md` §1d is why the match happens at all.
|
||||
"""
|
||||
target = n_params(True, hidden, cppn_hidden, n_edge)
|
||||
return min(range(hidden, 8 * hidden),
|
||||
key=lambda h: abs(n_params(False, h, cppn_hidden, n_edge) - target))
|
||||
|
||||
|
||||
def offsets(dests: np.ndarray) -> np.ndarray:
|
||||
"""(L,2) scaled displacements -> (L,) cells of the 15x15 offset grid."""
|
||||
d = np.rint(dests * 7).astype(int)
|
||||
return (d[:, 1] + 7) * 15 + (d[:, 0] + 7)
|
||||
|
||||
|
||||
def _stream(org, game, opt, bptt: int, oracle: bool, edges: bool, nostate: bool = False):
|
||||
memory: dict[int, torch.Tensor] = {}
|
||||
pending, losses, hits, chance = [], [], [], []
|
||||
zero = Affect().axes
|
||||
with torch.set_grad_enabled(opt is not None):
|
||||
for ply in game:
|
||||
n = len(ply.ids)
|
||||
attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs
|
||||
et = None
|
||||
if edges:
|
||||
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
|
||||
et = t[:, None].expand(n, n).contiguous()
|
||||
pred, memory = org(torch.from_numpy(attrs), flat_diff(torch.from_numpy(ply.coords)),
|
||||
ply.ids, zero, {} if nostate else memory, edge_types=et)
|
||||
legal = torch.from_numpy(offsets(ply.dests))
|
||||
logits = pred[ply.mover][legal] # only the legal destinations
|
||||
loss = torch.nn.functional.cross_entropy(logits[None, :],
|
||||
torch.tensor([ply.true_dest]))
|
||||
losses.append(loss.item())
|
||||
hits.append(float(int(logits.detach().argmax()) == ply.true_dest))
|
||||
chance.append(1.0 / len(legal))
|
||||
if opt is None:
|
||||
continue
|
||||
pending.append(loss)
|
||||
if len(pending) == bptt:
|
||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
||||
pending = []; memory = detach_memory(memory)
|
||||
if opt is not None and pending:
|
||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
||||
return losses, hits, chance
|
||||
|
||||
|
||||
def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int,
|
||||
oracle: bool, edges: bool, nostate: bool = False) -> dict:
|
||||
torch.manual_seed(seed)
|
||||
attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0)
|
||||
org = Organism(attr_dim, 2, GRID, n_edge_types=6 if edges else 1, hidden_dim=hidden,
|
||||
cppn_hidden=cppn_hidden, kappa=0.0, memory=memory)
|
||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
||||
order = np.random.default_rng(seed).permutation(len(games))
|
||||
cut = max(1, len(games) // 4)
|
||||
for gi in order[cut:]:
|
||||
_stream(org, games[gi], opt, bptt, oracle, edges, nostate)
|
||||
loss, hits, chance = [], [], []
|
||||
for gi in order[:cut]:
|
||||
l, h, c = _stream(org, games[gi], None, bptt, oracle, edges, nostate)
|
||||
loss += l; hits += h; chance += c
|
||||
return dict(seed=seed, memory=memory, oracle=oracle, nostate=nostate, hidden=hidden,
|
||||
params=sum(p.numel() for p in org.parameters()),
|
||||
loss=statistics.fmean(loss), acc=statistics.fmean(hits),
|
||||
chance=statistics.fmean(chance))
|
||||
|
||||
|
||||
def run_constant(games, seed: int) -> dict:
|
||||
"""The floor: rank offsets by how often a move uses them. Blind to piece and position."""
|
||||
order = np.random.default_rng(seed).permutation(len(games))
|
||||
cut = max(1, len(games) // 4)
|
||||
marg = np.zeros(GRID)
|
||||
for gi in order[cut:]:
|
||||
for ply in games[gi]:
|
||||
marg[offsets(ply.dests[ply.true_dest][None, :])[0]] += 1.0
|
||||
hits, chance = [], []
|
||||
for gi in order[:cut]:
|
||||
for ply in games[gi]:
|
||||
hits.append(float(int(marg[offsets(ply.dests)].argmax()) == ply.true_dest))
|
||||
chance.append(1.0 / len(ply.dests))
|
||||
return dict(seed=seed, memory=False, oracle=False, hidden=0, params=GRID,
|
||||
loss=float("nan"), acc=statistics.fmean(hits),
|
||||
chance=statistics.fmean(chance))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--games", type=int, default=400)
|
||||
ap.add_argument("--hist", type=int, default=3)
|
||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
||||
ap.add_argument("--hidden", type=int, default=32)
|
||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
||||
ap.add_argument("--lr", type=float, default=1e-3)
|
||||
ap.add_argument("--bptt", type=int, default=20)
|
||||
ap.add_argument("--edges", default="type", choices=("none", "type"))
|
||||
ap.add_argument("--arms", default="constant,rp,grp,rp_wide,rp_oracle")
|
||||
ap.add_argument("--out", default="results/chess_dist.json")
|
||||
a = ap.parse_args()
|
||||
|
||||
games = load(a.games, a.hist)
|
||||
edges = a.edges == "type"
|
||||
wide = match_width(a.hidden, a.cppn_hidden, 6 if edges else 1)
|
||||
all_arms = {"constant": None, "rp": (False, a.hidden, False), "grp": (True, a.hidden, False),
|
||||
"rp_wide": (False, wide, False),
|
||||
# the oracle sits at the SAME width as `rp`: same architecture, one of them
|
||||
# handed the past. Anything else confounds the ceiling with capacity.
|
||||
"rp_oracle": (False, a.hidden, True),
|
||||
# the control that separates the state from the gate: the SAME architecture and
|
||||
# the SAME parameters, handed an empty memory every ply. In the particles work
|
||||
# this is what turned "memory helps" into "the gated nonlinearity helps"
|
||||
# (results/frozen.md). A GRP gain is not a memory result until this arm is run.
|
||||
"grp_nostate": (True, a.hidden, 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, edges={a.edges}, "
|
||||
f"width-matched memoryless arm at hidden={wide}\n")
|
||||
|
||||
results = []
|
||||
for name, spec in arms.items():
|
||||
for seed in (int(s) for s in a.seeds.split(",")):
|
||||
r = (run_constant(games, seed) if spec is None else
|
||||
run(games, spec[0], spec[1], a.cppn_hidden, seed, a.lr, a.bptt, spec[2],
|
||||
edges, name == "grp_nostate")) | {"arm": name}
|
||||
print(f"{name:<10} seed={seed} params={r['params']:<6} "
|
||||
f"loss={r['loss']:.4f} acc={r['acc']:.4f}", flush=True)
|
||||
results.append(r)
|
||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
||||
|
||||
by = {n: [r for r in results if r["arm"] == n] for n in arms}
|
||||
print(f"\n{'arm':<10}{'params':>8}{'loss':>9}{'acc':>9}{'chance':>9}")
|
||||
print("-" * 45)
|
||||
for n, rs in by.items():
|
||||
print(f"{n:<10}{rs[0]['params']:>8}{statistics.fmean(r['loss'] 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}")
|
||||
for top, base in (("rp_oracle", "rp"), ("grp", "rp_wide"), ("grp", "rp"),
|
||||
("grp", "grp_nostate"), ("grp_nostate", "rp_wide")):
|
||||
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")
|
||||
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
||||
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- "
|
||||
f"{'ambiguous' if abs(statistics.fmean(d)) < se else 'a direction'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
"""Chess under contract A: which piece moves is given, where it goes is predicted.
|
||||
|
||||
Spec §2, contract A, on the chess instance. What justified coming here is
|
||||
`results/chess_history.md`: a piece's own past predicts its next square beyond the board,
|
||||
+0.034 with a non-linear decoder. That measured headroom is what this file spends.
|
||||
|
||||
Two design decisions, both load-bearing.
|
||||
|
||||
**The target is the mover's displacement, and the loss is masked to the mover.** Exactly one
|
||||
piece moves per ply, so the spec's literal default -- every entity's displacement -- is 31/32
|
||||
zeros and the constant predictor "nobody moves" wins. That leaves a mechanism no job, which is
|
||||
the shape of four nulls in the predecessor project. The cost of the fix is that the model is
|
||||
told *which* piece moves. It is not told where it goes, and this is the same conditioning the
|
||||
probe measured under, so the probe's number is the ceiling on this task and not on some other.
|
||||
|
||||
**Affect is held neutral.** psi = (0, 0), kappa = 0, so the only thing separating the arms is
|
||||
per-entity memory. `--affect stream` runs the real EMA chain instead; it exists so the neutral
|
||||
default is a choice rather than an absence.
|
||||
|
||||
There is no regime switch in chess. A1 -- arousal opens the gate after an unannounced change --
|
||||
has no analogue here and is not tested by this file.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import chess
|
||||
import chess.pgn
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
||||
|
||||
PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn"
|
||||
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
|
||||
|
||||
|
||||
def flat_diff(coords: torch.Tensor) -> torch.Tensor:
|
||||
"""r_ij = c_j - c_i. Chess is flat: no wrap, unlike `particles.wrapped_diff`."""
|
||||
return coords[None, :, :] - coords[:, None, :]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Ply:
|
||||
ids: list[int] # stable piece ids, the row order of everything below
|
||||
attrs: np.ndarray # (N, ATTR_DIM)
|
||||
coords: np.ndarray # (N, 2) file, rank, scaled
|
||||
mover: int # row index of the piece that moves
|
||||
target: np.ndarray # (2,) that piece's displacement
|
||||
dests: np.ndarray # (L, 2) displacement of every legal move from its square
|
||||
true_dest: int # index into dests
|
||||
past: np.ndarray # (N, 2*hist) each entity's previous squares, as displacements
|
||||
mask: np.ndarray # (N, N) the attack/defend graph, symmetric, self-loops on
|
||||
reach: np.ndarray # (N,) each entity's attack set as a bitboard, for chess_reach.py
|
||||
|
||||
|
||||
def advance_ids(board: chess.Board, move: chess.Move, piece: chess.Piece,
|
||||
id_at: dict[int, int]) -> None:
|
||||
"""Follow piece identity across a move, so "this knight" means the same knight later.
|
||||
|
||||
Castling moves the rook too; en passant removes a pawn from a square the mover never
|
||||
touches; promotion keeps the identity and changes only the type.
|
||||
|
||||
ponytail: this repeats the bookkeeping inside `chess_history.py` rather than importing it.
|
||||
That file is a committed measurement and is left untouched; the two must agree, and
|
||||
`plies()` asserts the result stays in sync with the board either way.
|
||||
"""
|
||||
if board.is_en_passant(move):
|
||||
id_at.pop(move.to_square + (-8 if piece.color == chess.WHITE else 8), None)
|
||||
id_at.pop(move.to_square, None) # a normal capture
|
||||
id_at[move.to_square] = id_at.pop(move.from_square, move.from_square)
|
||||
if board.is_castling(move):
|
||||
back = 0 if piece.color == chess.WHITE else 56
|
||||
r_from, r_to = ((back + 7, back + 5) if chess.square_file(move.to_square) == 6
|
||||
else (back, back + 3))
|
||||
if r_from in id_at:
|
||||
id_at[r_to] = id_at.pop(r_from)
|
||||
|
||||
|
||||
def plies(game: chess.pgn.Game, hist: int = 3) -> list[Ply]:
|
||||
board = game.board()
|
||||
id_at = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)}
|
||||
seen: dict[int, list[int]] = {}
|
||||
out: list[Ply] = []
|
||||
for move in game.mainline_moves():
|
||||
piece = board.piece_at(move.from_square)
|
||||
if piece is None:
|
||||
break
|
||||
# the identity map must name exactly the occupied squares, or a memory slot is
|
||||
# following the wrong piece and every number downstream is meaningless
|
||||
assert id_at.keys() == board.piece_map().keys(), "identity map drifted from the board"
|
||||
squares = sorted(id_at)
|
||||
attrs = np.zeros((len(squares), ATTR_DIM), dtype=np.float32)
|
||||
coords = np.zeros((len(squares), 2), dtype=np.float32)
|
||||
for k, sq in enumerate(squares):
|
||||
p = board.piece_at(sq)
|
||||
attrs[k, p.piece_type - 1] = 1.0
|
||||
attrs[k, 6] = float(p.color == chess.WHITE)
|
||||
coords[k] = (chess.square_file(sq) / SCALE, chess.square_rank(sq) / SCALE)
|
||||
mover = squares.index(move.from_square)
|
||||
attrs[mover, 7] = 1.0
|
||||
|
||||
# the spec's optional adjacency input (§2), which chess actually has: i sees j when
|
||||
# either attacks the other's square. With the all-ones default an entity's own
|
||||
# attributes reach it only through the diagonal term and are divided by deg ~= 30.
|
||||
sq = np.array(squares, dtype=np.uint64)
|
||||
bb = np.array([int(board.attacks(int(t))) for t in squares], dtype=np.uint64)
|
||||
att = ((bb[:, None] >> sq[None, :]) & np.uint64(1)).astype(np.float32)
|
||||
mask = np.maximum(att, att.T)
|
||||
np.fill_diagonal(mask, 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
|
||||
legal = list(dict.fromkeys(m.to_square for m in board.legal_moves
|
||||
if m.from_square == move.from_square))
|
||||
dests = np.array([[(chess.square_file(t) - chess.square_file(move.from_square)) / SCALE,
|
||||
(chess.square_rank(t) - chess.square_rank(move.from_square)) / SCALE]
|
||||
for t in legal], dtype=np.float32)
|
||||
j = legal.index(move.to_square)
|
||||
out.append(Ply([id_at[s] for s in squares], attrs, coords, mover, dests[j], dests, j,
|
||||
past, mask, bb.copy()))
|
||||
|
||||
seen.setdefault(id_at[move.from_square], []).append(move.from_square)
|
||||
advance_ids(board, move, piece, id_at)
|
||||
board.push(move)
|
||||
return out
|
||||
|
||||
|
||||
def load(n_games: int, hist: int = 3, min_plies: int = 20) -> list[list[Ply]]:
|
||||
games: list[list[Ply]] = []
|
||||
with open(PGN, encoding="utf-8", errors="replace") as fh:
|
||||
while len(games) < n_games:
|
||||
g = chess.pgn.read_game(fh)
|
||||
if g is None:
|
||||
break
|
||||
p = plies(g, hist)
|
||||
if len(p) >= min_plies:
|
||||
games.append(p)
|
||||
return games
|
||||
|
||||
|
||||
def n_params(memory: bool, hidden: int, cppn_hidden: int, attr_dim: int = ATTR_DIM,
|
||||
n_edge: int = 1) -> int:
|
||||
org = Organism(attr_dim, 2, 2, n_edge_types=n_edge, hidden_dim=hidden,
|
||||
cppn_hidden=cppn_hidden, memory=memory)
|
||||
return sum(p.numel() for p in org.parameters())
|
||||
|
||||
|
||||
def match_width(hidden: int, cppn_hidden: int, n_edge: int = 1) -> int:
|
||||
"""The memoryless width whose parameter count lands nearest the gated model's.
|
||||
|
||||
`rp_only` at 1442 against `grp_k0` at 5602 is confounded 3.9x and is not a memory
|
||||
result (`results/frozen.md` §1d). This is how that confound is removed here.
|
||||
"""
|
||||
target = n_params(True, hidden, cppn_hidden, n_edge=n_edge)
|
||||
return min(range(hidden, 8 * hidden),
|
||||
key=lambda h: abs(n_params(False, h, cppn_hidden, n_edge=n_edge) - target))
|
||||
|
||||
|
||||
def _stream(org: Organism, game: list[Ply], affect: Affect, acfg: AffectConfig,
|
||||
opt: torch.optim.Optimizer | None, bptt: int, use_affect: bool,
|
||||
oracle: bool, adjacency: bool, edges: bool):
|
||||
"""One game as one continuous stream. Memory starts empty: new game, new pieces."""
|
||||
memory: dict[int, torch.Tensor] = {}
|
||||
pending: list[torch.Tensor] = []
|
||||
losses, hits, chance = [], [], []
|
||||
with torch.set_grad_enabled(opt is not None):
|
||||
for ply in game:
|
||||
coords = torch.from_numpy(ply.coords)
|
||||
attrs = np.concatenate([ply.attrs, ply.past], 1) if oracle else ply.attrs
|
||||
# the receiving piece's type, into the CPPN's own channel. Without this the kernel
|
||||
# is one geometry function shared by all six types -- see results/chess_reach.md,
|
||||
# where that costs the knight's L entirely.
|
||||
et = None
|
||||
if edges:
|
||||
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
|
||||
et = t[:, None].expand(len(ply.ids), len(ply.ids)).contiguous()
|
||||
pred, memory = org(torch.from_numpy(attrs), flat_diff(coords), ply.ids,
|
||||
affect.axes, memory, edge_types=et,
|
||||
mask=torch.from_numpy(ply.mask) if adjacency else None)
|
||||
p = pred[ply.mover]
|
||||
loss = ((p - torch.from_numpy(ply.target)) ** 2).mean() # masked to the mover
|
||||
if use_affect:
|
||||
affect = update(affect, loss.item(), acfg)
|
||||
losses.append(loss.item())
|
||||
# snap to the nearest legal destination, so the number is comparable to the
|
||||
# accuracies in results/chess_history.md rather than to a raw MSE
|
||||
k = int(((torch.from_numpy(ply.dests) - p.detach()) ** 2).sum(1).argmin())
|
||||
hits.append(float(k == ply.true_dest))
|
||||
chance.append(1.0 / len(ply.dests))
|
||||
if opt is None:
|
||||
continue
|
||||
pending.append(loss)
|
||||
if len(pending) == bptt:
|
||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
||||
pending = []; memory = detach_memory(memory)
|
||||
if opt is not None and pending:
|
||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
||||
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,
|
||||
lr: float, bptt: int, kappa: float, use_affect: bool, oracle: bool = False,
|
||||
adjacency: bool = False, edges: bool = False) -> dict:
|
||||
torch.manual_seed(seed)
|
||||
attr_dim = ATTR_DIM + (games[0][0].past.shape[1] if oracle else 0)
|
||||
org = Organism(attr_dim, 2, 2, n_edge_types=6 if edges else 1, hidden_dim=hidden,
|
||||
cppn_hidden=cppn_hidden, kappa=kappa, memory=memory)
|
||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
||||
acfg, affect = AffectConfig(), Affect()
|
||||
|
||||
# split by GAME, never inside one: two positions from one game share almost everything
|
||||
order = np.random.default_rng(seed).permutation(len(games))
|
||||
cut = max(1, len(games) // 4)
|
||||
for gi in order[cut:]:
|
||||
affect, *_ = _stream(org, games[gi], affect, acfg, opt, bptt, use_affect, oracle, adjacency, edges)
|
||||
mse, hits, chance = [], [], []
|
||||
for gi in order[:cut]:
|
||||
affect, l, h, c = _stream(org, games[gi], affect, acfg, None, bptt, use_affect, oracle, adjacency, edges)
|
||||
mse += l; hits += h; chance += c
|
||||
return dict(seed=seed, hidden=hidden, memory=memory, oracle=oracle, mask=adjacency, edges=edges,
|
||||
params=sum(p.numel() for p in org.parameters()), plies=len(mse),
|
||||
mse=statistics.fmean(mse), acc=statistics.fmean(hits),
|
||||
chance=statistics.fmean(chance))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
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("--hidden", type=int, default=32)
|
||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
||||
ap.add_argument("--lr", type=float, default=1e-3)
|
||||
ap.add_argument("--bptt", type=int, default=20)
|
||||
ap.add_argument("--kappa", type=float, default=0.0)
|
||||
ap.add_argument("--affect", default="neutral", choices=("neutral", "stream"),
|
||||
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("--edges", default="none", choices=("none", "type"),
|
||||
help="type puts the receiving piece's type into e_ij, the CPPN's channel")
|
||||
ap.add_argument("--mask", default="all", choices=("all", "attack"),
|
||||
help="all is the spec default; attack is the domain's own adjacency")
|
||||
ap.add_argument("--out", default="results/chess.json")
|
||||
a = ap.parse_args()
|
||||
|
||||
games = load(a.games, a.hist)
|
||||
wide = match_width(a.hidden, a.cppn_hidden, 6 if a.edges == 'type' else 1)
|
||||
# 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(",")}
|
||||
deg = statistics.fmean(float(p.mask.sum(1).mean()) for g in games for p in g)
|
||||
print(f"{len(games)} games, {sum(len(g) for g in games)} plies; "
|
||||
f"width-matched memoryless arm at hidden={wide}; mask={a.mask}, "
|
||||
f"mean degree {deg if a.mask == 'attack' else statistics.fmean(len(p.ids) for g in games for p in g):.1f}\n")
|
||||
|
||||
results = []
|
||||
for name, (mem, h, orc) in arms.items():
|
||||
for seed in (int(s) for s in a.seeds.split(",")):
|
||||
r = (run_constant(games, seed) if name == "constant" else
|
||||
run(games, mem, h, a.cppn_hidden, seed, a.lr, a.bptt, a.kappa,
|
||||
a.affect == "stream", orc, a.mask == "attack",
|
||||
a.edges == "type")) | {"arm": name}
|
||||
print(f"{name:<8} seed={seed} params={r['params']:<6} "
|
||||
f"mse={r['mse']:.5f} acc={r['acc']:.4f}", flush=True)
|
||||
results.append(r)
|
||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
||||
|
||||
by = {n: [r for r in results if r["arm"] == n] for n in arms}
|
||||
print(f"\n{'arm':<8}{'params':>8}{'mse':>10}{'acc':>9}{'chance':>9}")
|
||||
print("-" * 44)
|
||||
for n, rs in by.items():
|
||||
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['chance'] for r in rs):>9.4f}")
|
||||
for top, base in (("grp", "rp"), ("grp", "rp_wide"), ("rp_oracle", "rp_wide")):
|
||||
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")
|
||||
verdict = "ambiguous" if abs(statistics.fmean(d)) < se else "a direction"
|
||||
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}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
"""Does the organism learn how a piece moves? Spec §3: the kernel is a function of geometry.
|
||||
|
||||
The move-prediction task in `chess_domain.py` never asks this. It hands legality to the model
|
||||
for free at readout time -- the prediction is snapped to the nearest legal destination -- so
|
||||
the model is never scored on knowing that a knight goes in an L. Its target also mixes what is
|
||||
legal with what a human chose, and move quality is not controlled. This file asks the first
|
||||
question instead: given the board, which squares can each piece reach?
|
||||
|
||||
Target: `board.attacks(square)` for every live piece, expressed as a 15x15 grid of RELATIVE
|
||||
offsets rather than 64 absolute squares. That is not a convenience -- the CPPN sees only
|
||||
`r_ij`, so an entity's representation is translation-invariant and cannot know which absolute
|
||||
square it stands on. An absolute target is unanswerable by construction. In offset space the
|
||||
question is the one worth asking: a knight's L is eight cells, a bishop's is four rays.
|
||||
|
||||
Deterministic, present-determined, same definition for all six types. The pawn caveat is real
|
||||
and stated rather than hidden: `attacks` is the two diagonals, not the forward push, so for
|
||||
pawns this measures the capture geometry only.
|
||||
|
||||
Two things this design is built to separate:
|
||||
|
||||
**Does the piece's type reach the kernel?** The CPPN sees `[r_ij ‖ onehot(e_ij) ‖ context]`.
|
||||
The piece type is NOT in there -- it lives in `attrs`, which enters through `feat` and only
|
||||
meets the kernel as an elementwise product. So the geometry function is shared across all six
|
||||
types. `--edges type` puts the receiving piece's type into `e_ij`, which is the spec's own
|
||||
sanctioned channel, and makes the kernel genuinely type-conditional: a knight-kernel and a
|
||||
bishop-kernel rather than one kernel scaled by a type vector.
|
||||
|
||||
**Memory is the control here, not the hypothesis.** Reachability is fully determined by the
|
||||
present -- type, square, blockers. This is the redundant case, so memory SHOULD buy nothing.
|
||||
An arm that shows no memory gain here is the instrument working, not a null about memory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from ailed import Affect, Organism, detach_memory
|
||||
from chess_domain import ATTR_DIM, flat_diff, load
|
||||
|
||||
SQ = np.arange(64, dtype=np.uint64)
|
||||
GRID = 15 * 15
|
||||
# OFFSET[a, b] is where b sits relative to a, as a cell of the 15x15 displacement grid
|
||||
_f, _r = np.arange(64) % 8, np.arange(64) // 8
|
||||
OFFSET = ((_r[None, :] - _r[:, None] + 7) * 15 + (_f[None, :] - _f[:, None] + 7))
|
||||
|
||||
|
||||
def unpack(ply) -> np.ndarray:
|
||||
"""Each entity's attack set as a (N, 225) multi-hot over relative offsets."""
|
||||
bits = ((ply.reach[:, None] >> SQ[None, :]) & np.uint64(1)).astype(np.float32) # (N,64)
|
||||
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
|
||||
out = np.zeros((len(sq), GRID), dtype=np.float32)
|
||||
np.add.at(out, (np.arange(len(sq))[:, None], OFFSET[sq]), bits)
|
||||
return out
|
||||
|
||||
|
||||
def _stream(org, game, opt, bptt: int, edges: bool, adjacency: bool):
|
||||
memory: dict[int, torch.Tensor] = {}
|
||||
pending, losses, prec, chance = [], [], [], []
|
||||
# per-type precision is the answer to "does it tell a pawn from a bishop"; the aggregate
|
||||
# can be carried by pawns alone, which are half the pieces on the board
|
||||
by_type = np.zeros((6, 2))
|
||||
zero = Affect().axes
|
||||
with torch.set_grad_enabled(opt is not None):
|
||||
for ply in game:
|
||||
n = len(ply.ids)
|
||||
y = torch.from_numpy(unpack(ply)) # (N,225)
|
||||
et = None
|
||||
if edges: # receiver's type
|
||||
t = torch.from_numpy(ply.attrs[:, :6]).argmax(1)
|
||||
et = t[:, None].expand(n, n).contiguous()
|
||||
pred, memory = org(torch.from_numpy(ply.attrs), flat_diff(torch.from_numpy(ply.coords)),
|
||||
ply.ids, zero, memory, edge_types=et,
|
||||
mask=torch.from_numpy(ply.mask) if adjacency else None)
|
||||
loss = torch.nn.functional.binary_cross_entropy_with_logits(pred, y)
|
||||
losses.append(loss.item())
|
||||
with torch.no_grad():
|
||||
k = y.sum(1)
|
||||
keep = k > 0
|
||||
if keep.any():
|
||||
# precision@k: of the k squares it ranks highest, how many are reachable
|
||||
rank = pred.argsort(1, descending=True).argsort(1)
|
||||
hit = ((rank < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
|
||||
prec.append(float(hit[keep].mean()))
|
||||
chance.append(float((k[keep] / GRID).mean())) # random ranking
|
||||
tt = ply.attrs[:, :6].argmax(1)[keep.numpy()]
|
||||
np.add.at(by_type, (tt, 0), hit[keep].numpy())
|
||||
np.add.at(by_type, (tt, 1), 1.0)
|
||||
if opt is None:
|
||||
continue
|
||||
pending.append(loss)
|
||||
if len(pending) == bptt:
|
||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
||||
pending = []; memory = detach_memory(memory)
|
||||
if opt is not None and pending:
|
||||
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step()
|
||||
return losses, prec, chance, by_type
|
||||
|
||||
|
||||
def run(games, memory: bool, hidden: int, cppn_hidden: int, seed: int, lr: float, bptt: int,
|
||||
edges: bool, adjacency: bool) -> dict:
|
||||
torch.manual_seed(seed)
|
||||
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=6 if edges else 1, hidden_dim=hidden,
|
||||
cppn_hidden=cppn_hidden, kappa=0.0, memory=memory)
|
||||
opt = torch.optim.Adam(org.parameters(), lr=lr)
|
||||
order = np.random.default_rng(seed).permutation(len(games))
|
||||
cut = max(1, len(games) // 4)
|
||||
for gi in order[cut:]:
|
||||
_stream(org, games[gi], opt, bptt, edges, adjacency)
|
||||
loss, prec, chance, tsum = [], [], [], np.zeros((6, 2))
|
||||
for gi in order[:cut]:
|
||||
l, p, c, t = _stream(org, games[gi], None, bptt, edges, adjacency)
|
||||
loss += l; prec += p; chance += c; tsum += t
|
||||
return dict(seed=seed, memory=memory, edges=edges, hidden=hidden,
|
||||
params=sum(p.numel() for p in org.parameters()),
|
||||
loss=statistics.fmean(loss), prec=statistics.fmean(prec),
|
||||
chance=statistics.fmean(chance),
|
||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
|
||||
|
||||
|
||||
def run_constant(games, seed: int) -> dict:
|
||||
"""The floor: every piece moves like the average piece. Type-blind and position-blind.
|
||||
|
||||
This is the control the question needs. Beating it means the model distinguishes a pawn
|
||||
from a bishop; sitting on it means it learned one average movement shape for everything.
|
||||
"""
|
||||
order = np.random.default_rng(seed).permutation(len(games))
|
||||
cut = max(1, len(games) // 4)
|
||||
marg = np.zeros(GRID)
|
||||
for gi in order[cut:]:
|
||||
for ply in games[gi]:
|
||||
marg += unpack(ply).sum(0)
|
||||
rank = torch.from_numpy((-marg).argsort().argsort())
|
||||
prec, chance, tsum = [], [], np.zeros((6, 2))
|
||||
for gi in order[:cut]:
|
||||
for ply in games[gi]:
|
||||
y = torch.from_numpy(unpack(ply))
|
||||
k = y.sum(1); keep = k > 0
|
||||
if keep.any():
|
||||
hit = ((rank[None, :] < k[:, None]) & (y > 0)).sum(1) / k.clamp(min=1)
|
||||
prec.append(float(hit[keep].mean())); chance.append(float((k[keep] / GRID).mean()))
|
||||
tt = ply.attrs[:, :6].argmax(1)[keep.numpy()]
|
||||
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
|
||||
return dict(seed=seed, memory=False, edges=False, hidden=0, params=GRID,
|
||||
loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance),
|
||||
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--games", type=int, default=400)
|
||||
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
|
||||
ap.add_argument("--hidden", type=int, default=32)
|
||||
ap.add_argument("--cppn-hidden", type=int, default=32)
|
||||
ap.add_argument("--lr", type=float, default=1e-3)
|
||||
ap.add_argument("--bptt", type=int, default=20)
|
||||
ap.add_argument("--mask", default="all", choices=("all", "attack"))
|
||||
ap.add_argument("--arms", default="constant,rp,rp_type,grp_type")
|
||||
ap.add_argument("--out", default="results/chess_reach.json")
|
||||
a = ap.parse_args()
|
||||
|
||||
games = load(a.games)
|
||||
# (memory, edge types)
|
||||
all_arms = {"constant": None, "rp": (False, False), "rp_type": (False, True),
|
||||
"grp": (True, False), "grp_type": (True, True)}
|
||||
arms = {k: all_arms[k] for k in a.arms.split(",")}
|
||||
print(f"{len(games)} games, {sum(len(g) for g in games)} plies, mask={a.mask}\n")
|
||||
|
||||
results = []
|
||||
for name, spec in arms.items():
|
||||
for seed in (int(s) for s in a.seeds.split(",")):
|
||||
r = (run_constant(games, seed) if spec is None else
|
||||
run(games, spec[0], a.hidden, a.cppn_hidden, seed, a.lr, a.bptt, spec[1],
|
||||
a.mask == "attack")) | {"arm": name}
|
||||
print(f"{name:<10} seed={seed} params={r['params']:<6} "
|
||||
f"loss={r['loss']:.4f} prec@k={r['prec']:.4f}", flush=True)
|
||||
results.append(r)
|
||||
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(a.out).write_text(json.dumps(results, indent=1))
|
||||
|
||||
by = {n: [r for r in results if r["arm"] == n] for n in arms}
|
||||
names = ["pawn", "knight", "bishop", "rook", "queen", "king"]
|
||||
print(f"\n{'arm':<10}{'loss':>9}{'prec@k':>9}" + "".join(f"{t:>9}" for t in names))
|
||||
print("-" * (28 + 9 * 6))
|
||||
for n, rs in by.items():
|
||||
bt = [statistics.fmean(r["by_type"][i] for r in rs) for i in range(6)]
|
||||
print(f"{n:<10}{statistics.fmean(r['loss'] for r in rs):>9.4f}"
|
||||
f"{statistics.fmean(r['prec'] for r in rs):>9.4f}"
|
||||
+ "".join(f"{v:>9.4f}" for v in bt))
|
||||
print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}")
|
||||
for top, base in (("rp_type", "rp"), ("grp_type", "rp_type"), ("grp", "rp")):
|
||||
if top not in by or base not in by:
|
||||
continue
|
||||
d = [x["prec"] - y["prec"] for x, y in zip(by[top], by[base])]
|
||||
se = statistics.stdev(d) / len(d) ** 0.5 if len(d) > 1 else float("nan")
|
||||
print(f"\n{top} - {base}: {statistics.fmean(d):+.4f} +/- {se:.4f} (paired se), "
|
||||
f"{sum(x > 0 for x in d)}/{len(d)} seeds -- "
|
||||
f"{'ambiguous' if abs(statistics.fmean(d)) < se else 'a direction'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,93 @@
|
||||
# Per-entity memory pays, and the state is what pays
|
||||
|
||||
The first positive result on the memory line, with the control that killed the equivalent
|
||||
claim in the particles domain.
|
||||
|
||||
**The readout was the bottleneck.** Swapping MSE-on-the-mean for cross-entropy over the legal
|
||||
destinations — same target, same chance level, same conditioning — lifts accuracy from 0.40 to
|
||||
0.47, and flips every memory comparison from negative to positive.
|
||||
|
||||
## Results
|
||||
|
||||
400 games, 28 067 plies, 8 seeds, split by game. Type in `e_ij`. Affect neutral, kappa 0.
|
||||
|
||||
```
|
||||
arm params loss acc chance
|
||||
constant 225 --- 0.3454 0.3618
|
||||
rp 9121 1.2453 0.4685 0.3618
|
||||
rp_oracle 9313 1.2449 0.4705 0.3618
|
||||
rp_wide 13393 1.2422 0.4722 0.3618
|
||||
grp_nostate 13281 1.2497 0.4616 0.3618
|
||||
grp 13281 1.2362 0.4780 0.3618
|
||||
|
||||
grp - rp_wide: +0.0058 +/- 0.0019 7/8 seeds
|
||||
grp - grp_nostate: +0.0164 +/- 0.0025 8/8 seeds
|
||||
grp_nostate - rp_wide: -0.0106 +/- 0.0017 0/8 seeds
|
||||
rp_oracle - rp: +0.0020 +/- 0.0015 5/8 seeds ambiguous
|
||||
```
|
||||
|
||||
`grp - grp_nostate`, per seed — the whole result in one column:
|
||||
|
||||
```
|
||||
seed 0 1 2 3 4 5 6 7
|
||||
+0.0155 +0.0206 +0.0197 +0.0125 +0.0216 +0.0271 +0.0052 +0.0091
|
||||
```
|
||||
|
||||
## Why the control is the result
|
||||
|
||||
`grp_nostate` is the same architecture with the same 13 281 parameters and the same gate,
|
||||
handed an **empty memory every ply**. The only difference from `grp` is whether the state is
|
||||
carried. It gains +0.0164 on 8/8 seeds, 6.6 paired standard errors.
|
||||
|
||||
This is the control that inverted the equivalent claim in particles, where the RP/GRP margin
|
||||
turned out to be the gated post-RP nonlinearity rather than the state (`frozen.md` §1d). Here
|
||||
it goes the other way, and further than that: **the gated architecture with an empty memory is
|
||||
worse than the plain memoryless one** (-0.0106, 0/8 seeds). The gate is a cost that the state
|
||||
more than repays. The +0.0058 over `rp_wide` is a net of those two.
|
||||
|
||||
## The oracle under-measured its own ceiling
|
||||
|
||||
`rp_oracle` hands the memoryless model each piece's previous three squares as relative
|
||||
displacements — six input dimensions. It reads +0.0020 on 5/8 seeds, ambiguous, while the
|
||||
learned state gains three times that on 8/8.
|
||||
|
||||
The state finds more than the encoding we handed over. Three squares as displacements is a
|
||||
narrow guess at what a piece's past contains; the state is 32 dimensions accumulated across a
|
||||
whole game. **The oracle read ambiguous in four configurations of this task, and this is the
|
||||
first evidence that the ambiguity was the oracle's encoding rather than the domain's
|
||||
information.** That is a caution about the oracle-first method as practised here, not a
|
||||
refutation of it: an oracle bounds what its own encoding can supply, and nothing more.
|
||||
|
||||
## Where it sits in the arc
|
||||
|
||||
- `chess_history.md` — the domain has per-entity past that predicts the future. Property of the
|
||||
domain, no organism involved.
|
||||
- `credit.md` — the state update can hold per-entity properties (entity type at 0.738 against
|
||||
chance 0.333) and cannot hold a global one.
|
||||
- `chess_reach.md` — the kernel must see the piece type or it learns one average movement
|
||||
shape; the knight's L is exactly zero without it.
|
||||
- `chess_move.md` — with an MSE readout the objective and the question move in opposite
|
||||
directions, and no memory number there is readable.
|
||||
- **this file** — with a readout that matches the target's shape, the carried state pays.
|
||||
|
||||
## Limits, stated rather than discovered later
|
||||
|
||||
- **What the state holds is not identified.** This measures that carrying it helps, not what is
|
||||
in it. The decode probe that `credit.md` ran on particles has not been run here.
|
||||
- 400 games and 8 seeds. The effect is 6.6 se on its own control and 3.1 se on the
|
||||
width-matched arm; the second of those would not survive much less data.
|
||||
- Affect is neutral throughout, so **A1 and A2 are untested here**. Chess has no regime switch
|
||||
and A1 has no analogue; A2 would need the CPPN's context to vary, which it does not.
|
||||
- Legality is handed to the model at readout: the candidate set is the legal destinations. The
|
||||
loss never sees a rule.
|
||||
- Move quality is uncontrolled — blitz games across a wide rating range.
|
||||
- `grp_nostate` is the state control, not a capacity control; `rp_wide` is the capacity control.
|
||||
Both are reported because neither answers the other's question.
|
||||
|
||||
Reproduce with:
|
||||
|
||||
```bash
|
||||
uv run --with chess python chess_dist.py --games 400 --seeds 0,1,2,3,4,5,6,7
|
||||
uv run --with chess python chess_dist.py --games 400 --seeds 0,1,2,3,4,5,6,7 \
|
||||
--arms grp,grp_nostate,rp_wide
|
||||
```
|
||||
@@ -0,0 +1,104 @@
|
||||
# Move prediction under contract A: three configurations, one null, and a measured mismatch
|
||||
|
||||
Predicting where the moving piece goes, given the board and which piece moves. Three
|
||||
configurations of the same task. The per-entity history oracle does not pay in any of them,
|
||||
and the reason is visible in the numbers rather than argued: **the objective and the question
|
||||
move in opposite directions.**
|
||||
|
||||
## Setup
|
||||
|
||||
Target: the mover's displacement, MSE, loss masked to the mover. Chess moves one piece per
|
||||
ply, so the spec's literal per-entity default is 31/32 zeros and the constant predictor wins;
|
||||
masking is what leaves the mechanism a job, at the cost of telling the model which piece moves.
|
||||
Accuracy snaps the prediction to the nearest legal destination, so legality is given for free
|
||||
and chance is 0.3618 (uniform among legal), not 1/64.
|
||||
|
||||
400 games, 28 067 plies, 8 seeds, split by game. Affect neutral, kappa 0.
|
||||
|
||||
`rp_oracle` is the gate: the memoryless model is *handed* each piece's previous three squares,
|
||||
which is exactly what memory would have to learn to carry. If that does not pay, memory has no
|
||||
job in this setup and any GRP number here is not a memory result.
|
||||
|
||||
## Results
|
||||
|
||||
```
|
||||
config arm params mse acc
|
||||
all-ones mask, type-blind constant 2 0.05564 0.3325
|
||||
rp 1602 0.03885 0.4148
|
||||
grp 5762 0.03889 0.4088
|
||||
rp_wide 5782 0.03888 0.4144
|
||||
rp_oracle 6544 0.03881 0.4159
|
||||
|
||||
attack mask, type-blind rp 1602 0.04063 0.3828
|
||||
grp 5762 0.04015 0.3832
|
||||
rp_wide 5782 0.04024 0.3809
|
||||
rp_oracle 6544 0.03980 0.3805
|
||||
|
||||
all-ones mask, type in e_ij rp 1762 0.03547 0.4029
|
||||
grp 5922 0.03547 0.3933
|
||||
rp_wide 5942 0.03548 0.3998
|
||||
rp_oracle 6704 0.03545 0.3992
|
||||
|
||||
chance (uniform among legal destinations) 0.3618
|
||||
```
|
||||
|
||||
The oracle, in all three:
|
||||
|
||||
```
|
||||
all-ones, type-blind rp_oracle - rp_wide +0.0014 +/- 0.0011 4/8 seeds ambiguous
|
||||
attack mask rp_oracle - rp_wide -0.0003 +/- 0.0019 4/8 seeds ambiguous
|
||||
type in e_ij rp_oracle - rp_wide -0.0006 +/- 0.0031 5/8 seeds ambiguous
|
||||
```
|
||||
|
||||
## The mismatch, which is the finding
|
||||
|
||||
Putting the piece's type into the CPPN improves the trained objective substantially — MSE
|
||||
0.03888 -> 0.03547 — and makes the answer to the actual question **worse**: accuracy
|
||||
0.4144 -> 0.3998. The same change that helps the model fit helps it less often name the right
|
||||
square. Compare `chess_reach.md`, where the identical change moved the knight's L from exactly
|
||||
zero to 0.758 on 8/8 seeds; the kernel is not the problem here.
|
||||
|
||||
MSE on a displacement vector fits the **conditional mean** of the destinations. A knight with
|
||||
five legal squares has a mean displacement pointing at none of them, and history shifts the
|
||||
*distribution* over destinations — which is what `chess_history.md` measured, +0.034 with a
|
||||
non-linear decoder over 64 squares — while barely moving the mean. The readout discards the
|
||||
shape of information the history carries. Improving the fit to the mean therefore costs
|
||||
accuracy, which is what the two configurations show.
|
||||
|
||||
The attack-mask configuration is a separate measured null: mean degree falls 30 -> 3.3 and
|
||||
accuracy falls with it, 0.414 -> 0.381 across all arms. The dilution hypothesis — that an
|
||||
entity's own attributes are drowned by 1/deg in the mean-pooled message — predicted the
|
||||
opposite and is not supported.
|
||||
|
||||
## Verdict
|
||||
|
||||
**Per-entity history does not pay under contract A with an MSE readout**, in three
|
||||
configurations, 8 paired seeds each, with a measured floor (0.0556 / 0.3325) confirming the
|
||||
models do learn from the board. This is a fact about this readout and not about chess: the
|
||||
domain measurement in `chess_history.md` stands, and the mismatch above says why the two
|
||||
disagree.
|
||||
|
||||
The GRP numbers here (-0.0057, +0.0023, -0.0065 against the width-matched memoryless arm)
|
||||
should not be read as memory results. The oracle gates them, and the oracle is ambiguous
|
||||
in every configuration.
|
||||
|
||||
## Limits
|
||||
|
||||
- The type-conditional kernel was verified to learn piece movement on the *reachability* task,
|
||||
not on this one. Representability here is inferred, not measured.
|
||||
- Move quality is uncontrolled: blitz games across a wide rating range.
|
||||
- Accuracy hands legality to the model at readout time; the loss never sees it.
|
||||
- No cross-entropy readout was tried here. That change was made in `chess_dist.py` and it
|
||||
reverses the conclusion: accuracy 0.40 -> 0.47 and every memory comparison flips positive.
|
||||
See `chess_dist.md`. The nulls in this file are facts about an MSE readout and nothing more.
|
||||
|
||||
Reproduce with:
|
||||
|
||||
```bash
|
||||
uv run --with chess python chess_domain.py --games 400 --seeds 0,1,2,3,4,5,6,7 \
|
||||
--arms constant,rp,grp,rp_wide,rp_oracle # all-ones, type-blind
|
||||
uv run --with chess python chess_domain.py --games 400 --seeds 0,1,2,3,4,5,6,7 --mask attack \
|
||||
--arms rp,grp,rp_wide,rp_oracle # attack mask
|
||||
uv run --with chess python chess_domain.py --games 400 --seeds 0,1,2,3,4,5,6,7 --edges type \
|
||||
--arms constant,rp,grp,rp_wide,rp_oracle # type in e_ij
|
||||
```
|
||||
@@ -0,0 +1,115 @@
|
||||
# Does the organism learn how a piece moves?
|
||||
|
||||
Every memory result in this project so far assumed the model understood its domain. On chess
|
||||
that assumption had never been measured. This file measures it, and the answer changes what
|
||||
the earlier chess nulls mean.
|
||||
|
||||
**Answer: only when the piece's type enters the CPPN.** With the type reaching the kernel
|
||||
through the spec's edge-type channel, the knight's L is recovered at 0.758. Without it, on
|
||||
every seed, the knight scores **exactly zero** — the model learns one average movement shape
|
||||
and applies it to all six types.
|
||||
|
||||
## Setup
|
||||
|
||||
Target: `board.attacks(square)` for every live piece, as a multi-hot over the 15x15 grid of
|
||||
**relative** offsets. Relative, not absolute, and that is not a convenience: the CPPN sees only
|
||||
`r_ij`, so an entity's representation is translation-invariant and cannot know which absolute
|
||||
square it stands on. A 64-square target is unanswerable by construction. In offset space the
|
||||
question is the one worth asking — a knight's L is eight cells, a bishop's is four rays.
|
||||
|
||||
Loss is BCE over all live entities, not just one mover. Metric is precision@k per entity, with
|
||||
k the true number of reachable offsets: of the k offsets it ranks highest, how many are real.
|
||||
|
||||
Three controls, and the first is the one the question needs:
|
||||
|
||||
- **`constant`** — every piece moves like the average piece: offsets ranked by their marginal
|
||||
frequency, blind to type and to position. Beating it is what "tells a pawn from a bishop"
|
||||
means. It is not a weak floor; it scores 0.4065 where random ranking scores 0.0191.
|
||||
- **`rp` vs `rp_type`** — `--edges type` puts the receiving piece's type into `e_ij`, which is
|
||||
the spec's own channel into the CPPN. Without it the kernel is type-blind: type lives in
|
||||
`attrs` and meets the kernel only as an elementwise product, so the *geometry function* is
|
||||
shared across all six types.
|
||||
- **`grp_type`** — memory, on the arm that works. Reachability is fully determined by the
|
||||
present, so this is the redundant case and memory should buy nothing.
|
||||
|
||||
400 games, 28 067 plies, 8 seeds, split by game. Affect neutral, kappa 0.
|
||||
|
||||
## Results
|
||||
|
||||
```
|
||||
arm loss prec@k pawn knight bishop rook queen king params
|
||||
constant --- 0.4065 0.4300 0.0000 0.5017 0.1665 0.5921 0.6617 225
|
||||
rp 0.0527 0.4570 0.5115 0.0000 0.5185 0.1907 0.6320 0.7004 8961
|
||||
rp_type 0.0316 0.5587 0.4363 0.7575 0.6409 0.5763 0.6762 0.7461 9121
|
||||
grp_type 0.0537 0.4122 0.4328 0.0000 0.5012 0.1709 0.6244 0.6613 13281
|
||||
|
||||
random ranking scores 0.0191
|
||||
|
||||
rp_type - rp: +0.1016 +/- 0.0280 (paired se), 7/8 seeds
|
||||
grp_type - rp_type: -0.1465 +/- 0.0010 (paired se), 0/8 seeds
|
||||
```
|
||||
|
||||
Per-seed knight precision, which is the whole result in one row:
|
||||
|
||||
```
|
||||
constant 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
|
||||
rp 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
|
||||
rp_type 0.742 0.755 0.749 0.768 0.750 0.768 0.766 0.763
|
||||
grp_type 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000
|
||||
```
|
||||
|
||||
## What it establishes
|
||||
|
||||
**The type must enter the kernel, not the features.** 160 extra parameters — 1.8% — flip the
|
||||
knight from exactly zero to 0.758 on 8/8 seeds. That is not capacity, and the discontinuity
|
||||
says why: the type-blind kernel is one geometry function scaled by a type vector, and the
|
||||
knight's L cannot be reached by scaling the average movement shape. The bishop (0.52 -> 0.64)
|
||||
and the rook (0.19 -> 0.58) move the same way; the rook's gain is the second-largest, and its
|
||||
rays are the second-least average-like pattern.
|
||||
|
||||
**Memory does not merely fail here; it destroys the result.** `grp_type` carries 46% more
|
||||
parameters than `rp_type` and lands back on the floor's profile, knight at zero on 8/8 seeds,
|
||||
at 146 paired standard errors. The mechanism is legible: the readout is `W_out M_i`, and with
|
||||
the gate near 0.5 half of that vector is the previous ply's state. A task determined entirely
|
||||
by the present is damaged by mixing in the past.
|
||||
|
||||
This is the redundant case from the poker framing — the evidence is already in the present —
|
||||
and it is the positive control the instrument needed. It also removes a possible objection to
|
||||
the earlier chess nulls: the GRP path is measurably capable of destroying a signal that is
|
||||
present, so those nulls were not produced by an inert mechanism.
|
||||
|
||||
**Why the per-type breakdown is not decoration.** On seed 4 the aggregate gain is *negative*
|
||||
(-0.082) while the knight sits at 0.750. Pawns are half the pieces on the board, so an
|
||||
aggregate can be carried, or masked, by pawns alone. Reading only `prec@k` would have reported
|
||||
this seed as evidence against the effect.
|
||||
|
||||
## Limits, stated rather than discovered later
|
||||
|
||||
- **Precision@k is a hard ranking threshold.** "Knight = 0.000" means no L cell reaches the
|
||||
top-k, not that the logits carry nothing. A soft metric could show partial structure below
|
||||
that threshold; this measurement does not look.
|
||||
- **`rp_type` makes pawns worse** (0.5115 -> 0.4363). Type-conditioning redistributes capacity,
|
||||
and the pawn — whose two diagonals are close to the average short-range shape — pays for it.
|
||||
Reported because it is a cost, not an artefact to explain away.
|
||||
- **Pawns are measured on captures only.** `board.attacks` is the two diagonals, not the
|
||||
forward push, so for pawns this is capture geometry.
|
||||
- **Pins and check are ignored.** `attacks` is geometry plus blockers. Legality proper is a
|
||||
more global question and is not asked here.
|
||||
- No width-matched arm for the memory comparison. `grp_type` already has 46% more parameters
|
||||
and is worse, so matching would only widen the gap; the direction is safe, the magnitude is
|
||||
not a clean estimate.
|
||||
|
||||
## What it means for the memory line
|
||||
|
||||
The earlier chess results (`chess_domain.py`, move prediction) were measured on a model whose
|
||||
kernel was type-blind — one that, as this file shows, had not learned that a knight moves in an
|
||||
L. Those nulls stand as facts about that setup and should not be read as facts about memory in
|
||||
chess. The domain question `chess_history.md` answered positively is still open at the level of
|
||||
the organism, and it is now askable on a model that understands the pieces.
|
||||
|
||||
Reproduce with:
|
||||
|
||||
```bash
|
||||
uv run --with chess python chess_reach.py --games 400 --seeds 0,1,2,3,4,5,6,7 \
|
||||
--arms constant,rp,rp_type,grp_type
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Identity is the load-bearing part: a memory slot must follow the same piece.
|
||||
|
||||
If `advance_ids` drifts, every arm still trains and every number still prints -- the memory
|
||||
just follows the wrong piece. That failure is silent, so it gets the test.
|
||||
"""
|
||||
import chess
|
||||
import chess.pgn
|
||||
import pytest
|
||||
|
||||
import chess_domain
|
||||
|
||||
|
||||
def _game(fen: str | None, sans: list[str]) -> chess.pgn.Game:
|
||||
board = chess.Board(fen) if fen else chess.Board()
|
||||
for san in sans:
|
||||
board.push_san(san)
|
||||
return chess.pgn.Game.from_board(board)
|
||||
|
||||
|
||||
CASTLE_EP = ["e4", "e5", "Nf3", "Nf6", "Bc4", "Bc5", "O-O", "O-O",
|
||||
"d4", "exd4", "e5", "d5", "exd6"]
|
||||
|
||||
|
||||
def test_rook_keeps_its_id_through_castling():
|
||||
plies = chess_domain.plies(_game(None, CASTLE_EP))
|
||||
h1 = chess.H1
|
||||
after = next(p for p in plies if h1 not in # h1 empty: rook has moved
|
||||
[chess.square(int(c[0] * 7), int(c[1] * 7)) for c in p.coords])
|
||||
f1_row = [k for k, c in enumerate(after.coords)
|
||||
if chess.square(int(c[0] * 7), int(c[1] * 7)) == chess.F1][0]
|
||||
assert after.ids[f1_row] == h1, "the castled rook was handed a new identity"
|
||||
|
||||
|
||||
def test_promoted_pawn_keeps_its_id_and_changes_type():
|
||||
plies = chess_domain.plies(_game("1r4k1/P7/8/8/8/8/8/6K1 w - - 0 1", ["axb8=Q", "Kf7"]))
|
||||
row = plies[-1].ids.index(chess.A7) # the pawn that started on a7
|
||||
coords = plies[-1].coords[row]
|
||||
assert chess.square(int(coords[0] * 7), int(coords[1] * 7)) == chess.B8
|
||||
assert plies[-1].attrs[row][chess.QUEEN - 1] == 1.0, "promotion did not change the type"
|
||||
|
||||
|
||||
def test_the_identity_assertion_can_actually_fire(monkeypatch):
|
||||
"""Sabotage: stop tracking captures, and the board must disagree with the map."""
|
||||
monkeypatch.setattr(chess_domain, "advance_ids",
|
||||
lambda board, move, piece, id_at: id_at.update(
|
||||
{move.to_square: id_at.pop(move.from_square, move.from_square)}))
|
||||
with pytest.raises(AssertionError, match="drifted"):
|
||||
chess_domain.plies(_game(None, CASTLE_EP))
|
||||
Reference in new issue
Block a user