diff --git a/pooled.py b/pooled.py new file mode 100644 index 0000000..c7339f5 --- /dev/null +++ b/pooled.py @@ -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() diff --git a/results/pooled.md b/results/pooled.md new file mode 100644 index 0000000..dc8db9d --- /dev/null +++ b/results/pooled.md @@ -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. diff --git a/tests/test_pooled.py b/tests/test_pooled.py new file mode 100644 index 0000000..940c8b8 --- /dev/null +++ b/tests/test_pooled.py @@ -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