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.
506 lines
25 KiB
Python
506 lines
25 KiB
Python
"""Task 7b: frozen-weights probe. Train, freeze every parameter, keep stepping.
|
|
|
|
Task 7 measured memory's advantage at lr=1e-3 and watched it decay to 1.06x at
|
|
lr=1e-2: mean error cannot tell state and fast weights apart, because raising lr
|
|
buys the same adaptation speed that memory buys. This file removes learning
|
|
instead of retuning it. After the freeze no parameter may change, so nothing the
|
|
model does can be attributed to an optimiser step. A frozen `rp_only` still carries
|
|
the 2-d affect state (`--freeze-affect` pins that too); a frozen `grp_k0` still
|
|
updates its per-entity M every step through the gate.
|
|
|
|
Part A measures recovery after a switch under frozen weights. Part B asks what the
|
|
state knows, by linearly decoding the world's regime id out of M (GRP) and out of h
|
|
(RP), against an empirically measured chance level.
|
|
|
|
What survives the freeze is state *only if the two conditions are capacity-matched*,
|
|
and they are not: `rp_only` has 1442 parameters and `grp_k0` 5602. `--ablate-state`
|
|
supplies the control that separates the two. See results/frozen.md; it is what turns
|
|
this file's result from a memory effect into a null.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import statistics
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
import torch
|
|
from torch import Tensor, nn
|
|
|
|
from ailed import Affect, AffectConfig, Organism, detach_memory, update
|
|
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
|
from regime import CONDITIONS, KAPPA_FLAG, _context, _metrics
|
|
|
|
TRAIN_STEPS = 8000 # matches the budget every headroom table in results/headroom.md used
|
|
FROZEN_STEPS = 4000
|
|
SPLIT = 0.7 # probe train fraction, taken as a prefix in time
|
|
|
|
|
|
# -- construction and the two phases ---------------------------------------------
|
|
|
|
def _build(name: str, seed: int, hidden: int, omega: float, kappa: float,
|
|
t_min: int | None = None, t_max: int | None = None):
|
|
"""Construct exactly as `regime.run` does, in the same order, so the RNG stream matches.
|
|
|
|
`t_min`/`t_max` override the regime duration for Task 9 Part 3. They are passed to
|
|
`ParticleConfig` here rather than changed in `particles.py`, so every other caller
|
|
keeps the 40-80 default and `test_train_copy_is_identical_to_regime_run` still pins
|
|
this loop against `regime.run`.
|
|
"""
|
|
spec = dict(CONDITIONS[name])
|
|
if spec["kappa"] == KAPPA_FLAG:
|
|
spec["kappa"] = kappa
|
|
dur = {}
|
|
if t_min is not None:
|
|
dur["t_min"] = t_min
|
|
if t_max is not None:
|
|
dur["t_max"] = t_max
|
|
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"], **dur)
|
|
torch.manual_seed(seed)
|
|
world = ParticleWorld(wcfg)
|
|
ctx_dim = wcfg.n_regimes if spec["ctx"] == "regime" else 2
|
|
org = Organism(attr_dim=world.attr_dim, coord_dim=2, target_dim=2, context_dim=ctx_dim,
|
|
hidden_dim=hidden, omega=omega, kappa=spec["kappa"], memory=spec["memory"])
|
|
return spec, wcfg, world, org
|
|
|
|
|
|
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,
|
|
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 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
|
|
always zero. The GRP keeps every parameter it had and loses only the carrying of
|
|
state -- the control that separates "memory helps" from "the GRP's extra 4160
|
|
parameters help". It is a call into the public API, not a change to the library.
|
|
|
|
`gate_arousal(t, affect) -> float` replaces the arousal the *gate* sees while the
|
|
CPPN keeps the organism's own live affect: the context is then passed explicitly,
|
|
built exactly as `Organism.forward` would have built it from the real affect. This
|
|
is Task 8's shuffled-affect control -- it has to move `-kappa*a` alone, because
|
|
shuffling the affect the CPPN reads would change a second input as well.
|
|
|
|
`on_step(t, obs, r, ctx, axes, prev, memory)` is a read-only callback fired after
|
|
the forward pass, for measuring the gate. `prev` is the M_prev the organism was
|
|
handed, captured before `memory` is rebound.
|
|
|
|
`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(list(org.parameters()) + list(extra_params), lr=lr)
|
|
acfg = AffectConfig() if acfg is None else acfg
|
|
affect = Affect()
|
|
memory: dict[int, Tensor] = {}
|
|
|
|
zero = torch.zeros(org.hidden_dim)
|
|
losses, switched, arousals = [], [], []
|
|
pending = []
|
|
for t in range(steps):
|
|
obs = world.step()
|
|
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
|
|
r = wrapped_diff(obs.coords)
|
|
axes = affect.axes
|
|
if gate_arousal is not None:
|
|
if ctx is None: # what Organism.forward builds from the real affect
|
|
ctx = torch.tensor(affect.axes, dtype=obs.attrs.dtype)
|
|
axes = (affect.valence, float(gate_arousal(t, affect)))
|
|
held = {} if stateless else memory
|
|
prev = (torch.stack([held.get(i, zero) for i in obs.ids])
|
|
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 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:
|
|
on_step(t, obs, r, ctx, axes, prev, memory)
|
|
if len(pending) == bptt:
|
|
opt.zero_grad()
|
|
torch.stack(pending).mean().backward()
|
|
opt.step()
|
|
pending = []
|
|
memory = detach_memory(memory)
|
|
|
|
trace = dict(losses=losses, switched=switched, arousals=arousals)
|
|
return affect, detach_memory(memory), trace
|
|
|
|
|
|
def _hidden(org: Organism, attrs: Tensor, r: Tensor, axes: tuple[float, float],
|
|
ctx: Tensor | None) -> Tensor:
|
|
"""h as `Organism.forward` computes it, by mirroring the tensors it builds internally.
|
|
|
|
`Organism.forward` returns only `out(h)` (or `out(M)`), so h has to be recomputed
|
|
from the public `org.rp`. Every argument here is built the way core.py builds it;
|
|
`_frozen` asserts the reconstruction is bit-identical to the organism's own output.
|
|
"""
|
|
n = attrs.shape[0]
|
|
valence, arousal = axes
|
|
if ctx is None:
|
|
ctx = torch.tensor([valence, arousal], dtype=attrs.dtype)
|
|
edge_types = torch.zeros(n, n, dtype=torch.long)
|
|
mask = torch.ones(n, n, dtype=attrs.dtype)
|
|
edge_onehot = nn.functional.one_hot(edge_types, org.n_edge_types).to(attrs.dtype)
|
|
return org.rp(attrs, r, edge_onehot, mask, ctx)
|
|
|
|
|
|
def _frozen(spec: dict, wcfg: ParticleConfig, world: ParticleWorld, org: Organism,
|
|
affect: Affect, memory: dict[int, Tensor], steps: int,
|
|
freeze_affect: bool = False, stateless: bool = False) -> dict:
|
|
"""Step the world with every parameter frozen. Memory and affect keep updating.
|
|
|
|
`freeze_affect` additionally pins (valence, arousal) at their end-of-training
|
|
values. It exists because `rp_only` runs with `ctx="affect"`, so a frozen RP is
|
|
*not* a fixed function of the current observation: affect is a 2-d state that
|
|
updates from the loss and feeds the CPPN. Pinning it removes the RP's last
|
|
adaptive channel and tests the premise Part A rests on."""
|
|
for p in org.parameters():
|
|
p.requires_grad_(False)
|
|
before = nn.utils.parameters_to_vector(org.parameters()).clone()
|
|
|
|
acfg = AffectConfig()
|
|
zero = torch.zeros(org.hidden_dim)
|
|
losses, switched, arousals, regimes = [], [], [], []
|
|
h_reps, m_reps, dM, gates, couple = [], [], [], [], []
|
|
# the regime id is an arbitrary label over four random coupling matrices; what an
|
|
# entity actually needs is its own row of the current one. Decoding the id can be
|
|
# at chance while the row is not, so both are probed.
|
|
rows = torch.stack([k[world.types] for k in world.regimes]) # (n_regimes, N, n_types)
|
|
|
|
with torch.no_grad():
|
|
for t in range(steps):
|
|
obs = world.step()
|
|
ctx = _context(spec["ctx"], affect, obs.regime, wcfg.n_regimes)
|
|
if stateless:
|
|
memory = {}
|
|
prev = torch.stack([memory.get(i, zero) for i in obs.ids]) if org.use_memory else None
|
|
r = wrapped_diff(obs.coords)
|
|
pred, memory = org(obs.attrs, r, obs.ids, affect.axes, memory, context=ctx)
|
|
loss = ((pred - obs.target) ** 2).mean()
|
|
|
|
h = _hidden(org, obs.attrs, r, affect.axes, ctx)
|
|
if org.use_memory:
|
|
M = torch.stack([memory[i] for i in obs.ids])
|
|
# if this holds, h is exactly the h the organism used
|
|
assert torch.equal(org.grp(h, prev, affect.arousal), M), "h reconstruction diverged"
|
|
m_reps.append(M.numpy().copy())
|
|
dM.append(float((M - prev).abs().max()))
|
|
g = torch.sigmoid(org.grp.gate(torch.cat([h, prev], -1)) - org.grp.kappa * affect.arousal)
|
|
gates.append((float(g.mean()), float(g.std()), float((g > 0.9).float().mean()),
|
|
float((g < 0.1).float().mean())))
|
|
else:
|
|
assert torch.equal(org.out(h), pred), "h reconstruction diverged"
|
|
h_reps.append(h.numpy().copy())
|
|
|
|
if not freeze_affect:
|
|
affect = update(affect, loss.item(), acfg)
|
|
losses.append(loss.item()); switched.append(obs.switched)
|
|
arousals.append(affect.arousal); regimes.append(obs.regime)
|
|
couple.append(rows[obs.regime].numpy().copy())
|
|
|
|
after = nn.utils.parameters_to_vector(org.parameters())
|
|
frozen_ok = bool(torch.equal(before, after))
|
|
assert frozen_ok, "a parameter changed during the frozen phase"
|
|
assert not any(p.requires_grad for p in org.parameters())
|
|
|
|
if org.use_memory and not stateless:
|
|
# freezing is about parameters, not state: if M stopped moving the GRP would
|
|
# have silently degenerated into an RP and any null would be for the wrong reason
|
|
assert min(dM[1:]) > 0.0, "M did not change between consecutive frozen steps"
|
|
|
|
return dict(losses=losses, switched=switched, arousals=arousals, regimes=regimes,
|
|
couple=(np.stack(couple) + 1).astype(int), # {-1,0,1} -> class {0,1,2}
|
|
gate=dict(zip(("mean", "sd", "frac_open", "frac_shut"),
|
|
(statistics.fmean(c) for c in zip(*gates)))) if gates else None,
|
|
h=np.stack(h_reps), M=np.stack(m_reps) if m_reps else None,
|
|
frozen_bit_identical=frozen_ok, n_params=int(before.numel()),
|
|
dM_min=min(dM[1:]) if dM else None,
|
|
dM_mean=statistics.fmean(dM[1:]) if dM else None)
|
|
|
|
|
|
# -- Part B: the linear probe ----------------------------------------------------
|
|
|
|
def _fit_lsq(X: np.ndarray, y: np.ndarray, R: int, ridge: float = 1e-6) -> np.ndarray:
|
|
G = X.T @ X
|
|
lam = ridge * np.trace(G) / X.shape[1]
|
|
return np.linalg.solve(G + lam * np.eye(X.shape[1]), X.T @ np.eye(R)[y])
|
|
|
|
|
|
def _fit_logit(X: np.ndarray, y: np.ndarray, R: int, l2: float = 1e-4) -> np.ndarray:
|
|
"""Multinomial logistic, so a null cannot be blamed on least squares.
|
|
|
|
X already carries the bias column, so the linear map needs no separate intercept.
|
|
LBFGS with strong-Wolfe converges deterministically here; there is no seed."""
|
|
Xt = torch.tensor(X); yt = torch.tensor(y, dtype=torch.long)
|
|
W = torch.zeros(X.shape[1], R, dtype=torch.float64, requires_grad=True)
|
|
opt = torch.optim.LBFGS([W], max_iter=300, tolerance_grad=1e-10,
|
|
line_search_fn="strong_wolfe")
|
|
|
|
def closure():
|
|
opt.zero_grad()
|
|
loss = nn.functional.cross_entropy(Xt @ W, yt) + l2 * (W[:-1] ** 2).sum()
|
|
loss.backward()
|
|
return loss
|
|
|
|
opt.step(closure)
|
|
return W.detach().numpy()
|
|
|
|
|
|
ESTIMATORS = {"lsq": _fit_lsq, "logit": _fit_logit}
|
|
|
|
|
|
def _design(reps: np.ndarray, mu: np.ndarray, sd: np.ndarray) -> np.ndarray:
|
|
"""(T, N, D) -> (T*N, D+1): standardised features plus a bias column."""
|
|
flat = reps.reshape(-1, reps.shape[-1]).astype(np.float64)
|
|
z = (flat - mu) / sd
|
|
return np.concatenate([z, np.ones((z.shape[0], 1))], axis=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]:
|
|
"""(per-entity accuracy, per-step accuracy after averaging the entity scores).
|
|
|
|
The per-step vote only exists when every entity shares one label; a per-entity
|
|
target such as the coupling row has no step-level answer to vote on.
|
|
"""
|
|
ent = float((scores.argmax(-1) == lab).mean())
|
|
step = float((scores.mean(1).argmax(-1) == step_lab).mean()) if step_lab is not None else float("nan")
|
|
return ent, step
|
|
|
|
|
|
def probe(reps: np.ndarray, labels: np.ndarray, switched: list[bool], n_regimes: int,
|
|
split: float = SPLIT, n_null: int = 20, seed: int = 0,
|
|
estimator: str = "lsq", center: bool = False) -> dict:
|
|
"""Linear decode from a representation onto a categorical target, split by time.
|
|
|
|
`labels` is either one label per step, shape (T,) -- the regime id -- or one per
|
|
entity per step, shape (T, N) -- the coupling row the current regime hands that
|
|
entity. The test split is a suffix in time, never a random subset, so the probe
|
|
cannot memorise steps adjacent to the ones it is scored on. Chance is measured,
|
|
not assumed, by two nulls that both refit the probe from scratch.
|
|
"""
|
|
if center:
|
|
# subtract each entity's own mean, computed on the probe-train prefix only.
|
|
# M is dominated by stable per-entity identity (the particle's type); if a
|
|
# regime code is hiding underneath that offset, this is what exposes it.
|
|
reps = reps - reps[:int(reps.shape[0] * split)].mean(0, keepdims=True)
|
|
T, N = reps.shape[0], reps.shape[1]
|
|
per_step = labels.ndim == 1
|
|
lab = np.repeat(labels[:, None], N, axis=1) if per_step else labels
|
|
cut = int(T * split)
|
|
tr, te = slice(0, cut), slice(cut, T)
|
|
fit = ESTIMATORS[estimator]
|
|
|
|
flat_tr = reps[tr].reshape(-1, reps.shape[-1]).astype(np.float64)
|
|
mu, sd = flat_tr.mean(0), flat_tr.std(0) + 1e-12
|
|
|
|
def fit_eval(z: np.ndarray) -> tuple[float, float, np.ndarray]:
|
|
W = fit(_design(reps[tr], mu, sd), z[tr].reshape(-1), n_regimes)
|
|
s = _scores(reps[te], W, mu, sd)
|
|
return _accuracy(s, lab[te], labels[te] if per_step else None) + (s,)
|
|
|
|
ent, step, s_te = fit_eval(lab)
|
|
|
|
# null 1: permute the step-level labels, keeping the 16 entities of a step together
|
|
# null 2: circularly shift the label sequence, which also keeps each regime's
|
|
# 40-80 step block structure intact -- the stricter of the two, because a
|
|
# probe that merely tracks slow drift still scores at this level
|
|
rng = np.random.default_rng(seed)
|
|
shuf, shift = [], []
|
|
for _ in range(n_null):
|
|
shuf.append(fit_eval(rng.permutation(lab))[0])
|
|
k = int(rng.integers(T // 10, T - T // 10))
|
|
shift.append(fit_eval(np.roll(lab, k, axis=0))[0])
|
|
|
|
# latency: steps from a switch until the decoded regime first matches the true one,
|
|
# measured on the test split only, and censored at the next switch
|
|
sw = [i for i, f in enumerate(switched[cut:]) if f]
|
|
lat, censored = [], 0
|
|
if per_step:
|
|
decoded, true = s_te.mean(1).argmax(-1), labels[te]
|
|
for a, b in zip(sw, sw[1:] + [T - cut]):
|
|
hit = next((k for k in range(b - a) if decoded[a + k] == true[a]), None)
|
|
if hit is None:
|
|
censored += 1
|
|
else:
|
|
lat.append(hit)
|
|
return dict(
|
|
estimator=estimator, centered=center, acc_entity=ent, acc_step=step,
|
|
chance_shuffle=float(np.mean(shuf)), chance_shuffle_max=float(np.max(shuf)),
|
|
chance_shift=float(np.mean(shift)), chance_shift_max=float(np.max(shift)),
|
|
n_test_steps=int(T - cut), n_test_switches=len(sw),
|
|
latency=float(np.mean(lat)) if lat else float("nan"),
|
|
latency_median=float(np.median(lat)) if lat else float("nan"),
|
|
censored=censored,
|
|
)
|
|
|
|
|
|
def persistence(reps: np.ndarray, max_lag: int = 60) -> dict:
|
|
"""Lag-1 autocorrelation and the lag where it falls below 1/e, per channel.
|
|
|
|
Model-agnostic, so `h` and `M` are measured the same way. It answers what the
|
|
state is doing when the regime is not decodable from it: a large integration
|
|
time means the GRP is running a temporal filter, not a regime classifier.
|
|
"""
|
|
x = reps - reps.mean(0, keepdims=True)
|
|
sd = x.std(0) + 1e-12
|
|
ac = [float((x[:-k] * x[k:]).mean(0).__truediv__(sd * sd).mean()) for k in range(1, max_lag + 1)]
|
|
tau = next((k + 1 for k, v in enumerate(ac) if v < np.exp(-1.0)), max_lag)
|
|
return dict(lag1=ac[0], tau=tau, ac=ac[:20])
|
|
|
|
|
|
# -- driver ----------------------------------------------------------------------
|
|
|
|
def run_one(name: str, seed: int, train_steps: int = TRAIN_STEPS, frozen_steps: int = FROZEN_STEPS,
|
|
window: int = 20, bptt: int = 20, lr: float = 1e-3, hidden: int = 32,
|
|
kappa: float = 4.0, omega: float = 10.0, freeze_affect: bool = False,
|
|
probes: bool = True, stateless: bool = False) -> dict:
|
|
spec, wcfg, world, org = _build(name, seed, hidden, omega, kappa)
|
|
if window >= wcfg.t_min:
|
|
raise ValueError(f"window={window} must be < t_min={wcfg.t_min}")
|
|
affect, memory, tr = _train(spec, wcfg, world, org, train_steps, bptt, lr, stateless)
|
|
fr = _frozen(spec, wcfg, world, org, affect, memory, frozen_steps, freeze_affect, stateless)
|
|
|
|
labels = np.asarray(fr["regimes"])
|
|
which = "M" if fr["M"] is not None else "h"
|
|
out = dict(
|
|
condition=name + ("_nostate" if stateless else ""), seed=seed,
|
|
train_steps=train_steps, frozen_steps=frozen_steps,
|
|
freeze_affect=freeze_affect, stateless=stateless,
|
|
n_params_rp=sum(p.numel() for p in org.rp.parameters()),
|
|
trained=_metrics(tr["losses"], tr["switched"], tr["arousals"], window),
|
|
frozen=_metrics(fr["losses"], fr["switched"], fr["arousals"], window),
|
|
frozen_bit_identical=fr["frozen_bit_identical"], n_params=fr["n_params"],
|
|
dM_min=fr["dM_min"], dM_mean=fr["dM_mean"], probe_on=which,
|
|
)
|
|
if not probes:
|
|
return out
|
|
# every variant on every representation the condition has: `M` is the GRP's state,
|
|
# `h` the RP output it is built from. Reporting `h` for the GRP too makes the
|
|
# comparison within one organism, holding the weights fixed.
|
|
got, pers = {}, {}
|
|
for tag, rep in (("M", fr["M"]), ("h", fr["h"])):
|
|
if rep is None:
|
|
continue
|
|
args = (rep, labels, fr["switched"], wcfg.n_regimes)
|
|
got[f"{tag}_lsq"] = probe(*args, seed=seed)
|
|
got[f"{tag}_lsq_centered"] = probe(*args, seed=seed, center=True)
|
|
got[f"{tag}_logit"] = probe(*args, seed=seed, n_null=5, estimator="logit")
|
|
for c in range(wcfg.n_types): # the coupling this entity's own type feels
|
|
got[f"{tag}_couple{c}"] = probe(rep, fr["couple"][:, :, c], fr["switched"],
|
|
3, seed=seed, n_null=10)
|
|
pers[tag] = persistence(rep)
|
|
out["probes"] = got
|
|
out["persistence"] = pers
|
|
out["gate"] = fr["gate"]
|
|
out["probe"] = got[f"{which}_lsq"] # headline
|
|
return out
|
|
|
|
|
|
def norm_table(results: list[dict], key: str = "frozen") -> str:
|
|
"""recovery[k] / steady, normalised per seed before averaging.
|
|
|
|
The raw curves are not comparable across conditions whose steady error differs
|
|
3x; this asks the shape question -- how far above its own floor does a condition
|
|
go after a switch, and does it come back down.
|
|
"""
|
|
by: dict[str, list[dict]] = {}
|
|
for r in results:
|
|
by.setdefault(r["condition"], []).append(r)
|
|
idxs = list(range(0, 20, 2)) + [19]
|
|
lines = [f"{'condition':<12}" + "".join(f"{'@' + str(i):>7}" for i in idxs),
|
|
"-" * (12 + 7 * len(idxs))]
|
|
for name, rs in by.items():
|
|
ratios = [[r[key]["recovery"][i] / r[key]["steady"] for i in idxs] for r in rs]
|
|
lines.append(f"{name:<12}" + "".join(f"{statistics.fmean(c):>7.2f}" for c in zip(*ratios)))
|
|
return "\n".join(lines)
|
|
|
|
|
|
def table(results: list[dict], key: str = "frozen") -> str:
|
|
by: dict[str, list[dict]] = {}
|
|
for r in results:
|
|
by.setdefault(r["condition"], []).append(r)
|
|
idxs = [0, 1, 2, 5, 10, 19]
|
|
head = "".join(f"{'rec@' + str(i):>11}" for i in idxs)
|
|
lines = [f"{'condition':<12}{'steady':>11}{'(sd)':>11}{'min':>11}{'max':>11}{head}",
|
|
"-" * (12 + 44 + 11 * len(idxs))]
|
|
for name, rs in by.items():
|
|
st = [r[key]["steady"] for r in rs]
|
|
row = "".join(f"{statistics.fmean(r[key]['recovery'][i] for r in rs):>11.3e}" for i in idxs)
|
|
sd = statistics.stdev(st) if len(st) > 1 else 0.0
|
|
lines.append(f"{name:<12}{statistics.fmean(st):>11.3e}{sd:>11.3e}"
|
|
f"{min(st):>11.3e}{max(st):>11.3e}{row}")
|
|
return "\n".join(lines)
|
|
|
|
|
|
def main() -> None:
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--conditions", default="rp_only,grp_k0")
|
|
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("--window", type=int, default=20)
|
|
ap.add_argument("--lr", type=float, default=1e-3)
|
|
ap.add_argument("--freeze-affect", action="store_true",
|
|
help="also pin (valence, arousal) in the frozen phase, so a frozen "
|
|
"rp_only really is a fixed function of the observation")
|
|
ap.add_argument("--no-probes", action="store_true")
|
|
ap.add_argument("--ablate-state", action="store_true",
|
|
help="hand the organism an empty memory every step: same parameters, "
|
|
"no state carried. Separates memory from the GRP's extra capacity.")
|
|
ap.add_argument("--out", default="results/frozen.json")
|
|
a = ap.parse_args()
|
|
|
|
results = []
|
|
for name in a.conditions.split(","):
|
|
for seed in (int(s) for s in a.seeds.split(",")):
|
|
r = run_one(name, seed, a.train_steps, a.frozen_steps, window=a.window, lr=a.lr,
|
|
freeze_affect=a.freeze_affect, probes=not a.no_probes,
|
|
stateless=a.ablate_state)
|
|
f = r["frozen"]
|
|
msg = (f"{r['condition']:<18} seed={seed} frozen_steady={f['steady']:.3e} "
|
|
f"rec@0={f['recovery'][0]:.3e} rec@10={f['recovery'][10]:.3e}")
|
|
if "probe" in r:
|
|
p = r["probe"]
|
|
msg += (f" probe({r['probe_on']})={p['acc_entity']:.3f} "
|
|
f"chance={p['chance_shift']:.3f} lat={p['latency']:.1f}")
|
|
print(msg, 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))
|
|
for key in ("trained", "frozen"):
|
|
print(f"\n{key} phase:"); print(table(results, key))
|
|
print(f"{key} recovery / steady:"); print(norm_table(results, key))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|