"""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): 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, 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) -> 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) loss, hits, chance = [], [], [] for gi in order[:cut]: l, h, c = _stream(org, games[gi], None, bptt, oracle, edges) loss += l; hits += h; chance += c return dict(seed=seed, memory=memory, oracle=oracle, 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)} 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)) | {"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")): 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()