Compare commits

...
30 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
chrnx 5ecf5d1146 results: apply Task 11's two corrections
The gate's weights moved 26.8% of their initial norm — more than any other block — so
"untrained" was wrong and pointed at a hypothesis Task 11 falsified. What did not move is
the function: the displacement stayed inside the sigmoid's linear band. frozen.md's three
affected passages now say so and a new section 6 carries the measurement, including why the
887x gradient-magnitude gap should not be led with (Adam is scale-invariant; the
per-coordinate SNR is comparable across blocks).

Section 7 and a note in when_memory_works.md mark the probe figures as linear-probe numbers.
An MLP probe reads +0.159 from M and +0.234 from h. The relative claim is unchanged; the
absolute fraction needed the qualifier.
2026-09-02 17:05:26 -05:00
chrnx 247d4d5280 exp: chess history probe, not yet run
Does a piece own past predict its next square beyond the current board? The same question
  identify.py asked of particles, asked of chess, and answered without building the organism.
  Split by game rather than by position, and a shuffled-history control for the gain to beat.
  
  Written against the local Lichess PGN. Not executed yet.
2026-09-02 17:00:26 -05:00
chrnx 0beba606cb exp: the gate gets the credit and the state cannot hold the regime -- (a) is dead too
Task 11. Both parts of the brief, 16 seeds each, plus a positive control. One
control is incomplete and is marked as such in results/credit.md and in
.sdd/task-11-report.md.

Part A falsifies hypothesis (a). The gradient reaching grp.gate.weight is
coherent above its own measured sign-flip null on 14/16 seeds (0.202 against
0.163, paired se 0.009), and 0.587 of it arrives through the truncated-BPTT
window rather than from the current step -- the temporal term is 1.187x the
per-step one, where (a) predicted it negligible. Every window is replayed twice
at the same parameters from the same recorded observations, carried and
detached, and pinned bit-identical against the gradient Adam actually used
(max relative difference exactly 0.0, 6400 windows).

The gate's gradient is 887x smaller than the identically-shaped candidate
layer's, and that is not the explanation: Adam is scale invariant, the
per-coordinate SNR is 0.066 against cand's 0.070, and gate.weight travelled
26.8% of its initial norm over training -- further than any other block
measured. "The weights did not move", which frozen.md §3 and a1.md both lean
on, is false. What did not move is the function: on the same inputs, trained
weights give g = 0.5008 +- 0.0270 where the initial weights give 0.5009 +-
0.0203. The displacement stayed inside the sigmoid's linear band.

Part B gives the brief's third outcome: M cannot hold the regime even under
direct supervision. The auxiliary head never leaves chance at any lambda from
1e-5 to 1.0, with no trend over 8000 steps; the frozen-phase decode moves by
-0.001 +- 0.019. The positive control -- the same head, optimiser, seeds and
probe, supervising the entity's own type instead -- installs it and raises the
regime decode by +0.073 +- 0.022 on 14/16 seeds in passing. The control that
had no business moving that number is the only one that moved it.

Incomplete: the non-linear control (2x128 head and probe) reached 10 of 16
seeds per shard and was stopped. Its section reports no numbers and the verdict
states the limitation it carries.

