"""Task 9 Part 2: how many steps of history does it take to identify the regime? `T_id` is a property of the *domain*, not of our architecture, so nothing in this file constructs an Organism. It rolls the world out and asks: given the last `L` observations an observer actually has at step `t`, how well can the regime in force at `t` be decoded? What the observer has at step t, and nothing more: * the coordinates c_{t-L+1} .. c_t (the current one included -- it is observed) * therefore the displacements d_s = wrap(c_{s+1} - c_s) for s = t-L+1 .. t-1 `d_t` is *not* available: that is the quantity the organism is asked to predict, and handing it to the decoder would be handing over the answer. So `L = 1` is the instantaneous configuration alone -- the read-off `results/frozen.md` ยง2 measured at +0.05 over chance -- and each extra step of window buys exactly one more observed displacement. ## The feature sets, and why the physics one is a fair stand-in for optimal The world's dynamics are d_i(s) = sum_c K[t_i, c] * B_i^c(s) + eps, B_i^c(s) = dt * sum_{j: t_j = c} kern(r_ij) r_ij with `kern` the fixed radial kernel and `eps ~ N(0, noise^2)`. `B` is the *message basis*: everything about the configuration that the coupling matrix multiplies. It is computable from the coordinates alone, so it is observer-side information, and it is the same decomposition `ceilings.py` fits against. `_check_basis` asserts the reconstruction is exact. Given that model, the log-likelihood of regime `g` from the window's displacements is -1/(2 noise^2) * sum_s sum_i || d_i(s) - sum_c K_g[t_i,c] B_i^c(s) ||^2 = const + (1/noise^2) * sum_c K_g[t_i,c] - (1/2noise^2) * sum_{c,c'} K_g[t_i,c] K_g[t_i,c'] which is **affine in the statistics `` and ``, with coefficients that depend on `g` and on the entity's own type**. So a linear classifier on those statistics, interacted with the type one-hot, can express the exact Bayes rule. That is what `phys` is, and it is why it is a fair stand-in for "optimal" rather than a weak probe that would understate the difficulty. `bayes` computes the same rule in closed form, with the true coupling matrices handed to it, as a cross-check on the fit: `phys` should track it and must not beat it by much. `lin` and `mlp` are the honest non-omniscient decoders -- least squares and a two-layer MLP on the raw window (the per-frame features at every step of the window, the observed displacements, the type one-hot). They know no coupling matrices. If they saturate where `bayes` does, the saturation is the domain's and not a decoder's limitation. ## The headline: how much does history add over the present? The number that decides whether memory can pay is not where accuracy saturates. It is `accuracy(L) - accuracy(1)`. `L = 1` is the present-only baseline: the current frame, no displacement, no history. Three cases a hidden variable can fall into -- 1. no evidence anywhere: nothing helps, memory included 2. evidence already in the present: history is *redundant* and feedforward suffices, however identifiable the variable is 3. evidence only in the past: memory is required (card counting is the pure case) -- and only case 3 gives per-entity state a job. `T_id` is a secondary quantity that matters only once `accuracy(L) - accuracy(1)` is materially above zero. This makes the *strength of the L = 1 decoder* the load-bearing choice, because an underpowered present-only baseline inflates the history gain. So the per-frame feature block (`_frame`) carries every rotation-invariant scalar the message basis misses -- the kernel mass and the kernel-weighted spread per neighbour type, alongside `B` itself -- and `L = 1` and `L = 40` are given the *same* per-frame features and the same decoder, differing only in how many frames. A better present-only decoder could only shrink the reported gain, never grow it. Chance is measured the way `frozen.py` measures it: two nulls, both refitting from scratch -- a label shuffle, and a circular shift that preserves each regime's block structure and is therefore the stricter of the two. uv run python identify.py --out results/identify.json """ 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 particles import ParticleConfig, ParticleWorld, wrapped_diff LS = (1, 2, 3, 5, 10, 20, 40) SEEDS = (0, 1, 2, 3, 4, 5, 6, 7) STEPS = 4000 SPLIT = 0.7 # -- the world, rolled out ------------------------------------------------------- def rollout(cfg: ParticleConfig, steps: int) -> dict: """Coordinates, observed displacements, the message basis, and the true regime. `coords[t]` is what an observer sees at step t; `disp[t] = wrap(coords[t+1] - coords[t])` is what it sees *after* step t resolves, so at step t the observer has `disp[:t]` and not `disp[t]`. `regime[t]` is the regime that generated `disp[t]`. """ w = ParticleWorld(cfg) coords, disp, regimes = [], [], [] for _ in range(steps): obs = w.step() coords.append(obs.coords) regimes.append(obs.regime) disp.append(wrapped_diff(torch.stack([obs.coords, w.coords]))[0, 1]) # wrap(c_{t+1} - c_t) C = torch.stack(coords) # (T, N, 2) D = torch.stack(disp) # (T, N, 2) B = torch.stack([_basis(c, w.types, cfg) for c in C]) # (T, N, n_types, 2) F = torch.stack([_frame(c, w.types, cfg) for c in C]) # (T, N, 4 * n_types) K = torch.stack(w.regimes) # (n_regimes, n_types, n_types) return dict(coords=C, disp=D, basis=B, frame=F, regimes=np.asarray(regimes), types=w.types, K=K, cfg=cfg) def _basis(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor: """B[i, c] = dt * sum_{j : t_j = c} kern(r_ij) r_ij, the message the coupling multiplies.""" r = wrapped_diff(coords) kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2) kern.fill_diagonal_(0.0) wr = cfg.dt * kern[:, :, None] * r # (N,N,2) onehot = nn.functional.one_hot(types, cfg.n_types).to(wr.dtype) # (N, n_types) return torch.einsum("ijd,jc->icd", wr, onehot) # (N, n_types, 2) def _frame(coords: torch.Tensor, types: torch.Tensor, cfg: ParticleConfig) -> torch.Tensor: """Everything one frame says about the configuration, per entity and neighbour type. The message basis `B` is a first moment and is therefore blind to arrangement that cancels by symmetry -- a ring of same-type neighbours contributes almost nothing to `B` however tight it is. Since `L = 1` is the present-only baseline the whole history gain is measured against, it must not be handicapped by that blindness, so the frame also carries the two rotation-invariant scalars per neighbour type: the kernel mass (how much of type c is nearby) and the kernel-weighted spread (how far out it sits). `L = 1` and `L = 40` see the same per-frame features. """ r = wrapped_diff(coords) d2 = (r ** 2).sum(-1) kern = torch.exp(-d2 / cfg.sigma ** 2) kern.fill_diagonal_(0.0) onehot = nn.functional.one_hot(types, cfg.n_types).to(r.dtype) # (N, n_types) B = torch.einsum("ijd,jc->icd", cfg.dt * kern[:, :, None] * r, onehot) # (N, n_types, 2) mass = kern @ onehot # (N, n_types) spread = (kern * d2) @ onehot # (N, n_types) return torch.cat([B.reshape(len(r), -1), mass, spread], dim=-1) def det(world: dict, regimes: np.ndarray) -> torch.Tensor: """The deterministic displacement each step would have had under `regimes[t]`.""" krow = world["K"][torch.as_tensor(regimes)][:, world["types"], :] # (T, N, n_types) return torch.einsum("tic,ticd->tid", krow, world["basis"]) def _check_basis(world: dict) -> float: """Self-check: the basis must reproduce the world's own dynamics up to the noise. The analogue of `ceilings.py`'s row A. If this residual is not the noise variance then `B` is not the world's message basis and every number below is meaningless. """ resid = float(((det(world, world["regimes"]) - world["disp"]) ** 2).mean()) floor = world["cfg"].noise ** 2 assert abs(resid - floor) < 0.03 * floor, f"basis residual {resid:.3e} != noise^2 {floor:.3e}" return resid # -- features -------------------------------------------------------------------- def features(world: dict, L: int, kind: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """(X, y, t_index) for every step at which a full window of L observations exists. Rows are per entity: X has shape (T', N, F). `y` is the regime at the step being decoded. The window at step t covers observations t-L+1 .. t, i.e. displacements t-L+1 .. t-1 -- never `d_t`. """ B, D = world["basis"].numpy(), world["disp"].numpy() Fr = world["frame"].numpy() T, N, C, _ = B.shape ts = np.arange(L - 1, T) onehot = nn.functional.one_hot(world["types"], C).numpy().astype(np.float64) # (N, C) if kind == "raw": cols = [] for k in range(L): # the per-frame features at each step cols.append(Fr[ts - (L - 1) + k]) for k in range(L - 1): # the displacements the observer has seen cols.append(D[ts - (L - 1) + k]) cols.append(np.broadcast_to(onehot, (len(ts), N, C))) X = np.concatenate(cols, axis=-1) elif kind == "phys": # the sufficient statistics of the Gaussian likelihood, summed over the window, # interacted with the entity's own type so the per-type coupling row is separable db = np.zeros((len(ts), N, C)) bb = np.zeros((len(ts), N, C * (C + 1) // 2)) for k in range(L - 1): s = ts - (L - 1) + k db += np.einsum("tid,ticd->tic", D[s], B[s]) pairs = [(a, b) for a in range(C) for b in range(a, C)] bb += np.stack([np.einsum("tid,tid->ti", B[s][:, :, a], B[s][:, :, b]) for a, b in pairs], axis=-1) stats = np.concatenate([db, bb], axis=-1) # (T', N, C + C(C+1)/2) X = (stats[:, :, None, :] * onehot[None, :, :, None]).reshape(len(ts), N, -1) else: raise ValueError(kind) return X.astype(np.float64), world["regimes"][ts], ts # -- decoders -------------------------------------------------------------------- def _standardise(X: np.ndarray, cut: int) -> np.ndarray: flat = X[:cut].reshape(-1, X.shape[-1]) mu, sd = flat.mean(0), flat.std(0) + 1e-12 return np.concatenate([(X - mu) / sd, np.ones(X.shape[:2] + (1,))], axis=-1) 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-6) -> np.ndarray: """Multinomial logistic, LBFGS with strong Wolfe -- as `frozen.py` fits its probe. Least squares onto a one-hot target is a poor classifier on the physics statistics, which are products of small numbers and heavy-tailed; it understates what the feature set can express. The `phys` set is meant to be a fair stand-in for optimal, so it gets the estimator that actually maximises the classification objective. X already carries the bias column, so no separate intercept. """ Xt, yt = torch.tensor(X), 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-12, 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() def _fit_mlp(X: np.ndarray, y: np.ndarray, R: int, hidden: int = 128, epochs: int = 40, seed: int = 0) -> callable: """Two-layer MLP -- the capacity check the brief asks for before concluding. A linear probe that never rises is not evidence the regime is unidentifiable, so the raw feature set is also given a nonlinear decoder. Full-batch Adam; the split is a time suffix, so there is no shuffling to seed beyond the initialisation. """ torch.manual_seed(seed) net = nn.Sequential(nn.Linear(X.shape[1], hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, R)).double() Xt, yt = torch.tensor(X), torch.tensor(y, dtype=torch.long) opt = torch.optim.Adam(net.parameters(), lr=3e-3, weight_decay=1e-5) n, bs = len(Xt), 4096 g = torch.Generator().manual_seed(seed) 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() nn.functional.cross_entropy(net(Xt[idx]), yt[idx]).backward() opt.step() net.eval() return lambda Z: net(torch.tensor(Z)).detach().numpy() def decode(X: np.ndarray, y: np.ndarray, n_regimes: int, estimator: str, split: float = SPLIT, n_null: int = 10, seed: int = 0) -> dict: """Fit on a time prefix, score on the suffix, with chance measured by two nulls. Reported twice: `entity` is one classification per entity per step, `step` pools the N entities of a step by averaging their scores -- what an observer watching the whole world would do. The regime is a global variable, so `step` is the domain-level number and `entity` is the one a per-entity memory could hold. """ T = X.shape[0] cut = int(T * split) Z = _standardise(X, cut) F = Z.shape[-1] flat = lambda A: A.reshape(-1, F) def fit_eval(lab: np.ndarray) -> tuple[float, float]: ytr = np.repeat(lab[:cut, None], X.shape[1], 1).reshape(-1) if estimator in ("lsq", "logit"): fit = _fit_lsq if estimator == "lsq" else _fit_logit W = fit(flat(Z[:cut]), ytr, n_regimes) s = (flat(Z[cut:]) @ W).reshape(T - cut, X.shape[1], n_regimes) elif estimator == "mlp": f = _fit_mlp(flat(Z[:cut]), ytr, n_regimes, seed=seed) s = f(flat(Z[cut:])).reshape(T - cut, X.shape[1], n_regimes) else: raise ValueError(estimator) ent = float((s.argmax(-1) == lab[cut:, None]).mean()) step = float((s.mean(1).argmax(-1) == lab[cut:]).mean()) return ent, step ent, step = fit_eval(y) rng = np.random.default_rng(seed) shuf, shift = [], [] for _ in range(n_null): shuf.append(fit_eval(rng.permutation(y))) k = int(rng.integers(T // 10, T - T // 10)) shift.append(fit_eval(np.roll(y, k))) return dict(estimator=estimator, acc_entity=ent, acc_step=step, chance_entity=float(np.mean([a for a, _ in shuf])), chance_step=float(np.mean([b for _, b in shuf])), shift_entity=float(np.mean([a for a, _ in shift])), shift_step=float(np.mean([b for _, b in shift])), n_test=T - cut, n_features=F) def bayes(world: dict, L: int, split: float = SPLIT) -> dict: """Exact Gaussian likelihood over the window, with the true coupling matrices given. No fitting, so no train split is needed; it is scored on the same test suffix the fitted decoders use so the numbers sit in one column. This is the floor on `T_id`: a decoder that knows the generative model exactly, including the four candidate matrices, and assumes the regime is constant across the window. """ B, D = world["basis"], world["disp"] T, N = B.shape[0], B.shape[1] ts = np.arange(L - 1, T) K = world["K"][:, world["types"], :] # (R, N, n_types) resid = np.zeros((len(ts), N, K.shape[0])) for k in range(L - 1): s = torch.as_tensor(ts - (L - 1) + k) pred = torch.einsum("ric,ticd->rtid", K, B[s]) # (R, T', N, 2) resid += ((pred - D[s][None]) ** 2).sum(-1).permute(1, 2, 0).numpy() y = world["regimes"][ts] cut = int(len(ts) * split) sc = -resid[cut:] return dict(estimator="bayes", acc_entity=float((sc.argmax(-1) == y[cut:, None]).mean()), acc_step=float((sc.sum(1).argmax(-1) == y[cut:]).mean()), n_test=len(ts) - cut) def switch_fraction(world: dict, L: int) -> float: """Fraction of decoded steps whose window spans a regime change. A window longer than the regime lasts contains two regimes, and a decoder that assumes one is then mis-specified. This is the mechanism behind `T_z < T_id`, so it is reported alongside every accuracy. """ g = world["regimes"] ts = np.arange(L - 1, len(g)) return float(np.mean([g[t - L + 1:t + 1].min() != g[t - L + 1:t + 1].max() for t in ts])) # -- driver ---------------------------------------------------------------------- def run(seed: int, steps: int, Ls: tuple[int, ...], t_min: int, t_max: int, estimators: tuple[str, ...]) -> list[dict]: cfg = ParticleConfig(seed=seed, t_min=t_min, t_max=t_max) world = rollout(cfg, steps) resid = _check_basis(world) out = [] for L in Ls: row = dict(seed=seed, L=L, t_min=t_min, t_max=t_max, steps=steps, basis_residual=resid, switch_frac=switch_fraction(world, L), decoders={}) for kind, est in (("raw", "lsq"), ("raw", "mlp"), ("phys", "logit")): tag = {"raw/lsq": "lin", "raw/mlp": "mlp", "phys/logit": "phys"}[f"{kind}/{est}"] if tag not in estimators: continue if kind == "phys" and L == 1: continue # no displacement observed yet: the likelihood has no terms X, y, _ = features(world, L, kind) # the MLP is refit from scratch for every null, so its chance level is # measured on fewer draws than the linear decoders' ten row["decoders"][tag] = decode(X, y, cfg.n_regimes, est, seed=seed, n_null=2 if est == "mlp" else 10) if "bayes" in estimators and L > 1: row["decoders"]["bayes"] = bayes(world, L) out.append(row) return out def table(results: list[dict], which: str = "step") -> str: by: dict[int, list[dict]] = {} for r in results: by.setdefault(r["L"], []).append(r) tags = ["lin", "mlp", "phys", "bayes"] head = "".join(f"{t:>18}" for t in tags) lines = [f"per-{which} accuracy (chance in brackets), means over seeds", f"{'L':>3}{'sw.frac':>9}{head}", "-" * (12 + 18 * len(tags))] for L in sorted(by): rs = by[L] cells = "" for t in tags: got = [r["decoders"][t] for r in rs if t in r["decoders"]] if not got: cells += f"{'--':>18}" continue acc = statistics.fmean(g[f"acc_{which}"] for g in got) ch = [g[f"shift_{which}"] for g in got if f"shift_{which}" in g] cells += f"{acc:>12.3f}{('[' + format(statistics.fmean(ch), '.3f') + ']') if ch else '':>6}" lines.append(f"{L:>3}{statistics.fmean(r['switch_frac'] for r in rs):>9.3f}{cells}") return "\n".join(lines) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--seeds", default=",".join(map(str, SEEDS))) ap.add_argument("--steps", type=int, default=STEPS) ap.add_argument("--Ls", default=",".join(map(str, LS))) ap.add_argument("--t-min", type=int, default=ParticleConfig().t_min) ap.add_argument("--t-max", type=int, default=ParticleConfig().t_max) ap.add_argument("--estimators", default="lin,mlp,phys,bayes") ap.add_argument("--out", default="results/identify.json") a = ap.parse_args() ests = tuple(a.estimators.split(",")) Ls = tuple(int(x) for x in a.Ls.split(",")) results = [] for seed in (int(s) for s in a.seeds.split(",")): rs = run(seed, a.steps, Ls, a.t_min, a.t_max, ests) for r in rs: d = r["decoders"] msg = " ".join(f"{k}={v['acc_step']:.3f}/{v['acc_entity']:.3f}" for k, v in d.items()) print(f"seed={seed} L={r['L']:<3} sw={r['switch_frac']:.3f} {msg}", flush=True) results.extend(rs) Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps(results, indent=1)) print(); print(table(results, "step")); print(); print(table(results, "entity")) if __name__ == "__main__": main()