The regime decodes from a single M at 0.332 and the question was whether it is distributed across the 16 per-entity states rather than absent from them. Mean-pooling lifts M's gap above the measured shift null by +0.045 -- and lifts the memoryless h it is built from by +0.048, on more seeds. Difference -0.003, paired se 0.015, M ahead on 8/16. Concatenating all 16 adds nothing over the mean once it has samples to fit. The instrument is not blind: a synthetic representation whose regime code is genuinely split across entities gains +0.589 through the same probe, thirteen times the effect measured here, and test_the_power_check_can_fail breaks the pooling on purpose and confirms that control fails. Eight seeds would have reported +0.010 in M's favour on 5/8. Sixteen report -0.003 on 8/16, which is the spread this project keeps being warned about. No training loop and no architecture added: _build, _train, _frozen and probe come from frozen.py unchanged, and seeds 0-7 reproduce results/frozen.json bit-identically.
258 lines
12 KiB
Python
258 lines
12 KiB
Python
"""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()
|