frozen.py gains two _train keywords (aux, extra_params), both defaulting to off
so test_train_copy_is_identical_to_regime_run still pins the loop, and one line
in _scores so an estimator may be a callable. results/*.json and the partial
sweep logs are committed past .gitignore as checkpoint data.
2026-09-02 16:56:01 -05:00
chrnx 0d682db353 docs: two rules earned by Task 10
Eight seeds reported the wrong sign here and flipped only at sixteen. And a null needs a
positive control, or it cannot be told apart from an instrument that sees nothing.
2026-09-02 14:41:58 -05:00
chrnx 63f8050bb7 exp: pooling the 16 states buys nothing memory-specific -- (b) is dead
The regime decodes from a single M at 0.332 and the question was whether it is
distributed across the 16 per-entity states rather than absent from them. Mean-pooling
lifts M's gap above the measured shift null by +0.045 -- and lifts the memoryless h it
is built from by +0.048, on more seeds. Difference -0.003, paired se 0.015, M ahead on
8/16. Concatenating all 16 adds nothing over the mean once it has samples to fit.

The instrument is not blind: a synthetic representation whose regime code is genuinely
split across entities gains +0.589 through the same probe, thirteen times the effect
measured here, and test_the_power_check_can_fail breaks the pooling on purpose and
confirms that control fails.

Eight seeds would have reported +0.010 in M's favour on 5/8. Sixteen report -0.003 on
8/16, which is the spread this project keeps being warned about.

No training loop and no architecture added: _build, _train, _frozen and probe come from
frozen.py unchanged, and seeds 0-7 reproduce results/frozen.json bit-identically.
2026-09-02 14:38:56 -05:00
chrnx 9710d4e84c docs: the gain is knowledge, not performance
Optimising the GRP is a grave error, not a goal. Adds the operational test before running
anything: is the negative result as informative as the positive one?
2026-09-02 14:28:28 -05:00
46 changed files with 39144 additions and 14 deletions

No files matched your search

+37 -3
View File
@@ -19,6 +19,12 @@ directory.
## The rules that matter
- **The gain is knowledge, not performance.** These experiments exist to establish what is
missing, not to make a mechanism work. Optimising the GRP is a grave error, not a goal.
Before running anything, apply the test: **is the negative result as informative as the
positive one?** If the experiment only makes sense when it comes out positive, it is a
performance experiment wearing a diagnostic costume — redesign it. Write verdicts so both
branches carry equal weight, and describe no outcome as good or bad news.
- **Report a null plainly.** Every substantive result in this repo so far is a null, and each
one turned out more informative than the positive it replaced. Do not soften a negative, do
not hunt for a configuration that rescues it, and do not defer it by proposing a new domain.
@@ -33,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.
@@ -40,9 +69,14 @@ directory.
trajectory, regime schedule, switch times and noise draws stay byte-identical to the
non-oracle run at the same seed, or a measured difference could come from a different world
rather than from the extra information.
- **Seeds.** Across-seed spread here is comparable to the effects being claimed. Eight seeds
supports a direction; it does not support a ratio. Report per-seed values and the count of
seeds won, not only the ratio of means.
- **Seeds.** Across-seed spread here is comparable to the effects being claimed, and worse:
in Task 10 eight seeds reported the **wrong sign**, flipping only at sixteen. Report
per-seed values, the count of seeds won, and a paired standard error. If the effect sits
inside one se of zero, say it is ambiguous rather than reading its sign.
- **A null needs a positive control.** Task 10's null means something only because the same
probe, on a synthetic where the signal genuinely was distributed, recovered it at thirteen
times the measured effect. Without that, "we found nothing" is indistinguishable from "our
instrument cannot see anything".
- **Anything a results file quotes must be re-runnable from this repo.** An uncommitted
throwaway driver is not reproducible. `ceilings.py` exists because of this rule; there is a
standing debt where `frozen.md` §1d's width-matched rows still are not.
+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()
+203
View File
@@ -0,0 +1,203 @@
"""Does a piece's own past predict its next move, beyond the current board?
The same 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.
In particles the answer was that the past held the hidden variable almost perfectly (one
observed displacement identified the regime at 0.958) while the present held much less. The
per-entity version of that question is different and is the one chess is supposed to answer
differently: does *this piece's own history* say something about where it goes next that the
current board does not?
Two predictors of the same target, given the same conditioning:
A (present) board occupancy, the moving piece's type and colour, its current square
B (+history) the same, plus the squares that piece occupied on its previous moves
The gap B - A is the per-entity history's contribution. If it is ~0, chess is like particles
for this purpose and a per-entity memory has nothing to carry.
"""
from __future__ import annotations
import argparse
import random
from collections import defaultdict
import chess
import chess.pgn
import numpy as np
PGN = "/Users/chrnx/workspace/ailed/model/data/slice.pgn"
def piece_histories(game: chess.pgn.Game, hist: int):
"""Yield (piece_key, from_sq, to_sq, prev_squares, board) per move, tracking identity.
Identity is the point: `id_at[square]` follows a piece across its moves so that "this
knight" means the same knight ten moves later. Castling moves the rook too; en passant
removes a pawn from a square the mover never touches; promotion keeps the identity and
changes the type.
"""
board = game.board()
id_at: dict[int, int] = {sq: sq for sq in chess.SQUARES if board.piece_at(sq)}
past: dict[int, list[int]] = defaultdict(list)
nxt = 64
for move in game.mainline_moves():
piece = board.piece_at(move.from_square)
if piece is None:
return
key = id_at.get(move.from_square)
if key is None:
key = nxt; nxt += 1
prev = past[key][-hist:]
yield key, move.from_square, move.to_square, prev, board.copy(stack=False), piece
# advance identity bookkeeping alongside the board
if board.is_en_passant(move):
cap = move.to_square + (-8 if piece.color == chess.WHITE else 8)
id_at.pop(cap, None)
id_at.pop(move.to_square, None) # a normal capture
id_at[move.to_square] = id_at.pop(move.from_square, key)
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)
past[key].append(move.from_square)
board.push(move)
def features(from_sq, prev, board, piece, hist: int, with_history: bool):
"""Present-only features, then optionally the piece's own past squares."""
f = np.zeros(64 + 6 + 1 + 64 + (64 * hist if with_history else 0), dtype=np.float32)
f[from_sq] = 1.0 # where it is now
f[64 + piece.piece_type - 1] = 1.0 # what it is
f[70] = 1.0 if piece.color == chess.WHITE else 0.0
occ = board.occupied
for sq in chess.SQUARES: # what the board looks like
if occ >> sq & 1:
f[71 + sq] = 1.0
if with_history:
base = 135
for i in range(hist): # where it has been
if i < len(prev):
f[base + i * 64 + prev[-1 - i]] = 1.0
return f
def collect(n_games: int, hist: int, min_moves: int, seed: int):
rng = random.Random(seed)
A, B, y, gid = [], [], [], []
with open(PGN, encoding="utf-8", errors="replace") as fh:
for g in range(n_games):
game = chess.pgn.read_game(fh)
if game is None:
break
for key, frm, to, prev, board, piece in piece_histories(game, hist):
if len(prev) < min_moves: # only pieces with a history to speak of
continue
A.append(features(frm, prev, board, piece, hist, False))
B.append(features(frm, prev, board, piece, hist, True))
y.append(to)
gid.append(g)
return np.array(A), np.array(B), np.array(y), np.array(gid)
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()
A, B, y, gid = collect(a.games, a.hist, a.min_moves, 0)
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(",")):
# split by GAME, never by position: two positions from one game share almost
# everything, and splitting inside a game leaks the answer across the split.
games = np.unique(gid)
rng = np.random.default_rng(s)
rng.shuffle(games)
te = np.isin(gid, games[: max(1, len(games) // 4)])
tr = ~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(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}")
g = np.array(gains)
se = g[:, 2].std(ddof=1) / np.sqrt(len(g))
print("-" * 44)
print(f"{'mean':>5}{g[:, 0].mean():>10.4f}{g[:, 1].mean():>10.4f}"
f"{g[:, 2].mean():>+9.4f}{g[:, 3].mean():>10.4f}")
print(f"\nhistory gain {g[:, 2].mean():+.4f} +/- {se:.4f} (paired se), "
f"{(g[:, 2] > 0).sum()}/{len(g)} seeds positive")
print(f"shuffled-history control gains {g[:, 3].mean() - g[:, 0].mean():+.4f} over present, "
f"which is what the real gain must beat to mean anything")
if abs(g[:, 2].mean()) < se:
print("\nVERDICT: inside one se of zero — ambiguous, not a direction.")
elif g[:, 2].mean() > 0:
print("\nVERDICT: a piece's own past predicts its next square beyond the board.")
else:
print("\nVERDICT: the piece's own past adds nothing over the board.")
if __name__ == "__main__":
main()
+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()
+788
View File
@@ -0,0 +1,788 @@
"""Task 11: the ceiling on hypothesis (a), credit assignment.
`results/pooled.md` measured hypothesis (b) dead: the regime is not distributed across
the sixteen per-entity states, it is absent from them. (a) is what remains --
nothing in the training signal rewards carrying the regime forward, so the state
never learns to hold it.
**Part A** asks whether a gradient signal reaches the gate at all. Two failures look
identical from "the weights did not move": the gradient is ~0 (*absent*), or it is
substantial per step and averages to nothing (*cancelling*). Only the ratio of the norm
of the mean gradient to the mean of the per-step norms separates them, so that ratio is
the measurement and the magnitudes are reported beside it so "negligible" has a size.
The temporal split is paired inside a single run and isolates time alone. At every
optimiser step the same truncated-BPTT window is replayed twice at the same parameters
from the same recorded observations: once with `M` carried across the window, once with
`M` detached at every step. **Detaching changes the graph and nothing else** -- every
forward value is bit-identical, which `_replay` asserts against the `M` the organism
actually computed, exactly as `frozen._frozen` asserts its reconstruction of `h`. The
difference between the two gradients is the credit that flows through time.
**Part B** is the ceiling, and it is an oracle on the state rather than a proposed
architecture: a linear head from `M_i` to the current regime id, trained jointly at a
weight `lambda`, asking what the state *could* hold if it were told -- exactly as an
oracle condition asks what a model could do if it were handed the answer. Nothing here
recommends adopting it and no `lambda` is better than another.
Part B ships with two controls, because a null from a supervised head has two ways of
being an artefact rather than a result. `--target type` supervises `M` toward the
entity's own type instead, a signal that is in `attrs` and therefore certainly
reachable: if the head cannot install *that*, it is not connected. `--head mlp` and
`--mlp-probe` replace the linear head and the linear probe with 2x128 ReLU networks,
because `results/when_memory_works.md` §2b measured a linear decoder reading 0.23 on
this exact target where an MLP reads 0.83 -- a linear-only null would inherit that
objection.
`_build`, `_train`, `_frozen`, `_metrics` and `probe` are `frozen.py`'s, called
unchanged; `_train`'s `aux`/`extra_params` keywords are the only addition, and they
default to off so every earlier caller's run stays bit-identical (pinned by
`tests/test_frozen.py::test_train_copy_is_identical_to_regime_run`). The non-linear
probe is registered into `frozen.ESTIMATORS` rather than forked from `probe`; the one
line that made that possible is `frozen._scores` accepting a callable.
"""
from __future__ import annotations
import argparse
import json
import math
import statistics
from functools import partial
from pathlib import Path
import numpy as np
import torch
from torch import Tensor, nn
import frozen as frozen_mod
from frozen import FROZEN_STEPS, SPLIT, TRAIN_STEPS, _build, _frozen, _hidden, _train, probe
from regime import _metrics
# the two blocks hypothesis (a) is about, and two reference blocks that are certainly
# trained: `out.weight` is one linear map from the prediction, `rp.feat.weight` sits
# under everything. Both gate and cand take [h ‖ M], so their column halves are split
# out too -- the M half is the only place a temporal path can enter them.
BLOCKS = ("gate", "cand", "feat", "out", "gate[h]", "gate[M]", "cand[h]", "cand[M]")
LAMBDAS = (0.0, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1.0)
TARGETS = ("regime", "type")
def _params(org) -> list[Tensor]:
return [org.grp.gate.weight, org.grp.cand.weight, org.rp.feat.weight, org.out.weight]
def _split_blocks(gs: list[Tensor], d: int) -> dict[str, Tensor]:
"""The four whole blocks plus the column halves of gate and cand."""
gate, cand, feat, out = gs
return {"gate": gate, "cand": cand, "feat": feat, "out": out,
"gate[h]": gate[:, :d], "gate[M]": gate[:, d:],
"cand[h]": cand[:, :d], "cand[M]": cand[:, d:]}
# -- Part A: where the gradient goes ---------------------------------------------
class GradTrace:
"""Records, per optimiser step, the gradient each block receives.
Three gradients are held for every window, all at the same parameters and from the
same data:
- `carried` -- the real training gradient, `M` carried across the window
- `detached` -- the same window with `M` detached every step: the per-step term
- `temporal` -- their difference, which is the credit that flows through time
`carried` is *also* checked against the gradient the optimiser actually used, read
off the real backward through a parameter hook, so a replay bug cannot masquerade
as a temporal effect.
"""
def __init__(self, org, bptt: int, tol: float = 1e-9):
self.org, self.bptt, self.tol = org, bptt, tol
self.d = org.hidden_dim
self.params = _params(org)
self.carried: list[list[Tensor]] = []
self.detached: list[list[Tensor]] = []
self.win: list[tuple] = []
self.win_M: list[Tensor] = []
self.prev0: Tensor | None = None
self.pending: list[Tensor] | None = None
self.replaying = False # the replay's own backward must not trip the pin
self.max_rel = 0.0 # worst disagreement replay vs. the real backward
self.n_checked = 0
self.loss_equal = True # detaching left every forward value untouched
self._seen: dict[int, Tensor] = {}
for k, p in enumerate(self.params):
p.register_hook(partial(self._check, k))
# -- the pin: what the optimiser actually used --------------------------------
def _check(self, k: int, g: Tensor) -> Tensor:
"""Fires on the real backward, with the gradient Adam is about to consume.
One closure per parameter: `gate.weight` and `cand.weight` have the same shape,
so the hooks cannot be told apart after the fact and the index is bound here.
"""
if self.replaying or self.pending is None:
return g
self._seen[k] = g.detach().clone()
if len(self._seen) == len(self.params):
for i, want in enumerate(self.pending):
rel = float((want - self._seen[i]).norm()) / (float(want.norm()) + 1e-30)
self.max_rel = max(self.max_rel, rel)
assert rel < self.tol, f"replay disagrees with the real backward: {rel:.2e}"
self.n_checked += 1
self._seen, self.pending = {}, None
return g
# -- the replay ---------------------------------------------------------------
def _replay(self, carry: bool) -> Tensor:
"""Re-run the window at the current parameters. Only the graph changes.
Every forward value is asserted bit-identical to the `M` the organism computed
during training, which is what makes the carried/detached difference a
statement about time and not about anything else.
"""
org, prev = self.org, self.prev0
losses = []
for k, (obs, r, ctx, axes) in enumerate(self.win):
held = {i: prev[j] for j, i in enumerate(obs.ids)}
pred, mem = org(obs.attrs, r, obs.ids, axes, held, context=ctx)
M = torch.stack([mem[i] for i in obs.ids])
assert torch.equal(M.detach(), self.win_M[k]), "replayed M diverged from the organism's"
losses.append(((pred - obs.target) ** 2).mean())
prev = M if carry else M.detach()
return torch.stack(losses).mean()
def _measure(self) -> None:
self.replaying = True
try:
Lc = self._replay(carry=True)
gc = [g.detach().clone() for g in torch.autograd.grad(Lc, self.params)]
Ld = self._replay(carry=False)
gd = [g.detach().clone() for g in torch.autograd.grad(Ld, self.params)]
finally:
self.replaying = False
self.loss_equal &= bool(torch.equal(Lc.detach(), Ld.detach()))
self.carried.append(gc)
self.detached.append(gd)
self.pending = gc # the real backward, next, must reproduce these
def on_step(self, t, obs, r, ctx, axes, prev, memory) -> None:
if not self.win:
self.prev0 = prev.detach().clone()
self.win.append((obs, r, ctx, axes))
self.win_M.append(torch.stack([memory[i] for i in obs.ids]).detach().clone())
if len(self.win) == self.bptt:
self._measure()
self.win, self.win_M = [], []
# -- the measurement ----------------------------------------------------------
def _paths(self, i: int) -> dict[str, dict[str, Tensor]]:
c = _split_blocks(self.carried[i], self.d)
d = _split_blocks(self.detached[i], self.d)
return {"carried": c, "detached": d,
"temporal": {b: c[b] - d[b] for b in BLOCKS}}
def summary(self, n_null: int = 40, seed: int = 0) -> dict:
"""‖mean gradient‖ against mean ‖gradient‖, per block and per path.
The ratio is the whole of Part A: near 1 the signal is coherent, near 0 it
cancels. Its floor is not 0 -- averaging `n` directions that agree about
nothing still leaves `~1/sqrt(n)` behind -- so the floor is measured the way
every other chance level in this repo is, by destroying the effect and keeping
everything else: each optimiser step's gradient vector is multiplied by a
random sign, which removes any consistent direction and leaves every magnitude
exactly as it was.
`tail_` repeats the ratio over the second half of the optimiser steps, the
segment `regime._metrics` reports the error on, where a signal that only
arrives late in training would show.
"""
n = len(self.carried)
rng = np.random.default_rng(seed)
S = torch.tensor(rng.choice([-1.0, 1.0], size=(n_null, n)), dtype=torch.float32)
by_step = [self._paths(i) for i in range(n)]
t0 = n // 2
out: dict[str, dict] = {}
for b in BLOCKS:
per_path: dict = {}
for tag in ("carried", "detached", "temporal"):
V = torch.stack([s[tag][b].reshape(-1) for s in by_step]) # (n, d)
norms = V.norm(dim=1)
mean_norm = float(norms.mean())
mv = float(V.mean(0).norm())
null = float(((S @ V).norm(dim=1) / n).mean())
# what Adam actually consumes. Its step is lr * m / (sqrt(v) + eps),
# which is invariant to a uniform rescaling of the gradient, so a
# magnitude on its own says nothing about whether a block can move.
# This is the same ratio as `coherence`, taken per coordinate, and it
# is the factor by which a coordinate's step is shrunk from the full
# lr: 1 means every step agreed, 0 means they cancelled.
rms = V.pow(2).mean(0).sqrt() + 1e-30
snr = float((V.mean(0).abs() / rms).mean())
snr_null = float(statistics.fmean(
float(((S[k][:, None] * V).mean(0).abs() / rms).mean())
for k in range(n_null)))
tmean = float(norms[t0:].mean())
tmv = float(V[t0:].mean(0).norm())
per_path[tag] = dict(
mean_norm=mean_norm, norm_of_mean=mv, adam_snr=snr, adam_snr_null=snr_null,
coherence=mv / mean_norm if mean_norm > 0 else float("nan"),
null=null / mean_norm if mean_norm > 0 else float("nan"),
tail_mean_norm=tmean, tail_norm_of_mean=tmv,
tail_coherence=tmv / tmean if tmean > 0 else float("nan"),
)
per_step = per_path["detached"]["mean_norm"]
per_path["temporal_share"] = (per_path["temporal"]["mean_norm"] / per_step
if per_step > 0 else float("nan"))
out[b] = per_path
return dict(n_steps=n, blocks=out, n_checked=self.n_checked,
max_rel_vs_real_backward=self.max_rel, loss_equal=self.loss_equal)
def _gate_function(org, w0: Tensor, b0: Tensor, inputs: list[tuple]) -> dict:
"""What the gate's displacement did to the gate.
The gradient measurement says how much signal arrived; this says what arriving
changed. The pre-activation `W_g[h‖M] + b_g − κa` is evaluated on the *same*
inputs -- the ones the trained organism actually produces -- under the trained
weights and under the weights at initialisation. If the two agree, the block moved
and the function it computes did not.
"""
H = torch.cat([torch.cat([h, m], -1) for h, m, _ in inputs])
a = torch.tensor([ar for _, _, ar in inputs]).repeat_interleave(inputs[0][0].shape[0])
with torch.no_grad():
pre_t = (org.grp.gate(H).T - org.grp.kappa * a).T
pre_0 = (torch.nn.functional.linear(H, w0, b0).T - org.grp.kappa * a).T
g_t, g_0 = torch.sigmoid(pre_t), torch.sigmoid(pre_0)
c = torch.corrcoef(torch.stack([pre_t.reshape(-1), pre_0.reshape(-1)]))[0, 1]
return dict(
pre_trained_mean=float(pre_t.mean()), pre_trained_sd=float(pre_t.std()),
pre_init_mean=float(pre_0.mean()), pre_init_sd=float(pre_0.std()),
g_trained_mean=float(g_t.mean()), g_trained_sd=float(g_t.std()),
g_init_mean=float(g_0.mean()), g_init_sd=float(g_0.std()),
pre_rms_change=float((pre_t - pre_0).pow(2).mean().sqrt()),
pre_corr=float(c), n_samples=int(pre_t.numel()),
)
def part_a(seed: int, train_steps: int = TRAIN_STEPS, bptt: int = 20, lr: float = 1e-3,
hidden: int = 32, omega: float = 10.0, gate_window: int = 500) -> dict:
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
tr = GradTrace(org, bptt)
before = {b: v.detach().clone() for b, v in _split_blocks(_params(org), org.hidden_dim).items()}
w0, b0 = org.grp.gate.weight.detach().clone(), org.grp.gate.bias.detach().clone()
tail: list[tuple] = []
def on_step(t, obs, r, ctx, axes, prev, memory):
tr.on_step(t, obs, r, ctx, axes, prev, memory)
if t >= train_steps - gate_window: # the inputs the trained organism produces
with torch.no_grad():
tail.append((_hidden(org, obs.attrs, r, axes, ctx), prev.detach().clone(), axes[1]))
_, _, trace = _train(spec, wcfg, world, org, train_steps, bptt, lr, on_step=on_step)
after = _split_blocks(_params(org), org.hidden_dim)
s = tr.summary()
# how far each block actually travelled, relative to where it started. Adam's step
# is lr * m / (sqrt(v) + eps) and so is invariant to a uniform rescaling of the
# gradient: a block with a tiny gradient can still move a long way. This is what
# turns the gradient measurement into a statement about weights.
for b in BLOCKS:
s["blocks"][b]["displacement"] = float((after[b].detach() - before[b]).norm())
s["blocks"][b]["displacement_rel"] = (s["blocks"][b]["displacement"]
/ float(before[b].norm()))
s["gate_function"] = _gate_function(org, w0, b0, tail)
s.update(seed=seed, train_steps=train_steps, bptt=bptt,
trained=_metrics(trace["losses"], trace["switched"], trace["arousals"], 20))
return s
# -- Part B: the ceiling ----------------------------------------------------------
def _mlp(d_in: int, n_cls: int, width: int, seed: int) -> nn.Module:
with torch.random.fork_rng(): # the organism and the world keep their stream
torch.manual_seed(seed)
return nn.Sequential(nn.Linear(d_in, width), nn.ReLU(),
nn.Linear(width, width), nn.ReLU(), nn.Linear(width, n_cls))
def _fit_mlp(X: np.ndarray, y: np.ndarray, R: int, width: int = 128, steps: int = 400,
lr: float = 3e-3, seed: int = 0):
"""A 2x128 ReLU decoder, registered into `frozen.ESTIMATORS` rather than copied.
`results/when_memory_works.md` §2b is why this exists: on this exact target a
linear decoder on the raw window reads 0.23 at every history length while an MLP
on the same features reads 0.83. A linear-only probe would report "not there" for
a signal that is there non-linearly, so the null in this file needs both.
"""
net = _mlp(X.shape[1], R, width, seed)
Xt = torch.tensor(X, dtype=torch.float32)
yt = torch.tensor(y, dtype=torch.long)
opt = torch.optim.Adam(net.parameters(), lr=lr)
for _ in range(steps):
opt.zero_grad()
nn.functional.cross_entropy(net(Xt), yt).backward()
opt.step()
def score(design: np.ndarray) -> np.ndarray:
with torch.no_grad():
return net(torch.tensor(design, dtype=torch.float32)).numpy()
return score
# `probe` resolves its estimator through this table, so adding an entry extends the
# published probe rather than forking it. `_scores` already accepts a callable.
frozen_mod.ESTIMATORS["mlp"] = _fit_mlp
class AuxHead:
"""A linear head from `M_i` to a categorical target, trained jointly with the task.
The measuring instrument, not an architecture. `target="regime"` supervises the
state to hold the world's current regime id -- the thing hypothesis (a) says the
loss never asked for. `target="type"` supervises it to hold the entity's own type,
a signal that is in `attrs` and therefore certainly reachable: the positive control
that tells a null apart from a broken head.
"""
def __init__(self, org, world, n_cls: int, lam: float, target: str, seed: int,
kind: str = "linear", width: int = 128):
if kind == "linear":
with torch.random.fork_rng(): # the organism and the world keep their stream
torch.manual_seed(9000 + seed)
self.head = nn.Linear(org.hidden_dim, n_cls)
else:
self.head = _mlp(org.hidden_dim, n_cls, width, 9000 + seed)
self.world, self.lam, self.target, self.kind = world, lam, target, kind
self.hits: list[float] = []
def labels(self, obs) -> Tensor:
if self.target == "regime":
return torch.full((obs.attrs.shape[0],), obs.regime, dtype=torch.long)
return self.world.types.long()
def __call__(self, t, obs, memory) -> Tensor:
M = torch.stack([memory[i] for i in obs.ids])
y = self.labels(obs)
logits = self.head(M)
self.hits.append(float((logits.detach().argmax(-1) == y).float().mean()))
return self.lam * nn.functional.cross_entropy(logits, y)
def accuracy(self, half: bool = True) -> float:
h = self.hits[len(self.hits) // 2:] if half else self.hits
return statistics.fmean(h) if h else float("nan")
def part_b(seed: int, lam: float, target: str = "regime", train_steps: int = TRAIN_STEPS,
frozen_steps: int = FROZEN_STEPS, bptt: int = 20, lr: float = 1e-3,
hidden: int = 32, omega: float = 10.0, window: int = 20,
split: float = SPLIT, n_null: int = 20, head_kind: str = "linear",
mlp_probe: bool = False) -> dict:
"""Train `grp_k0` with the auxiliary head at `lam`, freeze, then probe as Task 7b did.
At `lam == 0` no head is built and `aux` is None, so the loop is literally the one
that produced the 0.332 baseline and this row is that baseline (pinned by
`tests/test_credit.py::test_lambda_zero_reproduces_the_frozen_baseline`).
"""
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
n_cls = wcfg.n_regimes if target == "regime" else wcfg.n_types
head = AuxHead(org, world, n_cls, lam, target, seed, head_kind) if lam > 0 else None
affect, memory, trace = _train(
spec, wcfg, world, org, train_steps, bptt, lr,
aux=head, extra_params=() if head is None else head.head.parameters())
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps)
assert fr["frozen_bit_identical"] and fr["dM_min"] > 0.0
labels = np.asarray(fr["regimes"])
types = world.types.numpy()
args = dict(split=split, n_null=n_null, seed=seed)
probes = {
# the regime decode, the number comparable with frozen.md Part B's 0.332
"M_regime": probe(fr["M"], labels, fr["switched"], wcfg.n_regimes, **args),
"h_regime": probe(fr["h"], labels, fr["switched"], wcfg.n_regimes, **args),
# the entity's own type: a signal known to be in M, so a floor on the probe
"M_type": probe(fr["M"], np.tile(types, (len(labels), 1)), fr["switched"],
wcfg.n_types, **args),
}
# both of `probe`'s nulls are degenerate for a target that is constant in time --
# permuting or circularly shifting the step axis of a label array whose rows are all
# identical returns that same array, so they report the accuracy back as its own
# chance level. The type's chance level therefore comes from permuting the
# assignment across entities, which breaks the association and keeps the marginal.
rp = np.random.default_rng(seed)
probes["M_type"]["degenerate_time_null"] = (
probes["M_type"]["chance_shift"] == probes["M_type"]["acc_entity"])
probes["M_type"]["chance_entity_perm"] = float(np.mean([
probe(fr["M"], np.tile(types[rp.permutation(len(types))], (len(labels), 1)),
fr["switched"], wcfg.n_types, split=split, n_null=1, seed=seed)["acc_entity"]
for _ in range(5)]))
if mlp_probe:
# the same split, the same two nulls, a decoder that is not linear
probes["M_regime_mlp"] = probe(fr["M"], labels, fr["switched"], wcfg.n_regimes,
split=split, n_null=5, seed=seed, estimator="mlp")
probes["h_regime_mlp"] = probe(fr["h"], labels, fr["switched"], wcfg.n_regimes,
split=split, n_null=5, seed=seed, estimator="mlp")
return dict(condition="grp_k0", seed=seed, lam=lam, target=target, head_kind=head_kind,
train_steps=train_steps, frozen_steps=frozen_steps,
trained=_metrics(trace["losses"], trace["switched"], trace["arousals"], window),
frozen=_metrics(fr["losses"], fr["switched"], fr["arousals"], window),
aux_train_acc=head.accuracy() if head else float("nan"),
gate=fr["gate"], probes=probes)
def trajectory(seed: int, lam: float = 1.0, bucket: int = 1000,
train_steps: int = TRAIN_STEPS, bptt: int = 20, lr: float = 1e-3,
hidden: int = 32, omega: float = 10.0, head_kind: str = "linear") -> dict:
"""The auxiliary head's accuracy over training, bucketed.
Separates "cannot" from "has not yet": a head that is going to get there climbs,
and one that is not wanders. Reported for both targets at the same lambda, so the
two curves are the same measurement on a reachable and an unreachable signal.
"""
out = {}
for target in TARGETS:
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
n_cls = wcfg.n_regimes if target == "regime" else wcfg.n_types
head = AuxHead(org, world, n_cls, lam, target, seed, head_kind)
_train(spec, wcfg, world, org, train_steps, bptt, lr,
aux=head, extra_params=head.head.parameters())
out[target] = dict(
chance=1.0 / n_cls,
curve=[statistics.fmean(head.hits[i:i + bucket])
for i in range(0, len(head.hits), bucket)])
return dict(seed=seed, lam=lam, bucket=bucket, head_kind=head_kind, targets=out)
def trajectory_table(runs: list[dict]) -> str:
lines = [f"{'target':<8}{'chance':>8}{'seed':>6}" +
"".join(f"{'@' + str((i + 1)) + 'k':>8}" for i in range(len(runs[0]["targets"]["regime"]["curve"]))),
"-" * 80]
for target in TARGETS:
for r in runs:
c = r["targets"][target]
lines.append(f"{target:<8}{c['chance']:>8.3f}{r['seed']:>6}" +
"".join(f"{v:>8.3f}" for v in c["curve"]))
return "\n".join(lines)
# -- reporting --------------------------------------------------------------------
def _se(xs: list[float]) -> float:
return statistics.stdev(xs) / math.sqrt(len(xs)) if len(xs) > 1 else 0.0
def grad_table(runs: list[dict]) -> str:
"""Magnitudes first, then the ratio they make."""
lines = [f"{'block':<9}{'‖mean g‖':>11}{'mean ‖g‖':>11}{'coher':>8}{'null':>7}"
f"{'snr':>7}{'snr null':>9}{'|dW|/|W|':>10}"
f"{'‖temporal‖':>12}{'‖per-step‖':>12}{'temp/step':>11}", "-" * 105]
for b in BLOCKS:
get = lambda path, f: statistics.fmean(r["blocks"][b][path][f] for r in runs)
at = lambda f: statistics.fmean(r["blocks"][b][f] for r in runs)
lines.append(
f"{b:<9}{get('carried', 'norm_of_mean'):>11.3e}{get('carried', 'mean_norm'):>11.3e}"
f"{get('carried', 'coherence'):>8.3f}{get('carried', 'null'):>7.3f}"
f"{get('carried', 'adam_snr'):>7.3f}{get('carried', 'adam_snr_null'):>9.3f}"
f"{at('displacement_rel'):>10.3f}"
f"{get('temporal', 'mean_norm'):>12.3e}{get('detached', 'mean_norm'):>12.3e}"
f"{at('temporal_share'):>11.3f}")
return "\n".join(lines)
def coherence_table(runs: list[dict]) -> str:
"""The measurement: is the signal coherent, or does it cancel?
Every block is read against *its own* measured null, because the floor depends on
how unevenly that block's gradient magnitude is spread over the run and is not the
same number for all of them.
"""
lines = [f"{'block':<9}{'coherence':>11}{'null':>8}{'excess':>9}{'paired se':>11}"
f"{'>null':>8}{'adam snr':>10}{'null':>7}{'excess':>9}{'se':>8}", "-" * 90]
for b in BLOCKS:
c = [r["blocks"][b]["carried"]["coherence"] for r in runs]
z = [r["blocks"][b]["carried"]["null"] for r in runs]
sn = [r["blocks"][b]["carried"]["adam_snr"] for r in runs]
zn = [r["blocks"][b]["carried"]["adam_snr_null"] for r in runs]
d = [x - y for x, y in zip(c, z)]
e = [x - y for x, y in zip(sn, zn)]
lines.append(
f"{b:<9}{statistics.fmean(c):>11.3f}{statistics.fmean(z):>8.3f}"
f"{statistics.fmean(d):>+9.3f}{_se(d):>11.3f}{sum(x > 0 for x in d):>5}/{len(d):<2}"
f"{statistics.fmean(sn):>10.3f}{statistics.fmean(zn):>7.3f}"
f"{statistics.fmean(e):>+9.3f}{_se(e):>8.3f}")
return "\n".join(lines)
def magnitude_table(runs: list[dict]) -> str:
"""How big "negligible" is, against the blocks that certainly train.
`gate` and `cand` have identical shapes and read identical inputs, so their ratio
is the like-for-like one; `per-par` divides by sqrt(#params) so the others are
comparable too.
"""
npar = {"gate": 2048, "cand": 2048, "feat": 96, "out": 64,
"gate[h]": 1024, "gate[M]": 1024, "cand[h]": 1024, "cand[M]": 1024}
g0 = statistics.fmean(r["blocks"]["gate"]["carried"]["mean_norm"] for r in runs)
lines = [f"{'block':<9}{'n_par':>7}{'mean ‖g‖':>11}{'per-par':>11}{'x gate':>9}"
f"{'x gate/par':>12}{'|dW|/|W|':>11}", "-" * 70]
for b in BLOCKS:
m = statistics.fmean(r["blocks"][b]["carried"]["mean_norm"] for r in runs)
pp = m / math.sqrt(npar[b])
lines.append(f"{b:<9}{npar[b]:>7}{m:>11.3e}{pp:>11.3e}{m / g0:>9.1f}"
f"{pp / (g0 / math.sqrt(npar['gate'])):>12.1f}"
f"{statistics.fmean(r['blocks'][b]['displacement_rel'] for r in runs):>11.4f}")
return "\n".join(lines)
def grad_per_seed(runs: list[dict], field: str = "coherence", path: str = "carried") -> str:
"""`field="temporal_share"` reads the block level; anything else reads a path."""
def cell(r, b):
v = r["blocks"][b]
return v[field] if field in v else v[path][field]
lines = [f"{'block':<9}" + "".join(f"{'s' + str(r['seed']):>8}" for r in runs),
"-" * (9 + 8 * len(runs))]
for b in BLOCKS:
lines.append(f"{b:<9}" + "".join(f"{cell(r, b):>8.3f}" for r in runs))
return "\n".join(lines)
def gate_table(runs: list[dict]) -> str:
"""The gate's pre-activation under the trained weights and under its initialisation."""
f = lambda k: statistics.fmean(r["gate_function"][k] for r in runs)
rows = [("pre-activation mean", "pre_trained_mean", "pre_init_mean"),
("pre-activation sd", "pre_trained_sd", "pre_init_sd"),
("g mean", "g_trained_mean", "g_init_mean"),
("g sd", "g_trained_sd", "g_init_sd")]
lines = [f"{'quantity':<22}{'trained':>10}{'at init':>10}", "-" * 42]
lines += [f"{n:<22}{f(a):>10.4f}{f(b):>10.4f}" for n, a, b in rows]
lines.append(f"{'rms change in pre':<22}{f('pre_rms_change'):>10.4f}")
lines.append(f"{'corr(trained, init)':<22}{f('pre_corr'):>10.4f}")
return "\n".join(lines)
def _by_lam(runs: list[dict]) -> dict[float, list[dict]]:
by: dict[float, list[dict]] = {}
for r in runs:
by.setdefault(r["lam"], []).append(r)
return {k: sorted(v, key=lambda r: r["seed"]) for k, v in sorted(by.items())}
def aux_table(runs: list[dict], key: str = "M_regime") -> str:
"""Reading 1: can the state hold it, measured against both nulls."""
lines = [f"{'lambda':>8}{'aux(train)':>12}{'probe acc':>11}{'shuffle':>9}{'shift':>8}"
f"{'gap':>8}{'sd':>7}{'>chance':>9}{'M_type':>9}{'(perm)':>9}", "-" * 90]
for lam, rs in _by_lam(runs).items():
acc = [r["probes"][key]["acc_entity"] for r in rs]
shuf = [r["probes"][key]["chance_shuffle"] for r in rs]
shift = [r["probes"][key]["chance_shift"] for r in rs]
gap = [a - c for a, c in zip(acc, shift)]
ty = [r["probes"]["M_type"]["acc_entity"] for r in rs]
tyc = [r["probes"]["M_type"]["chance_entity_perm"] for r in rs]
aux = statistics.fmean(r["aux_train_acc"] for r in rs) if lam > 0 else float("nan")
lines.append(
f"{lam:>8.0e}{aux:>12.3f}{statistics.fmean(acc):>11.3f}{statistics.fmean(shuf):>9.3f}"
f"{statistics.fmean(shift):>8.3f}{statistics.fmean(gap):>+8.3f}"
f"{statistics.stdev(gap) if len(gap) > 1 else 0:>7.3f}"
f"{sum(g > 0 for g in gap):>6}/{len(gap):<3}{statistics.fmean(ty):>9.3f}"
f"{statistics.fmean(tyc):>9.3f}")
return "\n".join(lines)
def task_table(runs: list[dict], phase: str = "trained") -> str:
"""Reading 2: does the main task move, paired per seed against lambda = 0."""
by = _by_lam(runs)
base = {r["seed"]: r[phase]["steady"] for r in by.get(0.0, [])}
lines = [f"{'lambda':>8}{'steady':>11}{'ratio l0/l':>12}{'won':>8}{'log-ratio':>11}"
f"{'paired se':>11}{'reading':>12}", "-" * 73]
for lam, rs in by.items():
st = [r[phase]["steady"] for r in rs]
mean = statistics.fmean(st)
if lam == 0.0 or not base:
lines.append(f"{lam:>8.0e}{mean:>11.3e}{'--':>12}{'--':>8}{'--':>11}{'--':>11}{'--':>12}")
continue
pairs = [(base[r["seed"]], r[phase]["steady"]) for r in rs if r["seed"] in base]
lr_ = [math.log(b / x) for b, x in pairs] # > 0 means lambda helped
se, m = _se(lr_), statistics.fmean(lr_)
reading = "ambiguous" if abs(m) < se else ("lower err" if m > 0 else "higher err")
lines.append(f"{lam:>8.0e}{mean:>11.3e}{math.exp(m):>12.3f}"
f"{sum(x > 0 for x in lr_):>5}/{len(lr_):<2}{m:>+11.4f}{se:>11.4f}{reading:>12}")
return "\n".join(lines)
def per_seed_task(runs: list[dict], phase: str = "trained") -> str:
by = _by_lam(runs)
seeds = [r["seed"] for r in next(iter(by.values()))]
lines = [f"{'lambda':>8}" + "".join(f"{'s' + str(s):>10}" for s in seeds),
"-" * (8 + 10 * len(seeds))]
for lam, rs in by.items():
lines.append(f"{lam:>8.0e}" + "".join(f"{r[phase]['steady']:>10.2e}" for r in rs))
return "\n".join(lines)
def per_seed_gap(runs: list[dict], key: str = "M_regime") -> str:
by = _by_lam(runs)
seeds = [r["seed"] for r in next(iter(by.values()))]
lines = [f"{'lambda':>8}" + "".join(f"{'s' + str(s):>8}" for s in seeds),
"-" * (8 + 8 * len(seeds))]
for lam, rs in by.items():
lines.append(f"{lam:>8.0e}" + "".join(
f"{r['probes'][key]['acc_entity'] - r['probes'][key]['chance_shift']:>+8.3f}"
for r in rs))
return "\n".join(lines)
def joint(runs: list[dict], phase: str = "trained", key: str = "M_regime") -> str:
"""Reading 3: cross reading 1 with reading 2, which is what the verdict is read off.
Both columns are *paired changes against lambda = 0*, per seed, with a paired
standard error. The absolute gap is not the question -- the lambda = 0 row already
sits +0.044 above its null, which is the instantaneous read-off `frozen.md` §2 and
`pooled.md` both identified and neither attributed to memory. The question is
whether being told the regime raises it.
"""
by = _by_lam(runs)
base_s = {r["seed"]: r[phase]["steady"] for r in by.get(0.0, [])}
base_g = {r["seed"]: r["probes"][key]["acc_entity"] - r["probes"][key]["chance_shift"]
for r in by.get(0.0, [])}
lines = [f"{'lambda':>8}{'gap':>8}{'d(gap) vs l=0':>15}{'se':>8}{'won':>7}"
f"{'task log-ratio':>16}{'se':>8}{'won':>7}{'quadrant':>28}", "-" * 97]
for lam, rs in by.items():
gap = [r["probes"][key]["acc_entity"] - r["probes"][key]["chance_shift"] for r in rs]
if lam == 0.0:
lines.append(f"{lam:>8.0e}{statistics.fmean(gap):>+8.3f}{'--':>15}{'--':>8}"
f"{'--':>7}{'--':>16}{'--':>8}{'--':>7}{'(baseline)':>28}")
continue
dg = [g - base_g[r["seed"]] for g, r in zip(gap, rs) if r["seed"] in base_g]
lr_ = [math.log(base_s[r["seed"]] / r[phase]["steady"]) for r in rs if r["seed"] in base_s]
m, mse = statistics.fmean(dg), _se(dg)
t, tse = statistics.fmean(lr_), _se(lr_)
held = "no change in M" if abs(m) < mse else ("M holds more" if m > 0 else "M holds less")
moved = "task ambiguous" if abs(t) < tse else ("task improves" if t > 0 else "task worsens")
lines.append(f"{lam:>8.0e}{statistics.fmean(gap):>+8.3f}{m:>+15.3f}{mse:>8.3f}"
f"{sum(x > 0 for x in dg):>4}/{len(dg):<2}{t:>+16.4f}{tse:>8.4f}"
f"{sum(x > 0 for x in lr_):>4}/{len(lr_):<2}{held + ', ' + moved:>28}")
return "\n".join(lines)
# -- driver -----------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--part", choices=("grad", "aux", "traj"), default="grad")
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15")
ap.add_argument("--lambdas", default=",".join(str(l) for l in LAMBDAS))
ap.add_argument("--target", choices=TARGETS, default="regime")
ap.add_argument("--head", choices=("linear", "mlp"), default="linear",
help="the auxiliary head's form. `mlp` is the control on whether a "
"linear head was the binding constraint rather than M")
ap.add_argument("--mlp-probe", action="store_true",
help="also decode the frozen M with a 2x128 MLP, same splits and nulls")
ap.add_argument("--train-steps", type=int, default=TRAIN_STEPS)
ap.add_argument("--frozen-steps", type=int, default=FROZEN_STEPS)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--out", default=None)
ap.add_argument("--report", default=None,
help="comma-separated result files to report on instead of running. "
"Seeds are independent, so a sweep may be sharded across "
"processes and merged here; the tables are the same either way.")
a = ap.parse_args()
seeds = [int(s) for s in a.seeds.split(",")]
if a.report:
runs = [r for f in a.report.split(",") for r in json.loads(Path(f).read_text())]
runs.sort(key=lambda r: (r["lam"], r["seed"]))
_report_aux(runs, mlp="M_regime_mlp" in runs[0]["probes"],
target=runs[0]["target"])
return
if a.part == "grad":
runs = []
for seed in seeds:
r = part_a(seed, a.train_steps, lr=a.lr)
g = r["blocks"]
print(f"seed={seed} coherence gate={g['gate']['carried']['coherence']:.3f} "
f"cand={g['cand']['carried']['coherence']:.3f} "
f"feat={g['feat']['carried']['coherence']:.3f} "
f"out={g['out']['carried']['coherence']:.3f} | "
f"temporal/per-step gate={g['gate']['temporal_share']:.4f} "
f"cand={g['cand']['temporal_share']:.4f} "
f"(replay pinned on {r['n_checked']} windows, max rel "
f"{r['max_rel_vs_real_backward']:.1e})", flush=True)
runs.append(r)
out = a.out or "results/credit_grad.json"
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(runs, indent=1, default=float))
print("\n=== Part A ===")
print(grad_table(runs))
print("\ncoherence against each block's own measured null:")
print(coherence_table(runs))
print("\nmagnitudes:")
print(magnitude_table(runs))
print("\nwhat the displacement did to the gate (same inputs, trained vs initial weights):")
print(gate_table(runs))
print("\nper-seed coherence (carried):")
print(grad_per_seed(runs))
print("\nper-seed temporal/per-step:")
print(grad_per_seed(runs, "temporal_share"))
return
if a.part == "traj":
runs = [trajectory(seed, lam=max(float(x) for x in a.lambdas.split(",")),
train_steps=a.train_steps, lr=a.lr, head_kind=a.head)
for seed in seeds]
out = a.out or "results/credit_traj.json"
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(runs, indent=1, default=float))
print("\n=== the auxiliary head's accuracy over training ===")
print(trajectory_table(runs))
return
lams = [float(x) for x in a.lambdas.split(",")]
runs = []
for lam in lams:
for seed in seeds:
r = part_b(seed, lam, a.target, a.train_steps, a.frozen_steps, lr=a.lr,
head_kind=a.head, mlp_probe=a.mlp_probe)
p = r["probes"]["M_regime"]
print(f"lam={lam:<7g} seed={seed:<2} steady={r['trained']['steady']:.3e} "
f"aux={r['aux_train_acc']:.3f} M_regime={p['acc_entity']:.3f}"
f"/{p['chance_shift']:.3f} M_type={r['probes']['M_type']['acc_entity']:.3f} "
f"g={r['gate']['mean']:.3f}", flush=True)
runs.append(r)
out = a.out or f"results/credit_aux_{a.target}_{a.head}.json"
Path(out).parent.mkdir(parents=True, exist_ok=True)
Path(out).write_text(json.dumps(runs, indent=1, default=float))
_report_aux(runs, mlp=a.mlp_probe, target=a.target)
def _report_aux(runs: list[dict], mlp: bool, target: str) -> None:
print(f"\n=== Part B, target={target}, head={runs[0].get('head_kind', 'linear')} ===")
print("1. can the state hold it (M -> regime, frozen-phase probe):")
print(aux_table(runs))
if mlp:
print("\n the same M decoded by a 2x128 MLP instead:")
print(aux_table(runs, "M_regime_mlp"))
print("\n and the memoryless h, same MLP decoder:")
print(aux_table(runs, "h_regime_mlp"))
print("\n2. does the main task move (trained phase):")
print(task_table(runs, "trained"))
print("\n frozen phase:")
print(task_table(runs, "frozen"))
print("\nper-seed trained steady:")
print(per_seed_task(runs, "trained"))
print("\nper-seed regime gap above the shift null:")
print(per_seed_gap(runs))
print("\n3. the joint reading:")
print(joint(runs))
if mlp:
print("\n the joint reading on the MLP decode:")
print(joint(runs, key="M_regime_mlp"))
if __name__ == "__main__":
main()
+23 -6
View File
@@ -67,14 +67,15 @@ def _build(name: str, seed: int, hidden: int, omega: float, kappa: float,
def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
steps: int, bptt: int, lr: float, stateless: bool = False,
gate_arousal=None, on_step=None, acfg: AffectConfig | None = None):
gate_arousal=None, on_step=None, acfg: AffectConfig | None = None,
aux=None, extra_params=()):
"""A verbatim copy of `regime.run`'s training loop (the keyword arguments aside).
Copied rather than reused because `regime.run` returns metrics and drops the
organism and the world, and this task has to keep stepping the same world with
the same organism after training ends. `tests/test_frozen.py` pins the copy: it
asserts this loop reproduces `regime.run`'s metrics bit-identically. Every
keyword below defaults to off, and with all three off the loop body is the same
keyword below defaults to off, and with all of them off the loop body is the same
sequence of calls it always was.
`stateless=True` hands the organism an empty memory dict every step, so M_prev is
@@ -95,8 +96,15 @@ def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism
`acfg` overrides the affect time constants for Task 9 Part 1. It defaults to
`AffectConfig()`, the value this loop always used, so the copy stays verbatim for
every existing caller. `AffectConfig`'s own defaults are not touched.
`aux(t, obs, memory) -> Tensor | None` returns a scalar added to the loss that is
put in `pending`, and `extra_params` are optimised alongside the organism's. This
is Task 11 Part B's oracle on the state: a supervised head is attached to M to ask
what the state *could* hold if it were told. **Affect and the reported `losses`
stay on the main-task loss alone**, so the metric `_metrics` computes is still the
task's and a run with `aux=None` is bit-identical to every earlier caller's.
"""
opt = torch.optim.Adam(org.parameters(), lr=lr)
opt = torch.optim.Adam(list(org.parameters()) + list(extra_params), lr=lr)
acfg = AffectConfig() if acfg is None else acfg
affect = Affect()
memory: dict[int, Tensor] = {}
@@ -118,7 +126,7 @@ def _train(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism
if on_step is not None and org.use_memory else None)
pred, memory = org(obs.attrs, r, obs.ids, axes, held, context=ctx)
loss = ((pred - obs.target) ** 2).mean()
pending.append(loss)
pending.append(loss if aux is None else loss + aux(t, obs, memory))
affect = update(affect, loss.item(), acfg)
losses.append(loss.item()); switched.append(obs.switched); arousals.append(affect.arousal)
if on_step is not None:
@@ -264,8 +272,17 @@ def _design(reps: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return np.concatenate([z, np.ones((z.shape[0], 1))], axis=1)
def _scores(reps: np.ndarray, W: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
return (_design(reps, mu, sd) @ W).reshape(reps.shape[0], reps.shape[1], -1)
def _scores(reps: np.ndarray, W, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
"""An estimator returns either a linear map or a callable that scores a design.
The callable form is what lets a non-linear decoder use this probe unchanged --
`results/when_memory_works.md` §2b is the reason one is wanted: on this target a
linear decoder reads 0.23 where an MLP reads 0.83, so a linear-only probe would
answer a question nobody asked.
"""
X = _design(reps, mu, sd)
S = W(X) if callable(W) else X @ W
return np.asarray(S).reshape(reps.shape[0], reps.shape[1], -1)
def _accuracy(scores: np.ndarray, lab: np.ndarray, step_lab: np.ndarray | None) -> tuple[float, float]:
+257
View File
@@ -0,0 +1,257 @@
"""Task 10: is the regime information distributed across the 16 per-entity states?
`results/frozen.md` Part B decoded the world's regime id from a *single* entity's `M`
at 0.332, from the memoryless RP's `h` at 0.342, and from the `h` inside the same GRP
at 0.338 -- all against a measured chance near 0.273. Two explanations were left open:
(b) shape mismatch -- the regime is one global 3x3 matrix `K`, the state is per-entity,
so the information could be *distributed across* the 16 states while being absent
from any one of them;
(a) credit assignment -- nothing in the loss rewards carrying the regime forward, so
the state never learns to hold it at all.
This file decodes from three views of the same frozen representation: one entity, the
mean over the 16, and all 16 concatenated. Pooling is applied to `M` *and* to `h`.
**The `h` control is the whole measurement.** Pooling 16 samples of anything averages
away per-entity noise, and that alone lifts a probe. `h` is the feedforward layer `M`
is built from and carries no memory, so whatever pooling buys on `h` is the value of
pooling as such. (b) is live only if pooled `M` gains what pooled `h` does not.
Nothing here is an architecture change: `_build`, `_train`, `_frozen` and `probe` are
imported from `frozen.py` unmodified, so the organism, the world and the estimator are
the ones that produced the 0.332 baseline. `power_check` is the positive control -- a
synthetic representation whose regime code is genuinely distributed, confirming this
pipeline detects (b) when (b) is true.
"""
from __future__ import annotations
import argparse
import json
import statistics
from pathlib import Path
import numpy as np
from frozen import FROZEN_STEPS, SPLIT, TRAIN_STEPS, _build, _frozen, _train, probe
VIEWS = ("single", "mean", "concat")
REPS = ("M", "h")
def views(rep: np.ndarray) -> dict[str, np.ndarray]:
"""(T, N, D) -> the three pooling views, each shaped (T, samples_per_step, features).
`single` is the published baseline: one sample per entity per step, D features.
`mean` is one sample per step of the entity-averaged state, D features.
`concat` is one sample per step of every entity's state, N*D features -- the
strongest form of pooling, and the one whose feature count inflates a fitted
probe's chance level, which is why the shift null is not optional.
Entity order is stable: `ParticleWorld.ids` is `list(range(n))` on every step, so
column block `i` of `concat` is always particle `i`.
"""
T, N, D = rep.shape
return {"single": rep,
"mean": rep.mean(axis=1, keepdims=True),
"concat": rep.reshape(T, 1, N * D)}
# -- one seed --------------------------------------------------------------------
def run_one(seed: int, train_steps: int = TRAIN_STEPS, frozen_steps: int = FROZEN_STEPS,
bptt: int = 20, lr: float = 1e-3, hidden: int = 32, omega: float = 10.0,
split: float = SPLIT, n_null: int = 20, estimators: tuple[str, ...] = ("lsq",)) -> dict:
"""Train `grp_k0` as `regime.run` does, freeze, then probe every view.
The training and frozen phases are `frozen.py`'s, called unchanged, so this seed's
`M_single` row is the same number `results/frozen.md` Part B reports.
"""
spec, wcfg, world, org = _build("grp_k0", seed, hidden, omega, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, train_steps, bptt, lr)
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps)
assert fr["frozen_bit_identical"] and fr["dM_min"] > 0.0
labels = np.asarray(fr["regimes"])
got: dict[str, dict] = {}
for tag in REPS:
for view, r in views(fr[tag]).items():
for est in estimators:
p = probe(r, labels, fr["switched"], wcfg.n_regimes, split=split,
n_null=n_null if est == "lsq" else 5, seed=seed, estimator=est)
p["n_features"] = int(r.shape[-1])
p["n_train_samples"] = int(int(r.shape[0] * split) * r.shape[1])
got[f"{tag}_{view}_{est}"] = p
return dict(condition="grp_k0", seed=seed, train_steps=train_steps,
frozen_steps=frozen_steps, split=split, n_regimes=wcfg.n_regimes,
n_entities=wcfg.n, hidden=hidden, probes=got)
# -- the positive control --------------------------------------------------------
def power_check(labels: np.ndarray, switched: list[bool], n_regimes: int = 4,
n: int = 16, d: int = 32, seed: int = 0, split: float = SPLIT) -> dict:
"""Can this pipeline see a distributed code at all? Two synthetic representations.
`distributed`: the regime is 2 bits. Entities 0-7 write bit 0 into channel 0 and
entities 8-15 write bit 1 into channel 1; every other channel is noise. **No single
entity carries more than one bit**, so a per-entity probe caps near 0.5 however good
it is, while the mean and the concatenation carry both and can reach 1.0. This is
hypothesis (b) made true by construction -- if the measurement cannot find it here,
a null on the real data would mean nothing.
`redundant`: every entity carries the *whole* regime code plus independent noise.
Nothing is distributed; pooling only averages the noise away. This is the confound
the `h` control exists to catch, reproduced deliberately so its signature -- a lift
on any representation, memory or not -- can be compared with the real rows.
"""
rng = np.random.default_rng(seed)
T = len(labels)
bit0 = (labels % 2).astype(float) * 2 - 1
bit1 = (labels // 2).astype(float) * 2 - 1
dist = rng.normal(size=(T, n, d))
half = n // 2
dist[:, :half, 0] += 4.0 * bit0[:, None]
dist[:, half:, 1] += 4.0 * bit1[:, None]
code = rng.normal(size=(n_regimes, d))
red = code[labels][:, None, :] + 4.0 * rng.normal(size=(T, n, d))
out = {}
for tag, rep in (("distributed", dist), ("redundant", red)):
for view, r in views(rep).items():
out[f"{tag}_{view}"] = probe(r, labels, switched, n_regimes, split=split,
n_null=10, seed=seed)
return out
# -- reporting -------------------------------------------------------------------
def _col(results: list[dict], key: str, field: str) -> list[float]:
return [r["probes"][key][field] for r in results]
def table(results: list[dict], est: str = "lsq") -> str:
"""acc, both measured chance levels, and the gap, per view."""
lines = [f"{'representation':<16}{'feat':>6}{'n_tr':>8}{'acc':>8}{'shuffle':>9}"
f"{'shift':>8}{'gap':>8}{'sd(gap)':>9}{'>chance':>9}",
"-" * 81]
for tag in REPS:
for view in VIEWS:
k = f"{tag}_{view}_{est}"
acc = _col(results, k, "acc_entity")
sh = _col(results, k, "chance_shuffle")
sf = _col(results, k, "chance_shift")
gap = [a - c for a, c in zip(acc, sf)]
p0 = results[0]["probes"][k]
lines.append(
f"{tag + ', ' + view:<16}{p0['n_features']:>6}{p0['n_train_samples']:>8}"
f"{statistics.fmean(acc):>8.3f}{statistics.fmean(sh):>9.3f}"
f"{statistics.fmean(sf):>8.3f}{statistics.fmean(gap):>+8.3f}"
f"{statistics.stdev(gap) if len(gap) > 1 else 0.0:>9.3f}"
f"{sum(g > 0 for g in gap):>6}/{len(gap):<3}")
return "\n".join(lines)
def gains(results: list[dict], est: str = "lsq") -> str:
"""The measurement: pooling's gain on `M` beside pooling's gain on `h`.
Gain is measured on the gap above the *shift* null, per seed, because the three
views do not share a chance level -- concatenation multiplies the feature count by
16 and lifts what a fitted probe scores on shuffled labels.
"""
def gap(k: str) -> list[float]:
return [a - c for a, c in zip(_col(results, k, "acc_entity"),
_col(results, k, "chance_shift"))]
lines = [f"{'pooling':<10}{'M gain':>9}{'h gain':>9}{'M-h':>9}{'M wins':>9}"
f"{'h wins':>9}{'M>h':>7}", "-" * 62]
for view in ("mean", "concat"):
gm = [p - s for p, s in zip(gap(f"M_{view}_{est}"), gap(f"M_single_{est}"))]
gh = [p - s for p, s in zip(gap(f"h_{view}_{est}"), gap(f"h_single_{est}"))]
d = [a - b for a, b in zip(gm, gh)]
n = len(gm)
lines.append(f"{view:<10}{statistics.fmean(gm):>+9.3f}{statistics.fmean(gh):>+9.3f}"
f"{statistics.fmean(d):>+9.3f}{sum(g > 0 for g in gm):>6}/{n:<3}"
f"{sum(g > 0 for g in gh):>6}/{n:<3}{sum(x > 0 for x in d):>4}/{n}")
return "\n".join(lines)
def per_seed(results: list[dict], est: str = "lsq") -> str:
seeds = [r["seed"] for r in results]
lines = [f"{'representation':<16}" + "".join(f"{'s' + str(s):>8}" for s in seeds),
"-" * (16 + 8 * len(seeds))]
for tag in REPS:
for view in VIEWS:
k = f"{tag}_{view}_{est}"
row = [a - c for a, c in zip(_col(results, k, "acc_entity"),
_col(results, k, "chance_shift"))]
lines.append(f"{tag + ', ' + view:<16}" + "".join(f"{v:>+8.3f}" for v in row))
return "\n".join(lines)
def vote_table(results: list[dict], est: str = "lsq") -> str:
"""The single-entity probe's per-step vote: 16 decisions aggregated, not 16 states.
Separates pooling the *representation* from aggregating 16 independent decoders,
which is the other way a per-step number can rise without any state holding more.
"""
lines = [f"{'representation':<16}{'per-entity':>12}{'16-vote':>10}{'mean-pooled':>13}", "-" * 51]
for tag in REPS:
e = statistics.fmean(_col(results, f"{tag}_single_{est}", "acc_entity"))
v = statistics.fmean(_col(results, f"{tag}_single_{est}", "acc_step"))
m = statistics.fmean(_col(results, f"{tag}_mean_{est}", "acc_entity"))
lines.append(f"{tag:<16}{e:>12.3f}{v:>10.3f}{m:>13.3f}")
return "\n".join(lines)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7")
ap.add_argument("--train-steps", type=int, default=TRAIN_STEPS)
ap.add_argument("--frozen-steps", type=int, default=FROZEN_STEPS)
ap.add_argument("--lr", type=float, default=1e-3)
ap.add_argument("--estimators", default="lsq")
ap.add_argument("--power-check", action="store_true",
help="also run the synthetic distributed/redundant controls")
ap.add_argument("--out", default="results/pooled.json")
a = ap.parse_args()
ests = tuple(a.estimators.split(","))
results = []
for seed in (int(s) for s in a.seeds.split(",")):
r = run_one(seed, a.train_steps, a.frozen_steps, lr=a.lr, estimators=ests)
p = r["probes"]
print(f"seed={seed} " + " ".join(
f"{t}_{v}={p[f'{t}_{v}_lsq']['acc_entity']:.3f}"
f"/{p[f'{t}_{v}_lsq']['chance_shift']:.3f}"
for t in REPS for v in VIEWS), flush=True)
results.append(r)
payload: dict = dict(results=results)
if a.power_check:
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
affect, memory, _ = _train(spec, wcfg, world, org, 200, 20, a.lr)
fr = _frozen(spec, wcfg, world, org, affect, memory, a.frozen_steps)
pc = power_check(np.asarray(fr["regimes"]), fr["switched"], wcfg.n_regimes)
payload["power_check"] = pc
print("\npositive control (synthetic):")
for k, v in pc.items():
print(f" {k:<24} acc={v['acc_entity']:.3f} shift={v['chance_shift']:.3f}")
Path(a.out).parent.mkdir(parents=True, exist_ok=True)
Path(a.out).write_text(json.dumps(payload, indent=1, default=float))
for est in ests:
print(f"\n=== {est} ===")
print(table(results, est))
print("\npooling gain on the gap above the shift null:")
print(gains(results, est))
print("\nper-seed gap above the shift null:")
print(per_seed(results, est))
print("\nrepresentation pooling vs decision voting:")
print(vote_table(results, est))
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
```
+541
View File
@@ -0,0 +1,541 @@
# Credit assignment: is there a signal, and is there a ceiling?
Task 11. `results/pooled.md` measured hypothesis (b) dead — the regime is not distributed
across the sixteen per-entity states, it is absent from them. Hypothesis (a) was what
remained:
> Nothing in the training signal rewards carrying the regime forward, so the state never
> learns to hold it.
This file measures the ceiling on (a) before anything is built, following the standing
methodology: a mechanism ships with an oracle that is *given* what the mechanism is
supposed to infer, and if the oracle does not pay, the mechanism has no job. **Direct
supervision is used here as a measuring instrument, an oracle on the state. It is not a
proposed architecture and nothing below recommends one.**
**Verdict: hypothesis (a) is not supported, and what replaces it is narrower and harder.
Part A finds the gate is neither starved of gradient nor cancelling it: the temporal path
supplies 59% of the gradient the gate receives, and after 8000 steps `gate.weight` has
travelled further from its initialisation than any other block measured — 27% of its own
norm, against `out.weight`'s 15%. Part B gives the brief's third outcome. Supervised
directly, at every weight from 1e-5 to 1.0, `M` does not come to hold the regime: the
auxiliary head never leaves chance, and the frozen-phase decode moves by −0.001 ± 0.019.
The same head, at the same weights, installs the entity's own type into `M` (0.738 against
a chance of 0.333) and — the control that matters — raises the *regime* decode by
+0.073 ± 0.022 while doing it. The instrument can move the number being read. Regime
supervision does not move it.**
The credit does reach the gate and does flow through time. What it cannot do is put this
hidden variable into this state.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. `grp_k0`, 16 seeds (0-15), 8000 training steps then 4000 frozen steps,
`lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`, `kappa=0`. Test split is the last 30% of the
frozen phase, taken as a suffix in time. Part A: 16 runs, 400 optimiser steps each, three
gradients per step. Part B: 296 training runs.
```
uv run python credit.py --part grad --seeds 0,...,15 --out results/credit_grad.json
uv run python credit.py --part aux --target regime --seeds 0,...,15 \
--out results/credit_aux_regime.json
uv run python credit.py --part aux --target type --seeds 0,...,15 \
--out results/credit_aux_type.json # positive control
uv run python credit.py --part aux --target regime --head mlp --mlp-probe \
--lambdas 0.0,0.01,0.1,1.0 --seeds 0,...,15 # non-linear control
uv run python credit.py --part traj --seeds 0,1,2,3 --lambdas 1.0 \
--out results/credit_traj.json
```
`credit.py` adds no training loop. `_build`, `_train`, `_frozen`, `_metrics` and `probe` are
imported from `frozen.py` and `regime.py` and called unchanged. Two keywords were added to
`_train` — `aux`, which adds a scalar to the loss that goes into `pending`, and
`extra_params`, which puts the head in the optimiser — both defaulting to off, so
`test_train_copy_is_identical_to_regime_run` still pins the loop against `regime.run`.
`frozen._scores` was extended by one line to accept a callable estimator, which is what
lets the non-linear control use the published probe rather than a fork of it.
## 0. The pins, and how each was made able to fail
Four properties carry the numbers below. Each is asserted in code on every run, and each
assertion has a test that breaks it on purpose.
| check | how | result |
|---|---|---|
| the replay is the real training step | every window is replayed at the same parameters from the recorded observations, and the replayed `M` is `torch.equal` to the `M` the organism computed | **bit-identical, 400/400 windows on 16/16 seeds** |
| the replayed gradient is the one Adam used | a per-parameter hook reads the real backward and compares it against the replay's | **max relative difference exactly 0.0**, on all 6400 windows |
| detaching changed only the graph | the carried and detached window losses must be `torch.equal` | holds on every window |
| `lambda = 0` is the published baseline | `part_b(seed, 0.0)` against `frozen.run_one("grp_k0", seed)` | `steady`, `recovery`, probe accuracy and chance level all **bit-identical** |
`test_the_replay_pin_can_fail` perturbs the replay's starting `M` by 1e-3 and the pin
raises, as required. `test_the_readout_block_has_no_temporal_path` is the structural
control on the carried/detached split with a known answer: `out.weight` multiplies `M` at
the current step and nothing else, so its temporal term must be exactly zero — it is —
while the gate's, applied at every step of the window, must not be. If both had come out
zero the split would have been measuring nothing.
`test_coherence_is_one_for_a_constant_gradient_and_at_the_null_for_noise` pins the ratio at
both ends. Full suite: 78 passed (70 existing, 8 new); no existing test was modified.
## 1. Part A — is there a gradient signal at all, or is it cancelling?
Two failures look identical from "the weights did not move": the gradient reaching the gate
is ~0 (*absent*), or it is substantial per step and averages to nothing (*cancelling*). The
ratio of `‖mean gradient‖` to `mean ‖gradient‖` is what separates them, and it is the whole
of this part.
`gate` and `cand` are `grp.gate.weight` and `grp.cand.weight`; `feat` and `out` are
`rp.feat.weight` and `out.weight`, the reference blocks. Both gate and cand take `[h ‖ M]`,
so their column halves are reported separately — `[M]` is the only place a temporal path
can enter them. 16 seeds, 400 optimiser steps each.
### 1a. The ratio, against each block's own measured null
The coherence floor is not zero: averaging `n` directions that agree about nothing still
leaves `~1/sqrt(n)`, and how much it leaves depends on how unevenly that block's gradient
magnitude is spread over the run. So the floor is measured the way every other chance level
in this repo is — by destroying the effect and keeping everything else. Each optimiser
step's gradient vector is multiplied by a random sign, which removes any consistent
direction and leaves every magnitude exactly as it was; 40 draws.
`adam snr` is the same ratio taken per coordinate, `|mean_t g|/rms_t(g)`, which is what
Adam's `m/(sqrt(v)+eps)` actually consumes.
```
block coherence null excess paired se >null adam snr null excess se
------------------------------------------------------------------------------------------
gate 0.202 0.163 +0.039 0.009 14/16 0.066 0.042 +0.024 0.003
cand 0.173 0.108 +0.066 0.016 16/16 0.070 0.041 +0.030 0.004
feat 0.193 0.119 +0.075 0.007 16/16 0.082 0.041 +0.040 0.003
out 0.193 0.101 +0.091 0.022 15/16 0.079 0.040 +0.039 0.007
gate[h] 0.220 0.189 +0.031 0.007 15/16 0.063 0.042 +0.021 0.003
gate[M] 0.191 0.141 +0.050 0.012 14/16 0.069 0.042 +0.027 0.004
cand[h] 0.146 0.110 +0.036 0.008 14/16 0.062 0.041 +0.021 0.002
cand[M] 0.189 0.106 +0.083 0.020 15/16 0.078 0.040 +0.038 0.006
```
Per-seed coherence, `gate` then the three others:
```
block s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
-----------------------------------------------------------------------------------------------------------------------------------------
gate 0.259 0.160 0.258 0.196 0.221 0.234 0.176 0.279 0.184 0.150 0.124 0.226 0.190 0.240 0.163 0.173
cand 0.210 0.134 0.206 0.179 0.102 0.295 0.251 0.210 0.154 0.123 0.085 0.133 0.115 0.167 0.095 0.316
feat 0.203 0.228 0.248 0.191 0.146 0.180 0.204 0.279 0.157 0.202 0.157 0.208 0.146 0.194 0.199 0.153
out 0.252 0.107 0.236 0.206 0.088 0.334 0.321 0.216 0.161 0.147 0.063 0.127 0.136 0.178 0.113 0.393
```
**The signal at the gate does not cancel.** Its coherence is 0.202 against its own measured
floor of 0.163, above that floor on 14 seeds of 16, with a paired standard error of 0.009 —
and 0.202 is the *highest* raw coherence of the four blocks. Read as an excess over its own
null it is the smallest, +0.039 against `out`'s +0.091 and `cand`'s +0.066, so the gate's
signal is somewhat less consistent than the rest of the network's; but it is a signal, on
the same order as the blocks that certainly train, not a quantity averaging to nothing.
Every block in this network is mostly-cancelling — coherence 0.15-0.26 against nulls of
0.10-0.19 — which is what 400 minibatch gradients look like, and the gate is not an
exception to it.
### 1b. And "negligible" is a thousandfold — which turns out not to matter
```
block n_par mean ‖g‖ per-par x gate x gate/par |dW|/|W|
----------------------------------------------------------------------
gate 2048 3.412e-06 7.539e-08 1.0 1.0 0.2682
cand 2048 3.026e-03 6.686e-05 886.9 886.9 0.1904
feat 96 3.670e-04 3.746e-05 107.6 496.8 0.0443
out 64 4.353e-03 5.441e-04 1275.8 7217.3 0.1529
gate[h] 1024 2.287e-06 7.148e-08 0.7 0.9 0.2408
gate[M] 1024 2.472e-06 7.724e-08 0.7 1.0 0.2921
cand[h] 1024 1.815e-03 5.672e-05 532.0 752.4 0.1792
cand[M] 1024 2.390e-03 7.468e-05 700.5 990.6 0.1996
```
`gate` and `cand` have identical shapes and read identical inputs, so their ratio is the
like-for-like one: **the gate's gradient is 887 times smaller than the candidate layer's
sitting beside it**, and 1276 times smaller than the readout's. The mechanism is in the
architecture — `∂L/∂(gate pre-activation) = (∂L/∂M) · (M − M̃) · g(1−g)`, and with `g`
pinned near 0.5 the update is a fixed 50/50 blend under which `M` and `M̃` stay close, so
the factor the gate's gradient carries is a difference that the gate's own inaction keeps
small.
**But a magnitude on its own says nothing here, and the last column is why.** Adam's step
is `lr · m/(sqrt(v)+eps)`, which is invariant to a uniform rescaling of the gradient: what
survives is consistency, not size. Measured per coordinate, the gate's signal-to-noise is
0.066 against `cand`'s 0.070 and `out`'s 0.079 — the same order. And the consequence is
visible in the weights: over 8000 steps **`gate.weight` moved 26.8% of its initial norm,
more than any other block measured**, against `cand`'s 19.0%, `out`'s 15.3% and `feat`'s
4.4%.
This retires the premise both of Part A's two failure modes were built to explain. It is
not true that the gate's weights did not move. They moved the furthest.
### 1c. What moved, and what did not
The gradient measurement says how much signal arrived; this says what arriving changed. The
gate's pre-activation `W_g[h‖M] + b_g − κa` is evaluated on the *same* inputs — the ones the
trained organism actually produces, the last 500 training steps — under the trained weights
and under the weights at initialisation. 16 seeds, 256 000 gate evaluations each.
```
quantity trained at init
------------------------------------------
pre-activation mean 0.0030 0.0038
pre-activation sd 0.1083 0.0811
g mean 0.5008 0.5009
g sd 0.0270 0.0203
rms change in pre 0.0787
corr(trained, init) 0.7001
```
The trained row reproduces `frozen.md` §3's `g = 0.500 ± 0.029` on 16 seeds. The point is
the column beside it. **After a 27% displacement of its weight matrix, the gate computes a
function whose output distribution is where it started**: `g` mean 0.5008 against 0.5009,
and an sd of 0.0270 against 0.0203. The pre-activations did change — they correlate at 0.70
across the displacement, with an rms change of 0.079 that is as large as the sd itself — but
they changed *within* a band of ±0.1 around zero, which is where the sigmoid is linear and
the update `M ← (1−g)M̃ + gM` is a fixed blend regardless.
The gate is not stuck because nothing pushed it. It is stuck because the pushing moved it
sideways: 8000 steps of a real, temporally-informed, Adam-rescaled gradient rearranged 2048
weights without once taking the pre-activation out of the neighbourhood of zero where the
gate does not gate.
### 1d. The temporal path
Paired inside a single run. At every optimiser step the same window is replayed twice at the
same parameters from the same recorded observations — once with `M` carried across the
window, once with `M` detached at every step. Detaching changes the graph and nothing else:
every forward value is bit-identical, asserted against the `M` the organism computed, and
the two window losses are `torch.equal`. The difference is the credit that flows through
time.
```
block ‖carried‖ ‖per-step‖ ‖temporal‖ temporal/per-step se temporal/carried
---------------------------------------------------------------------------------------
gate 3.412e-06 1.682e-06 2.033e-06 1.187 0.036 0.587
cand 3.026e-03 1.510e-03 1.753e-03 1.142 0.028 0.572
feat 3.670e-04 1.871e-04 2.116e-04 1.136 0.043 0.576
out 4.353e-03 4.353e-03 0.000e+00 0.000 0.000 0.000
gate[h] 2.287e-06 1.126e-06 1.362e-06 1.189 0.037 0.586
gate[M] 2.472e-06 1.221e-06 1.473e-06 1.184 0.036 0.587
cand[h] 1.815e-03 9.081e-04 1.053e-03 1.141 0.028 0.572
cand[M] 2.390e-03 1.191e-03 1.384e-03 1.142 0.028 0.572
```
Per-seed `temporal/per-step` for the gate:
```
s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
1.395 1.204 1.162 1.252 1.009 1.226 1.268 1.521 1.284 1.153 1.122 1.095 1.103 0.994 0.973 1.227
```
**Hypothesis (a) predicted the temporal term would be negligible next to the per-step one.
It is 1.187 times larger, on 14 seeds of 16, with a paired standard error of 0.036.** Just
under three-fifths of the gradient the gate receives — 0.587 of it — arrives through the
carried state rather than from the current step. The `out.weight` row is the structural
control: it multiplies `M` at the current step and nothing else, and its temporal term is
exactly 0.000e+00 on every seed, so the split is not manufacturing a difference where there
is none.
The temporal path is also no less coherent than the per-step one: the gate's temporal
gradient has coherence 0.201 against a null of 0.171, essentially the whole block's 0.202
against 0.163. Credit through time arrives, and it arrives with the same directional
consistency as the rest.
### 1e. Part A's answer
**Neither absent nor cancelling.** The gradient reaching the gate is a thousandfold smaller
than its neighbours' in magnitude, but Adam does not care about magnitude; it is
directionally consistent above its own measured floor on 14/16 seeds, at a per-coordinate
signal-to-noise of 0.066 against `cand`'s 0.070 and `out`'s 0.079 — the lowest of the four
and measurably so, but the same order and not a different regime; a majority of it
comes through the truncated-BPTT window rather than from the current step; and it moved
`gate.weight` further than it moved any other block in the network. The training signal
that hypothesis (a) says is missing is there.
What is missing is any consequence. The displacement leaves the gate's output where it
began.
## 2. Part B — the ceiling: if the state were told, could it hold it?
A linear head from `M_i` to the current regime id, trained jointly with the task at a weight
`lambda`. Seven weights, 16 seeds each. At `lambda = 0` no head is built and the loop is
literally the one that produced Task 7b's baseline, pinned bit-identical.
`aux(train)` is the head's own accuracy over the second half of training, which is the
direct "can it" number: the head is linear on `M`, so its accuracy tracks the linear
separability of the regime in `M` — running rather than exact, since the head is chasing a
representation that is still moving, which is why the independent frozen-phase probe is
reported beside it and why §2a traces the curve rather than only its mean. `probe acc` is the independent least-squares probe on the
frozen phase, the number comparable with `frozen.md` Part B's 0.332 and `pooled.md`'s 0.312.
### 2a. Reading 1 — can it?
```
lambda aux(train) probe acc shuffle shift gap sd >chance M_type (perm)
------------------------------------------------------------------------------------------
0e+00 nan 0.312 0.270 0.268 +0.044 0.053 13/16 0.634 0.479
1e-05 0.251 0.311 0.270 0.268 +0.043 0.053 13/16 0.634 0.479
1e-04 0.251 0.311 0.270 0.268 +0.043 0.053 13/16 0.634 0.479
1e-03 0.252 0.314 0.270 0.269 +0.045 0.053 13/16 0.635 0.480
1e-02 0.250 0.306 0.273 0.266 +0.040 0.071 13/16 0.641 0.482
1e-01 0.253 0.301 0.275 0.268 +0.033 0.029 15/16 0.661 0.486
1e+00 0.259 0.307 0.271 0.264 +0.043 0.047 12/16 0.672 0.485
```
**The auxiliary head never leaves chance.** Against 1/4, it reads 0.250 to 0.259 at every
weight over five orders of magnitude — including `lambda = 1.0`, where the auxiliary term at chance
is 5.8x10^4 times the main loss and demonstrably dominates the run (§2b: the task degrades
5.9x). And the independent frozen-phase decode is flat: +0.044 above the
shift null at `lambda = 0`, +0.043 at `lambda = 1.0`.
The `M_type` column is the same probe on the entity's own type, a signal that is in `attrs`
and therefore certainly in reach. Note that both of `probe`'s time-based nulls are
degenerate for a target that is constant in time — permuting or circularly shifting the step
axis of a label array whose rows are all identical returns that same array, and they report
the accuracy back as its own chance level — so the type's chance level is measured by
permuting the assignment across entities instead, which breaks the association and keeps the
marginal. That is the `(perm)` column.
**"Cannot" and "has not yet" are different claims**, so the head's accuracy was traced over
training rather than summarised. Four seeds, `lambda = 1.0`, bucketed by 1000 steps:
```
target chance seed @1k @2k @3k @4k @5k @6k @7k @8k
--------------------------------------------------------------------------------------
regime 0.250 0 0.268 0.284 0.210 0.420 0.270 0.197 0.200 0.224
regime 0.250 1 0.202 0.380 0.239 0.279 0.248 0.291 0.403 0.222
regime 0.250 2 0.337 0.169 0.346 0.300 0.140 0.342 0.220 0.244
regime 0.250 3 0.222 0.167 0.234 0.293 0.173 0.328 0.318 0.372
type 0.333 0 0.438 0.558 0.544 0.655 0.695 0.682 0.733 0.746
type 0.333 1 0.438 0.608 0.651 0.623 0.649 0.689 0.737 0.768
type 0.333 2 0.418 0.463 0.553 0.626 0.588 0.676 0.724 0.762
type 0.333 3 0.419 0.486 0.663 0.685 0.731 0.720 0.754 0.820
```
The regime curve wanders around chance on all four seeds with no trend across 8000 steps.
The type curve climbs monotonically on all four. This is not a budget problem.
### 2b. Reading 2 — does the task improve?
Main-task `steady`, paired per seed against `lambda = 0`. The log-ratio is positive when the
error fell.
```
lambda steady ratio l0/l won log-ratio paired se reading
-------------------------------------------------------------------------
0e+00 2.399e-05 -- -- -- -- --
1e-05 2.397e-05 1.001 9/16 +0.0008 0.0012 ambiguous
1e-04 2.396e-05 1.002 9/16 +0.0018 0.0015 lower err
1e-03 2.408e-05 0.997 4/16 -0.0028 0.0032 ambiguous
1e-02 2.956e-05 0.809 0/16 -0.2118 0.0443 higher err
1e-01 7.760e-05 0.341 0/16 -1.0759 0.1238 higher err
1e+00 1.416e-04 0.171 0/16 -1.7671 0.1040 higher err
```
Per-seed trained `steady`:
```
lambda s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
0e+00 2.39e-05 1.67e-05 2.11e-05 2.72e-05 1.68e-05 2.49e-05 3.53e-05 1.68e-05 2.10e-05 2.06e-05 6.20e-05 1.23e-05 2.51e-05 1.60e-05 2.73e-05 1.70e-05
1e-04 2.39e-05 1.67e-05 2.11e-05 2.71e-05 1.68e-05 2.49e-05 3.51e-05 1.68e-05 2.10e-05 2.01e-05 6.20e-05 1.23e-05 2.51e-05 1.60e-05 2.73e-05 1.70e-05
1e-02 2.42e-05 2.27e-05 2.62e-05 5.15e-05 1.99e-05 2.67e-05 3.89e-05 1.95e-05 3.37e-05 2.18e-05 6.28e-05 1.75e-05 2.88e-05 1.79e-05 4.02e-05 2.08e-05
1e-01 2.98e-04 5.67e-05 6.20e-05 6.59e-05 3.96e-05 6.05e-05 9.43e-05 5.19e-05 1.07e-04 4.76e-05 9.74e-05 3.66e-05 4.98e-05 2.58e-05 7.40e-05 7.48e-05
1e+00 1.61e-04 1.09e-04 1.22e-04 1.97e-04 1.05e-04 2.28e-04 3.13e-04 1.64e-04 1.36e-04 5.06e-05 1.36e-04 7.97e-05 1.40e-04 9.01e-05 1.16e-04 1.17e-04
```
Below `lambda = 1e-3` the auxiliary term is too small to change anything and the reading is
ambiguous or a fourth-decimal improvement — the `1e-4` row's `+0.0018 ± 0.0015` is a 0.2%
effect on 9/16 seeds and is not worth a sentence. Above it, the auxiliary term is large
enough to matter and the task gets monotonically worse, on 0 seeds of 16 at every weight
from `1e-2` up. That is what an auxiliary loss competing with the task does when it buys
nothing; the frozen phase agrees at every row.
This column is reported because the brief asked for it, not because it is informative on its
own. Reading 2 only means something conditional on reading 1, and reading 1 says the state
never held the regime at any weight, so there was never anything for the task to benefit
from.
### 2c. Reading 3 — the joint reading, and the control that carries it
Both columns are paired changes against `lambda = 0`, per seed. The absolute gap is not the
question: the `lambda = 0` row already sits +0.044 above its null, which is the
instantaneous read-off `frozen.md` §2 and `pooled.md` §4 both identified and neither
attributed to memory. The question is whether being told the regime raises it.
**Regime target — the measurement:**
```
lambda gap d(gap) vs l=0 se won task log-ratio se won
------------------------------------------------------------------------------
0e+00 +0.044 -- -- -- -- -- --
1e-05 +0.043 -0.001 0.001 6/16 +0.0008 0.0012 9/16
1e-04 +0.043 -0.001 0.001 10/16 +0.0018 0.0015 9/16
1e-03 +0.045 +0.001 0.003 8/16 -0.0028 0.0032 4/16
1e-02 +0.040 -0.004 0.014 8/16 -0.2118 0.0443 0/16
1e-01 +0.033 -0.011 0.011 5/16 -1.0759 0.1238 0/16
1e+00 +0.043 -0.001 0.019 9/16 -1.7671 0.1040 0/16
```
**Type target — the positive control, run identically:**
```
lambda gap d(gap) vs l=0 se won task log-ratio se won
------------------------------------------------------------------------------
0e+00 +0.044 -- -- -- -- -- --
1e-05 +0.044 -0.000 0.000 5/16 +0.0001 0.0002 5/16
1e-04 +0.043 -0.001 0.001 4/16 -0.0025 0.0014 3/16
1e-03 +0.054 +0.010 0.008 9/16 -0.0892 0.0374 3/16
1e-02 +0.115 +0.071 0.027 11/16 -1.5275 0.1440 0/16
1e-01 +0.120 +0.076 0.024 12/16 -3.0582 0.1603 0/16
1e+00 +0.117 +0.073 0.022 14/16 -3.6922 0.2028 0/16
```
with the type itself, in `M`, going from 0.634 at `lambda = 0` to 0.789 at `lambda = 1.0`
against an entity-permutation chance of 0.48-0.51, and the head's own accuracy from 0.472 to
0.738 against 0.333.
**This is the pair the verdict rests on.** The same head, the same optimiser, the same
weights, the same 16 seeds, the same probe — the only difference is what the head is told to
put in `M`. Told the entity's type, it installs it, and it raises the *regime* decode as a
side effect by +0.073 ± 0.022 on 14 seeds of 16. Told the regime, it moves the regime
decode by −0.001 ± 0.019 on 9 of 16 — a change this measurement cannot tell apart from
zero. **The control that had no business moving the number is the only one that moved it.**
A null that survives that is not a broken instrument.
(Why type supervision lifts the regime decode is not established here and no claim is made
about it. The obvious guess is the one `frozen.md` §2's entity-centred variant was probing —
`M` is dominated by stable per-entity structure, and sharpening it changes the geometry the
regime probe fits in. It is a side effect of the control, not a result.)
### 2d. The linear head is not the binding constraint — MEASUREMENT INCOMPLETE
`when_memory_works.md` §2b is explicit that a linear decoder is the wrong instrument for
this target: on the raw observation window a linear decoder reads 0.23 at every history
length while an MLP on the same features reads 0.83, so a linear probe there "would have
said the regime is unidentifiable, and it would have been wrong by 0.7 in accuracy". A null
from a linear head on `M` inherits exactly that objection.
**This control was run and did not finish. No numbers from it are reported here.** Part B
was re-run with the auxiliary head replaced by a 2×128 ReLU network and the frozen-phase
decode taken by a second one, at `lambda ∈ {0, 0.01, 0.1, 1.0}` and the same 16 seeds; the
sweep reached 10 of 16 runs per shard before it was stopped. `.sdd/task-11-report.md`
records exactly what completed and the one command that finishes it.
What was observed in the incomplete run, recorded so it is not lost and **not relied on
below**: the MLP head's own training accuracy sat at 0.21-0.31 against a chance of 0.25 at
`lambda = 0.01` and `lambda = 0.1`, the same flat reading the linear head gave. Separately,
a single full-budget seed at `lambda = 0` decoded the regime from `M` at a gap of +0.159
above the shift null with the MLP probe where the linear probe read +0.064 on the same run,
and from the memoryless `h` at +0.234. **§3's verdict is stated on the linear head alone
and carries that limitation explicitly.**
## 3. Verdict
**Part A: the signal exists, reaches the gate, and flows through time.** Hypothesis (a) as
stated — that nothing in the training signal rewards carrying the regime forward — is not
supported. The gate's gradient is coherent above its own measured null on 14/16 seeds
(0.202 against 0.163, paired se 0.009), 59% of it arrives through the truncated-BPTT window
rather than from the current step, its per-coordinate signal-to-noise is 0.066 where the
blocks that certainly train read 0.070 to 0.082, and it moved `gate.weight` 27% of its norm — further than any
other block in the network. It is 887x smaller in magnitude than the identically-shaped
candidate layer's, which is worth knowing and is not the explanation, because Adam is scale
invariant. What the displacement did not do is change the gate's output: on the same inputs,
trained weights give `g = 0.5008 ± 0.0270` where the initial weights give `0.5009 ± 0.0203`.
**Part B gives the brief's third outcome: `M` cannot hold the regime even under direct
supervision.** The head never leaves chance at any weight over five orders of magnitude,
with no trend across 8000 steps; the frozen-phase decode moves by −0.001 ± 0.019; and the
same head at the same weights installs the entity's type into `M` and raises the regime
decode by +0.073 ± 0.022 in passing. The brief's reading of that outcome — "the state update
is not expressive enough; a different problem from credit assignment" — is what the numbers
give, and Part A independently rules out the credit-assignment alternative from the other
direction.
**The limitation this verdict carries.** It is stated on a linear head and a least-squares
probe. §2d's non-linear control was run and did not finish, so the possibility that `M`
holds the regime non-linearly and a linear head could not install it is *not* closed here.
Two things bear against it and neither settles it: the head's failure is not a readout
failure but a training-signal one — the same linear head installs the entity's type and
moves the regime decode while doing so — and the incomplete MLP-head run showed the same
flat chance reading at the two weights it reached. **A reader acting on this file should
treat outcome 3 as established for a linear readout of `M` and open for a non-linear one,
and should finish §2d before spending anything on the consequence.**
Neither part is good or bad news, and the second is the more useful of the two. A
credit-assignment failure would have been repairable by an auxiliary signal, a longer BPTT
window, or a different optimiser, and the natural next month would have been spent trying
them. The measurement says that month would have bought nothing: the state was told, at
weights that destroyed the task to make room, and it still did not hold the regime.
**One paragraph of argument, flagged as argument.** The following is not measured here;
it is offered because §4's second bullet turns on it and it should be visible enough to
be attacked. What the state update would have to do to hold this variable is legible in
`identify.py`. The regime is identifiable from one observed displacement,
but only through the statistics `⟨d, B^c⟩` and `⟨B^c, B^c'⟩` — inner products of the current
message basis with the *previous* step's, which are quadratic in a pair of consecutive
frames. `M ← (1−g)·tanh(W_c[h‖M]) + g·M` has one `tanh` between `h_t` and `M_{t−1}` and no
product of the two. With the gate pinned at 0.5 it is an exponential moving average of
`tanh` of a linear map, and an EMA of a nonlinearity is not where a cross-frame inner product
lives. If that is right it is a statement about this update rule and not about memory, and
the way to find out is to measure the ceiling on a rule that does carry such a product —
which §4 says how to do and does not do here.
## 4. What each outcome would have meant for keeping per-entity memory
This file is the last measurement on the memory line, so the consequence of each of the
brief's three outcomes is written out rather than left to be inferred. **The decision to
keep or drop the GRP is not made here.**
| outcome | what it would say about keeping per-entity memory |
|---|---|
| `M` holds the regime **and** the task improves | credit assignment is the blocker and the prize is measured. Keep the GRP; the work is to get the signal to it, and the size of the win is known in advance. |
| `M` holds the regime **and** the task does not improve | the regime is not useful to this architecture's prediction. That is an argument the GRP has no job on this domain *regardless of how credit reaches it*, and no amount of pushing from the unbuilt modules changes it. |
| **`M` cannot hold it even under direct supervision** — what the numbers give | the update rule cannot represent the variable. This says nothing about whether per-entity memory is worth keeping in general, and everything about `(1−g)·tanh(W_c[h‖M]) + g·M`. Giving the GRP more push from metabolism, reflexes or the policy readout would be pushing on a state that has been shown not to hold the thing they would be pushing it to hold. Replacing the update rule is a different move from dropping memory, and this file distinguishes them without choosing between them. |
## 5. What this does and does not bear on
**Measured, across four files.** `frozen.md`, `when_memory_works.md`, `pooled.md` and this
one measure claim A1 — that per-entity gated memory helps on a domain with an unannounced
hidden regime — and every mechanism they attach to it: the state's contribution over the
gated head (`frozen.md` §1a, §1d), affect on the gate (`a1.md`, `when_memory_works.md`
Part 1), the shape of the memory (`pooled.md`), the domain's suitability
(`when_memory_works.md` Parts 2-3), and now the training signal and the ceiling on the
state itself.
**Not measured, and untouched by any of it.** Claim A2 — the CPPN kernel taking `ψ` as
input — does not route through memory. Nothing in this file, `pooled.md`, `frozen.md` or
`when_memory_works.md` bears on it in either direction; the `grp_k_noctx` and
`grp_k_regimectx` conditions exist in `regime.py` and have not been run against it. A
decision to drop the GRP would not cost A2, and this file should not be read as evidence
for or against it. Spec §6's other organism modules — metabolism, reflexes S1/S2, the
instinct/EQ policy readout — are likewise unbuilt and unmeasured; §4's third row is a
statement about what pushing them into *this state update* could achieve, not an
evaluation of the modules.
## 6. Consequences
- **Do not build a mechanism to fix credit assignment on this domain.** An auxiliary
regime loss, a longer BPTT window, a gate-specific learning rate, or a gradient-boosting
reparameterisation of the gate are all motivated by (a), and (a) is measured dead here in
both directions: the credit arrives (§1) and being handed the answer changes nothing (§2).
The oracle did not pay, so the mechanism has no job — the same test `headroom.md` and
`when_memory_works.md` applied, reaching the same kind of answer.
- **The remaining question is about the update rule, and it is a design question rather
than a training one.** Nothing here says a per-entity state cannot hold this regime;
it says `(1−g)·tanh(W_c[h‖M]) + g·M` does not, and §3 gives the algebraic reason to
expect that. A state update carrying an explicit product of the current frame with the
previous one is the shape the domain asks for. **That is a hypothesis, and it comes with
the same obligation as every other in this repo: measure the ceiling before building it.**
The ceiling measurement is the one in §2 — supervise a candidate state to hold the regime
and decode it back out — and `credit.py --part aux` runs it against any update rule that
`ailed` exposes, with the type target already in place as its positive control.
- **`frozen.md` §3's "the gate is untrained" needs one word changed.** The gate's
pre-activation is at its initialisation, which is what that section measured and it is
correct. Its *weights* are not: they travel further than any other block's. "Untrained"
should read "trained without effect", and the distinction matters, because the first
invites a fix to the training and the second does not.
- **A magnitude is not a diagnosis under an adaptive optimiser.** The gate's 887-fold
gradient deficit is the kind of number that would have carried a claim, and it would have
been the wrong claim: the block with the smallest gradient in this network is the one that
moved the furthest. Any future gradient argument in this project needs the displacement
beside it.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+138
View File
@@ -0,0 +1,138 @@
[
{
"seed": 0,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.268,
0.2836875,
0.210375,
0.4199375,
0.270375,
0.1966875,
0.199875,
0.224125
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.4378125,
0.5581875,
0.544375,
0.6551875,
0.6945625,
0.6823125,
0.7328125,
0.746
]
}
}
},
{
"seed": 1,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.2015,
0.379875,
0.239,
0.2786875,
0.2479375,
0.2911875,
0.403,
0.2215625
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.4375,
0.6081875,
0.6514375,
0.6228125,
0.6495,
0.68875,
0.73675,
0.7685
]
}
}
},
{
"seed": 2,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.336875,
0.1686875,
0.34575,
0.3,
0.139875,
0.3416875,
0.220125,
0.244125
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.417875,
0.4633125,
0.5529375,
0.6264375,
0.5883125,
0.675625,
0.7235,
0.7624375
]
}
}
},
{
"seed": 3,
"lam": 1.0,
"bucket": 1000,
"head_kind": "linear",
"targets": {
"regime": {
"chance": 0.25,
"curve": [
0.22225,
0.1665,
0.234375,
0.2925625,
0.1735,
0.3280625,
0.3179375,
0.37225
]
},
"type": {
"chance": 0.3333333333333333,
"curve": [
0.4186875,
0.4863125,
0.6628125,
0.6854375,
0.7305,
0.7199375,
0.7541875,
0.819875
]
}
}
}
]
+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.
+55 -5
View File
@@ -23,8 +23,9 @@ builds an internal regime variable.**
less — and the same +0.05 appears in a state-free network, so it is a read-off of
the current configuration, not a memory.
3. The mechanism is visible: the gate sits at `g = 0.500 ± 0.029`, never above 0.9,
never below 0.1, on any seed. It is at its initialisation. The GRP as trained here
is not gating anything.
never below 0.1, on any seed. Its *function* is at its initialisation — the weights
themselves moved more than any other block's, see the correction in §6 — and the GRP
as trained here is not gating anything.
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. 8 seeds (0-7), 8000 training steps then 4000 frozen steps,
@@ -329,8 +330,10 @@ grp_k0_nostate 0.509 0.025 0.000 0.000
```
`g = σ(W_g[h‖M] − κa)` with `κ = 0`. A mean of 0.500 with sd 0.029 and no saturation
in either direction, on every seed, means the gate's pre-activation is sitting at zero:
it is at its initialisation and 8000 training steps have not moved it. The update
in either direction, on every seed, means the gate's pre-activation is sitting at zero.
**The weights that produce it did move** — Task 11 measured a displacement of 26.8% of
their initial norm, larger than any other block's; what stayed put is the function, because
the displacement remained inside the band where the sigmoid is linear. See §6. The update
`M ← (1−g)M̃ + gM` degenerates to a fixed 50/50 blend — a two-step exponential moving
average of `tanh(W_c[h‖M])`, with no input dependence. **Nothing is being decided about
what to keep.**
@@ -371,7 +374,8 @@ What the frozen probe does establish, and it is worth having:
- **The margin is not memory.** It is 4160 extra feedforward parameters. Ablating the
state while keeping them preserves the entire effect (1.06x, 4/8 seeds) and leaves
the recovery curve unchanged at every lag.
- **The GRP's gate is untrained.** It sits at 0.5 with no input dependence, which is a
- **The GRP's gate does not gate.** It is *not* untrained — that reading is corrected in
§6. It sits at 0.5 with no input dependence, which is a
sufficient mechanistic explanation for both nulls and is a fact about this setup, not
about the architecture.
@@ -399,3 +403,49 @@ is the same conclusion §6(c) of `headroom.md` reached from the other direction.
- **`recovery[k]` is not an adaptation measurement in this domain.** It tracks the
world's post-switch transient, and a stateless frozen model reproduces its shape. Any
A1 claim phrased on recovery curves needs a different observable.
---
## 6. Correction (Task 11): the gate's weights moved; its function did not
This file originally read `g = 0.500 ± 0.029` as meaning the gate was *untrained*.
`results/credit.md` measured the weights directly and that reading is wrong.
- `grp.gate.weight` moved **26.8% of its initial norm** over training — **more than any
other block** (`cand` 19.0%, `out` 15.3%, `feat` 4.4%). The gate is among the
most-updated parameters in the model, not the least.
- What did not move is the **function**. On identical inputs the trained weights give
`g = 0.5008 ± 0.0270` and the weights at initialisation give `g = 0.5009 ± 0.0203`. The
displacement stayed inside the ±0.1 pre-activation band where the sigmoid is linear, so a
large change in the weights produces no change in behaviour.
- The gradient is **coherent, not cancelling**: 0.202 against its own measured sign-flip
null of 0.163, above null on 14/16 seeds. And **0.587 of it arrives through the
truncated-BPTT window**, making the temporal path 1.187x the per-step one.
Two things follow for anyone quoting this file.
**Do not lead with the gradient magnitude.** The gate's mean gradient norm is 887x smaller
than `cand`'s on identically shaped tensors, and that number is not the story: Adam is
scale-invariant, and the per-coordinate signal-to-noise ratio it actually consumes is
comparable across blocks (gate 0.066, `cand` 0.070, `out` 0.079).
**"Untrained" was the wrong word and it pointed at the wrong hypothesis.** It suggested the
training signal never reached the gate, which Task 11 falsified. What is true is narrower:
the gate receives a coherent signal, mostly through time, moves a long way in weight space,
and lands somewhere functionally indistinguishable from where it started.
`credit.md` Part B says why that is not merely a tuning accident: `M` cannot hold the regime
even when an auxiliary loss 5.8e4 times the main one demands it, while the same head
installs the entity *type* at 0.738 against chance 0.333. The state update can represent
per-entity properties and cannot represent this one.
## 7. Correction (Task 11): the probe figures here are linear-probe figures
Part B's decodes, and the "roughly a fifth of the available signal" reading they support in
`when_memory_works.md` §4, come from a linear probe. An MLP probe on the same runs reads the
regime from `M` at a gap of **+0.159** where the linear probe reads +0.064, and from the
memoryless `h` at **+0.234**.
The relative claim is unchanged and is what this file argues from: `M` holds no more about
the regime than the `h` it is built from, and on the MLP probe it holds visibly less. The
*absolute* fraction needs the qualifier wherever it is quoted.
+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.
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=0 steady=2.388e-05 aux=nan M_regime=0.351/0.286 M_type=0.631 g=0.494
lam=0 seed=1 steady=1.666e-05 aux=nan M_regime=0.256/0.239 M_type=0.487 g=0.504
lam=0 seed=2 steady=2.110e-05 aux=nan M_regime=0.289/0.247 M_type=0.547 g=0.496
lam=0 seed=3 steady=2.716e-05 aux=nan M_regime=0.426/0.309 M_type=0.536 g=0.498
lam=0.01 seed=0 steady=2.385e-05 aux=0.270 M_regime=0.344/0.276 M_type=0.625 g=0.495
lam=0.01 seed=1 steady=1.681e-05 aux=0.292 M_regime=0.254/0.240 M_type=0.497 g=0.503
lam=0.01 seed=2 steady=2.132e-05 aux=0.213 M_regime=0.285/0.247 M_type=0.546 g=0.497
lam=0.01 seed=3 steady=2.729e-05 aux=0.266 M_regime=0.419/0.307 M_type=0.540 g=0.495
lam=0.1 seed=0 steady=6.219e-05 aux=0.210 M_regime=0.342/0.284 M_type=0.627 g=0.498
lam=0.1 seed=1 steady=2.465e-05 aux=0.308 M_regime=0.258/0.240 M_type=0.536 g=0.498
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=12 steady=2.512e-05 aux=nan M_regime=0.325/0.272 M_type=0.703 g=0.496
lam=0 seed=13 steady=1.600e-05 aux=nan M_regime=0.298/0.250 M_type=0.466 g=0.503
lam=0 seed=14 steady=2.726e-05 aux=nan M_regime=0.229/0.249 M_type=0.604 g=0.493
lam=0 seed=15 steady=1.704e-05 aux=nan M_regime=0.325/0.257 M_type=0.713 g=0.505
lam=0.01 seed=12 steady=2.504e-05 aux=0.233 M_regime=0.330/0.272 M_type=0.706 g=0.496
lam=0.01 seed=13 steady=1.586e-05 aux=0.259 M_regime=0.295/0.250 M_type=0.468 g=0.501
lam=0.01 seed=14 steady=2.853e-05 aux=0.257 M_regime=0.229/0.250 M_type=0.608 g=0.493
lam=0.01 seed=15 steady=1.863e-05 aux=0.233 M_regime=0.336/0.258 M_type=0.710 g=0.505
lam=0.1 seed=12 steady=3.474e-05 aux=0.232 M_regime=0.334/0.272 M_type=0.698 g=0.500
lam=0.1 seed=13 steady=1.907e-05 aux=0.254 M_regime=0.316/0.258 M_type=0.484 g=0.506
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=4 steady=1.683e-05 aux=nan M_regime=0.333/0.286 M_type=0.723 g=0.505
lam=0 seed=5 steady=2.491e-05 aux=nan M_regime=0.262/0.309 M_type=0.688 g=0.492
lam=0 seed=6 steady=3.528e-05 aux=nan M_regime=0.370/0.270 M_type=0.666 g=0.506
lam=0 seed=7 steady=1.680e-05 aux=nan M_regime=0.369/0.241 M_type=0.594 g=0.506
lam=0.01 seed=4 steady=1.745e-05 aux=0.274 M_regime=0.341/0.283 M_type=0.722 g=0.504
lam=0.01 seed=5 steady=2.534e-05 aux=0.195 M_regime=0.275/0.309 M_type=0.690 g=0.491
lam=0.01 seed=6 steady=3.762e-05 aux=0.237 M_regime=0.327/0.266 M_type=0.699 g=0.503
lam=0.01 seed=7 steady=1.678e-05 aux=0.289 M_regime=0.370/0.245 M_type=0.586 g=0.506
lam=0.1 seed=4 steady=2.809e-05 aux=0.245 M_regime=0.321/0.292 M_type=0.723 g=0.490
lam=0.1 seed=5 steady=3.386e-05 aux=0.202 M_regime=0.257/0.303 M_type=0.692 g=0.482
+10
View File
@@ -0,0 +1,10 @@
lam=0 seed=8 steady=2.099e-05 aux=nan M_regime=0.250/0.236 M_type=0.652 g=0.503
lam=0 seed=9 steady=2.061e-05 aux=nan M_regime=0.325/0.283 M_type=0.650 g=0.503
lam=0 seed=10 steady=6.197e-05 aux=nan M_regime=0.244/0.302 M_type=0.705 g=0.506
lam=0 seed=11 steady=1.230e-05 aux=nan M_regime=0.345/0.257 M_type=0.781 g=0.503
lam=0.01 seed=8 steady=2.142e-05 aux=0.252 M_regime=0.256/0.239 M_type=0.644 g=0.503
lam=0.01 seed=9 steady=2.121e-05 aux=0.298 M_regime=0.303/0.277 M_type=0.650 g=0.502
lam=0.01 seed=10 steady=6.103e-05 aux=0.254 M_regime=0.243/0.303 M_type=0.717 g=0.506
lam=0.01 seed=11 steady=1.241e-05 aux=0.212 M_regime=0.345/0.258 M_type=0.785 g=0.503
lam=0.1 seed=8 steady=3.096e-05 aux=0.184 M_regime=0.258/0.254 M_type=0.665 g=0.503
lam=0.1 seed=9 steady=2.303e-05 aux=0.298 M_regime=0.287/0.274 M_type=0.662 g=0.499
+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
```
+270
View File
@@ -0,0 +1,270 @@
# Pooled probe: is the regime distributed across the 16 per-entity states?
Task 10. `results/frozen.md` Part B decoded the world's regime id from a *single*
entity's `M` at 0.332 against a measured chance of 0.273, and from the `h` inside the
same GRP at 0.338 against 0.274. An exact decoder reaches 0.958 from one observed
displacement (`results/when_memory_works.md` §2), so the information is there and the
organism holds about a fifth of it. Two explanations were left open:
- **(b) shape mismatch** — the regime is one global 3×3 matrix `K` and the state is
per-entity, so the information could be *distributed across* the 16 states while
being absent from any one of them.
- **(a) credit assignment** — nothing in the loss rewards carrying the regime forward,
so the state never learns to hold it at all.
**Verdict: (b) is dead. Pooling the 16 states does lift the decode — by +0.045 — but
it lifts the memoryless `h` by +0.048 at the same time. Pooled `M` gains nothing that
pooled `h` does not. The gain is noise-averaging over 16 samples, not a global variable
assembled out of per-entity fragments. (a) is the remaining suspect.**
Environment: `experiments/`, `ailed/` unmodified, no default in `particles.py` or
`regime.py` changed. `grp_k0`, 16 seeds (0-15), 8000 training steps then 4000 frozen
steps, `lr=1e-3`, `bptt=20`, `hidden=32`, `omega=10`, `kappa=0`. Test split is the last
30% of the frozen phase, taken as a suffix in time. 24 training runs total.
```
uv run python pooled.py --seeds 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 \
--estimators lsq,logit --power-check --out results/pooled.json
uv run python pooled.py --seeds 0,1,2,3,4,5,6,7 --frozen-steps 16000 \
--out results/pooled_long.json
```
`pooled.py` adds no training loop and no architecture. `_build`, `_train`, `_frozen`
and `probe` are imported from `frozen.py` unchanged; the only new code is the three
views of the representation, the reporting, and the synthetic positive control.
## 0. The pin
The `single` rows are not a re-implementation of the baseline, they *are* the baseline.
Every seed 0-7 `M_single` and `h_single` accuracy and chance level in this file is
**bit-identical to the corresponding entry in `results/frozen.json`** (asserted by
comparing the two files, and by `test_single_view_reproduces_the_frozen_probe_exactly`,
which pins `pooled.run_one` against `frozen.run_one` at a small budget). Restricted to
seeds 0-7 the table below reproduces `frozen.md` Part B exactly: `M` 0.332 against
0.273, `h` 0.338 against 0.274.
## 1. The table
16 seeds, least squares, means over seeds. `shuffle` permutes the step labels keeping a
step's 16 entities together; `shift` circularly shifts the label sequence, preserving
each regime's 40-80 step block structure, and is the stricter of the two. `gap` is
`acc − shift`, per seed, then averaged. `feat` is the probe's feature count and `n_tr`
its training samples — pooling trades 16× the samples for one pooled sample per step,
and concatenation multiplies the feature count by 16, which is exactly what inflates a
fitted probe's chance level and why `shift` is not optional.
```
representation feat n_tr acc shuffle shift gap sd(gap) >chance
---------------------------------------------------------------------------------
M, single 32 44800 0.312 0.270 0.268 +0.044 0.053 13/16
M, mean 32 2800 0.349 0.265 0.260 +0.089 0.066 15/16
M, concat 512 2800 0.292 0.251 0.258 +0.034 0.055 10/16
h, single 32 44800 0.313 0.272 0.268 +0.045 0.058 13/16
h, mean 32 2800 0.354 0.267 0.261 +0.093 0.065 16/16
h, concat 512 2800 0.291 0.251 0.256 +0.036 0.061 12/16
```
The concatenated chance levels do sit lower than the single-entity ones (0.256-0.258
against 0.268) — the control caught the direction, though not the magnitude some
inflation argument would predict.
## 2. The measurement
Pooling's gain is `gap(pooled) − gap(single)`, computed per seed and then averaged.
**The `h` row is the whole measurement.** `h` is the feedforward layer `M` is built
from and carries no memory across steps, so whatever pooling buys on `h` is the value
of pooling as such. (b) is live only if `M` gains what `h` does not.
```
M gain h gain M − h M>h seeds
------------------------------------------------------------------------
mean-pooled +0.045 (sd 0.043) +0.048 (sd 0.060) -0.003 8/16
concatenated -0.010 (sd 0.053) -0.009 (sd 0.063) -0.001 8/16
```
**Mean-pooled `M` gains +0.045. Mean-pooled `h` gains +0.048. The difference is
−0.003, with a paired across-seed standard error of 0.015, and `M` beats `h` on
exactly 8 seeds out of 16 — a coin flip.** The gain itself is real: it is positive on
14/16 seeds for `M` and 13/16 for `h`. It is simply not a memory effect. Concatenation
gains nothing at all at this budget, on either representation (see §4).
Per-seed pooling gains, mean-pooled, seeds 0-15:
```
M gain +0.041 +0.126 +0.025 +0.057 +0.049 +0.088 -0.033 +0.041 +0.081 +0.001 -0.017 +0.106 +0.063 +0.003 +0.056 +0.038
h gain +0.076 +0.060 +0.055 +0.054 +0.115 +0.086 -0.069 -0.062 +0.066 +0.038 +0.089 +0.116 -0.038 +0.000 +0.062 +0.120
M − h -0.036 +0.066 -0.030 +0.003 -0.066 +0.003 +0.036 +0.103 +0.015 -0.036 -0.106 -0.010 +0.101 +0.003 -0.006 -0.082
```
Per-seed gap above the shift null, all six representations:
```
representation s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15
------------------------------------------------------------------------------------------------------------------------------------------------
M, single +0.064 +0.017 +0.042 +0.117 +0.047 -0.047 +0.101 +0.127 +0.014 +0.042 -0.058 +0.087 +0.053 +0.048 -0.019 +0.069
M, mean +0.105 +0.143 +0.067 +0.174 +0.096 +0.041 +0.068 +0.168 +0.095 +0.043 -0.075 +0.193 +0.116 +0.051 +0.037 +0.106
M, concat -0.014 -0.050 +0.146 +0.090 +0.093 -0.007 +0.009 +0.091 +0.026 +0.002 -0.010 +0.076 -0.001 +0.061 -0.027 +0.052
h, single +0.060 +0.019 +0.040 +0.124 +0.082 -0.055 +0.110 +0.137 +0.027 +0.028 -0.072 +0.087 +0.050 +0.039 -0.009 +0.054
h, mean +0.136 +0.079 +0.094 +0.179 +0.197 +0.031 +0.041 +0.076 +0.093 +0.066 +0.017 +0.203 +0.013 +0.039 +0.053 +0.174
h, concat +0.034 -0.030 +0.109 +0.127 +0.077 -0.045 +0.047 +0.046 +0.004 -0.063 +0.038 +0.139 +0.006 +0.052 +0.069 -0.035
```
**Eight seeds are worth reporting on their own, because eight is what would have been
run.** Restricted to seeds 0-7 the mean-pooling gains are `M` +0.049 and `h` +0.039, a
difference of +0.010 with `M` ahead on 5/8 — which reads, faintly, like support for
(b). Adding seeds 8-15 flips the sign to −0.003 at 8/16. The apparent effect at 8 seeds
is smaller than the across-seed spread that produces it, which is the failure mode
`AGENTS.md` warns about, caught here by running twice the seeds.
## 3. Controls
### 3a. Pooling representations vs. aggregating decisions
A per-step number can also rise by letting 16 independent per-entity decoders vote,
which involves no pooled representation at all. `frozen.probe` already computes that
vote. 16 seeds, least squares, accuracies:
```
representation per-entity 16-vote mean-pooled
---------------------------------------------------
M 0.312 0.327 0.349
h 0.313 0.327 0.354
```
Voting recovers roughly half of what mean-pooling recovers, and it recovers exactly the
same amount for `M` and for `h`. Both routes to a per-step answer are indifferent to
whether the representation carries memory.
### 3b. Second estimator
Multinomial logistic (LBFGS, strong Wolfe), same 16 seeds, same splits:
```
M gain h gain M − h M>h seeds
--------------------------------------------------------------
mean-pooled +0.054 +0.048 +0.005 7/16
concatenated -0.001 +0.002 -0.003 6/16
```
The sign of `M − h` flips between the two estimators (−0.003 least squares, +0.005
logistic) while both stay inside one standard error of zero. Not a least-squares
artefact; not an effect either.
### 3c. The concatenated view was sample-starved — and it does not change the answer
`M, concat` fits 513 parameters to 2800 pooled samples and comes out *below* the
single-entity probe, with a per-seed spread (sd 0.055) as large as the effect. That is
a fit problem, not an information one, and it had to be separated from the null.
Re-running 8 seeds with a 16000-step frozen phase — 11200 pooled training samples, 22
per feature, the only change — turns concatenation into a working probe:
```
representation gap (4000 frozen) gap (16000 frozen)
-------------------------------------------------------------
M, single +0.058* +0.097
M, mean +0.108* +0.160
M, concat +0.045* +0.105
h, single +0.065* +0.090
h, mean +0.104* +0.150
h, concat +0.046* +0.102
```
`*` seeds 0-7 at 4000 frozen steps, so the two columns are the same eight seeds.
Every representation decodes better with a longer probe budget, and concatenation
recovers to parity with the single-entity probe rather than beating it. The gains:
```
M gain h gain M − h M>h seeds (8 seeds, 16000 frozen)
------------------------------------------------------------------------------------------
mean-pooled +0.063 +0.060 +0.003 5/8
concatenated +0.008 +0.012 -0.003 4/8
```
Same null, measured more precisely: every seed's pooling gain is positive for `M`
(8/8) and for `h` (7/8), and the difference between them is +0.003 on a coin flip.
**The strongest form of pooling, given enough samples to fit it, adds nothing over the
mean and still splits evenly between the state and the state-free layer.**
### 3d. The positive control: this measurement can detect (b)
A null is worth nothing without evidence the instrument has the power to see the
positive. `pooled.power_check` builds two synthetic representations over a real
4000-step regime label sequence from the same world (seed 0), so the block structure
is the world's, and runs them through the same three views and the same probe:
- **`distributed`** — hypothesis (b) made true by construction. The regime is two bits;
entities 0-7 write bit 0 into channel 0 and entities 8-15 write bit 1 into channel 1,
every other channel noise. No single entity holds more than one bit, so a per-entity
probe caps near 0.5 while the pool holds both.
- **`redundant`** — every entity carries the whole regime code plus independent noise.
Nothing is distributed; pooling only averages noise away. This is the confound the
`h` control exists to catch, reproduced deliberately.
```
view acc shuffle shift gap pooling gain
--------------------------------------------------------------------
distributed single 0.421 0.281 0.328 +0.093 --
distributed mean 1.000 0.266 0.318 +0.682 +0.589
distributed concat 0.963 0.252 0.267 +0.696 +0.603
redundant single 0.691 0.294 0.310 +0.381 --
redundant mean 1.000 0.283 0.336 +0.664 +0.283
redundant concat 0.999 0.261 0.280 +0.719 +0.338
```
**A genuinely distributed code produces a pooling gain of +0.589. The measured gain on
`M` is +0.045, and `h` produces +0.048 of it.** The instrument's demonstrated
sensitivity is thirteen times the effect it was asked to find, and the effect it did
find has the redundant signature — present on the memoryless layer too — not the
distributed one.
### 3e. The controls can fail
`AGENTS.md`: a test that cannot fail is worse than no test, so the property was broken
on purpose. `test_the_power_check_can_fail` replaces `views` with one whose `mean` and
`concat` read entity 0 alone — every downstream shape unchanged, only the aggregation
removed — and asserts the `distributed` control then **fails** to clear its threshold.
It does. `test_views_preserve_the_representation` separately pins that `concat` block
`i` is always particle `i` and that `mean` is the entity average. Full suite: 70 passed
(66 existing, 4 new); the existing `frozen.py` and `regime.py` tests are untouched and
still pass.
## 4. Verdict
**Is the regime information distributed across the per-entity states, or absent from
them?** Absent from them. Pooling the 16 states does raise the decode — mean-pooled
`M` reaches 0.349 against a measured chance of 0.260, where a single state reached
0.312 against 0.268 — but the memoryless `h` inside the very same organism rises by
the same amount at the same time, from +0.045 to +0.093 above its own chance, and does
so on more seeds than `M` does. Across three settings (16 seeds at 4000 frozen steps, 8
seeds at 4000, 8 seeds at 16000) and two estimators, the difference between `M`'s
pooling gain and `h`'s ranges from −0.003 to +0.010, with a paired standard error of
about 0.015 and a seed-win count that never leaves the 4/8-to-5/8 band. Against that,
a synthetic representation whose regime code is genuinely distributed across entities
gains +0.589 from the same pooling through the same probe. The lift that pooling
delivers here is what averaging 16 noisy samples of one instantaneous quantity
delivers, and the instantaneous quantity is the particle configuration the current
coupling matrix is imposing — visible in `r` right now, in a state-free layer,
exactly as `frozen.md` §2 concluded from the state-ablated GRP. Even pooled, the decode sits 0.089
above chance where an exact decoder given one observed displacement sits about 0.73
above its own measured chance. **Hypothesis (b), that the regime is present but distributed across the
per-entity states, is not supported: the shape of the memory is not what is stopping
it. (a), that nothing in the loss ever rewarded carrying the regime forward, is the
remaining suspect.**
## 5. Consequences
- **Do not spend the next month on the shape of the memory.** A global read-out head,
a cross-entity aggregation, or a shared regime slot alongside the per-entity states
would all be motivated by (b), and (b) is measured dead here. Whatever such a change
bought would have to come from somewhere other than recovering information the 16
states already hold, because they do not hold it.
- **The remaining suspect is testable, and it is testable the way this project already
knows how.** (a) says the loss never asked. `frozen.md` §3 supplies the mechanism —
the gate sits at 0.500 ± 0.029, untrained, on every seed — and §1b supplies the
reason it had no job: the post-switch error is dominated by the world's own
configuration transient, which no state can shorten. Measure the ceiling first: an
oracle condition given the regime, in a setting where holding it is worth something,
before any mechanism is built to hold it.
- **Eight seeds would have reported the wrong sign.** At seeds 0-7 this measurement
reads +0.010 in `M`'s favour on 5/8; at 16 seeds it reads −0.003 on 8/16. Nothing
in this file's design changed between those two numbers except the seed count.
+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.
+4
View File
@@ -462,6 +462,10 @@ history, using a decoder with no privileged knowledge. `M` holds roughly a fifth
signal that a fair observer extracts from one step of the past, and no more than the
memoryless RP's own `h` holds.
(Both figures are **linear-probe** numbers. An MLP probe reads +0.159 from `M` and +0.234
from `h` on the same runs — see `frozen.md` §7. The relative claim is unchanged; the
absolute fraction needs the qualifier.)
**So the failure is ours, not the domain's.** That is the uncomfortable branch, and it was
named in advance precisely so it could not be avoided afterwards: `T_id << T_z` was
pre-registered as meaning "the domain can reward memory and the failure is ours". It came
+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))
+156
View File
@@ -0,0 +1,156 @@
import math
import numpy as np
import pytest
import torch
import credit
import frozen
from credit import AuxHead, GradTrace, part_b
from frozen import _build, _train
SMALL = dict(train_steps=300, frozen_steps=300)
# -- Part A ----------------------------------------------------------------------
def test_replayed_gradient_is_the_one_the_optimiser_used():
"""The pin. Part A's whole comparison is between two replays, so if the replay
does not reproduce the real backward, the carried/detached difference is a
statement about the replay rather than about time.
`GradTrace._check` asserts this on every window during training; this test makes
the check itself visible and confirms it actually ran.
"""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
_train(spec, wcfg, world, org, 200, 20, lr=1e-3, on_step=tr.on_step)
assert tr.n_checked == 10 # every window, not a subset
assert tr.max_rel == 0.0 # bit-identical, not merely close
assert tr.loss_equal # detaching changed the graph and no value
def test_the_replay_pin_can_fail():
"""A check that cannot fail defends nothing (AGENTS.md).
The replay is broken on purpose -- the window is replayed from a perturbed
starting M -- and the pin against the real backward must notice.
"""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
real_replay = tr._replay
def sneaky(carry):
if tr.prev0 is not None:
tr.prev0 = tr.prev0 + 1e-3
return real_replay(carry)
tr._replay = sneaky
with pytest.raises(AssertionError):
_train(spec, wcfg, world, org, 200, 20, lr=1e-3, on_step=tr.on_step)
def test_the_readout_block_has_no_temporal_path():
"""A structural control on the carried/detached split, with a known answer.
`out.weight` multiplies `M` at the current step and nothing else, so detaching `M`
between steps cannot change the gradient it receives. Its temporal term must be
exactly zero -- and the gate's, which is applied at every step of the window, must
not be. If both came out zero the split would be measuring nothing.
"""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
_train(spec, wcfg, world, org, 200, 20, lr=1e-3, on_step=tr.on_step)
s = tr.summary()["blocks"]
assert s["out"]["temporal"]["mean_norm"] == 0.0
assert s["gate"]["temporal"]["mean_norm"] > 0.0
assert s["cand"]["temporal"]["mean_norm"] > 0.0
def test_coherence_is_one_for_a_constant_gradient_and_at_the_null_for_noise():
"""The ratio has to read 1 when every step agrees and ~1/sqrt(n) when none do."""
spec, wcfg, world, org = _build("grp_k0", seed=0, hidden=32, omega=10.0, kappa=4.0)
tr = GradTrace(org, bptt=20)
n, shapes = 200, [p.shape for p in tr.params]
g = torch.Generator().manual_seed(0)
fixed = [torch.randn(s, generator=g) for s in shapes]
tr.carried = [[f.clone() for f in fixed] for _ in range(n)]
tr.detached = [[torch.zeros(s) for s in shapes] for _ in range(n)]
assert tr.summary()["blocks"]["gate"]["carried"]["coherence"] == pytest.approx(1.0, abs=1e-5)
tr.carried = [[torch.randn(s, generator=g) for s in shapes] for _ in range(n)]
got = tr.summary()["blocks"]["gate"]["carried"]
assert got["coherence"] == pytest.approx(1 / math.sqrt(n), rel=0.35)
assert got["coherence"] == pytest.approx(got["null"], rel=0.35)
# -- Part B ----------------------------------------------------------------------
def test_lambda_zero_reproduces_the_frozen_baseline():
"""`lam=0` must *be* Task 7b's grp_k0 run, not a re-implementation of it.
The whole of Part B is read against this row, so if the auxiliary machinery moved
the world, the organism or the estimator by so much as a bit, every comparison
below is against the wrong baseline.
"""
mine = part_b(seed=0, lam=0.0, **SMALL)
theirs = frozen.run_one("grp_k0", seed=0, **SMALL)
assert mine["trained"]["steady"] == theirs["trained"]["steady"]
assert mine["frozen"]["steady"] == theirs["frozen"]["steady"]
assert mine["probes"]["M_regime"]["acc_entity"] == theirs["probes"]["M_lsq"]["acc_entity"]
assert mine["probes"]["M_regime"]["chance_shift"] == theirs["probes"]["M_lsq"]["chance_shift"]
def test_the_auxiliary_head_does_not_move_the_world():
"""An oracle is opt-in and free (AGENTS.md): enabling one may not change the run
it is measuring, other than through the gradient it is there to supply.
The head is built inside `fork_rng`, so the world's trajectory, its regime
schedule and the organism's initialisation are the same draws at every lambda.
Checked by giving the head a weight of zero: the loss is then numerically the
baseline's and every reported number must match it exactly.
"""
from regime import _metrics
a = part_b(seed=0, lam=0.0, **SMALL)
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
head = AuxHead(org, world, wcfg.n_regimes, lam=0.0, target="regime", seed=0)
_, _, tr = _train(spec, wcfg, world, org, SMALL["train_steps"], 20, 1e-3,
aux=head, extra_params=head.head.parameters())
m = _metrics(tr["losses"], tr["switched"], tr["arousals"], 20)
assert m["steady"] == a["trained"]["steady"]
assert m["recovery"] == a["trained"]["recovery"]
def test_the_auxiliary_loss_reaches_the_state():
"""The instrument has to be able to do the thing it is measuring the ceiling of.
A head supervising `M` toward the entity's own type -- a signal that is in `attrs`
and therefore certainly reachable -- must train, while the same head at the same
budget on shuffled labels must not. Without this, "M cannot hold the regime" is
indistinguishable from "the head is not connected".
"""
real = part_b(seed=0, lam=1.0, target="type", train_steps=2000, frozen_steps=300)
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
head = AuxHead(org, world, wcfg.n_types, lam=1.0, target="type", seed=0)
rng = np.random.default_rng(0)
head.labels = lambda obs: torch.tensor(rng.integers(0, 3, size=16), dtype=torch.long)
_train(spec, wcfg, world, org, 2000, 20, 1e-3, aux=head,
extra_params=head.head.parameters())
# the same head, the same budget, the same optimiser: the only difference is
# whether the labels mean anything. Chance is 1/3.
assert real["aux_train_acc"] > 0.50 # a reachable signal is reached
assert head.accuracy() < 0.40 # an unreachable one is not
assert real["aux_train_acc"] - head.accuracy() > 0.15
def test_the_head_is_linear_in_M_alone():
"""The ceiling is a claim about `M`, so the head may read nothing else."""
spec, wcfg, world, org = _build("grp_k0", 0, 32, 10.0, kappa=4.0)
head = AuxHead(org, world, wcfg.n_regimes, lam=1.0, target="regime", seed=0)
assert isinstance(head.head, torch.nn.Linear)
assert head.head.in_features == org.hidden_dim
assert head.head.out_features == wcfg.n_regimes
+81
View File
@@ -0,0 +1,81 @@
import numpy as np
import pytest
import frozen
import pooled
from pooled import power_check, run_one, views
def _labels(t: int = 4000, seed: int = 0):
"""A regime label sequence with the world's own 40-80 step block structure."""
rng = np.random.default_rng(seed)
lab, sw, g = [], [], 0
while len(lab) < t:
g = int(rng.choice([i for i in range(4) if i != g]))
n = int(rng.integers(40, 81))
sw += [True] + [False] * (n - 1)
lab += [g] * n
return np.array(lab[:t]), sw[:t]
def test_views_preserve_the_representation():
"""Pooling must aggregate the entities it claims to, in a stable order."""
rep = np.random.default_rng(0).normal(size=(50, 16, 32))
v = views(rep)
assert v["single"] is rep
assert v["mean"].shape == (50, 1, 32)
assert v["concat"].shape == (50, 1, 16 * 32)
assert np.allclose(v["mean"][:, 0], rep.mean(1))
for i in range(16): # concat block i is always particle i
assert np.array_equal(v["concat"][:, 0, i * 32:(i + 1) * 32], rep[:, i])
def test_single_view_reproduces_the_frozen_probe_exactly():
"""The `single` row must be the published baseline, not a re-implementation of it.
Same organism, same world, same estimator: bit-identical or the comparison this
file draws against `results/frozen.md` is not against anything.
"""
kw = dict(train_steps=300, frozen_steps=300)
mine = run_one(seed=0, **kw)["probes"]
theirs = frozen.run_one("grp_k0", seed=0, **kw)["probes"]
for tag in ("M", "h"):
assert mine[f"{tag}_single_lsq"]["acc_entity"] == theirs[f"{tag}_lsq"]["acc_entity"]
assert mine[f"{tag}_single_lsq"]["chance_shift"] == theirs[f"{tag}_lsq"]["chance_shift"]
def test_power_check_finds_a_code_that_is_only_in_the_pool():
"""The positive control: hypothesis (b) made true by construction.
In `distributed` no entity holds more than one of the regime's two bits, so a
per-entity probe caps near 0.5 while the pool holds both. If this pipeline could
not find that, a null on the real data would carry no information.
"""
lab, sw = _labels()
pc = power_check(lab, sw, seed=0)
gap = lambda k: pc[k]["acc_entity"] - pc[k]["chance_shift"]
assert gap("distributed_single") < 0.30
assert gap("distributed_mean") > 0.60
assert gap("distributed_concat") > 0.60
# and pooling lifts a merely redundant code too -- the confound the `h` row controls
assert gap("redundant_mean") - gap("redundant_single") > 0.20
def test_the_power_check_can_fail(monkeypatch):
"""Break the pooling on purpose; the positive control must notice.
`views` is replaced by one whose `mean` and `concat` read entity 0 alone -- the
shape of every downstream call is unchanged, only the aggregation is gone. A test
that still passed here would be defending nothing.
"""
def broken(rep):
t, n, d = rep.shape
one = rep[:, :1]
return {"single": rep, "mean": one, "concat": np.tile(one, (1, 1, n)).reshape(t, 1, n * d)}
monkeypatch.setattr(pooled, "views", broken)
lab, sw = _labels()
pc = power_check(lab, sw, seed=0)
gap = lambda k: pc[k]["acc_entity"] - pc[k]["chance_shift"]
with pytest.raises(AssertionError):
assert gap("distributed_mean") > 0.60
+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()