Files
ailed-experiments-rp/frozen.py
T

473 lines
23 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):
"""Construct exactly as `regime.run` does, in the same order, so the RNG stream matches."""
spec = dict(CONDITIONS[name])
if spec["kappa"] == KAPPA_FLAG:
spec["kappa"] = kappa
wcfg = ParticleConfig(seed=seed, oracle=spec["oracle"])
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):
"""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
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.
"""
opt = torch.optim.Adam(org.parameters(), lr=lr)
acfg = AffectConfig()
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)
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: 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 _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()