Compare commits

...
24 Commits
Author SHA1 Message Date
chrnxandClaude Opus 5 4fc5b38be9 feat: learned-frame arm and an orbit-consistency diagnostic
rp_learn_K learns K linear maps on the displacement and averages the CPPN over
them, so a set closed under the domain's group makes the kernel invariant to it
without anyone naming the group. orbit_consistency measures that invariance from
the kernel's behaviour rather than its parameters, validated against the two
kernels whose answers are known exactly.

Both false-positive modes are instrumented: fit-versus-held-out separates extra
capacity from discovery, and the spread of the learned maps catches a collapse
to K=1.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 19:45:14 -05:00
chrnxandClaude Opus 5 ff8ccbc819 feat: D4-invariant kernel input recovers the knight rule from partial support
InvariantCPPN canonicalises the displacement to (min|dx|, max|dy|), collapsing
the square's eight symmetries to one orbit, plus a knight_sym teacher whose
eight L-squares carry one value and are therefore a genuine D4 orbit.

Trained on six of the eight, it recovers the other two at 0.4% of the floor on
6/6 seeds where the raw-displacement kernel sits above the floor.

Two controls, both predicted beforehand: on a teacher whose eight squares share
a support but not a value the invariance is worse than nothing, and on a smooth
teacher with no D4 symmetry it costs 31x.

The arm dispatch now raises on unknown names -- an edit had silently failed to
land and rp_inv ran as plain rp, which looked like a null.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 19:12:03 -05:00
chrnxandClaude Opus 5 3feba1baac feat: vary kernel sharpness and hold-out structure -- both readings change
Four teacher families on one axis (how predictable the kernel is from its
neighbours): smooth, high-frequency, a rule-generated sparse knight, and iid
noise as the negative control, which is asserted to have neighbour correlation
below 0.2 where the smooth teacher's is above 0.8.

The knight teacher forced a new hold-out: most of its cells are exactly zero, so
withholding uniformly asks nothing and the floor collapses. --holdout support
withholds cells the kernel uses, closed under negation since a pair contributes
r and -r.

Under it the CPPN beats a lookup plus blur 4.4x on smooth and 3.0x on
high-frequency, 6/6 seeds, reversing the earlier headline. And on the knight
nothing generalises at all -- both arms at or above the floor.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 18:42:15 -05:00
chrnxandClaude Opus 5 ac10bbca4e feat: psi as a continuous kernel axis -- the deciding test
Teacher changes the kernel's shape with psi (valence rotates the frequency,
arousal widens the envelope), never its gain, guarded by a test checked against
a teacher deliberately reduced to a gain.

The CPPN answers for withheld psi at 1.18x its trained-psi error from 720
parameters. A binned table plus interpolation along psi matches it on 6 seeds of
6 using 57,600. Not a sample-budget artefact: the largest table at 4x the steps
fits three times better and generalises not at all better.

The bare tables' 19x failure is arithmetic -- their bin never saw gradient --
and is labelled as scale rather than evidence, which is why the interp arms
exist at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 18:12:53 -05:00
chrnxandClaude Opus 5 d95383f8a2 feat: omega curve and unseen-N, the two steps before psi
omega.md: a plateau at [1,4] that does not track the domain across a 4.7x range,
so the bandwidth is a knob that was set wrong rather than a defect to design
around. omega=8 is an optimisation cliff, not a mis-tune. The project default of
10 is outside the plateau.

scale.md: one parameter set works at an entity count it never trained on --
trained on N<=16 it beats the oracle at N=32 -- and a lookup table does it too.
Read against an oracle because the mse/floor ratio is not comparable across N,
which is asserted as a test rather than claimed in prose. The cost runs
large->small only, at 2.28x, which makes it the pooling's 1/deg dilution rather
than a degree-distribution shift.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 17:45:41 -05:00
chrnxandClaude Opus 5 6c545fd035 feat: unseen relations -- the one property that separates the RP from a GNN
A GNN holds fixed weights per edge type: a lookup with one entry per discrete
relation. The CPPN computes weights from geometry, so it has something to say
about a displacement absent from training. Every chess run trained and evaluated
on the same offset grid, so this had never been tested.

Student-teacher with an analytic Gabor kernel; held-out cells masked out of
training via the RP's own mask argument; evaluation always on pairs so seen and
unseen measure the same object. Eight seeds, two hold-out structures.

The property is real -- held-out error 1.28x seen error, lower on 3/8 seeds -- and
smaller than the framing assumed. The bare table fails by construction and is
labelled as scale, not evidence. Against a table plus neighbour diffusion the
CPPN wins interpolation 2x on 6/8 seeds and loses extrapolation on 8/8. At
omega=10, the default every chess run used, it is 17x worse and below the
smoothed table even on interpolation.

The boundary is the useful part: the diffusion control exists only because the
relation space was enumerable. Chess is exactly such a domain.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb
2026-09-07 17:02:46 -05:00
chrnx 79b0324537 exp: colour in the kernel helps exactly the pieces whose law depends on it
rp_typecol gains on pawn (+0.085), knight (+0.010) and bishop (+0.015) and loses on rook
(-0.022), queen (-0.015) and king (-0.010). The owner named that split in advance from chess,
not from the data. A capacity story predicts a uniform gain and the sign flip rules it out:
twelve kernels halve the data behind each, which pays only where colour changes the law.

First arm to exceed the rule-knowing control in aggregate, 0.8353 against 0.8305 -- by a
different route than rp, which beats it on rook, queen and king where typecol does not.
2026-09-02 20:10:20 -05:00
chrnx 9859bad9d7 exp: the RP learns the movement rules, and reads the board where it counts
Beats the rule-knowing control on rook (+0.016), queen (+0.006) and king (+0.009) -- the
pieces whose moves are cut by occupancy. Still below on pawn, bishop and knight.

Absolute position is worth +0.020 and halves the gap to the control, which had been handed
the square all along. The rim mechanism proposed for why it pays is recorded as unverified:
per type the gain is flat and the knight, 43% of which sit on the rim, gained less than the
queen.
2026-09-02 20:04:43 -05:00
chrnx 67cf06bd71 exp: type-by-colour edge types, twelve kernels instead of six
The type-conditional kernel lost 0.14 on pawns and nothing elsewhere, because e_ij carried the
piece type and not its colour: a white pawn and a black pawn share one kernel and their moves
are mirrored. typecol gives each colour its own.
2026-09-02 19:59:14 -05:00
chrnx 4567c2e18b exp: absolute position and own-side rank as attributes
The CPPN sees only r_ij, so the representation is translation-invariant and a chess board has
edges: a knight has 2.96 destinations on the rim against 6.85 in the middle, and 43% of them
sit on the rim. Relative geometry to other pieces cannot recover that on a near-empty board,
and the shape control is handed the square while the organism was not.

own_rank is rank from the piece's own back rank, so a pawn's push, its double-push rank, its
promotion and castling are one law rather than two mirrored ones.
2026-09-02 19:38:10 -05:00
chrnx 9e7f347464 exp: teach the movement rules directly, on generated positions
Games are a bad curriculum for this and both reasons are measured. Coverage: a rook or queen
is blocked in 98-100% of real positions, so the model learned the geometry it saw and scored
worse in open positions than blocked ones. Content: the reachability target left out three
rules entirely -- a pawn on e2 attacks d3 and f3 while its moves are e3 and e4, no overlap at
all; castling and en passant never appeared. The target here is generate_pseudo_legal_moves.

Piece count is sampled uniformly from 2 to 32, so an empty board is as common as a crowded
one. Castling rights and the ep square are handed over as attributes, because they are state
rather than position and without them the same board has two correct answers. Taking them
away is the cleanest memory experiment available, and belongs to the parked GRP line.

Positions are streamed, never stored: 200k dense targets would be 6 GB.
2026-09-02 19:16:49 -05:00
chrnx 18345f2a3e exp: the shape control — knows the movement rule, reads nothing from the board
The open/blocked split cannot work as posed: in real games a rook and a queen are blocked
essentially always (share blocked 1.00, 1.00, bishop 0.89), so there is no open bucket to
contrast against. The control that does answer the question is a floor that knows each
piece's type and its empty-board attack set and nothing else. Beating it means reading
occupancy. For a knight or a king it is the exact answer, so it doubles as a ceiling.
2026-09-02 19:00:00 -05:00
chrnx 70ddc7a856 exp: per-entity memory pays, and grp_nostate says the state is what pays
grp - grp_nostate is +0.0164 +/- 0.0025 on 8/8 seeds: same architecture, same 13281
parameters, same gate, handed an empty memory every ply. The state is the difference.

The gated architecture with empty memory is WORSE than the plain memoryless one (-0.0106,
0/8), inverting the particles finding where the margin was the gate rather than the state.

The history oracle reads +0.0020 on 5/8 while the learned state gains three times that, so
the oracle's six-dimensional encoding was bounding its own ceiling, not the domain's.
2026-09-02 18:37:14 -05:00
chrnx cde475016f exp: grp_nostate, the control that separates the state from the gate 2026-09-02 18:31:55 -05:00
chrnx 2470370a4e exp: move prediction as a distribution over legal destinations
Cross-entropy over the legal offsets instead of MSE on their mean. Same target, same chance,
same conditioning -- only the readout changes, which is the sanctioned move when a metric
cannot tell the mechanism apart from a cheaper one.

The width match is recomputed at target_dim=225: with the readout dominating, a width matched
at target_dim=2 is wrong several times over. The oracle sits at the same width as rp, so the
ceiling is not confounded with capacity.
2026-09-02 18:26:26 -05:00
chrnx 6e3326426e exp: the move task's objective and its question move in opposite directions
Type in the CPPN improves MSE 0.03888 -> 0.03547 and makes accuracy worse, 0.4144 -> 0.3998.
MSE fits the conditional mean of the destinations; history shifts their distribution and
barely moves the mean, so the readout discards the shape of information history carries.

The history oracle is ambiguous in all three configurations (+0.0014, -0.0003, -0.0006), so
no GRP number in this task is a memory result.
2026-09-02 18:23:41 -05:00
chrnx e7737b8138 exp: --edges type on the move task, so the kernel is type-conditional there too 2026-09-02 18:16:37 -05:00
chrnx f49840f73d docs: verify the model represents the domain before asking what memory adds 2026-09-02 18:15:16 -05:00
chrnx f89472dca3 exp: the CPPN learns the knight's L only when the type enters the kernel
Knight precision@k is exactly 0.000 on 8/8 seeds without type in e_ij and 0.758 on 8/8 with
it -- 160 extra parameters, 1.8%. The type-blind kernel is one geometry function scaled by a
type vector, and a knight's L is not a scaling of the average movement shape.

grp_type carries 46% more parameters and lands back on the floor, knight at zero on 8/8, at
146 paired se. Reachability is present-determined, so this is the redundant case: the gate
mixes the previous ply into a representation that only needs now. It doubles as the positive
control the instrument lacked -- the GRP path can measurably destroy a signal that is there.

The earlier chess move-prediction nulls were measured on a type-blind model and are facts
about that setup, not about memory in chess.
2026-09-02 18:10:16 -05:00
chrnx 2b11e2acd2 exp: does the organism learn how a piece moves
Reachability in relative-offset space, not absolute squares: the CPPN sees only r_ij, so an
entity's representation is translation-invariant and an absolute-square target is
unanswerable by construction. In offset space a knight's L is eight cells.

The floor is 'every piece moves like the average piece', which is the control the question
needs: beating it means the model tells a pawn from a bishop. Precision is also reported per
piece type, since pawns are half the board and can carry the aggregate on their own.

--edges type puts the receiving piece's type into e_ij, the spec's own channel into the CPPN.
Without it the kernel is type-blind: type reaches it only as an elementwise product.
2026-09-02 18:03:03 -05:00
chrnx 1c28987649 exp: chess attack adjacency is a measured null, and the oracle still does not pay
Mean degree falls 30 -> 3.3. Accuracy falls with it (0.414 -> 0.381): the mask removes
board information the model was using. The dilution hypothesis is not supported -- the
history oracle reads -0.0003 +/- 0.0019 on 4/8 seeds, ambiguous, same as under all-ones.
grp - rp_wide is +0.0023 +/- 0.0026 on 4/8, so the earlier -0.0057 dissolves too.

Twice-controlled: per-entity history does not pay under contract A with an MSE readout,
in either adjacency.
2026-09-02 17:54:10 -05:00
chrnx 8ea61f9617 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.
2026-09-02 17:42:44 -05:00
chrnx ceb98ce33c feat: chess domain under contract A, RP vs GRP width-matched
The target is the mover's displacement with the loss masked to the mover: one piece
moves per ply, so the spec's literal per-entity default is 31/32 zeros and the constant
predictor wins. Same conditioning the history probe measured under, so its headroom is
the ceiling on this task.

Affect held neutral (psi=(0,0), kappa=0) so memory is the only axis that moves;
--affect stream runs the real chain when that changes.

A memoryless arm is width-matched to the gated model's parameter count, since 1442 vs
5602 is confounded 3.9x and is not a memory result.
2026-09-02 17:32:37 -05:00
chrnx 38a090e1f7 exp: chess has the per-entity history particles lacked
A piece's own past predicts its next square beyond the board: +0.056 with ridge on 6/6
seeds, +0.034 with a 2x128 MLP on 3/3, eleven paired standard errors from zero. The
shuffled-history control is negative in both arms, so the gain is about the alignment
between a piece's past and its future rather than about feature count. Split by game,
never by position.

The MLP reads more from the board alone than ridge does, so part of what history gave the
linear model was recoverable from the present; the gain shrinks from +0.056 to +0.034 and
this measurement does not establish where that stops. Stated as the caveat it is.

This is the property particles lacked. There the hidden variable was global -- one coupling
matrix belonging to no entity -- and the per-entity state held less about it than the
memoryless representation it was built from. Here what there is to remember belongs to the
piece.
2026-09-02 17:20:45 -05:00
29 changed files with 4032 additions and 8 deletions

No files matched your search

+23
View File
@@ -39,6 +39,29 @@ 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.
- **Teach the basics before measuring anything on top of them.** Training from scratch means
the domain's laws have to be *reachable* from what the organism is given, and on chess five
separate things were not, each found by measurement rather than argument:
the piece type never entered the kernel (knight's L at exactly 0.000, `chess_reach.md`);
the target was `attacks`, which for a pawn on e2 returns d3/f3 while its moves are e3/e4 —
no overlap — and omits castling and en passant entirely;
games never show an open board (a rook is blocked in 98-100% of real positions), so the rule
cannot be induced from play;
absolute position was erased by a translation-invariant input, while the answer depends on it
(a knight has 2.96 destinations on the rim and 6.85 in the middle, and 43% sit on the rim);
and rank was not oriented to the piece's own side, which splits one pawn law into two
mirrored ones.
Every memory null measured before these were fixed stands as a fact about that setup and
about nothing else. Before asking what a mechanism adds, check that the domain's own laws
are expressible in the inputs, the target, and the training distribution.
- **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.
+46
View File
@@ -0,0 +1,46 @@
"""Does one parameter set still WORK at an entity count it never trained on?
Read against the ORACLE, never down the N axis. `y_i` is a mean over neighbours, so the target's
variance falls as N rises and any error-over-floor ratio climbs with N for a model that is doing
nothing wrong. The oracle -- trained over the full range [2,32] -- absorbs all of that: at each
N, `forward / oracle` is the cost of never having seen that entity count, and nothing else.
Both directions are reported. A cost in BOTH is the degree distribution shifting under the mean
pooling; a cost in ONE is the extrapolation that was actually asked for.
"""
import json, statistics as st
def load(tag, arm):
rs = json.load(open(f"results/scale_{tag}.json"))["rows"]
return [r for r in rs if r["arm"] == arm]
def per_n(rows, n):
return st.mean([r["per_n"][str(n)]["mse"] for r in rows])
def paired(a, b, n):
d = [x["per_n"][str(n)]["mse"] - y["per_n"][str(n)]["mse"] for x, y in zip(a, b)]
return st.mean(d), st.stdev(d) / len(d) ** 0.5, sum(1 for v in d if v > 0), len(d)
NS = [2, 4, 8, 12, 16, 20, 24, 28, 32]
for arm in ("rp", "table"):
fwd, rev, orc = (load(t, arm) for t in ("forward", "reverse", "oracle"))
print(f"\n{'=' * 78}\n{arm.upper()} raw MSE, and cost against the oracle trained on [2,32]\n{'=' * 78}")
print(f"{'N':>4} {'fwd[2,16]':>10} {'rev[17,32]':>11} {'oracle':>10} "
f"{'fwd/orc':>8} {'rev/orc':>8} trained on N?")
for n in NS:
f, r, o = per_n(fwd, n), per_n(rev, n), per_n(orc, n)
tag = "fwd" if n <= 16 else "rev"
print(f"{n:>4} {f:10.5f} {r:11.5f} {o:10.5f} {f / o:8.2f} {r / o:8.2f} {tag} only")
print()
for label, arms_, ns in (("forward, unseen N (17-32)", fwd, [20, 24, 28, 32]),
("reverse, unseen N (2-16)", rev, [2, 4, 8, 12])):
ms = [paired(orc, arms_, n) for n in ns]
tot = st.mean([m for m, _, _, _ in ms])
won = sum(w for _, _, w, _ in ms)
print(f" {label}: mean cost over oracle {tot:+.5f} "
f"{won}/{sum(k for _, _, _, k in ms)} seed-points worse than oracle")
+39
View File
@@ -0,0 +1,39 @@
"""The omega curve. Prints all of it, which is the point.
omega sets the CPPN's bandwidth. `unseen.md` found a 17x swing between two hand-picked values
and every chess number sits at one of them, unexamined. This decides which of two things that
is: a knob that was set wrong (broad plateau -> document it, choose per domain, leave
AffectiveCPPN alone) or an architectural defect (narrow, domain-dependent optimum -> a learned
or multi-scale frequency is a mechanism question worth asking).
THE TRAP, stated so it cannot be walked into: this reports the whole curve. Picking the omega
that beats table+interp and quoting that number would be tuning a mechanism until it wins,
which is the move AGENTS.md exists to forbid.
"""
import glob, json, re, statistics as st
REF = {"random": 0.00016, "band": 0.00006} # table+interp, from unseen.md
def load(path):
return [r for r in json.load(open(path))["rows"] if r["arm"] == "rp"]
for kind in ("random", "band"):
files = sorted(glob.glob(f"results/sweep_{kind}_w*.json"),
key=lambda f: float(re.search(r"_w([\d.]+)\.json", f).group(1)))
if not files:
print(f"{kind}: nothing yet")
continue
print(f"\n{'=' * 78}\n{kind.upper()} hold-out — omega curve, 8 seeds"
f" (table+interp reference: {REF[kind]:.5f})\n{'=' * 78}")
print(f"{'omega':>6} {'seen':>10} {'unseen':>10} {'u/s':>6} {'vs ref':>8} "
f"{'seeds<ref':>10} per-seed unseen")
for f in files:
w = float(re.search(r"_w([\d.]+)\.json", f).group(1))
rs = load(f)
seen, uns = st.mean([r["seen"] for r in rs]), st.mean([r["unseen"] for r in rs])
beat = sum(1 for r in rs if r["unseen"] < REF[kind])
per = " ".join(f"{r['unseen']:.5f}" for r in sorted(rs, key=lambda r: r["seed"]))
print(f"{w:>6g} {seen:10.5f} {uns:10.5f} {uns / seen:6.2f} "
f"{uns / REF[kind]:8.2f}x {beat:>7}/8 {per}")
+49
View File
@@ -0,0 +1,49 @@
"""Paired comparison across the arms of unseen.py. Per-seed values, seeds won, paired se."""
import json, statistics as st
def rows(path, arm=None):
rs = json.load(open(path))["rows"]
return {r["seed"]: r for r in rs if arm is None or r["arm"] == arm}
def paired(a, b, key="unseen"):
d = [b[s][key] - a[s][key] for s in sorted(a)]
return st.mean(d), st.stdev(d) / len(d) ** 0.5, sum(1 for x in d if x > 0), len(d)
def col(d, key="unseen"):
return st.mean([r[key] for r in d.values()])
for kind in ("random", "band"):
rp = rows(f"results/unseen_{kind}.json", "rp")
tb = rows(f"results/unseen_{kind}.json", "table")
it = rows(f"results/unseen_{kind}_interp.json", "table_interp")
try:
w10 = rows(f"results/unseen_{kind}_w10.json", "rp")
except FileNotFoundError:
w10 = None
print(f"\n{'=' * 72}\n{kind.upper()} hold-out, {rp[0]['n_held']}/225 cells "
f"(MSE on held-out relations, lower is better)\n{'=' * 72}")
print(f"{'seed':>4} {'rp':>10} {'table':>10} {'tbl+interp':>12} {'rp w=10':>10} {'floor':>10}")
for s in sorted(rp):
w = f"{w10[s]['unseen']:10.5f}" if w10 else f"{'-':>10}"
print(f"{s:>4} {rp[s]['unseen']:10.5f} {tb[s]['unseen']:10.5f} "
f"{it[s]['unseen']:12.5f} {w} {rp[s]['floor_unseen']:10.5f}")
wm = f"{col(w10):10.5f}" if w10 else f"{'-':>10}"
print(f"{'mean':>4} {col(rp):10.5f} {col(tb):10.5f} {col(it):12.5f} {wm} "
f"{col(rp, 'floor_unseen'):10.5f}")
for name, other in (("table", tb), ("table+interp", it)):
m, se, won, n = paired(rp, other)
verdict = ("inside one se of zero" if abs(m) < se
else ("rp better" if m > 0 else "*** rp WORSE ***"))
print(f"\n {name:12s} - rp: {m:+.5f} +/- {se:.5f} {won}/{n} seeds {verdict}")
if w10:
m, se, won, n = paired(rp, w10)
print(f" omega=10 - rp: {m:+.5f} +/- {se:.5f} {won}/{n} seeds")
r = [rp[s]["unseen"] / rp[s]["seen"] for s in sorted(rp)]
print(f"\n rp unseen/seen mean {st.mean(r):.2f} per seed {' '.join(f'{x:.2f}' for x in r)}")
+195
View File
@@ -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
View File
@@ -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()
+40 -8
View File
@@ -105,22 +105,52 @@ def collect(n_games: int, hist: int, min_moves: int, seed: int):
return np.array(A), np.array(B), np.array(y), np.array(gid)
def fit_eval(Xtr, ytr, Xte, yte, l2: float = 1.0):
"""Ridge onto one-hot targets, argmax at test. One estimator for both arms, so the
difference between them is about the features and not about the fit."""
K = 64
Y = np.zeros((len(ytr), K), dtype=np.float32)
def fit_ridge(Xtr, ytr, Xte, yte, l2: float = 1.0):
"""Ridge onto one-hot targets, argmax at test."""
Y = np.zeros((len(ytr), 64), dtype=np.float32)
Y[np.arange(len(ytr)), ytr] = 1.0
d = Xtr.shape[1]
W = np.linalg.solve(Xtr.T @ Xtr + l2 * np.eye(d, dtype=np.float32), Xtr.T @ Y)
return float((np.argmax(Xte @ W, axis=1) == yte).mean())
def fit_mlp(Xtr, ytr, Xte, yte, hidden: int = 128, epochs: int = 12, bs: int = 512):
"""A 2xN ReLU net on the same features.
Task 11 is why this arm exists: on the particles domain a linear decoder read 0.23
where an MLP read 0.83 on identical features, so a linear null there would have been
wrong by 0.6 in accuracy. A linear-only null here would inherit that objection.
"""
import torch
g = torch.Generator().manual_seed(0)
Xtr_t = torch.from_numpy(Xtr); ytr_t = torch.from_numpy(ytr).long()
net = torch.nn.Sequential(
torch.nn.Linear(Xtr.shape[1], hidden), torch.nn.ReLU(),
torch.nn.Linear(hidden, hidden), torch.nn.ReLU(),
torch.nn.Linear(hidden, 64))
opt = torch.optim.Adam(net.parameters(), lr=1e-3)
n = len(ytr_t)
for _ in range(epochs):
perm = torch.randperm(n, generator=g)
for i in range(0, n, bs):
idx = perm[i:i + bs]
opt.zero_grad()
torch.nn.functional.cross_entropy(net(Xtr_t[idx]), ytr_t[idx]).backward()
opt.step()
with torch.no_grad():
pred = net(torch.from_numpy(Xte)).argmax(1).numpy()
return float((pred == yte).mean())
FITS = {"ridge": fit_ridge, "mlp": fit_mlp}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--games", type=int, default=3000)
ap.add_argument("--hist", type=int, default=3, help="how many past squares B may see")
ap.add_argument("--min-moves", type=int, default=2, help="skip a piece's first moves")
ap.add_argument("--estimator", default="ridge", choices=sorted(FITS))
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7,8,9,10,11")
a = ap.parse_args()
@@ -128,7 +158,9 @@ def main() -> None:
print(f"{len(y)} moves from {gid.max() + 1} games, {A.shape[1]} present features, "
f"{B.shape[1]} with history\n")
fit = FITS[a.estimator]
gains = []
print(f"estimator: {a.estimator}\n")
print(f"{'seed':>5}{'present':>10}{'+history':>10}{'gain':>9}{'shuffled':>10}")
print("-" * 44)
for s in (int(x) for x in a.seeds.split(",")):
@@ -139,14 +171,14 @@ def main() -> None:
rng.shuffle(games)
te = np.isin(gid, games[: max(1, len(games) // 4)])
tr = ~te
acc_a = fit_eval(A[tr], y[tr], A[te], y[te])
acc_b = fit_eval(B[tr], y[tr], B[te], y[te])
acc_a = fit(A[tr], y[tr], A[te], y[te])
acc_b = fit(B[tr], y[tr], B[te], y[te])
# chance for the history arm: same features, history block shuffled across rows,
# so its marginal is intact and only its alignment with the target is broken
Bs = B.copy()
idx = rng.permutation(len(Bs))
Bs[:, 135:] = Bs[idx, 135:]
acc_s = fit_eval(Bs[tr], y[tr], Bs[te], y[te])
acc_s = fit(Bs[tr], y[tr], Bs[te], y[te])
gains.append((acc_a, acc_b, acc_b - acc_a, acc_s))
print(f"{s:>5}{acc_a:>10.4f}{acc_b:>10.4f}{acc_b - acc_a:>+9.4f}{acc_s:>10.4f}")
+307
View File
@@ -0,0 +1,307 @@
"""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 chess
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)
# how many squares each sliding piece would attack from each square on an EMPTY board. A piece
# attacking fewer than this is blocked, and a blocked ray is the part of chess geometry that
# cannot be memorised as a shape: the knight's L never changes, a rook's does.
_EMPTY_BB, _EMPTY = {}, {}
for _pt in range(1, 7):
for _col in (chess.WHITE, chess.BLACK):
for _sq in chess.SQUARES:
_b = chess.Board(None)
_b.set_piece_at(_sq, chess.Piece(_pt, _col))
bb = int(_b.attacks(_sq))
_EMPTY_BB[(_pt, _col, _sq)] = bb
_EMPTY[(_pt, _sq)] = bin(bb).count("1") # colour-free: only sliding uses this
SLIDING = (chess.BISHOP, chess.ROOK, chess.QUEEN)
def blocked_flags(ply) -> np.ndarray:
"""(N,) True where a sliding piece attacks fewer squares than it would on an empty board."""
t = ply.attrs[:, :6].argmax(1) + 1
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
have = np.array([bin(int(r)).count("1") for r in ply.reach])
full = np.array([_EMPTY.get((int(a), int(b)), -1) for a, b in zip(t, sq)])
return (full > 0) & (have < full)
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 run_shape(games, seed: int) -> dict:
"""The control the blocking question needs: knows the piece's type and its movement RULE,
reads nothing from the board.
Each entity is scored by its EMPTY-BOARD attack set from its own square, ties broken by
the marginal frequency of the offset. For a knight or a king this is the exact answer, so
the arm is also a ceiling: whatever it scores there is what perfect knowledge of the rule
is worth. For a sliding piece it is the un-blocked ray, so beating it means reading
occupancy -- knowing how far the ray is actually cut.
"""
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)
marg = marg / max(marg.max(), 1.0)
prec, chance, tsum, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
for gi in order[:cut]:
for ply in games[gi]:
y = torch.from_numpy(unpack(ply))
t = ply.attrs[:, :6].argmax(1) + 1
col = ply.attrs[:, 6].astype(bool)
sq = (np.rint(ply.coords[:, 0] * 7) + 8 * np.rint(ply.coords[:, 1] * 7)).astype(int)
score = np.tile(marg, (len(sq), 1)) * 0.5
for k_, (tt, cc, ss) in enumerate(zip(t, col, sq)):
bb = _EMPTY_BB[(int(tt), bool(cc), int(ss))]
hit_sq = [j for j in range(64) if bb >> j & 1]
score[k_, OFFSET[int(ss)][hit_sq]] += 1.0
rank = torch.from_numpy((-score).argsort(1).argsort(1))
k = y.sum(1); keep = k > 0
if keep.any():
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()))
kn = keep.numpy(); tt = ply.attrs[:, :6].argmax(1)[kn]
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
bl = blocked_flags(ply)[kn].astype(int)
np.add.at(bsum, (tt, bl, 0), hit[keep].numpy())
np.add.at(bsum, (tt, bl, 1), 1.0)
return dict(seed=seed, memory=False, edges=False, hidden=0, params=0,
loss=float("nan"), prec=statistics.fmean(prec), chance=statistics.fmean(chance),
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)),
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
n_block=bsum[:, :, 1].tolist())
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))
by_block = np.zeros((6, 2, 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
kn = keep.numpy()
tt = ply.attrs[:, :6].argmax(1)[kn]
np.add.at(by_type, (tt, 0), hit[keep].numpy())
np.add.at(by_type, (tt, 1), 1.0)
bl = blocked_flags(ply)[kn].astype(int)
np.add.at(by_block, (tt, bl, 0), hit[keep].numpy())
np.add.at(by_block, (tt, bl, 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, by_block
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, bsum = [], [], [], np.zeros((6, 2)), np.zeros((6, 2, 2))
for gi in order[:cut]:
l, p, c, t, b = _stream(org, games[gi], None, bptt, edges, adjacency)
loss += l; prec += p; chance += c; tsum += t; bsum += b
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)),
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
n_block=bsum[:, :, 1].tolist())
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, bsum = [], [], np.zeros((6, 2)), np.zeros((6, 2, 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()))
kn = keep.numpy()
tt = ply.attrs[:, :6].argmax(1)[kn]
np.add.at(tsum, (tt, 0), hit[keep].numpy()); np.add.at(tsum, (tt, 1), 1.0)
bl = blocked_flags(ply)[kn].astype(int)
np.add.at(bsum, (tt, bl, 0), hit[keep].numpy())
np.add.at(bsum, (tt, bl, 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)),
by_block=(bsum[:, :, 0] / np.maximum(bsum[:, :, 1], 1)).tolist(),
n_block=bsum[:, :, 1].tolist())
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,shape,rp,rp_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, "shape": "shape", "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_shape(games, seed) if spec == "shape" 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}")
# the blocker split: a knight's L never changes, a sliding piece's ray is cut by occupancy.
# Reported against the floor inside each bucket, because a blocked piece has a smaller
# attack set and therefore a different chance level -- the buckets are not comparable raw.
print(f"\n{'':<10}" + "".join(f"{t:>20}" for t in ("bishop", "rook", "queen")))
print(f"{'arm':<10}" + "".join(f"{'open':>10}{'blocked':>10}" for _ in range(3)))
print("-" * 70)
for n, rs in by.items():
row = ""
for i in (2, 3, 4):
for b in (0, 1):
row += f"{statistics.fmean(r['by_block'][i][b] for r in rs):>10.4f}"
print(f"{n:<10}{row}")
counts = by[list(by)[0]][0]["n_block"]
print("share blocked: " + " ".join(
f"{t}={counts[i][1] / max(counts[i][0] + counts[i][1], 1):.2f}"
for i, t in ((2, "bishop"), (3, "rook"), (4, "queen"))))
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()
+310
View File
@@ -0,0 +1,310 @@
"""How the pieces move, taught directly instead of inferred from games.
Two things games got wrong as a curriculum, both measured rather than assumed:
**Coverage.** In real play a rook or queen is blocked in 98-100% of positions
(`chess_shape.json`), so the model learns the geometry it sees rather than the rule that
generates it -- it scored *worse* in open positions than blocked ones. Here the number of
pieces is sampled uniformly from 2 to 32, so an empty board is as common as a crowded one.
**The target left out three rules entirely.** `board.attacks` is what the reachability task
asked for, and for a pawn on e2 it returns d3 and f3 while the pawn's actual moves are e3 and
e4 -- *no overlap at all*. Castling never appeared (the king's attack set is five adjacent
squares; c1 and g1 are not in it). Nor did en passant. The model did not fail to learn these;
it was never asked. The target here is `generate_pseudo_legal_moves`, which carries pushes,
castling and en passant.
Castling rights and the en-passant square are **state, not position**: a rook must remember
whether it has moved, and en passant depends on the opponent's last move. They are handed over
as per-entity attributes here so the rule is learnable at all -- without them the same board
has two different correct answers. Taking them away is the cleanest memory experiment this
project has available, and it belongs to the GRP line, which is parked (`AGENTS.md`).
No memory in this file. One position, one answer, no stream: this is the RP question alone.
"""
from __future__ import annotations
import argparse
import json
import statistics
from dataclasses import dataclass
from pathlib import Path
import chess
import numpy as np
import torch
from ailed import Affect, Organism
from chess_domain import flat_diff
from chess_reach import GRID, OFFSET
# type (6), colour (1), castling right (1), ep flag (1), file, rank, rank-from-my-own-side (3)
ATTR_DIM = 12
# The last three exist because the CPPN sees only r_ij, which makes the representation
# translation-invariant -- and a chess board has EDGES. A knight on the rim has 2.96
# destinations on average and one in the middle has 6.85, and 43% of knights sit on the rim
# (measured). Relative geometry to other pieces cannot recover that on a near-empty board.
# `own_rank` is rank from the piece's own back rank: a pawn's push, its double-push rank, its
# promotion rank and castling are all one law in that frame and two mirrored laws without it.
HOME = ((chess.WHITE, chess.E1, chess.H1, chess.A1), (chess.BLACK, chess.E8, chess.H8, chess.A8))
@dataclass
class Position:
attrs: np.ndarray # (N, 9)
coords: np.ndarray # (N, 2)
types: np.ndarray # (N,) 0-5, for the per-type breakdown
y: np.ndarray # (N, 225) multi-hot over relative offsets
shape: np.ndarray # (N, 225) what knowing the rule alone would answer
def _rights(b: chess.Board, rng) -> None:
fen = ""
for col, k_sq, r_k, r_q in HOME:
if b.piece_at(k_sq) == chess.Piece(chess.KING, col):
for r_sq, ch in ((r_k, "k"), (r_q, "q")):
if b.piece_at(r_sq) == chess.Piece(chess.ROOK, col) and rng.random() < 0.7:
fen += ch.upper() if col else ch
b.set_castling_fen(fen or "-")
def random_board(rng) -> chess.Board | None:
"""A position sampled for coverage, not for plausibility. Density is uniform by design."""
for _ in range(60):
b = chess.Board(None)
sqs = rng.permutation(64)
b.set_piece_at(int(sqs[0]), chess.Piece(chess.KING, chess.WHITE))
b.set_piece_at(int(sqs[1]), chess.Piece(chess.KING, chess.BLACK))
for sq in sqs[2:int(rng.integers(2, 33))]:
pt = int(rng.choice([1, 2, 3, 4, 5], p=[0.42, 0.16, 0.16, 0.16, 0.10]))
if pt == chess.PAWN and chess.square_rank(int(sq)) in (0, 7):
continue
b.set_piece_at(int(sq), chess.Piece(pt, bool(rng.integers(2))))
b.turn = bool(rng.integers(2))
_rights(b, rng)
if not b.is_valid():
continue
# an en-passant square, where a pawn sits as if it had just double-pushed
rank = 4 if b.turn == chess.WHITE else 3
cands = [s for s in chess.SQUARES if b.piece_at(s) == chess.Piece(chess.PAWN, not b.turn)
and chess.square_rank(s) == rank]
if cands and rng.random() < 0.35:
keep = b.ep_square
b.ep_square = int(rng.choice(cands)) + (8 if b.turn == chess.WHITE else -8)
if not b.is_valid():
b.ep_square = keep
return b
return None
def _dests(b: chess.Board) -> dict[int, set[int]]:
"""Every piece's pseudo-legal destinations, for both colours. Pushes, castling, ep."""
out: dict[int, set[int]] = {}
turn = b.turn
for col in (chess.WHITE, chess.BLACK):
b.turn = col
for m in b.generate_pseudo_legal_moves():
out.setdefault(m.from_square, set()).add(m.to_square)
b.turn = turn
return out
_RULE_CACHE: dict[tuple, frozenset] = {}
def _rule_only(piece: chess.Piece, sq: int, right: bool, ep: int | None) -> set[int]:
"""The control: this piece's moves on an EMPTY board, plus its own flags. Reads nothing.
Memoised: it is deterministic in its arguments and was rebuilding a Board per piece per
position, which dominated generation.
"""
key = (piece.piece_type, piece.color, sq, right, ep)
if key in _RULE_CACHE:
return _RULE_CACHE[key]
b = chess.Board(None)
b.set_piece_at(sq, piece)
b.turn = piece.color
b.set_castling_fen("-")
out = {m.to_square for m in b.generate_pseudo_legal_moves()}
if right and piece.piece_type == chess.KING:
out |= {sq - 2, sq + 2} # both castling destinations
if ep is not None and piece.piece_type == chess.PAWN:
out.add(ep)
_RULE_CACHE[key] = frozenset(out)
return _RULE_CACHE[key]
def build(b: chess.Board) -> Position:
dests = _dests(b)
squares = sorted(b.piece_map())
n = len(squares)
attrs = np.zeros((n, ATTR_DIM), dtype=np.float32)
coords = np.zeros((n, 2), dtype=np.float32)
types = np.zeros(n, dtype=np.int64)
y = np.zeros((n, GRID), dtype=np.float32)
shape = np.zeros((n, GRID), dtype=np.float32)
for k, sq in enumerate(squares):
p = b.piece_at(sq)
types[k] = p.piece_type - 1
attrs[k, p.piece_type - 1] = 1.0
attrs[k, 6] = float(p.color == chess.WHITE)
right = ((p.piece_type == chess.KING and bool(b.castling_rights & (
chess.BB_RANK_1 if p.color else chess.BB_RANK_8)))
or (p.piece_type == chess.ROOK and bool(b.castling_rights & chess.BB_SQUARES[sq])))
attrs[k, 7] = float(right)
ep = b.ep_square if (b.ep_square is not None and p.piece_type == chess.PAWN
and b.ep_square in _rule_only(p, sq, False, None)) else None
attrs[k, 8] = float(ep is not None)
f, r = chess.square_file(sq), chess.square_rank(sq)
coords[k] = (f / 7.0, r / 7.0)
attrs[k, 9] = f / 7.0
attrs[k, 10] = r / 7.0
attrs[k, 11] = (r if p.color == chess.WHITE else 7 - r) / 7.0
for t in dests.get(sq, ()):
y[k, OFFSET[sq][t]] = 1.0
for t in _rule_only(p, sq, right, ep):
if 0 <= t < 64:
shape[k, OFFSET[sq][t]] = 1.0
return Position(attrs, coords, types, y, shape)
def stream(n: int, seed: int):
"""Positions are generated, never stored: training is a single pass and 200k dense targets
would be 6 GB. The test set is materialised because every arm must see the same one."""
rng = np.random.default_rng(seed)
made = 0
while made < n:
b = random_board(rng)
if b is not None:
made += 1
yield build(b)
def _precision(score: np.ndarray, y: np.ndarray):
"""precision@k per entity, k = the true number of destinations."""
s = torch.as_tensor(score); yy = torch.as_tensor(y)
k = yy.sum(1)
keep = k > 0
rank = s.argsort(1, descending=True).argsort(1)
hit = ((rank < k[:, None]) & (yy > 0)).sum(1) / k.clamp(min=1)
return hit, keep, k
def evaluate(scores, batch, tsum):
hit, keep, k = _precision(scores, batch.y)
if not keep.any():
return [], []
np.add.at(tsum, (batch.types[keep.numpy()], 0), hit[keep].numpy())
np.add.at(tsum, (batch.types[keep.numpy()], 1), 1.0)
return list(hit[keep].numpy()), list((k[keep] / GRID).numpy())
EDGES = {"none": 1, "type": 6, "typecol": 12}
def _edge_types(pos: Position, kind: str, n: int):
"""What the CPPN is told about the pieces it relates, beyond their geometry.
`type` shares one kernel between a white pawn and a black pawn, whose moves are mirrored --
which is why the type-conditional arm lost 0.14 on pawns and nothing elsewhere. `typecol`
gives each colour its own.
"""
if kind == "none":
return None
t = torch.from_numpy(pos.types if kind == "type"
else pos.types * 2 + (1 - pos.attrs[:, 6].astype(np.int64)))
return t[:, None].expand(n, n).contiguous()
def run(n_train: int, seed_train: int, test, hidden: int, cppn_hidden: int, seed: int,
lr: float, batch: int, edges: str) -> dict:
torch.manual_seed(seed)
org = Organism(ATTR_DIM, 2, GRID, n_edge_types=EDGES[edges], hidden_dim=hidden,
cppn_hidden=cppn_hidden, memory=False)
opt = torch.optim.Adam(org.parameters(), lr=lr)
zero = Affect().axes
pending = []
for pos in stream(n_train, seed_train):
n = len(pos.types)
pred, _ = org(torch.from_numpy(pos.attrs), flat_diff(torch.from_numpy(pos.coords)),
list(range(n)), zero, {}, edge_types=_edge_types(pos, edges, n))
pending.append(torch.nn.functional.binary_cross_entropy_with_logits(
pred, torch.from_numpy(pos.y)))
if len(pending) == batch:
opt.zero_grad(); torch.stack(pending).mean().backward(); opt.step(); pending = []
prec, chance, tsum = [], [], np.zeros((6, 2))
with torch.no_grad():
for pos in test:
n = len(pos.types)
pred, _ = org(torch.from_numpy(pos.attrs), flat_diff(torch.from_numpy(pos.coords)),
list(range(n)), zero, {}, edge_types=_edge_types(pos, edges, n))
p, c = evaluate(pred.numpy(), pos, tsum)
prec += p; chance += c
return dict(seed=seed, params=sum(q.numel() for q in org.parameters()),
prec=statistics.fmean(prec), chance=statistics.fmean(chance),
by_type=list(tsum[:, 0] / np.maximum(tsum[:, 1], 1)))
def run_baseline(n_marg: int, seed_train: int, test, seed: int, kind: str) -> dict:
"""`shape` knows each piece's rule and reads no other piece. `constant` knows neither."""
marg = np.zeros(GRID)
for pos in stream(n_marg, seed_train):
marg += pos.y.sum(0)
marg /= max(marg.max(), 1.0)
prec, chance, tsum = [], [], np.zeros((6, 2))
for pos in test:
score = np.tile(marg, (len(pos.types), 1)) * 0.5
if kind == "shape":
score = score + pos.shape
p, c = evaluate(score, pos, tsum)
prec += p; chance += c
return dict(seed=seed, params=0, 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("--positions", type=int, default=200000)
ap.add_argument("--test", type=int, default=4000)
ap.add_argument("--seeds", default="0,1,2,3")
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("--batch", type=int, default=16)
ap.add_argument("--arms", default="constant,shape,rp,rp_type,rp_typecol")
ap.add_argument("--out", default="results/chess_rules.json")
a = ap.parse_args()
test = list(stream(a.test, 10_000)) # a different seed: never a training position
print(f"{a.positions} training positions streamed, {a.test} held out "
f"({sum(int(p.y.sum()) for p in test)} moves to predict), "
f"{a.positions // a.batch} optimiser steps\n")
results = []
for name in a.arms.split(","):
for seed in (int(s) for s in a.seeds.split(",")):
r = (run_baseline(min(a.positions, 5000), seed, test, seed, name)
if name in ("constant", "shape") else
run(a.positions, seed, test, a.hidden, a.cppn_hidden, seed, a.lr, a.batch,
{"rp": "none", "rp_type": "type",
"rp_typecol": "typecol"}[name])) | {"arm": name}
print(f"{name:<10} seed={seed} params={r['params']:<6} 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))
names = ["pawn", "knight", "bishop", "rook", "queen", "king"]
by = {n: [r for r in results if r["arm"] == n] for n in a.arms.split(",")}
print(f"\n{'arm':<10}{'prec@k':>9}" + "".join(f"{t:>9}" for t in names))
print("-" * (19 + 9 * 6))
for n, rs in by.items():
print(f"{n:<10}{statistics.fmean(r['prec'] for r in rs):>9.4f}"
+ "".join(f"{statistics.fmean(r['by_type'][i] for r in rs):>9.4f}" for i in range(6)))
print(f"\nrandom ranking would score {statistics.fmean(r['chance'] for r in results):.4f}")
if __name__ == "__main__":
main()
+269
View File
@@ -0,0 +1,269 @@
"""psi as a continuous kernel axis: the one place a lookup cannot be built.
Where the argument stands after `scale.md` and `unseen.md`: variable N and permutation
equivariance are shared with any GNN, identity-in-the-kernel is the same statement as indexing a
lookup by type as well as offset, and generating weights from geometry is real but bounded to
relation spaces that cannot be enumerated. What is left is parameter compression where the
relation space is NOT enumerable -- and psi is the only genuinely continuous axis this
architecture has. A table over (offset x valence x arousal) has to bin the last two.
This is claim A2 of the paper arriving from the front rather than as a later chapter.
TWO MEASUREMENTS, because accuracy alone did not separate the arms in `unseen.md` and there is
no reason to expect it to here:
1. ACCURACY on a region of psi space held out of training. A binned table can interpolate
across psi bins exactly as it interpolated across offset cells, so this is expected to be
close and is not the headline.
2. COST to get there -- parameters, and samples. The CPPN shares statistical strength across
the psi axis by construction; a binned table cannot, and pays for every bin separately.
Kernel parameters: CPPN ~720 regardless of resolution; table 3600 * B^2.
THE NEGATIVE BRANCH, worth as much: if a COARSE table (B=2) plus interpolation matches the CPPN
at a fraction of the parameters, then psi-continuity buys nothing either, and the RP has no
distinguishing claim left against a GNN. That outcome ends a line of argument, which is why it
is written down before the run rather than after.
The teacher changes the kernel's SHAPE with psi, not its gain: valence rotates the spatial
frequency and arousal widens the envelope. A gain would be reproducible by scaling one shared
kernel, which is the failure mode `chess_reach.md` measured for piece type.
"""
from __future__ import annotations
import argparse
import json
import math
import statistics
from pathlib import Path
import torch
from torch import nn
from unseen import ATTR, CELLS, D, G, R, cell_of
# The interior box of psi space withheld from training, both axes. Aligned to the bin grid:
# psi in [-1,1] split into B bins puts edges at multiples of 2/B, so [0, 0.5] is exactly one bin
# at B=4 and exactly two at B=8.
#
# A TABLE CANNOT WITHHOLD ANYTHING FINER THAN ITS OWN BIN, and this favours the coarse arms
# rather than the CPPN. At B=1 the box is not held out at all -- that arm ignores psi entirely
# and its "unseen" column is just its ordinary error. At B=2 the box is half of a bin whose
# other half is trained, so the entry it reads has seen data. Only B>=4 withholds it honestly.
# Stated here rather than corrected for: correcting it would mean a different box per arm, and
# then the arms would no longer be answering the same question.
HELD = (0.0, 0.5) # overridden by --held; see main()
def psi_offsets() -> torch.Tensor:
ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij")
return torch.stack([xs, ys], -1).reshape(CELLS, 2).float()
class PsiTeacher(nn.Module):
"""W*(r, psi): valence rotates the frequency, arousal widens the envelope.
Both are shape changes. A psi that only scaled the kernel would be satisfiable by any model
with a gain on its output and would make the experiment vacuous.
"""
def __init__(self, seed: int = 0, kfreq: float = 0.35):
super().__init__()
g = torch.Generator().manual_seed(seed)
self.register_buffer("r", psi_offsets())
self.register_buffer("k", torch.randn(D, 2, generator=g) * kfreq)
self.register_buffer("phi", torch.rand(D, generator=g) * 2 * math.pi)
def kernel(self, psi: torch.Tensor) -> torch.Tensor:
val, aro = psi[0], psi[1]
th = val * (math.pi / 2)
rot = torch.stack([torch.stack([torch.cos(th), -torch.sin(th)]),
torch.stack([torch.sin(th), torch.cos(th)])])
k = self.k @ rot.T # (D,2) frequency rotated by valence
sigma = 3.0 * (1.0 + 0.4 * aro) # envelope widened by arousal
env = torch.exp(-(self.r * self.r).sum(-1) / (2 * sigma * sigma))[:, None]
return env * torch.cos(self.r @ k.T + self.phi) # (CELLS, D)
def forward(self, r, edge_onehot, context):
return self.kernel(context)[cell_of(r)]
class BinnedTable(nn.Module):
"""A lookup over (psi bin, offset cell): what a GNN has to do with a continuous axis.
B=1 is a table that ignores psi entirely -- the floor for this experiment, and the shape a
plain edge-type lookup actually has.
"""
def __init__(self, bins: int):
super().__init__()
self.bins = bins
self.w = nn.Parameter(torch.randn(bins * bins, CELLS, D) * 0.1)
def bin_of(self, psi: torch.Tensor) -> int:
i, j = (((psi.clamp(-1, 1) + 1) / 2 * self.bins).long().clamp(0, self.bins - 1)).tolist()
return i * self.bins + j
def forward(self, r, edge_onehot, context):
return self.w[self.bin_of(context)][cell_of(r)]
def make(arm: str, seed: int, omega: float = 2.0) -> nn.Module:
from ailed.core import RelationalPerceptron
torch.manual_seed(seed)
rp = RelationalPerceptron(ATTR, 2, 1, 2, hidden_dim=D, cppn_hidden=32, omega=omega)
if arm.startswith("table"):
rp.cppn = BinnedTable(int(arm.split("_")[1])) # "table_4" and "table_4_interp" alike
return nn.ModuleDict({"rp": rp, "out": nn.Linear(D, D)})
def untrained_bins(bins: int) -> torch.Tensor:
"""(bins*bins,) bool: bins lying wholly inside the withheld box, so never gradient-updated.
A bin only partly inside the box still sees training psi from its other part, which is why
B=1 and B=2 have nothing to fill and their `unseen` column is not really held out.
"""
t = BinnedTable(bins)
out = torch.zeros(bins * bins, dtype=torch.bool)
lo, hi = HELD
eps = 1e-4
for i in range(bins):
for j in range(bins):
x0, x1 = -1 + 2 * i / bins + eps, -1 + 2 * (i + 1) / bins - eps
y0, y1 = -1 + 2 * j / bins + eps, -1 + 2 * (j + 1) / bins - eps
corners = [torch.tensor([x, y]) for x in (x0, x1) for y in (y0, y1)]
if all(in_held(c) for c in corners):
out[t.bin_of(corners[0])] = True
return out
@torch.no_grad()
def fill_bins_by_diffusion(table: BinnedTable, held: torch.Tensor) -> None:
"""THE CONTROL THAT DECIDES WHAT THIS MEASURES, and the same one `unseen.md` needed.
A bin that never received gradient sits at its initialisation, so a table failing on the
withheld psi region is arithmetic rather than evidence. Filling those bins from their
trained neighbours in psi space asks the question that matters: does generating the kernel
from a continuous psi beat a lookup plus the obvious smoothing along the same axis?
"""
B = table.bins
grid = table.w.data.view(B, B, -1).clone()
know = (~held).view(B, B).clone()
while not know.all():
acc = torch.zeros_like(grid)
cnt = torch.zeros(B, B)
for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)):
src_v = torch.roll(grid * know[..., None], shifts=(dy, dx), dims=(0, 1))
src_k = torch.roll(know.float(), shifts=(dy, dx), dims=(0, 1))
if dy: # do not wrap around the psi range
(src_v[0] if dy > 0 else src_v[-1]).zero_()
(src_k[0] if dy > 0 else src_k[-1]).zero_()
if dx:
(src_v[:, 0] if dx > 0 else src_v[:, -1]).zero_()
(src_k[:, 0] if dx > 0 else src_k[:, -1]).zero_()
acc += src_v
cnt += src_k
newly = (~know) & (cnt > 0)
if not newly.any():
break
grid[newly] = acc[newly] / cnt[newly][:, None]
know |= newly
table.w.data.copy_(grid.view(B * B, CELLS, D))
def teacher(seed: int) -> nn.Module:
m = make("rp", seed + 1000)
m["rp"].cppn = PsiTeacher(seed)
for p in m.parameters():
p.requires_grad_(False)
return m
def in_held(psi: torch.Tensor) -> bool:
lo, hi = HELD
return bool(((psi >= lo) & (psi <= hi)).all())
def sample_psi(want_held: bool, gen: torch.Generator) -> torch.Tensor:
while True:
psi = torch.rand(2, generator=gen) * 2 - 1
if in_held(psi) == want_held:
return psi
def batch(want_held: bool, gen: torch.Generator, size=24, n_lo=2, n_hi=5):
out = []
for _ in range(size):
n = int(torch.randint(n_lo, n_hi + 1, (1,), generator=gen))
c = torch.randint(0, 8, (n, 2), generator=gen).float()
out.append((torch.randn(n, ATTR, generator=gen), c[None, :, :] - c[:, None, :],
torch.ones(n, n), sample_psi(want_held, gen)))
return out
def run(model, a, r, mask, psi):
edge = torch.ones(a.shape[0], a.shape[0], 1)
return model["out"](model["rp"](a, r, edge, mask, psi))
def evaluate(model, tea, data):
with torch.no_grad():
err = sum(((run(model, *d) - run(tea, *d)) ** 2).sum().item() for d in data)
ys = torch.cat([run(tea, *d) for d in data])
n = sum(d[0].shape[0] * D for d in data)
return err / n, ((ys - ys.mean(0)) ** 2).mean().item()
def one_seed(arm, steps, seed, omega):
tea, gen = teacher(seed), torch.Generator().manual_seed(seed)
model = make(arm, seed, omega)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for _ in range(steps):
data = batch(False, gen)
loss = sum(((run(model, *d) - run(tea, *d)) ** 2).mean() for d in data) / len(data)
opt.zero_grad(); loss.backward(); opt.step()
if arm.endswith("_interp"):
fill_bins_by_diffusion(model["rp"].cppn, untrained_bins(model["rp"].cppn.bins))
ev = torch.Generator().manual_seed(seed + 5000)
seen, floor_s = evaluate(model, tea, batch(False, ev, size=64))
unseen, floor_u = evaluate(model, tea, batch(True, ev, size=64))
return {"seed": seed, "arm": arm, "seen": seen, "unseen": unseen, "floor": floor_u,
"kernel_params": sum(p.numel() for p in model["rp"].cppn.parameters())}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--arms", default="rp,table_1,table_2,table_4")
ap.add_argument("--omega", type=float, default=2.0)
ap.add_argument("--steps", type=int, default=2500)
ap.add_argument("--seeds", default="0,1,2,3,4,5")
ap.add_argument("--held", default="0.0,0.5",
help="the withheld psi box. The interior default is the easy case: every "
"bin around it is trained. A corner box (0.5,1.0) leaves neighbours "
"on two sides only, which is what sharp.md showed the offset axis was "
"sensitive to -- the earlier conclusion there flipped with the "
"hold-out structure, so this axis gets the same check.")
ap.add_argument("--out", default="results/psi.json")
args = ap.parse_args()
global HELD
HELD = tuple(float(x) for x in args.held.split(","))
rows = []
for arm in args.arms.split(","):
for s in (int(x) for x in args.seeds.split(",")):
rows.append(one_seed(arm, args.steps, s, args.omega))
r = rows[-1]
print(f"{arm:9s} seed {s} seen {r['seen']:.5f} unseen {r['unseen']:.5f}"
f" params {r['kernel_params']}", flush=True)
print(f"\npsi held out: box [{HELD[0]},{HELD[1]}]^2, omega={args.omega}")
print(f"{'arm':9s} {'seen':>9s} {'unseen':>9s} {'floor':>9s} {'kernel params':>14s}")
for arm in args.arms.split(","):
a = [r for r in rows if r["arm"] == arm]
print(f"{arm:9s} {statistics.mean([r['seen'] for r in a]):9.5f} "
f"{statistics.mean([r['unseen'] for r in a]):9.5f} "
f"{statistics.mean([r['floor'] for r in a]):9.5f} {a[0]['kernel_params']:14d}")
Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1))
if __name__ == "__main__":
main()
+93
View File
@@ -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
```
+93
View File
@@ -0,0 +1,93 @@
# Does a piece's own past predict its next move, beyond the current board?
The question `identify.py` asked of the particles domain, asked of chess. Nothing here builds
or trains the organism; this measures a property of the domain, before committing to it.
**Answer: yes, and it survives a stronger estimator.** A piece's own history of squares
predicts its next square beyond what the board says. The gain is +0.034 accuracy with a
non-linear decoder — eleven paired standard errors from zero — against a shuffled-history
control that is *negative*.
This is the property particles lacked. There, the per-entity state held no more about the
hidden variable than the memoryless representation it was built from (`frozen.md` Part B,
`pooled.md`), because the hidden variable was **global** — one coupling matrix shared by all
sixteen particles, belonging to no entity. Here what there is to remember belongs to the
piece.
## Setup
1500 games from the local Lichess PGN, 38 719 moves from pieces with at least two prior moves.
Two predictors of the same target — the destination square of the piece that moves — given the
same conditioning:
| arm | features |
|---|---|
| present | board occupancy (64), the moving piece's type (6) and colour (1), its current square (64) |
| + history | the same 135, plus the squares that piece occupied on its previous 3 moves (192) |
Both arms are told which piece moves and from where. The only difference is the piece's own
past, so the gap between them is that past's contribution and nothing else.
Two things guard the number:
- **The split is by game, never by position.** Two positions from one game share almost
everything; splitting inside a game leaks the answer across the split.
- **A shuffled-history control.** The same 327 features, with the history block permuted across
rows so its marginal distribution is intact and only its alignment with the target is broken.
This is what the real gain has to beat: it controls for the extra features themselves.
## Results
```
estimator present +history gain shuffled seeds paired se
-----------------------------------------------------------------------
ridge 0.1227 0.1789 +0.0563 0.1190 6/6 0.0011
mlp 2x128 0.1586 0.1926 +0.0341 0.1489 3/3 0.0031
```
Per-seed, every seed positive in both arms. The shuffled control gains **−0.0036** (ridge) and
**−0.0096** (mlp) over the present-only arm: adding the history features with their timing
destroyed makes the predictor slightly *worse*, so the real gain is about the alignment
between a piece's past and its future, not about feature count.
## What the estimator comparison says, and the caveat it carries
The MLP reads more from the board alone than ridge does — 0.1586 against 0.1227 — so part of
what history supplied to the linear model was recoverable from the present by a non-linear one.
The gain shrinks accordingly, from +0.056 to +0.034.
**That trend is the honest caveat: a stronger estimator shrinks the gain, and this measurement
does not establish where it stops.** What it does establish is that the gain is still there,
and large relative to its error, for a decoder that is not linear. The particles result it is
being compared against went the other way — there the per-entity representation held *less*
than the memoryless one, at every estimator tried.
Other limits worth stating rather than discovering later:
- 1500 games and three seeds for the MLP arm. This project has already been bitten by eight
seeds reporting the wrong sign (`pooled.md`); three is enough for a gain of eleven se, and
would not be enough for a smaller one.
- The target — a piece's destination square — is a proxy chosen because it is cheap and needs
no organism. It is not the contract the organism is trained on.
- Move quality is not controlled. These are blitz games across a wide rating range, and a
piece's past may predict its future partly because weaker players shuffle pieces.
## What it means
Chess has the property the memory line needs and particles did not: **information that belongs
to an entity, is absent from the present, and persists.** That is the condition the poker
framing named — the evidence lives in the past rather than being redundant with the present —
and it is here at a size a decoder can see.
This does not say the GRP will work on chess. It says the domain is not the reason it would
fail, which is exactly what could not be said of particles. `credit.md` established that the
state update can hold per-entity properties (the entity's type, at 0.738 against chance 0.333)
and cannot hold a global one; this file establishes that chess's rememberable content is the
per-entity kind.
Reproduce with:
```bash
uv run --with chess python chess_history.py --games 1500 --seeds 0,1,2,3,4,5
uv run --with chess python chess_history.py --games 1500 --seeds 0,1,2 --estimator mlp
```
+104
View File
@@ -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
```
+115
View File
@@ -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
```
+138
View File
@@ -0,0 +1,138 @@
# Teaching the movement rules, on generated positions
The organism was never taught how the pieces move. Every memory result before this file was
measured on top of that gap. This is the base.
**Where it stands: the RP learns the rules from a generated curriculum and, on the pieces where
reading the board matters most, exceeds a control that knows the rules and cannot see.**
## Why not games
Two failures of games as a curriculum, both measured rather than argued:
- **Coverage.** A rook or queen is blocked in 98-100% of real positions (`chess_shape.json`), so
the model learned the geometry it saw instead of the rule behind it — it scored *worse* in
open positions (rook 0.811) than blocked ones (0.891). Here the piece count is sampled
uniformly from 2 to 32, so a near-empty board is as common as a crowded one, and every piece
type visits all its legal squares: measured at 3000 positions, a knight lands on each of the
64 squares between 65 and 107 times.
- **The target left out three rules entirely.** The reachability task asked for
`board.attacks`, which for a pawn on e2 returns d3 and f3 while its moves are e3 and e4 —
**no overlap at all**. Castling never appeared (a king's attack set is its five adjacent
squares; c1 and g1 are not in it) and neither did en passant. The model did not fail to learn
these. It was never asked. The target here is `generate_pseudo_legal_moves`.
## Setup
300 000 generated positions streamed for training (never stored: dense targets would be 6 GB),
4 000 held out from a disjoint seed. Target: every piece's pseudo-legal destinations, as a
multi-hot over the 15x15 grid of relative offsets. Metric: precision@k per piece, k the true
number of destinations. 4 seeds. No memory anywhere in this file — this is the RP question
alone, per the sequencing policy in `AGENTS.md`.
**`shape` is the control**: it knows each piece's type, its movement rule and its own flags, and
reads *nothing else on the board*. It proposes the un-blocked ray. Beating it is what "reads the
occupancy" means, and it is the bar this file is measured against — not 1.0.
Castling rights and the en-passant square are handed over as per-entity attributes. They are
**state, not position** — a rook must remember whether it has moved — and without them the same
board has two different correct answers. Removing them is the cleanest memory experiment this
project has available, with exact ground truth instead of a 0.03 correlation, and it belongs to
the parked GRP line.
## Results
```
arm prec@k pawn knight bishop rook queen king
constant 0.4075 0.4491 0.0000 0.1730 0.4947 0.5609 0.7781
rp_type 0.7793 0.6573 0.8574 0.7856 0.7569 0.7510 0.9124
rp 0.8161 0.7835 0.8481 0.7748 0.7837 0.7680 0.9227
shape 0.8305 0.8156 0.8624 0.8299 0.7679 0.7618 0.9134
random ranking scores 0.0233
```
**The RP exceeds the rule-knower on rook (+0.016), queen (+0.006) and king (+0.009)** — the
pieces whose moves are cut by occupancy, where ignoring the board costs most. It remains below
on pawn (-0.032), bishop (-0.055) and knight (-0.014).
Absolute position, added as attributes, is worth +0.020 and closes the gap to `shape` from
0.034 to 0.014:
```
without position with position
rp 0.7962 0.8161
rp_type 0.7583 0.7793
shape (was always given it) 0.8305 0.8305
```
The CPPN sees only `r_ij`, which makes the representation translation-invariant, and a chess
board has edges: a knight has 2.96 destinations on the rim against 6.85 in the middle, and 43%
of knights sit on the rim. `shape` was handed the square all along, so the comparison had been
biased *against* the organism.
**A prediction that did not verify.** The improvement was predicted to concentrate on rim
pieces. Per type it is roughly flat — pawn +0.008, knight +0.016, bishop +0.028, rook +0.028,
queen +0.029, king +0.022 — and the knight, 43% of which sit on the rim, gained *less* than the
queen. The per-type cut cannot settle a per-square hypothesis, so this is recorded as
unverified rather than as either confirmed or refuted. Position pays; the mechanism proposed
for why it pays is not demonstrated.
## Type in the kernel reverses sign with coverage
On game data, putting the piece type into `e_ij` was worth +0.10 and took the knight's L from
exactly zero to 0.758 (`chess_reach.md`). On the generated curriculum `rp_type` lands *below*
`rp`, and the whole deficit is the pawn: 0.6573 against 0.7835, with knight and bishop still
slightly ahead. That earlier jump was in part a crutch against scarce data.
The likely cause is specific and testable: `e_ij` carries the piece **type** and not its
**colour**, so a white pawn and a black pawn share one kernel while their moves are mirrored.
`own_rank` — rank counted from the piece's own back rank — is present in this run and did not
fix it on its own, which points at the colour rather than the orientation.
**`rp_typecol` confirms it, and splits along a line predicted in advance.** Twelve kernels
(type x colour) instead of six, 4 seeds (0.8330, 0.8375, 0.8331, 0.8378):
```
arm prec@k pawn knight bishop rook queen king
rp 0.8161 0.7835 0.8481 0.7748 0.7837 0.7680 0.9227
rp_typecol 0.8353 0.8689 0.8580 0.7895 0.7615 0.7528 0.9127
delta +0.085 +0.010 +0.015 -0.022 -0.015 -0.010
shape 0.8305 0.8156 0.8624 0.8299 0.7679 0.7618 0.9134
```
The owner named the split before the run, from chess rather than from the data: colour and
starting square matter for the **pawn, bishop and knight**, and not for the **rook, queen and
king**. Giving each colour its own kernel gains on exactly the first three and **loses on
exactly the second three**. A capacity story predicts a uniform gain and is ruled out by the
sign flip.
The mechanism is a bias-variance trade made per piece type: splitting six kernels into twelve
halves the data behind each one. Where colour changes the law — a pawn's direction above all,
at +0.085 — that is worth paying. Where the law is colour-symmetric it is pure loss.
`rp_typecol` is the first arm to exceed the rule-knowing control **in aggregate** (0.8353
against 0.8305). Note that it does so by a different route than `rp`, which beat `shape` on
rook, queen and king while `rp_typecol` does not. Neither arm dominates; a kernel conditioned
on colour only for the pieces whose law depends on it is untested and is the obvious next
question.
## Limits
- One training pass, no schedule, no ordering. A graded curriculum (piece alone, then one
blocker, then a full board) has not been tried; the sampler is i.i.d.
- The model is still data-limited: 6k positions gave 0.41, 30k gave 0.61, 300k gives 0.82. It
had not plateaued at any budget measured.
- Legality of the *position* is not modelled: these are sampled placements, valid but not
reachable from the opening.
- Pins and check are excluded — the target is pseudo-legal. King safety is a global rule and a
separate question.
- `shape` is a control, not a ceiling: it scores 0.83 because it cannot see the board, and the
true ceiling is 1.0.
Reproduce with:
```bash
uv run --with chess python chess_rules.py --positions 300000 --seeds 0,1,2,3
uv run --with chess python chess_rules.py --positions 300000 --seeds 0,1,2,3 --arms rp_typecol
```
+109
View File
@@ -0,0 +1,109 @@
# Discovering an invariance instead of being handed one — and why the objective forbids it
`invariance.md` settled that a group **given** to the kernel converts unseen orbit members into
seen ones: six of a knight's eight L-squares yields the other two at 0.4% of the floor. Every
result in this project is a model applying structure it was handed. This asks the only question
whose answer would justify the word "understanding" in the project's own framing: can the model
**find** the reparameterisation?
**No. And more optimisation makes it worse, which is the useful part — it means the objective,
not the optimiser, is what forbids it.**
## Setup
`rp_learn_K` learns K linear maps on the displacement and averages: `m = (1/K) Σ_k CPPN(T_k r)`.
If the learned set is closed under the domain's group the average is invariant to it and the
eight knight squares become one input, without anyone having said "D4". The `T_k` start at the
identity plus noise, so collapse to K=1 is the null the run has to move away from rather than
where it accidentally begins.
The band is measured on the same harness and seeds, not assumed: `rp` 0.02395 below,
`rp_inv` 0.00009 above, floor 0.02182. And at K=8 **the solution exists in the parameter space** —
`T_k` equal to the eight D4 matrices makes the average invariant by construction — so a null here
cannot be a capacity result.
`orbit` measures D4-invariance of the kernel's behaviour as a fraction of its own scale, so it
answers "did it find the group" without the learned maps having to look like anything. Validated
against the one kernel whose answer is known exactly: `rp_inv` reads 0.000, raw `rp` reads 1.12.
## Results, knight_sym, 6 seeds
```
arm steps seen unseen orbit spread
rp 2500 0.00097 0.02395 1.121 -
rp_learn_2 2500 0.00093 0.02143 1.019 0.664
rp_learn_4 2500 0.00087 0.02031 1.005 1.111
rp_learn_4 12000 0.00032 0.04258 1.129 1.236
rp_learn_8 2500 0.00065 0.02742 0.969 1.424
rp_learn_8 12000 0.00020 0.04341 1.042 1.558
rp_inv 2500 0.00002 0.00009 0.000 -
floor 0.02182
```
**The 266x band is essentially untravelled.** The learned arms sit at the floor. `orbit` moves
from 1.121 to 0.969 at best — a weak drift towards invariance that buys nothing.
**Both false-positive modes appeared, and both were instrumented before the run.** `seen`
improves monotonically with K and with steps (0.00097 → 0.00020, a 5x fit) while `unseen` does
not: the K transforms were used as extra capacity. And `spread` rises with K (0.66 → 1.56), so
the maps did not collapse to one — they diverged, just not towards the group.
**Training to convergence makes it worse, not better.** This was run to the same standard applied
to the binned table in `psi.md`, because under-training an arm is the mirror of tuning one until
it catches up. At 12000 steps `seen` improves 3x and `unseen` **doubles** (0.02031 → 0.04258),
while `orbit` moves *away* from invariance (1.005 → 1.129). The null is not a budget artefact; it
is the opposite of one.
## Why, and this is the finding
**Nothing in the objective rewards invariance.** The loss scores fit on the cells the model was
shown. Invariance only pays on the cells it was not shown, and those are by construction absent
from the loss. An unconstrained kernel fits the training cells better than one tied to an orbit,
so gradient descent walks away from the invariant solution — correctly, by its own lights.
That reframes the null. It is not that the architecture cannot hold the answer (it can, at K=8),
and not that the optimiser is too weak (more of it hurts). It is that **the thing we want was
never in what we asked for.** Which is the same shape as the five previous nulls in this project,
one level up: those were about what the input could express, this one is about what the objective
could reward.
It also gives the next paper a measured starting line rather than a hunch. Evolutionary search —
already recorded as where this project goes next — selects on fitness, and a fitness that
includes held-out relations puts invariance *in* the objective, where gradient on a training loss
cannot. That is now a stated prediction with a number to beat: 0.02395 floor, 0.00009 ceiling,
and gradient reaching 0.02031.
## One thing the learned frame does buy
On the `smooth` teacher, which has no D4 symmetry, `rp_learn` costs nothing: 0.00006-0.00007
against plain `rp`'s 0.00007. The hardcoded invariance costs **31x** there (0.00216). So a
learnable frame is free where the domain lacks the symmetry and a fixed one is not — the
advantage of discovering over committing is real. It just does not come with any discovering.
And the `knight` control behaves: eight squares sharing a support but not a rule, every arm flat
at ~0.024 with `orbit` unmoved at ~1.49. Nothing to discover, nothing discovered.
## What this does not establish
One route to invariance (averaging over learned frames), one objective (fit the shown cells), one
optimiser (Adam 3e-3), one initialisation (identity plus 0.4 noise), K ∈ {2,4,8}, one group.
Other parameterisations exist — a learned canonicalisation, a Lie-algebra generator basis — and
they are not the same experiment. **This is a null about this route to discovery, not about
discovery.** The mechanism it points at, though, is not specific to the route: an objective that
scores only what was seen has no term that invariance improves, whatever the parameterisation.
## Reproduce
```
for t in knight_sym knight smooth; do for a in rp rp_inv rp_learn_2 rp_learn_4 rp_learn_8; do
uv run python unseen.py --teacher $t --holdout support --arms $a --omega 2 --steps 2500 \
--seeds 0,1,2,3,4,5 --out results/disc_${t}_${a}.json
done; done
for k in 4 8; do
uv run python unseen.py --teacher knight_sym --holdout support --arms rp_learn_$k --omega 2 \
--steps 12000 --seeds 0,1,2,3,4,5 --out results/disc_long_k$k.json
done
```
Runs go 10-wide with `OMP_NUM_THREADS=1`; torch takes ~2 threads per process by default, so
pinning to one and going wide turns a 40-minute sweep into 6 minutes on this machine.
+90
View File
@@ -0,0 +1,90 @@
# The knight null was an input, not an architecture
`sharp.md` measured that shown six of a knight's eight L-squares, neither the CPPN nor any
control finds the other two — everything at or above the floor. That looked like a verdict on
relational architectures. It was a verdict on what the kernel was allowed to see.
The CPPN reads `r_ij` raw. It has no reason to know that (1,2) and (-2,-1) are the same law;
they are two different points of the plane. Canonicalise the displacement to
`(min|dx|, max|dy|)` — a D4 invariant — and the square's eight symmetries collapse to one orbit.
The knight's eight squares become **a single input**.
```
teacher arm seen unseen floor u/floor vs rp
knight_sym rp 0.00097 0.02395 0.02182 1.098
knight_sym rp_inv 0.00002 0.00009 0.02182 0.004 -0.02386 +/- 0.00154 6/6
knight_sym table_interp 0.00001 0.02205 0.02182 1.010 -0.00190 +/- 0.00014 6/6
knight rp 0.00117 0.02359 0.02228 1.059
knight rp_inv 0.00130 0.02611 0.02228 1.172 +0.00252 +/- 0.00189 2/6
smooth rp 0.00006 0.00007 0.01533 0.004
smooth rp_inv 0.00138 0.00216 0.01533 0.141 +0.00209 +/- 0.00025 0/6
```
**Six of eight L-squares gives the other two, exactly.** 0.02395 → 0.00009, 0.4% of the floor,
6 seeds out of 6, per-seed 0.00012 0.00008 0.00007 0.00012 0.00004 0.00012 — no spread worth
reporting. The same architecture, the same parameters, the same training data. Only the
parameterisation of the relation changed.
It is also 48x better on the cells it *did* train on (0.00097 → 0.00002). Eight squares became
one thing to learn, so this is sample efficiency and generalisation from the same cause.
## The two controls are why this means anything
Handing a model an invariance does not sneak the held-out cells into training — it hands over
the **claim** that those cells are equivalent to ones it saw. The controls test that claim in
both directions, and both were predicted before the run.
**When the claim is false, the invariance hurts.** The `knight` teacher puts a different value on
each of the eight squares: they share a support but not a rule. `rp_inv` reads 0.02611 against
plain `rp`'s 0.02359 — worse than doing nothing, and worse than the floor. It is not that
invariants always win.
**When the claim is the wrong one, it costs 31x.** The smooth Gabor has random frequency
directions and no D4 symmetry. Collapsing eight directions into one destroys information the
model needed: 0.00007 → 0.00216, 0/6 seeds. **An invariance is a commitment, not a free lunch.**
## What this says
A relational architecture infers a rule exactly when the domain's invariance is in its input,
and pays for the invariance where the domain does not have it. That is a statement about
relational architectures rather than about knights, and it is the same shape as this project's
other good result — `chess_reach.md`'s finding that the piece type must enter the kernel rather
than scale it. Both are failures of **what was expressible in the input**, not of capacity. That
is now five separate times in this project, and it is the pattern worth taking to the paper.
For the RP verdict, this reverses the conclusion `sharp.md` was heading towards. The RP does not
have to be let go. Its knight null was our input design, and when the input carries the group the
same mechanism does rule inference cleanly.
## What it does not say, and this is the real frontier
**The model is GIVEN the group. It does not find it.** `rp_inv` is handed the exact symmetry the
teacher was built with. So the claim earned is: *if you know a domain's invariance, putting it in
the kernel's input converts unseen orbit members into seen ones.* Whether a model can **discover**
which invariance a domain has is untouched, and it is arguably what the word "understanding" in
this project's framing actually means. Everything measured so far — including this — is a model
applying structure it was given.
That is the sharpest open question the project has, and unlike the ones before it, it does not
have an obvious cheap oracle. Candidates: a model that learns the canonicalisation, or one
scored across a family of domains with different groups so that discovering the right one is the
only way to win.
**Also untested:** one group (D4), one sparse family, one exactly-representable student-teacher
setup. And a prediction this now makes, for the parked chess arc: a kernel given D4 invariants
should learn piece movement from fewer positions and generalise to offsets it never saw. That is
recorded as a prediction, not a result.
## Reproduce
```
for t in knight_sym knight smooth; do
uv run python unseen.py --teacher $t --holdout support --arms rp,rp_inv,table_interp \
--omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/inv_${t}.json
done
```
Tests: `tests/test_unseen.py`. One of them exists because an edit silently failed to land and
`rp_inv` ran as plain `rp`, producing two identical columns that could have been read as
"invariants change nothing"; the arm dispatch now raises on an unknown name and the test asserts
each arm builds the kernel it claims.
+88
View File
@@ -0,0 +1,88 @@
# omega: a knob that was set wrong, not a defect to design around
`unseen.md` found a 17x swing in held-out error between two hand-picked values of `omega`, the
CPPN's bandwidth, and noted that every chess number in this project sits at one of them without
anyone having examined it. This file decides which of two things that is:
- a **knob** that wants a value per domain — document it, choose it, leave `AffectiveCPPN` alone;
- a **defect** — a narrow optimum that moves with the domain, in which case a learned or
multi-scale frequency is a mechanism question worth asking rather than a tune.
The answer is the first one, and the reason the code already gave for it is measured **false**.
## The curve, one domain, 8 seeds
MSE on held-out relations, `unseen.py`, teacher bandwidth `kfreq=0.35`.
```
omega 0.25 0.5 1 2 4 8 16
random 0.00052 0.00016 0.00008 0.00006 0.00007 0.00112 0.00019
band 0.00087 0.00034 0.00014 0.00008 0.00007 0.00064 0.00028
(seen) 0.00044 0.00012 0.00007 0.00006 0.00006 0.00024 0.00011
```
A plateau at **omega ∈ [1,4]**, in the same place for both hold-out structures. The project's
default of 10 sits outside it, 7-11x worse than the optimum. `omega=1`, which `unseen.md` ran
at and which was picked without measuring, is not the optimum either — 2 is. That result was
obtained by luck, and it is recorded as luck.
**omega=8 is unstable, not merely mis-tuned.** Per seed: 0.00028, 0.00425, 0.00016, 0.00127,
0.00037, 0.00159, 0.00043, 0.00059. `seen` degrades with it (0.00024), so this is optimisation
breaking down rather than a bandwidth mismatch — and 16 recovers to 0.00019. The curve has a
cliff in the middle, not a single valley, and a sweep of three points could have missed it.
## Does the optimum move with the domain? No.
The deciding axis. `kfreq` is the **domain's** spatial frequency, `omega` the **model's**.
6 seeds, random hold-out, MSE on held-out relations.
```
kfreq \ omega 0.5 1 2 4 8 best
0.15 0.00006 0.00003 0.00003 0.00003 0.00138 4
0.35 0.00017 0.00009 0.00006 0.00006 0.00132 2
0.70 0.00118 0.00046 0.00028 0.00020 0.00143 4
```
The optimum sits at 2-4 across a domain bandwidth that varies by 4.7x. It does not track the
domain. What *does* change with the domain is the **penalty for being under-banded**: at
`kfreq=0.7` an `omega` of 0.5 costs 6x the optimum, at `kfreq=0.15` only 2x. And `omega=8`
fails at ~0.0013-0.0014 for every domain tested, which confirms the cliff is a property of the
model, not of what it is fitting.
**This contradicts the comment in `core.py`**, which states that omega "is a calibration knob
that wants tuning against the domain's length scale". That was a plausible assumption and it is
now measured false over the range tested: a fixed value in [2,4] is near-optimal for every
domain bandwidth here. The comment should say what the measurement says.
## What follows
**Do not rework `AffectiveCPPN`.** There is a broad plateau, it does not move, and a learned or
multi-scale frequency would be solving a problem that was not found. That option stays available
if a domain ever turns up whose optimum is outside [1,4]; none has.
**The default is a footgun and the debt is recorded rather than paid here.** Every chess number
in this project was produced at `omega=10`, outside the plateau. Those results are comparisons
at a *fixed* omega, so the comparisons remain fair and nothing in `chess_reach.md`,
`chess_rules.md` or `chess_dist.md` is invalidated — but their absolute levels come from a
badly calibrated kernel, and how much of the gap to the rule-knowing control was bandwidth is
unknown. Re-running the chess arc in the plateau belongs to the chess arc, which is parked.
## What this does not establish
Three domain bandwidths over one order of magnitude, one teacher family (Gabor), one hold-out
structure for the grid, 6 seeds. The grid's resolution in omega is 2x, so a shift in the optimum
smaller than that would not show. "The optimum does not move" is a statement about this range,
and the honest form of it is: nothing was found that would justify redesigning the kernel's
frequency, which is a weaker claim than nothing exists.
## Reproduce
```
for w in 0.25 0.5 1 2 4 8 16; do for k in random band; do
uv run python unseen.py --holdout $k --arms rp --omega $w --steps 2500 \
--seeds 0,1,2,3,4,5,6,7 --out results/sweep_${k}_w${w}.json; done; done
for kf in 0.15 0.35 0.70; do for w in 0.5 1 2 4 8; do
uv run python unseen.py --holdout random --arms rp --omega $w --kfreq $kf --steps 2500 \
--seeds 0,1,2,3,4,5 --out results/grid_k${kf}_w${w}.json; done; done
uv run python analyse_sweep.py
```
+114
View File
@@ -0,0 +1,114 @@
# psi as a continuous kernel axis — the deciding test, and it decided against
> **SUPERSEDED IN PART by `sharp.md`.** The withheld box here is interior, with trained bins on
> all four sides, which is the easy case. Re-run with a corner box the CPPN goes from losing to
> beating the same-resolution table on 5/6 seeds and tying the one with 320x its parameters.
After `unseen.md` and `scale.md` the RP's distinguishing claim against a lookup had narrowed to
one thing: **parameter compression where the relation space cannot be enumerated.** psi is the
only genuinely continuous axis this architecture has — a table over (offset × valence × arousal)
must bin the last two — so this was the experiment that would settle whether the CPPN is a
capability or a parameterisation.
**It is a parameterisation.** A binned table plus interpolation along psi matches the CPPN's
accuracy on withheld psi, on 6 seeds out of 6, using 80× to 320× more parameters. What the CPPN
buys is size, not answers.
The negative branch was written into `psi.py` before the run: *"if a coarse table plus
interpolation matches the CPPN, then psi-continuity buys nothing either, and the RP has no
distinguishing claim left against a GNN."* It is recorded here as it was predicted.
## Setup
Teacher kernel changes **shape** with psi, not gain: valence rotates the spatial frequency,
arousal widens the envelope. A psi that only scaled the kernel would be satisfiable by any model
with a gain on its output — the failure mode `chess_reach.md` measured for piece type — and is
guarded by `test_teacher_kernel_changes_shape_with_psi_not_only_gain`, which was checked against
a teacher deliberately reduced to a gain.
Withheld: the box psi ∈ [0, 0.5]², aligned to the bin grid. `omega=2`, the measured optimum from
`omega.md`. 6 seeds. Arms share `RelationalPerceptron`'s forward with the kernel swapped.
## Results
```
arm steps seen unseen u/s vs rp kernel params
rp 2500 0.00032 0.00038 1.18 1.00x 720
table_1 2500 0.00091 0.00081 0.89 2.11x 3600
table_2 2500 0.00042 0.00070 1.64 1.81x 14400
table_4 2500 0.00022 0.00733 32.87 19.12x 57600
table_4_interp 2500 0.00022 0.00034 1.54 0.90x 57600
table_8 2500 0.00025 0.00746 29.52 19.47x 230400
table_8 10000 0.00009 0.00691 80.75 18.04x 230400
table_8_interp 2500 0.00025 0.00033 1.32 0.87x 230400
floor 0.00656
table_4_interp - rp: -0.00004 +/- 0.00002 table better on 6/6 seeds
table_8_interp - rp: -0.00005 +/- 0.00003 table better on 5/6 seeds
```
## What this establishes
**1. The CPPN does answer for psi it never saw.** 0.00038 against 0.00032 on trained psi — a
1.18x cost, at 6% of the floor, from 720 parameters. The property is real.
**2. And a binned table with the gaps filled does it at least as well.** `table_4_interp` reads
0.00034 and beats the CPPN on 6 seeds of 6. The margin is small in absolute terms and outside
one paired se, so it is readable, but the direction is what matters: **there is no accuracy
advantage to generating the kernel from a continuous psi.**
**3. The bare tables' failure is arithmetic, and was labelled so before the run.** `table_4` and
`table_8` read ~19x the CPPN on withheld psi because the bin covering the box never received
gradient and sat at its initialisation. Reporting that as evidence would have been the same
tautology `unseen.md` avoided, and it is the reason the interpolation arms exist.
**4. It is not a sample-budget artefact.** `table_8` at 4x the steps fits trained psi three times
better (0.00025 → 0.00009) and generalises **not at all** better (0.00746 → 0.00691, floor
0.00656). More training buys memorisation and nothing else. Under-training a baseline is the
mirror image of tuning one until it catches up, and this rules it out.
**5. Resolution in psi and generalisation over psi are opposed in a table.** The arms that
generalise without help (`table_1`, `table_2`) do so by being blind to psi or by having half
their bin trained; the arms that can actually resolve psi are the ones that fail. Only the
explicit fill breaks the trade-off. The CPPN has no such trade-off, which is a structural
difference — it just is not an accuracy one.
## What is left of the claim
Parameters. 720 against 57,600 and 230,400 — 80x and 320x — at equal accuracy. That is a real
engineering property and it is now quantified rather than asserted, and its shape matters more
than its size here: **the table's cost is B^(number of continuous axes) × cells × channels, and
the CPPN's is constant.** At two psi axes and B=8 that is already 320x. At four it would be
4096 bins. The compression advantage grows exponentially in the number of continuous inputs and
the CPPN's does not grow at all.
That is the honest form of what the RP buys, and it is smaller than "a capability a lookup does
not have". Nothing measured in this project distinguishes the RP from a lookup **in what it can
represent**. What distinguishes it is what that representation costs.
## What this does not establish
Two continuous axes, one teacher family, a smooth dependence on psi by construction (a rotation
and an envelope width, both continuous and monotone). A psi dependence that was *not* smooth —
discontinuous, or high frequency in psi — is the case where interpolation between bins should
fail and the CPPN should not, and it has not been run. That is the sharpest remaining version of
this question and it is the natural sibling of the deferred capacity sweep, which asks the same
thing along the offset axis.
The interpolation control also needs to know which bins are untrained. That is realistic — a
system knows which regions it has seen — but it is an extra piece of machinery the CPPN does not
require, and at higher axis counts building it is the exponential above.
## Reproduce
```
uv run python psi.py --arms rp,table_1,table_2,table_4,table_8 --omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi.json
uv run python psi.py --arms table_8 --omega 2 --steps 10000 --seeds 0,1,2,3,4,5 --out results/psi_table8_long.json
uv run python psi.py --arms table_4_interp,table_8_interp --omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi_interp.json
```
Tests: `tests/test_psi.py`. Both silent-failure risks are defended and both defences were checked
against deliberately broken versions: a teacher reduced to a psi-gain fails the shape test, and
the bin bookkeeping (`untrained_bins`) is asserted exactly rather than approximately, because an
interp arm quietly filling bins that had data would look like a result.
+195
View File
@@ -0,0 +1,195 @@
# What the RP is: a property card
Every experiment so far has moved a limit to see whether something worked. This file asks the
prior question: **what does the RP do that a fixed-weight perceptron does not, and what is that
good for?** It is a map, not a result. Each row is a property with its evidence, and the point
of the exercise is that three of the five rows need no experiment at all — they are properties
of the construction, and writing them down is what shows which two rows are actually open.
## How the perceptron comparison is read here
`AGENTS.md` forbids a standard MLP or perceptron baseline. That prohibition is on the **error
race** — tuning two architectures until one lands lower — and it stands. This file makes a
different comparison: what class of function each one can express. In the regime that matters
the baseline **cannot be run at all**, and that is the finding rather than an obstacle to it.
Where it can be run (fixed N, fixed entity ordering) is exactly where the distinction it would
measure has already been assumed away. No MLP is trained anywhere in this file.
## The card
| # | Property | Status | Evidence |
|---|----------|--------|----------|
| 1 | **One parameter set, any N** | **Measured. Holds — and a GNN has it too** | `scale.md`, `test_rp_same_parameters_any_n` |
| 2 | **Permutation equivariance** | **Asserted, sabotage-verified** | `test_rp_permutation_equivariance`, `test_organism_permutation_equivariance_with_memory` |
| 3 | **Weights generated from the relation** | **Measured. Real, and smaller than assumed** | `unseen.md` |
| 4 | **Translation invariance** | **Asserted, and its cost measured** | `test_rp_translation_invariance`; `chess_rules.md` |
| 5 | **Kernel conditioned by identity** | **Measured, discontinuous** | `chess_reach.md`, `chess_rules.md` |
### 1. One parameter set, any N
The CPPN generates `m_ij` from `[r_ij ‖ onehot(e_ij) ‖ context]`, so the parameter count depends
on the coordinate, edge-type and hidden dimensions and **not** on how many entities there are.
The same ~9k parameters ran boards of 2 and of 32 pieces across the whole chess arc.
A fixed-weight layer over N entities is not worse at this; it is **undefined**. Its input
dimension is N·d (or N²·d for pairs) and has to be chosen before training. Changing N is a
different model, not a different input. That is the cleanest statement of what the RP buys, and
it is structural — no run establishes it and no run can refute it.
What the wording invites confusion with is a separate claim: that the RP still **works** at an N
it never trained on. Measured in `scale.md`, and it holds strongly — a model trained on N ≤ 16
scores 0.84 of the oracle's error at N=32, i.e. *better* than the model that trained there.
Two qualifications, both from that file. **A lookup table does the same** (0.86-0.90): neither
has a parameter tied to entity count, so this separates the RP from a perceptron and from
nothing else. And the cost that does exist runs the other way — training on N ∈ [17,32] and
evaluating at N=2 costs 2.28x, because mean pooling dilutes each pair's contribution by 1/deg
and the kernel is learned less sharply at large N. **The RP's pooling is a low-pass filter on
the learning signal, strength 1/N**; the cheap curriculum is to train small and deploy large.
### 2. Permutation equivariance
`h_i` does not depend on the order the entities are listed in. An MLP over a flattened board has
to learn this from data, and learns it approximately at best.
Asserted at two levels because there are two places order could leak: the RP's positional
tensors, and the `Organism`'s memory dict keyed by entity id. Per the repo's rule, both were run
against a deliberately broken RP (an index-dependent term added to the pooled message) and both
failed there; no other test in the suite did.
### 3. Weights generated from the relation — measured, and it does not carry what it was asked to
This is the property that separates the RP from a **GNN**, not merely from a perceptron, and it
is the only one on this card with no evidence at all.
A GNN holds fixed weights per edge type: a lookup with one entry per discrete relation. The
CPPN computes weights from continuous geometry, so it has an answer for a relation **it has
never seen** — an offset absent from training — where a lookup has no entry to read.
Measured in `unseen.md`, and the answer is three-sided.
The property is **real**: on a random hold-out the CPPN's error on displacements it never saw is
indistinguishable from its error on trained ones (1.28x, lower on 3 of 8 seeds), at 0.6% of the
floor. The kernel is defined between its training points.
It is **worth less than the framing assumed**. The bare table fails by construction — its held
entries never see gradient — so beating it is arithmetic. Against a table plus iterated
neighbour averaging, the obvious smoothing, the CPPN wins interpolation by 2x on 6/8 seeds and
**loses extrapolation on 8/8**. Smoothness is what answers for an unseen relation, and a table
can be smoothed.
And it is **absent at the bandwidth every chess run used**. At `omega=10` the held-out error is
17x worse than at `omega=1` (8/8 seeds), below the smoothed table even on interpolation. The
setting that makes the property visible was chosen for this file without measuring it.
Where it could still be load-bearing is a **continuous** relation space, where no table exists
to smooth. Chess is not that: 225 integer offsets are enumerable. Particles are. Not run.
### 4. Translation invariance, and what it costs
The kernel sees only `r_ij`, so the representation is translation-invariant by construction
rather than by training. The symmetry is free and exact.
The same sentence is a **limit**, and this is the one row where the card is not flattering.
Absolute position is unanswerable by construction, and a chess board has edges: a knight on the
rim has 2.96 destinations against 6.85 in the middle, and 43% of knights sit on the rim. Handing
absolute position and `own_rank` in through `attrs` was worth +0.020 and closed the gap to the
rule-knowing control from 0.034 to 0.014 (`chess_rules.md`). A domain whose law is anchored to
absolute location has to be told, and the telling goes through the features, not the kernel.
### 5. The kernel must be conditioned by identity, not scaled by it
The measured row, and it is a statement about relational architectures rather than about chess.
With the piece type only in `attrs`, it meets the kernel as an elementwise product: one geometry
function scaled per type. Put it into the CPPN's own input (`e_ij`) and the kernel becomes
genuinely type-conditional.
```
knight precision@k, per seed (chess_reach.md)
rp 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 8961 params
rp_type 0.742 0.755 0.749 0.768 0.750 0.768 0.766 0.763 9121 params
```
Exactly zero on 8/8 seeds, to 0.758, for 160 extra parameters — 1.8%. Not capacity. A knight's L
is not a scaling of the average movement shape, and one shared geometry function cannot be both.
The rook (second least average-like pattern) shows the second largest gain, 0.19 → 0.58.
Refinement, from `chess_rules.md`: the conditioning must cover whatever the law actually varies
over. Type alone put a white and a black pawn on one kernel with mirrored moves and cost 0.13 on
pawns; type × colour (12 kernels) recovered it, pawn 0.7835 → 0.8689, aggregate 0.8353 against
the rule-knowing control's 0.8305, 4 seeds.
## What this says about uses
The RP earns its cost where at least one of these is load-bearing:
- **The entity count varies, or is unknown at training time** (row 1). Not "handles it better" — the alternative is not defined.
- **Entity order carries no meaning** (row 2).
- **The relation space is continuous, or too large to enumerate** (row 3). Narrowed by measurement: where relations are few and discrete, a lookup plus smoothing is a serious competitor. This is the one reason to prefer the RP over a plain GNN, and it is bounded.
- **The law varies by identity** (row 5) — and then identity must enter the kernel, not the features.
And it is the wrong tool where the law is anchored to absolute position (row 4), which has to be
patched in through attributes.
## Where the argument stands
Rows 1 and 2 are **shared with any GNN** — measured, not assumed (`scale.md`). Row 5, identity in
the kernel, is the same statement as indexing a lookup by type as well as by offset.
Row 3 went through a full reversal and the reversal is the interesting part. Measured against
hold-outs that withheld cells uniformly (`unseen.md`) or a psi box with trained bins on all four
sides (`psi.md`), a lookup plus a neighbour average matched the CPPN and the conclusion was that
nothing distinguishes the RP in what it can *represent*. `sharp.md` withheld cells the kernel
actually **uses**, and the CPPN wins 4.4x on a smooth teacher and 3.0x on a high-frequency one,
6 seeds out of 6 in both; on a corner psi box it goes from losing to winning 5/6. One sentence
covers every hold-out tried: **a blur wins where the kernel is near zero, the CPPN wins where the
kernel carries signal.**
So the RP does have a representational advantage over a lookup, it is not large, and it lives
exactly where interpolation is hard — high-frequency content, and withheld regions that carry
signal or sit at a boundary. On top of that sits the cost argument, which is unaffected: the
table scales as B^(continuous axes) × cells × channels and the CPPN is constant, 80-320× at two
continuous axes.
**And the null that looked like a verdict was an input.** `sharp.md` found that shown six of a
knight's eight L-squares nothing infers the other two. `invariance.md` gives the CPPN D4
invariants of the displacement instead of the raw vector — the eight squares become one input —
and the same architecture recovers them exactly: 0.02395 → 0.00009, 0.4% of the floor, 6/6 seeds,
and 48× better on the training cells too. Two controls make it mean something: where the eight
squares share a support but not a rule the invariance is *worse* than nothing, and on a domain
without that symmetry it costs 31×. **An invariance is a commitment, not a free lunch.**
That is the fifth time in this project that a null turned out to be what was expressible in the
input rather than what the mechanism could do. It also bounds `chess_reach.md` differently than
`sharp.md` did: the type-conditioned kernel represents a knight's L, and a D4-conditioned one
would generalise it — a prediction for the parked chess arc, not a result.
**The model is GIVEN the group, and `discovery.md` measured that it cannot find one.** A learned
frame — K linear maps on the displacement, averaged — leaves the 266x band between floor and
oracle essentially untravelled, and **training to convergence makes it worse**: `seen` improves
5x while `unseen` doubles and the invariance metric moves away from zero. At K=8 the invariant
solution exists in the parameter space, so this is neither capacity nor optimiser strength.
The reason is the objective. The loss scores fit on cells the model was shown; invariance only
pays on cells it was not, and those are by construction absent from the loss. An unconstrained
kernel fits the shown cells better than one tied to an orbit, so gradient descent walks away from
the answer, correctly by its own lights. **The five earlier nulls were about what the input could
express. This one is about what the objective could reward.**
One thing the learned frame does buy: on a domain without the symmetry it costs nothing, where
the hardcoded invariance costs 31x. Discovering beats committing — it just does no discovering.
## What is open, in order
1. **An objective that can reward invariance at all.** `discovery.md` located the obstacle
precisely: a loss over shown relations has no term that invariance improves, whatever the
parameterisation. Gradient descent is not the thing to fix. The candidates are objectives, not
architectures — selection on held-out relations (which is what evolutionary search does by
construction, and is where this project already said it goes next), or a family of domains
sharing a group so that transfer is in the loss.
2. **Kernel capacity and interference.** How many distinct kernels fit before they collide, and
which pairs collide first. The pawn/colour result is one measured point of this curve; the
sweep makes similarity an independent variable instead of an accident of chess. Deliberately
last: how far a mechanism stretches is only worth measuring once it is known what it is for.
Nothing here touches the GRP line, which stays parked at `chess_dist.md` per `AGENTS.md`.
+86
View File
@@ -0,0 +1,86 @@
# One parameter set, an entity count it never trained on
Row 1 of `rp_properties.md`, second half. That the RP is *defined* at any N is structural and
asserted in the library's tests — a fixed-weight layer is not worse there, it has no input
dimension to use. Whether it still **works** at an N it never saw is a different claim, and
defined is not competent.
Two things come out, and the second is the more useful one.
## Read against an oracle, never down the N axis
`y_i` is a mean over neighbours, so raising N averages more terms, the target's variance falls,
and any error-over-floor ratio climbs with N for a model doing nothing wrong. This was found in
the smoke run and is asserted in `tests/test_scale.py::test_floor_shrinks_as_n_grows` rather
than left in prose.
What makes the axis comparable is an oracle: a model trained over the full range [2,32] and
evaluated at the same N. Three runs, `omega=2` (the measured optimum from `omega.md`, not the
value picked by hand for `unseen.md`), 8 seeds, both arms:
- `forward` trained on N ∈ [2,16] — large N unseen
- `reverse` trained on N ∈ [17,32] — small N unseen
- `oracle` trained on N ∈ [2,32]
The reverse direction is a control, not symmetry: mean pooling means degree rises with N, so a
cost at large N could be the pooled statistics shifting rather than a failure to generalise over
entity count. A cost in **both** directions would be the degree distribution; a cost in **one**
is the extrapolation actually asked for.
## Result: generalising over N is free, and the table does it too
Ratio to the oracle at the same N. Below 1 means *better* than the model that trained there.
```
N 2 4 8 12 16 20 24 28 32
rp fwd/orc 0.75 0.71 0.76 0.80 0.78 0.80 0.80 0.82 0.84
rp rev/orc 2.28 1.26 0.91 0.87 0.84 0.83 0.82 0.84 0.84
table fwd/orc 0.86 0.76 0.84 0.86 0.86 0.86 0.86 0.91 0.90
table rev/orc 1.82 1.27 1.10 1.06 1.04 0.97 0.98 1.03 1.00
| unseen for forward ->
<- unseen for reverse |
```
**The property holds, strongly.** A model that never saw more than 16 entities is not merely
competent at 32: at 0.84 it beats the oracle that trained there.
**And it does not distinguish the RP from a GNN.** The lookup table shows the same pattern
(0.86-0.90 forward). Neither has a parameter tied to the entity count, so neither needs to. Row
1 separates the RP from a *perceptron*, for which variable N is undefined, and from nothing
else. The property card already said this; it is now measured rather than argued.
## The asymmetry is the finding
The cost appears in **one** direction only — large→small, 2.28x at N=2 and 1.26x at N=4, gone by
N=8. Small→large is free and better than free.
The mechanism is the pooling. `h_i = tanh(mean_j m_ij ⊙ W p_j + b)`, so a single pair's
contribution to the target is diluted by 1/deg. Training at N=32 dilutes every kernel value by
~1/32 before the gradient sees it, and the kernel is learned less sharply; that imprecision is
invisible at large N, where averaging hides it, and shows up immediately at N=2, where it does
not. **The RP's mean pooling is a low-pass filter on the learning signal, with strength 1/N.**
That is actionable and it is the opposite of the intuition that more entities means more signal:
the cheap curriculum is to train on few entities and deploy on many. It is also a statement
about relational architectures rather than about this domain, which is the kind this project is
for. The table arm showing the same asymmetry (1.82x at N=2) confirms it is the pooling and not
the kernel.
## What this does not establish
One domain, one teacher family, N from 2 to 32 on an 8x8 lattice, so density rises with N and is
confounded with count — at N=32 half the squares are occupied and the displacement distribution
is not the same as at N=2. Separating count from density needs a board that grows with N, and
that was not run. The 2.28x at N=2 is the point where that confound is largest.
## Reproduce
```
uv run python scale.py --train 2,16 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_forward.json
uv run python scale.py --train 17,32 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_reverse.json
uv run python scale.py --train 2,32 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_oracle.json
uv run python analyse_scale.py
```
Tests: `tests/test_scale.py`. The training range is the experiment and a leak would be silent;
the range check was run against a deliberately widened sampler and failed there.
+113
View File
@@ -0,0 +1,113 @@
# Where a blur competes and where it does not — and one prediction that failed
Every null in `unseen.md`, `scale.md` and `psi.md` was measured against a **smooth** teacher, and
smoothness is exactly what lets a lookup plus a neighbour average compete. Those files concluded
that nothing distinguishes the RP from a lookup in what it can represent. This one varies the
smoothness and the hold-out structure, and **that conclusion does not survive**: it was an
artefact of hold-outs that made interpolation easy.
It also contains a prediction of mine that was falsified, which is the more useful half.
## Four teacher families, one axis: how predictable the kernel is from its neighbours
- `smooth` — band-limited Gabor. The replication.
- `highfreq` — the same at a frequency near the grid's resolution. Structured, not smooth.
- `knight` — 1 on the eight L-offsets, 0 elsewhere. Not smooth, and **rule-generated**. This is
`chess_reach.md`'s knight asked as a mechanism question.
- `noise` — iid per cell. **The negative control.** Without it, "the CPPN wins on non-smooth
kernels" cannot be told apart from "the setup favours the CPPN". Asserted to have neighbour
correlation < 0.2 where the smooth teacher's is > 0.8.
The hold-out also changed, and the change was forced by the knight teacher: most of its 225 cells
are exactly zero, so a uniform hold-out withholds cells carrying no signal, the target's variance
there is ~0 and the floor collapses. **`--holdout support` withholds cells the kernel actually
uses.** For the knight that is: *having seen six of the eight L-squares, can it infer the other
two?* The set is closed under negation, since a pair contributes r and −r.
## Result, 6 seeds
```
teacher omega arm seen unseen floor verdict
smooth 2 rp 0.00007 0.00007 0.01533
smooth 2 table 0.00005 0.00563 0.01533 +0.00556 +/- 0.00079 6/6 rp
smooth 2 table_interp 0.00005 0.00031 0.01533 +0.00024 +/- 0.00007 6/6 rp
highfreq 8 rp 0.00057 0.00126 0.01512
highfreq 8 table_interp 0.00015 0.00376 0.01512 +0.00251 +/- 0.00050 6/6 rp
knight 2 rp 0.00117 0.02359 0.02228 both AT OR ABOVE the floor
knight 2 table_interp 0.00002 0.02248 0.02228 -0.00112 +/- 0.00051 0/6 rp
noise 2 rp 0.00087 0.00157 0.00221 control: nothing generalises
noise 2 table_interp 0.00007 0.00150 0.00221 -0.00007 +/- 0.00007 2/6 rp
```
And psi re-checked with a corner box instead of an interior one, because if the hold-out
structure flipped the answer on the offset axis it could not be left untested on this one:
```
psi hold-out arm seen unseen floor params verdict
interior [0,0.5]^2 rp 0.00032 0.00038 0.00656 720
interior table_4_interp 0.00022 0.00034 0.00656 57600 table better
CORNER [0.5,1.0]^2 rp 0.00032 0.00073 0.00729 720
CORNER table_4_interp 0.00023 0.00086 0.00729 57600 +0.00013 5/6 rp
CORNER table_8_interp 0.00024 0.00069 0.00729 230400 -0.00004 ambiguous
```
## What this changes
**1. The CPPN does have a representational advantage, and it appears exactly where interpolation
is hard.** On the support hold-out it beats a lookup-plus-blur 4.4x on smooth and 3.0x on
high-frequency kernels, 6 seeds out of 6 in both. On the corner psi box it goes from losing to
winning 5/6 against the same-resolution table and tying the one with 320x its parameters.
**2. The earlier conclusion was an artefact of easy hold-outs, and this retro-explains the band
result rather than contradicting it.** `unseen.md`'s random hold-out withheld cells uniformly,
most of them peripheral, where the Gabor envelope has decayed and predicting ~0 is nearly
correct; its band hold-out was measured to have a kernel 4x weaker inside it and the RP lost
there 0/8. One sentence covers all three: **a blur wins where the kernel is near zero, the CPPN
wins where the kernel carries signal.** `unseen.md` and `psi.md` are not withdrawn — they are
correct for what they withheld — but their headline reading is superseded by this file.
**3. My prediction about the knight was wrong, and nothing generalises there.** I predicted the
CPPN would win on a rule-generated sparse kernel because a neighbour average cannot recover an
isolated spike. The average indeed cannot — and neither can the CPPN. Both sit at or above the
floor (1.06 and 1.01 of it). Having seen six of the eight L-squares, **the symmetry group is not
inferred by anything here.**
That has a direct consequence for a result of ours. `chess_reach.md` measured the knight going
from exactly 0.000 to 0.758 when the piece type entered the kernel, on 8/8 seeds for 1.8% more
parameters. That result stands as what it is — the kernel can **represent** eight cells once it
is conditioned by identity. What it does not support is the reading that the organism learned
*how a knight moves*. Shown six of the eight squares it does not find the other two. It
memorised a shape it was shown in full; it did not acquire a rule.
**4. The negative control behaves.** On `noise` both arms sit at ~0.7 of the floor — the part of
the target recoverable without the withheld relation at all, through the self-message and the
readout — and neither beats the other outside noise. The setup can produce a null.
## What this does not establish
The support and random hold-outs differ in more than their principle: `support` withholds ~25% of
the cells the kernel uses (2 of 8 for the knight, a few dozen for the smooth teacher) while
`random` withheld 56 of 225 regardless of magnitude. The comparison between this file's smooth
row and `unseen.md`'s is therefore indicative, not paired. What is paired, and unanimous, is
`rp` against `table_interp` **within** each row here.
`omega` was fixed at 2 except for the high-frequency family, where 8 is reported because a
band-limited model cannot fit a high-frequency teacher and reporting only omega=2 would have
handicapped the CPPN on the one family built to need bandwidth. Both values were run for every
family and both are in the json.
The knight null is one sparse family with one symmetry group. It says the group was not inferred
here; it does not say no relational architecture can infer one.
## Reproduce
```
for t in smooth highfreq knight noise; do
uv run python unseen.py --teacher $t --holdout support --arms rp,table,table_interp \
--omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/sharp_${t}_w2.json
uv run python unseen.py --teacher $t --holdout support --arms rp,table_interp \
--omega 8 --steps 2500 --seeds 0,1,2,3,4,5 --out results/sharp_${t}_w8.json
done
uv run python psi.py --arms rp,table_4,table_4_interp,table_8_interp --held 0.5,1.0 \
--omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi_corner.json
```
+157
View File
@@ -0,0 +1,157 @@
# Can the kernel answer for a relation it never saw?
> **SUPERSEDED IN PART by `sharp.md`.** The hold-outs here withhold cells regardless of whether
> the kernel carries signal there, and the band hold-out was measured to sit where the kernel is
> 4x weaker. Under a hold-out that withholds cells the kernel actually uses, the CPPN beats
> table+interp 4.4x on 6/6 seeds. The numbers below stand; the reading "there is no accuracy
> advantage" does not.
The property that separates the RP from a **GNN** rather than from a perceptron, and the one
row of `rp_properties.md` that had no evidence at all. A GNN holds fixed weights per edge type
— a lookup with one entry per discrete relation. The CPPN computes weights from continuous
geometry, so it has something to say about a displacement absent from training, where a lookup
has no entry to read. Every chess run trained and evaluated on the same offset grid, so nothing
in this project had tested it.
**The short version: the property is real, it is worth far less than the framing assumed, and
it disappears at the bandwidth setting the whole chess arc ran at.**
## Setup
Student-teacher on a 15×15 grid of integer displacements (225 cells). The teacher is the same
RP with an analytic Gabor kernel in place of the CPPN, so the target is exactly representable
and the ceiling is 0 by construction. 2–5 entities per configuration, 2500 steps, 8 seeds.
Held-out cells are **masked out** of training — the RP's own `mask` argument — so they
contribute no message and receive no gradient. The first design rejected whole configurations
instead; it was abandoned before any run because finding a 5-entity placement whose 20 ordered
displacements all avoid a scattered 25% of cells has probability ~0.3%, which would have skewed
training towards small N silently, and that skew would have been read afterwards as a property
of the kernel.
Evaluation is always on **pairs**, both cells of the pair wholly seen or wholly held, so `seen`
and `unseen` measure the same object. The floor is a predictor that ignores the relation and
returns the mean target.
Arms, all sharing `RelationalPerceptron`'s exact forward with the kernel swapped in place:
- `rp` — the CPPN. 720 kernel parameters.
- `table` — one weight vector per discrete displacement: a GNN with one edge type per relation. 3600 kernel parameters, **5× more than the CPPN**.
- `table+interp` — the same table, with its held-out entries filled after training by iterated neighbour averaging from trained cells.
- `rp w=10` — the CPPN at `omega=10`, the project default, which every chess run used.
## Results
MSE on held-out relations. Lower is better.
```
RANDOM hold-out (interpolation), 56/225 cells
seed rp table tbl+interp rp w=10 floor
0 0.00006 0.00352 0.00029 0.00055 0.01429
1 0.00007 0.00420 0.00025 0.00260 0.01305
2 0.00008 0.00371 0.00010 0.00012 0.01029
3 0.00011 0.00400 0.00023 0.00288 0.01333
4 0.00007 0.00096 0.00003 0.00181 0.00580
5 0.00013 0.00258 0.00013 0.00129 0.01880
6 0.00009 0.00558 0.00017 0.00052 0.02043
7 0.00006 0.00252 0.00009 0.00149 0.00848
mean 0.00008 0.00338 0.00016 0.00141 0.01306
table - rp: +0.00330 +/- 0.00049 8/8 seeds
table+interp - rp: +0.00008 +/- 0.00003 6/8 seeds
omega=10 - rp: +0.00132 +/- 0.00035 8/8 seeds
rp unseen/seen mean 1.28 per seed 0.90 1.13 1.23 1.74 2.39 1.03 0.91 0.90
BAND hold-out (extrapolation), 44/225 cells
seed rp table tbl+interp rp w=10 floor
0 0.00010 0.00176 0.00008 0.00053 0.01516
1 0.00012 0.00109 0.00007 0.00071 0.01032
2 0.00008 0.00119 0.00005 0.00014 0.00803
3 0.00017 0.00117 0.00004 0.00054 0.01101
4 0.00017 0.00116 0.00006 0.00060 0.00666
5 0.00020 0.00136 0.00007 0.00086 0.01933
6 0.00016 0.00123 0.00006 0.00036 0.01589
7 0.00011 0.00133 0.00005 0.00166 0.00856
mean 0.00014 0.00129 0.00006 0.00068 0.01187
table - rp: +0.00115 +/- 0.00008 8/8 seeds
table+interp - rp: -0.00008 +/- 0.00002 0/8 seeds *** rp WORSE ***
omega=10 - rp: +0.00053 +/- 0.00016 8/8 seeds
rp unseen/seen mean 2.38 per seed 1.83 1.84 1.66 2.62 4.51 2.40 2.54 1.66
```
## What this establishes
**1. The property is real.** On the random hold-out the CPPN's error on cells it never saw is
indistinguishable from its error on cells it trained on — 1.28× on average, and on three seeds
of eight the held-out error is *lower*. It sits at 0.6% of the floor. The kernel is a function
of the relation, and the function is defined between the training points.
**2. The bare table is not the comparison, and never was.** Its held-out entries never receive
gradient and stay at initialisation, so its failure (0.00338, 42× the CPPN) is arithmetic, not
evidence. It is reported for scale and was labelled as such before the runs.
**3. Against a table plus the obvious smoothing, the advantage is small or absent.**
`table+interp` is a lookup with its gaps filled by iterated neighbour averaging — the first
thing anyone would try. On interpolation the CPPN still wins, but by 2× and on 6/8 seeds rather
than the order of magnitude the framing had assumed. On the band it **loses on 8 seeds out of
8**. Generating the kernel from geometry is not, on this evidence, what buys the answer for an
unseen relation. Smoothness does, and a table can be smoothed.
**4. It disappears at the project's own default.** `omega` sets the CPPN's bandwidth. This file
ran at `omega=1`; every chess run used `omega=10`, and at 10 the held-out error is 17× worse on
the random hold-out (0.00141 vs 0.00008, 8/8 seeds) and worse than `table+interp` even there. A
wide-band kernel fits the training cells with structure that says nothing about the gaps between
them. **The bandwidth was picked here without measuring it, and it turned out to be the only
regime in which the property is visible at all.** That is a knob the chess results were never
examined against.
## What it does not establish, stated rather than buried
**The band hold-out is confounded by target magnitude.** Mean |W*| is 0.040 inside the band
against 0.172 in the seen cells — the Gabor envelope has already decayed there, so predicting
near-zero is nearly correct and both arms have an easier target. The 0/8 loss is real but its
*magnitude* is not comparable with the random hold-out's. The random hold-out is **not**
confounded this way (0.164 held against 0.141 seen), which is why the interpolation result
carries the weight here. A clean extrapolation test needs a radius-matched hold-out or a flat
envelope, and has not been run.
**The teacher kernel is smooth and band-limited by design.** Low spatial frequencies, σ=3. The
claim earned is that the CPPN interpolates a *smooth* kernel. Whether it interpolates a sharp
one — a knight's L is eight isolated cells, which is the opposite of smooth — is untested and is
exactly what the deferred capacity sweep would ask.
**The diffusion control only exists because the relation space was enumerable.** 225 cells on an
integer lattice. This is the finding's real boundary, and it points somewhere concrete: in a
domain whose relations are few and discrete, a table plus smoothing is a serious competitor and
the generated kernel buys little. **Chess is exactly such a domain** — board offsets are
integers and there are 225 of them. The particles domain is not: displacements there are real
valued and there is no table to smooth.
## Consequence for the property card
Row 3 of `rp_properties.md` moves from *untested* to **measured, and it does not carry the
weight it was being asked to carry.** Rows 1 and 2 — one parameter set at any N, permutation
equivariance — are what distinguish the RP, and a plain GNN has both. What the CPPN adds over a
GNN is now bounded: a 2× interpolation edge at a bandwidth the project was not using, on a
relation space small enough that its competitor is a lookup and a blur.
The place the property could still be load-bearing is a **continuous** relation space, where no
table exists. That is a different experiment and it has not been run.
## Reproduce
```
uv run python unseen.py --holdout random --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_random.json
uv run python unseen.py --holdout band --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_band.json
uv run python unseen.py --holdout random --arms table_interp --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_random_interp.json
uv run python unseen.py --holdout band --arms table_interp --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_band_interp.json
uv run python unseen.py --holdout random --arms rp --omega 10 --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_random_w10.json
uv run python unseen.py --holdout band --arms rp --omega 10 --steps 2500 --seeds 0,1,2,3,4,5,6,7 --out results/unseen_band_w10.json
uv run python analyse_unseen.py
```
Tests: `tests/test_unseen.py`. The held-out mask is the experiment, and a leak would be silent —
every arm still trains and every number still prints. Both the mask and the diffusion fill were
run against deliberately broken versions and the defending tests failed there; no others did.
+124
View File
@@ -0,0 +1,124 @@
"""One parameter set, an entity count it never trained on.
Row 1 of `rp_properties.md`, second half. That the RP is *defined* at any N is structural and
already asserted in the library's tests; a fixed-weight layer is not worse there, it has no
input dimension to use. What is not established is whether it still WORKS at an N it never saw,
and defined is not competent.
THE TABLE ARM IS HERE ON PURPOSE. A lookup kernel generalises over N for the same reason the
CPPN does -- neither has a parameter tied to the entity count. If it holds up, this property
separates the RP from a perceptron and NOT from a GNN, which is what the property card already
claims and what should be measured rather than argued.
THE CONFOUND THIS IS BUILT TO SEPARATE. `h_i` is a mean over neighbours, so raising N raises the
degree and changes the pooled statistics. Degradation at large N could be that, not a failure to
generalise over entity count. Hence the reverse direction: train large and evaluate small. A
failure in BOTH directions is about the degree distribution shifting; a failure in one is about
the direction it was asked to extrapolate.
MEASUREMENT NOTE, found in the smoke run and worth more than the run that found it. Dividing by
a per-N floor does NOT make the axis comparable. `y_i` is a mean over neighbours, so raising N
averages more terms, the target's variance falls, the floor falls with it, and the ratio climbs
even for a model that is doing fine. The ratio is reported because it is informative WITHIN one
N, across arms -- never read down a column as a trend.
What makes the axis comparable is an ORACLE, which is this repo's rule anyway: a model trained
over the FULL range [2,32] and evaluated at the same N. Degradation from an unseen entity count
is then (model trained on [2,16]) against (model trained on [2,32]) at the same N, and every
N-dependent difficulty cancels. Three runs, compared in `analyse_scale.py`:
--train 2,16 forward: small seen, large unseen
--train 17,32 reverse: large seen, small unseen
--train 2,32 the oracle both are read against
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import torch
from unseen import ATTR, D, make_model, run_model, teacher
def configs(n: int, count: int, gen: torch.Generator):
out = []
for _ in range(count):
c = torch.randint(0, 8, (n, 2), generator=gen).float()
out.append((torch.randn(n, ATTR, generator=gen), c[None, :, :] - c[:, None, :],
torch.ones(n, n)))
return out
def mixed_batch(lo: int, hi: int, gen: torch.Generator, size=24):
out = []
for _ in range(size):
n = int(torch.randint(lo, hi + 1, (1,), generator=gen))
out += configs(n, 1, gen)
return out
def evaluate(model, tea, data):
with torch.no_grad():
err = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).sum().item()
for a, r, m in data)
ys = torch.cat([run_model(tea, a, r, m) for a, r, m in data])
n = sum(a.shape[0] * D for a, _, _ in data)
return err / n, ((ys - ys.mean(0)) ** 2).mean().item()
def one_seed(arm, lo, hi, evals, steps, seed, omega):
tea = teacher(seed)
gen = torch.Generator().manual_seed(seed)
model = make_model(arm, seed, omega)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for _ in range(steps):
data = mixed_batch(lo, hi, gen)
loss = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).mean()
for a, r, m in data) / len(data)
opt.zero_grad(); loss.backward(); opt.step()
ev = torch.Generator().manual_seed(seed + 5000)
per_n = {}
for n in evals:
mse, floor = evaluate(model, tea, configs(n, 24, ev))
per_n[n] = {"mse": mse, "floor": floor, "ratio": mse / floor}
return {"seed": seed, "arm": arm, "omega": omega, "train_lo": lo, "train_hi": hi,
"per_n": per_n}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--train", default="2,16", help="lo,hi entity count seen in training")
ap.add_argument("--evals", default="2,4,8,12,16,20,24,28,32")
ap.add_argument("--arms", default="rp,table")
ap.add_argument("--omega", type=float, default=1.0)
ap.add_argument("--steps", type=int, default=2000)
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
ap.add_argument("--out", default="results/scale.json")
args = ap.parse_args()
lo, hi = (int(x) for x in args.train.split(","))
evals = [int(x) for x in args.evals.split(",")]
rows = []
for arm in args.arms.split(","):
for s in (int(x) for x in args.seeds.split(",")):
rows.append(one_seed(arm, lo, hi, evals, args.steps, s, args.omega))
print(f"{arm:6s} seed {s} " + " ".join(
f"N{n}:{rows[-1]['per_n'][n]['ratio']:.4f}" for n in evals), flush=True)
print(f"\ntrained on N in [{lo},{hi}], omega={args.omega} (mse / per-N floor)")
print(f"{'arm':6s} " + " ".join(f"{('N' + str(n)) + ('*' if lo <= n <= hi else ''):>9s}"
for n in evals))
for arm in args.arms.split(","):
a = [r for r in rows if r["arm"] == arm]
print(f"{arm:6s} " + " ".join(
f"{statistics.mean([r['per_n'][n]['ratio'] for r in a]):9.4f}" for n in evals))
print("* = inside the training range")
Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1))
if __name__ == "__main__":
main()
+48
View File
@@ -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))
+81
View File
@@ -0,0 +1,81 @@
"""The withheld psi region is the experiment, and a leak would be silent as usual.
Plus the property that makes the experiment non-vacuous: the teacher's kernel must change SHAPE
with psi, not gain. A psi that only scaled the kernel would be satisfiable by any model with a
gain on its output, and every arm would pass for the wrong reason.
"""
import torch
import psi as P
def test_training_psi_never_lands_in_the_held_box():
gen = torch.Generator().manual_seed(0)
for *_, p in P.batch(False, gen, size=256):
assert not P.in_held(p)
def test_eval_psi_is_always_inside_the_held_box():
gen = torch.Generator().manual_seed(1)
for *_, p in P.batch(True, gen, size=128):
assert P.in_held(p)
def test_teacher_kernel_changes_shape_with_psi_not_only_gain():
# The same check the library makes for the CPPN's context input, applied to the teacher:
# if psi were a gain the ratio between two kernels would be constant.
tea = P.PsiTeacher(0)
a = tea.kernel(torch.tensor([-0.8, 0.0]))
b = tea.kernel(torch.tensor([0.8, 0.0]))
assert (b / (a + 1e-9)).std() > 1e-2
c = tea.kernel(torch.tensor([0.0, -0.9]))
d = tea.kernel(torch.tensor([0.0, 0.9]))
assert (d / (c + 1e-9)).std() > 1e-2 # arousal too, not just valence
def test_bins_partition_psi_and_the_box_aligns_at_b4():
t4 = P.BinnedTable(4)
lo, hi = P.HELD
inside = {t4.bin_of(torch.tensor([x, y]))
for x in (lo + 0.01, hi - 0.01) for y in (lo + 0.01, hi - 0.01)}
assert len(inside) == 1 # the held box is exactly one bin at B=4
outside = t4.bin_of(torch.tensor([-0.9, -0.9]))
assert outside not in inside
def test_table_1_ignores_psi_entirely():
# The floor arm: it must be unable to represent any psi dependence, or it is not a floor.
t = P.BinnedTable(1)
r = torch.randint(-3, 4, (3, 3, 2)).float()
a = t(r, None, torch.tensor([-0.9, -0.9]))
b = t(r, None, torch.tensor([0.9, 0.9]))
assert torch.equal(a, b)
def test_untrained_bins_are_exactly_the_ones_inside_the_box():
# At B=4 the withheld box is exactly one bin; at B=2 it is half of one, so nothing is
# wholly untrained and there is nothing for the control to fill. If this drifted, the
# interp arm would quietly be filling bins that had data.
assert int(P.untrained_bins(4).sum()) == 1
assert int(P.untrained_bins(8).sum()) == 4
assert int(P.untrained_bins(2).sum()) == 0
assert int(P.untrained_bins(1).sum()) == 0
def test_diffusion_fills_held_bins_only_from_trained_ones():
# Trained bins all hold 1, untrained hold 0: after filling, every bin must be 1. A 0 left
# anywhere means an untrained bin was used as a source.
t = P.BinnedTable(4)
held = P.untrained_bins(4)
t.w.data.fill_(1.0)
t.w.data[held] = 0.0
P.fill_bins_by_diffusion(t, held)
assert torch.allclose(t.w.data, torch.ones_like(t.w.data), atol=1e-6)
def test_diffusion_leaves_trained_bins_untouched():
t = P.BinnedTable(4)
held = P.untrained_bins(4)
before = t.w.data.clone()
P.fill_bins_by_diffusion(t, held)
assert torch.equal(t.w.data[~held], before[~held])
+44
View File
@@ -0,0 +1,44 @@
"""The training range is the experiment. If an unseen N appears in training, nothing complains.
Same silent-failure shape as the held-out cells in test_unseen: every arm still trains and every
number still prints, and `unseen N` quietly becomes `seen N`.
"""
import torch
import scale
def test_training_never_sees_an_n_outside_its_range():
gen = torch.Generator().manual_seed(0)
for lo, hi in ((2, 16), (17, 32)):
ns = {a.shape[0] for a, _, _ in scale.mixed_batch(lo, hi, gen, size=200)}
assert ns and min(ns) >= lo and max(ns) <= hi
def test_training_range_actually_varies_n():
# A range that collapsed to a single N would make the whole axis meaningless while still
# satisfying the bounds check above.
gen = torch.Generator().manual_seed(1)
ns = {a.shape[0] for a, _, _ in scale.mixed_batch(2, 16, gen, size=200)}
assert len(ns) > 8
def test_one_parameter_set_evaluates_at_every_n():
# The property under test: the same object, unchanged, runs at any entity count.
model = scale.make_model("rp", 0, 1.0)
before = [p.clone() for p in model.parameters()]
gen = torch.Generator().manual_seed(2)
for n in (2, 7, 16, 25, 32):
for a, r, m in scale.configs(n, 1, gen):
assert scale.run_model(model, a, r, m).shape == (n, scale.D)
assert all(torch.equal(x, y) for x, y in zip(before, model.parameters()))
def test_floor_shrinks_as_n_grows():
# The measurement note in scale.py depends on this being true, so it is checked rather
# than asserted in prose: pooling more neighbours lowers the target's variance, which is
# why the mse/floor ratio must not be read as a trend down the N axis.
tea = scale.teacher(0)
gen = torch.Generator().manual_seed(3)
floors = [scale.evaluate(tea, tea, scale.configs(n, 32, gen))[1] for n in (2, 8, 32)]
assert floors[0] > floors[1] > floors[2]
+193
View File
@@ -0,0 +1,193 @@
"""The held-out cells are the experiment. If one leaks into training, the result is decorative.
That leak is silent: every arm still trains, every number still prints, and `unseen` quietly
becomes `seen`. So it gets the test, and the test was checked against a broken mask.
"""
import pytest
import torch
import unseen
def _held(kind="random", frac=0.25, seed=0):
return unseen.holdout_cells(kind, frac, seed)
def test_training_masks_out_every_held_cell():
held = _held()
gen = torch.Generator().manual_seed(0)
for _a, r, mask in unseen.train_batch(held, gen, size=64):
assert not held[unseen.cell_of(r)][mask.bool()].any() # nothing held survives
assert (mask.bool() | held[unseen.cell_of(r)]).all() # nothing seen was dropped
def test_a_masked_pair_cannot_move_the_output():
# The mask is only meaningful if it actually severs the message. Perturb a masked
# neighbour's attributes and the receiver must not notice.
held = _held()
model = unseen.make_model("rp", 0)
gen = torch.Generator().manual_seed(3)
for a, r, mask in unseen.train_batch(held, gen, size=40):
if mask.min() == 1:
continue
i, j = (mask == 0).nonzero()[0].tolist()
a2 = a.clone(); a2[j] += 7.0
y0 = unseen.run_model(model, a, r, mask)
y1 = unseen.run_model(model, a2, r, mask)
assert torch.allclose(y0[i], y1[i], atol=1e-6)
return
raise AssertionError("no masked pair was generated")
def test_eval_pairs_are_wholly_seen_or_wholly_held():
held = _held()
gen = torch.Generator().manual_seed(1)
off = ~torch.eye(2, dtype=torch.bool)
for _a, r, _m in unseen.pair_batch(held, True, gen, size=32):
assert held[unseen.cell_of(r)][off].all()
for _a, r, _m in unseen.pair_batch(held, False, gen, size=32):
assert not held[unseen.cell_of(r)][off].any()
def test_centre_cell_is_never_held():
# r = 0 is every entity's message to itself, so it appears in every configuration. Holding
# it out would mask a pathway that has nothing to do with the relation under test.
centre = unseen.R * unseen.G + unseen.R
for kind in ("random", "band"):
for seed in range(4):
assert not _held(kind, 0.25, seed)[centre]
def test_both_holdouts_withhold_a_real_fraction():
for kind in ("random", "band"):
n = int(_held(kind, 0.25, 0).sum())
assert 0.15 * unseen.CELLS < n < 0.35 * unseen.CELLS
def test_table_kernel_matches_cppn_call_signature():
# The table arm is swapped into RelationalPerceptron in place, so a signature drift would
# show up as a confusing shape error inside the RP rather than here.
k = unseen.TableKernel()
r = torch.randint(-3, 4, (4, 4, 2)).float()
assert k(r, torch.ones(4, 4, 1), torch.zeros(2)).shape == (4, 4, unseen.D)
def test_diffusion_fills_only_from_trained_cells():
# The control is only a control if the filled values come from cells that actually saw
# gradient. Trained cells all hold 1, held cells hold 0 (their "init"): after filling,
# every held cell must be 1 -- a 0 anywhere means an untrained entry was used as a source.
held = _held()
w = torch.ones(unseen.CELLS, unseen.D)
w[held] = 0.0
unseen.fill_by_diffusion(w, held)
assert torch.allclose(w, torch.ones_like(w), atol=1e-6)
def test_diffusion_reaches_every_held_cell_in_both_holdouts():
for kind in ("random", "band"):
held = _held(kind)
w = torch.zeros(unseen.CELLS, unseen.D)
w[~held] = 1.0
unseen.fill_by_diffusion(w, held)
assert (w[held] > 0).all() # no held cell was left stranded at its init
def _support(kind, frac=0.25, seed=0):
W = unseen.gabor_kernel(seed=seed, kind=kind)
return unseen.holdout_cells("support", frac, seed, W), W
def test_support_holdout_is_closed_under_negation():
# A pair contributes r and -r. An asymmetric hold-out would leave pair_batch with nothing
# to evaluate and it would spin forever rather than fail.
for kind in ("smooth", "knight", "highfreq"):
held, _ = _support(kind)
for c in held.nonzero().flatten().tolist():
dy, dx = divmod(c, unseen.G)
assert held[(2 * unseen.R - dy) * unseen.G + (2 * unseen.R - dx)]
def test_support_holdout_only_withholds_cells_that_carry_signal():
# The whole reason this hold-out exists: withholding a zero cell of the knight kernel asks
# nothing, the floor collapses, and the arms tie at a number that means nothing.
for kind in ("smooth", "knight"):
held, W = _support(kind)
mag = W.abs().mean(1)
assert (mag[held] > 0.2 * mag.max()).all()
def test_knight_kernel_lives_on_exactly_the_eight_l_squares():
W = unseen.gabor_kernel(kind="knight", seed=0)
live = (W.abs().mean(1) > 0).nonzero().flatten().tolist()
expect = {(dy + unseen.R) * unseen.G + (dx + unseen.R) for dx, dy in unseen.KNIGHT}
assert set(live) == expect and len(expect) == 8
def test_noise_teacher_has_no_neighbour_structure():
# The negative control is only a control if it really is unpredictable from neighbours:
# correlation between a cell and its right-hand neighbour should be near zero, where the
# smooth teacher's is high.
def neighbour_corr(kind):
W = unseen.gabor_kernel(seed=0, kind=kind).view(unseen.G, unseen.G, -1)
a, b = W[:, :-1].flatten(), W[:, 1:].flatten()
return abs(float(torch.corrcoef(torch.stack([a, b]))[0, 1]))
assert neighbour_corr("smooth") > 0.8
assert neighbour_corr("noise") < 0.2
def test_every_arm_name_actually_changes_the_kernel():
# This test exists because an edit silently failed to land and rp_inv ran as plain rp,
# producing two identical columns that could have been read as "invariants change nothing".
kinds = {arm: type(unseen.make_model(arm, 0)["rp"].cppn).__name__
for arm in ("rp", "rp_inv", "table", "table_interp")}
assert kinds["rp"] == "AffectiveCPPN"
assert kinds["rp_inv"] == "InvariantCPPN"
assert kinds["table"] == kinds["table_interp"] == "TableKernel"
with pytest.raises(ValueError):
unseen.make_model("rp_typo_arm_that_does_not_exist", 0)
def test_invariant_cppn_gives_one_answer_for_the_whole_d4_orbit():
# The mechanism under test: the eight knight offsets must reach the CPPN as one input.
m = unseen.make_model("rp_inv", 0)
edge, ctx = torch.ones(1, 1, 1), torch.zeros(2)
outs = [m["rp"].cppn(torch.tensor([[[float(dx), float(dy)]]]), edge, ctx)
for dx, dy in unseen.KNIGHT]
for o in outs[1:]:
assert torch.allclose(outs[0], o, atol=1e-6)
other = m["rp"].cppn(torch.tensor([[[3.0, 1.0]]]), edge, ctx) # not in the orbit
assert not torch.allclose(outs[0], other)
def test_knight_sym_is_one_orbit_and_knight_is_not():
cells = [(dy + unseen.R) * unseen.G + (dx + unseen.R) for dx, dy in unseen.KNIGHT]
sym = unseen.gabor_kernel(kind="knight_sym", seed=0)[cells]
asym = unseen.gabor_kernel(kind="knight", seed=0)[cells]
assert (sym.std(0) == 0).all() # same value on all eight squares, per channel
assert (asym.std(0) > 0).any() # the control shares support but not a rule
def test_orbit_consistency_reads_zero_for_a_kernel_that_is_invariant_by_construction():
# Validates the metric itself against the one kernel whose answer is known exactly.
inv = unseen.make_model("rp_inv", 0)["rp"].cppn
raw = unseen.make_model("rp", 0)["rp"].cppn
assert unseen.orbit_consistency(inv) < 1e-6
assert unseen.orbit_consistency(raw) > 0.1
def test_learned_frame_starts_spread_and_can_collapse():
# The null hypothesis for the learned arm is that the maps collapse to one, making it K=1
# with more compute. They start apart, and a deliberate collapse must read as one.
k = unseen.make_model("rp_learn_4", 0)["rp"].cppn
assert unseen.frame_spread(k) > 0.1
with torch.no_grad():
k.T.copy_(k.T[0].expand_as(k.T))
assert unseen.frame_spread(k) < 1e-6
def test_learned_frame_averages_over_its_maps():
k = unseen.make_model("rp_learn_2", 0)["rp"].cppn
r = torch.randint(-3, 4, (4, 4, 2)).float()
edge, ctx = torch.ones(4, 4, 1), torch.zeros(2)
manual = torch.stack([k.cppn(r @ t.T, edge, ctx) for t in k.T]).mean(0)
assert torch.allclose(k(r, edge, ctx), manual, atol=1e-6)
+442
View File
@@ -0,0 +1,442 @@
"""Can the kernel answer for a relation it never saw?
This is the one property that separates the RP from a GNN rather than from a perceptron.
A GNN holds fixed weights per edge type -- a lookup with one entry per discrete relation. The
CPPN computes weights from continuous geometry, so it has *something* to say about a
displacement absent from training, where a lookup has no entry to read. Nothing in this project
had tested it: every chess run trained and evaluated on the same offset grid.
WHAT IS MEASURED, and what is not. The `table` arm fails on held-out cells BY CONSTRUCTION --
those entries never receive gradient and stay at their initialisation. Reporting that as a
finding would be a tautology. It is here to give the scale, and it is labelled as such. The
measurement is WITHIN the `rp` arm: its error on held-out cells against its error on seen cells
and against the floor. If held-out sits at the floor, the CPPN memorised the training cells and
the generated kernel is a parameterisation, not a capability. That is the informative negative.
Two hold-out structures, because "unseen" is two different questions:
--holdout random cells scattered among seen ones -> interpolation
--holdout band a contiguous annulus of cells -> extrapolation
Student-teacher. The teacher is the same RP with an analytic Gabor kernel in place of the
CPPN, so the target is exactly representable and the ceiling is 0 by construction. What the
student must recover is the kernel as a function of r, which is the object under test.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
import torch
from torch import nn
from ailed.core import RelationalPerceptron
R = 7 # displacements live in [-R, R]^2
G = 2 * R + 1 # 15
CELLS = G * G # 225
D = 16 # kernel channels / hidden width
ATTR = 4
def cell_of(r: torch.Tensor) -> torch.Tensor:
"""(N,N,2) integer displacement -> (N,N) cell index on the GxG grid."""
dx = r[..., 0].round().long() + R
dy = r[..., 1].round().long() + R
return dy * G + dx
KNIGHT = [(1, 2), (2, 1), (-1, 2), (-2, 1), (1, -2), (2, -1), (-1, -2), (-2, -1)]
def gabor_kernel(sigma: float = 3.0, seed: int = 0, kfreq: float = 0.35,
kind: str = "smooth") -> torch.Tensor:
"""(CELLS, D) true kernel. `kind` varies HOW PREDICTABLE IT IS FROM ITS NEIGHBOURS.
Every null in unseen.md, scale.md and psi.md was measured against a smooth teacher, and
smoothness is exactly what lets a lookup plus a blur compete. These four families vary that
and nothing else:
smooth a band-limited Gabor. The replication: a blur should match the CPPN.
highfreq the same, at a frequency near the grid's resolution. Structured, not smooth.
knight_sym 1 on the eight L-offsets with the SAME value at all eight, 0 elsewhere. A
genuine D4 orbit: the eight squares are one rule under the square's symmetries.
knight 1 on the eight L-offsets, 0 elsewhere. NOT smooth and RULE-GENERATED -- a
neighbour average cannot recover an isolated spike, since its neighbours are 0.
This is chess_reach.md's knight, asked as a mechanism question.
noise iid per cell. THE CONTROL: nothing should generalise here, the CPPN included.
Without it, "the CPPN wins on non-smooth kernels" cannot be told apart from
"the setup favours the CPPN".
"""
g = torch.Generator().manual_seed(seed)
ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij")
r = torch.stack([xs, ys], -1).reshape(CELLS, 2).float()
if kind == "noise":
return torch.randn(CELLS, D, generator=g) * 0.2
if kind in ("knight", "knight_sym"):
w = torch.zeros(CELLS, D)
# knight_sym gives every channel ONE value across all eight offsets, so the pattern is a
# true D4 orbit and an invariant input can express it. knight varies the sign per offset,
# so the eight squares share a support but NOT a rule -- the control that keeps
# "invariants win" from being indistinguishable from "invariants always win".
sign = torch.randint(0, 2, (D, 1 if kind == "knight_sym" else len(KNIGHT)),
generator=g).float() * 2 - 1
for c in range(D):
for m, (dx, dy) in enumerate(KNIGHT):
w[(dy + R) * G + (dx + R), c] = sign[c, 0 if kind == "knight_sym" else m]
return w
if kind == "highfreq":
kfreq = 1.5
k = torch.randn(D, 2, generator=g) * kfreq # spatial frequencies of the domain
phi = torch.rand(D, generator=g) * 6.2831853
env = torch.exp(-(r * r).sum(-1) / (2 * sigma * sigma))[:, None]
return env * torch.cos(r @ k.T + phi)
class InvariantCPPN(nn.Module):
"""The CPPN over D4 invariants of the displacement instead of the displacement itself.
The knight null in `sharp.md` says nothing here induces a symmetry group from partial
support. This asks the other question: the CPPN sees raw r_ij, and has no reason to know
that (1,2) and (-2,-1) are the same law -- they are two different points of the plane.
Canonicalising to (min|dx|,max|dy|) collapses the square's eight symmetries to one orbit,
and the knight's eight squares become a single input.
STATED PLAINLY BECAUSE A CRITIC WILL SAY IT: this does not sneak the held-out cells into
training. It hands the model the CLAIM that those cells are equivalent to ones it did see.
The experiment measures whether that claim, when it is true of the domain, converts unseen
displacements into seen ones -- and the `knight` teacher, whose eight squares share a
support but not a value, is the control for when the claim is FALSE.
"""
def __init__(self, cppn: nn.Module):
super().__init__()
self.cppn = cppn
def forward(self, r, edge_onehot, context):
a = r.abs()
inv = torch.stack([a.min(-1).values, a.max(-1).values], dim=-1)
return self.cppn(inv, edge_onehot, context)
class LearnedFrameCPPN(nn.Module):
"""K learned linear maps on the displacement, averaged: m = (1/K) sum_k CPPN(T_k r).
`invariance.md` settled that a group HANDED to the kernel converts unseen orbit members into
seen ones. This asks the question that one could not: can the model FIND the reparameterisation
instead of being given it? If the learned set of T_k is closed under the domain's group, the
average is invariant to it and the eight knight squares become one input -- without anyone
having said the word D4.
The oracle and the floor are both already measured on the same harness and seeds, so this
lands inside a 266x band rather than against nothing: `rp_inv` 0.00009 above, `rp` 0.02395
below (knight_sym, sharp/invariance runs).
TWO WAYS THIS CAN LOOK LIKE A RESULT WITHOUT BEING ONE, both checked:
- K transforms are extra capacity. A wider kernel fits training cells better and says
nothing about held-out ones, so the hold-out is the discriminator, not `seen`.
- The T_k collapse to one map, making this K=1 with more compute. Reported as their spread.
And `orbit_consistency` measures the property directly, independent of accuracy: apply a D4
element to r and see whether the kernel's output moves.
"""
def __init__(self, cppn: nn.Module, k: int, seed: int = 0):
super().__init__()
self.cppn = cppn
g = torch.Generator().manual_seed(seed + 77)
# near identity plus noise: initialised AT the group's identity element, so a collapse to
# K=1 is the null hypothesis the run has to move away from rather than the thing it
# accidentally starts from.
self.T = nn.Parameter(torch.eye(2).repeat(k, 1, 1)
+ torch.randn(k, 2, 2, generator=g) * 0.4)
def forward(self, r, edge_onehot, context):
return torch.stack([self.cppn(r @ t.T, edge_onehot, context) for t in self.T]).mean(0)
D4 = [torch.tensor(m, dtype=torch.float32) for m in
([[1, 0], [0, 1]], [[0, -1], [1, 0]], [[-1, 0], [0, -1]], [[0, 1], [-1, 0]],
[[-1, 0], [0, 1]], [[1, 0], [0, -1]], [[0, 1], [1, 0]], [[0, -1], [-1, 0]])]
@torch.no_grad()
def orbit_consistency(kernel: nn.Module) -> float:
"""How D4-invariant the kernel actually is, as a fraction of its own scale. 0 = invariant.
Measured on the kernel's behaviour, not on its parameters, so it answers "did it find the
group" without needing the learned maps to look like anything in particular.
"""
# (n, n, 2): the CPPN expands its context to r's first two dims, so the probe grid has to
# be square. 9x9 covers offsets -4..4, which contains the knight's orbit with room around it.
ys, xs = torch.meshgrid(torch.arange(-4, 5), torch.arange(-4, 5), indexing="ij")
r = torch.stack([xs, ys], -1).float()
edge, ctx = torch.ones(9, 9, 1), torch.zeros(2)
base = kernel(r, edge, ctx)
scale = base.abs().mean().clamp(min=1e-9).item()
return max((kernel(r @ g.T, edge, ctx) - base).abs().mean().item() for g in D4[1:]) / scale
@torch.no_grad()
def frame_spread(kernel: nn.Module) -> float:
"""Mean pairwise distance between the learned maps. ~0 means they collapsed to one."""
T = kernel.T
return float(torch.cdist(T.flatten(1), T.flatten(1)).mean())
class TableKernel(nn.Module):
"""One weight vector per discrete displacement: a GNN with one edge type per relation.
Same call signature as AffectiveCPPN so it can be swapped into RelationalPerceptron in
place. It has MORE parameters than the CPPN (225*16 vs ~720), so a failure on held-out
cells is not a capacity failure -- it is an information failure, which is the point.
"""
def __init__(self):
super().__init__()
self.w = nn.Parameter(torch.randn(CELLS, D) * 0.1)
def forward(self, r, edge_onehot, context):
return self.w[cell_of(r)]
def make_model(arm: str, seed: int, omega: float = 1.0) -> nn.Module:
"""omega sets the CPPN's bandwidth and is the knob this experiment is most exposed to.
1.0 is not the project default -- chess ran at 10.0 -- so both are reported. A wide-band
kernel can fit the training cells with high-frequency structure that says nothing about
the gaps between them, which is exactly the failure mode `unseen` is looking for.
"""
torch.manual_seed(seed)
rp = RelationalPerceptron(ATTR, 2, 1, 2, hidden_dim=D, cppn_hidden=32, omega=omega)
if arm.startswith("table"):
rp.cppn = TableKernel() # ponytail: swap in place so all arms share RP's exact forward
elif arm.startswith("rp_inv"):
rp.cppn = InvariantCPPN(rp.cppn)
elif arm.startswith("rp_learn_"):
rp.cppn = LearnedFrameCPPN(rp.cppn, int(arm.split("_")[2]), seed)
elif arm != "rp":
# Exact, not a prefix check: "rp_inv" typed as "rp_invariant" or "rp_nv" would otherwise
# fall through and run as plain rp, which is how this went unnoticed the first time.
raise ValueError(f"unknown arm {arm!r}")
return nn.ModuleDict({"rp": rp, "out": nn.Linear(D, D)})
@torch.no_grad()
def fill_by_diffusion(w: torch.Tensor, held: torch.Tensor) -> None:
"""Fill a table's held-out entries from their trained neighbours, in place.
THE CONTROL THAT DECIDES WHAT THE RESULT MEANS. A bare table fails on held cells by
construction -- those entries never see gradient. Beating that is not a finding. The real
question is whether generating the kernel from geometry beats a lookup PLUS the obvious
smoothing anyone would reach for, which is what this arm is. On the random hold-out every
held cell is surrounded by trained ones, so this control should be strong there; on the
band it has to push a front inwards across a gap, which is what extrapolation costs.
"""
grid = w.view(G, G, D).clone()
know = (~held).view(G, G).clone()
while not know.all():
pad_v = torch.zeros(G + 2, G + 2, D); pad_v[1:-1, 1:-1] = grid * know[..., None]
pad_k = torch.zeros(G + 2, G + 2); pad_k[1:-1, 1:-1] = know.float()
acc = sum(pad_v[1 + dy:G + 1 + dy, 1 + dx:G + 1 + dx] for dy, dx in
((-1, 0), (1, 0), (0, -1), (0, 1)))
cnt = sum(pad_k[1 + dy:G + 1 + dy, 1 + dx:G + 1 + dx] for dy, dx in
((-1, 0), (1, 0), (0, -1), (0, 1)))
newly = (~know) & (cnt > 0)
if not newly.any():
break # nothing reachable; leave the rest at init
grid[newly] = acc[newly] / cnt[newly][:, None]
know |= newly
w.copy_(grid.view(CELLS, D))
def teacher(seed: int, kfreq: float = 0.35, kind: str = "smooth") -> nn.Module:
"""kfreq is the DOMAIN's length scale, not the model's. Sweeping it against the CPPN's omega
is what separates a knob that wants calibrating per domain from a defect in the
architecture: if the best omega tracks kfreq, core.py's own comment was right all along and
nobody had calibrated it; if it sits still, the default can simply be corrected."""
m = make_model("table", seed + 1000)
with torch.no_grad():
m["rp"].cppn.w.copy_(gabor_kernel(seed=seed, kfreq=kfreq, kind=kind))
for p in m.parameters():
p.requires_grad_(False)
return m
def holdout_cells(kind: str, frac: float, seed: int, W: torch.Tensor | None = None
) -> torch.Tensor:
"""(CELLS,) bool, True = withheld from training.
`support` exists because the knight teacher broke the other two. Most of its 225 cells are
exactly zero, so a hold-out drawn uniformly withholds cells that carry no signal, the
target's variance there is ~0, and the floor collapses -- the question becomes vacuous
rather than hard. `support` withholds cells the kernel actually uses, which is the same
question for every family: having seen most of where the law lives, can the model infer the
rest? For the knight that is "seen six of the eight L-squares, infer the other two", and a
neighbour average cannot, because an isolated spike's neighbours are zero.
The set is closed under negation: a pair contributes displacements r and -r, so an
asymmetric hold-out would have no evaluable pairs.
"""
ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij")
centre = R * G + R # r = 0: every entity messages itself, so it is in every configuration
if kind == "random":
g = torch.Generator().manual_seed(seed)
n = int(round(frac * CELLS))
idx = torch.randperm(CELLS, generator=g)[:n]
m = torch.zeros(CELLS, dtype=torch.bool)
m[idx] = True
m[centre] = False
return m
if kind == "support":
assert W is not None, "support hold-out needs the teacher's kernel"
mag = W.abs().mean(1)
live = (mag > 0.2 * mag.max()).nonzero().flatten().tolist()
g = torch.Generator().manual_seed(seed)
order = torch.randperm(len(live), generator=g).tolist()
m = torch.zeros(CELLS, dtype=torch.bool)
want = max(2, int(round(frac * len(live))))
for idx in order:
c = live[idx]
if c == centre:
continue
dy, dx = divmod(c, G)
neg = (2 * R - dy) * G + (2 * R - dx) # the cell for -r
m[c] = m[neg] = True
if int(m.sum()) >= want:
break
return m
if kind == "band":
d = (xs.abs().float() + ys.abs().float()).reshape(-1) # L1 radius
lo = torch.quantile(d, 1.0 - frac - 0.12)
hi = torch.quantile(d, 1.0 - 0.12)
m = (d >= lo) & (d < hi)
m[centre] = False
return m
raise ValueError(kind)
def train_batch(held: torch.Tensor, gen: torch.Generator, size=24, n_lo=2, n_hi=5):
"""Configurations with the held-out pairs MASKED OUT rather than the configuration rejected.
Rejection was the first design and it was wrong twice over. Finding a 5-entity placement
whose 20 ordered displacements all avoid a scattered 25% of cells has probability ~0.3%,
so it was slow -- but the real fault is that it would have skewed training towards small N,
silently, since small configurations are the easy ones to satisfy. Masking is what the RP's
own `mask` argument is for: the held cell contributes nothing to the message and receives
no gradient, and every N stays equally represented. Teacher and student get the same mask,
so the target is defined by the surviving pairs alone.
"""
out = []
for _ in range(size):
n = int(torch.randint(n_lo, n_hi + 1, (1,), generator=gen))
c = torch.randint(0, 8, (n, 2), generator=gen).float()
r = c[None, :, :] - c[:, None, :]
out.append((torch.randn(n, ATTR, generator=gen), r, (~held[cell_of(r)]).float()))
return out
def pair_batch(held: torch.Tensor, want_held: bool, gen: torch.Generator, size=64):
"""Evaluation is always on PAIRS, so `seen` and `unseen` measure the same thing.
A pair's two ordered displacements are r and -r; both must be on the wanted side, so the
single relation under test is unambiguous.
"""
out = []
while len(out) < size:
c = torch.randint(0, 8, (2, 2), generator=gen).float()
r = c[None, :, :] - c[:, None, :]
off = ~torch.eye(2, dtype=torch.bool)
hit = held[cell_of(r)][off]
if bool(hit.all()) if want_held else not bool(hit.any()):
out.append((torch.randn(2, ATTR, generator=gen), r, torch.ones(2, 2)))
return out
def run_model(model, a, r, mask):
edge = torch.ones(a.shape[0], a.shape[0], 1)
h = model["rp"](a, r, edge, mask, torch.zeros(2))
return model["out"](h)
def evaluate(model, tea, data) -> float:
with torch.no_grad():
num = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).sum().item()
for a, r, m in data)
den = sum(a.shape[0] * D for a, _, _ in data)
return num / den
def floor_mse(tea, data) -> float:
"""What a predictor that ignores the relation entirely achieves: predict the mean target."""
with torch.no_grad():
ys = torch.cat([run_model(tea, a, r, m) for a, r, m in data])
return ((ys - ys.mean(0)) ** 2).mean().item()
def one_seed(arm: str, kind: str, frac: float, steps: int, seed: int, omega: float = 1.0,
kfreq: float = 0.35, teacher_kind: str = "smooth") -> dict:
# `kind` is the HOLD-OUT structure and `teacher_kind` is the kernel family. They are
# different axes and were briefly the same identifier, which Python caught.
tea = teacher(seed, kfreq, teacher_kind)
held = holdout_cells(kind, frac, seed, gabor_kernel(seed=seed, kfreq=kfreq, kind=teacher_kind))
gen = torch.Generator().manual_seed(seed)
model = make_model(arm, seed, omega)
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for _ in range(steps):
data = train_batch(held, gen)
loss = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).mean()
for a, r, m in data) / len(data)
opt.zero_grad(); loss.backward(); opt.step()
if arm == "table_interp":
fill_by_diffusion(model["rp"].cppn.w.data, held)
ev = torch.Generator().manual_seed(seed + 5000)
seen = pair_batch(held, False, ev)
unseen = pair_batch(held, True, ev)
k = model["rp"].cppn
diag = {"orbit": orbit_consistency(k)}
if isinstance(k, LearnedFrameCPPN):
diag["spread"] = frame_spread(k)
return {"seed": seed, "arm": arm, "omega": omega, "kfreq": kfreq, "teacher": teacher_kind,
**diag, "seen": evaluate(model, tea, seen),
"unseen": evaluate(model, tea, unseen),
"floor_seen": floor_mse(tea, seen), "floor_unseen": floor_mse(tea, unseen),
"n_held": int(held.sum())}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--holdout", default="random", choices=["random", "band", "support"])
ap.add_argument("--frac", type=float, default=0.25)
ap.add_argument("--steps", type=int, default=1500)
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
ap.add_argument("--arms", default="rp,table")
ap.add_argument("--omega", type=float, default=1.0)
ap.add_argument("--kfreq", type=float, default=0.35, help="the DOMAIN's spatial frequency")
ap.add_argument("--teacher", default="smooth",
choices=["smooth", "highfreq", "knight", "knight_sym", "noise"])
ap.add_argument("--out", default="results/unseen.json")
args = ap.parse_args()
rows = []
for arm in args.arms.split(","):
for s in (int(x) for x in args.seeds.split(",")):
rows.append(one_seed(arm, args.holdout, args.frac, args.steps, s, args.omega, args.kfreq,
args.teacher))
r = rows[-1]
print(f"{arm:6s} seed {s} seen {r['seen']:.5f} unseen {r['unseen']:.5f}"
f" floor {r['floor_unseen']:.5f}", flush=True)
print(f"\n{args.teacher} teacher, {args.holdout} hold-out, frac={args.frac}, "
f"omega={args.omega}, {rows[0]['n_held']}/{CELLS} cells")
print(f"{'arm':6s} {'seen':>9s} {'unseen':>9s} {'floor':>9s} unseen/floor")
for arm in args.arms.split(","):
a = [r for r in rows if r["arm"] == arm]
se, un, fl = (statistics.mean([r[k] for r in a]) for k in ("seen", "unseen", "floor_unseen"))
print(f"{arm:6s} {se:9.5f} {un:9.5f} {fl:9.5f} {un / fl:.3f}")
Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1))
if __name__ == "__main__":
main()