Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KAWnnPg2qvmLNySamE2k85
124 lines
5.3 KiB
Python
124 lines
5.3 KiB
Python
"""Information ceilings for the particles domain. Task 7.
|
|
|
|
Fits, by least squares over a rolled-out world, the best predictor of the form
|
|
|
|
d_i = a[offset(i)] + sum_j c[key(i,j)] * dt * kern(r_ij) * r_ij
|
|
|
|
under several information sets. The radial kernel is handed to the fit exactly, so
|
|
each row is the best a predictor with that information can do *within this family*.
|
|
|
|
SCOPE. The family is linear in the messages. The real RP applies tanh on top of the
|
|
aggregate and the GRP adds per-entity state, so these numbers are NOT a bound on what
|
|
the trained architecture can reach -- a memoryless rp_only run with the regime frozen
|
|
gets below rows C and D. Read the table as a map of where the information sits, not
|
|
as a proof about the model.
|
|
|
|
Row A is the self-check: given (regime, t_i, t_j) the family spans the dynamics
|
|
exactly, so its deterministic residual must be ~0 and its residual against the noisy
|
|
target must equal noise**2.
|
|
|
|
uv run python ceilings.py [steps] [seeds]
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import statistics
|
|
import sys
|
|
|
|
import torch
|
|
|
|
from particles import ParticleConfig, ParticleWorld, wrapped_diff
|
|
|
|
|
|
def collect(cfg: ParticleConfig, steps: int) -> list[tuple]:
|
|
"""Roll the world out, recovering the deterministic part of each step's target."""
|
|
w, rows = ParticleWorld(cfg), []
|
|
for _ in range(steps):
|
|
coords, types = w.coords.clone(), w.types.clone()
|
|
obs = w.step()
|
|
# obs.regime, not w.regime read before step(): step() switches the regime
|
|
# *before* computing the delta, so the pre-step value is stale on switch steps.
|
|
r = wrapped_diff(coords)
|
|
kern = torch.exp(-(r ** 2).sum(-1) / cfg.sigma ** 2)
|
|
kern.fill_diagonal_(0.0)
|
|
K = w.regimes[obs.regime][types[:, None], types[None, :]]
|
|
det = cfg.dt * ((K * kern)[:, :, None] * r).sum(1)
|
|
rows.append((r, kern, types, obs.regime, det, obs.target))
|
|
return rows
|
|
|
|
|
|
def design(rows: list[tuple], cfg: ParticleConfig, key, offset) -> tuple[torch.Tensor, ...]:
|
|
"""key(types, regime) -> (N,N) coefficient index; offset(types, regime) -> (N,) index."""
|
|
n_key = max(key(t, g).max().item() for _, _, t, g, _, _ in rows) + 1
|
|
n_off = max(offset(t, g).max().item() for _, _, t, g, _, _ in rows) + 1
|
|
X, Y, Yn = [], [], []
|
|
for r, kern, types, regime, det, target in rows:
|
|
w = cfg.dt * kern[:, :, None] * r # (N,N,2)
|
|
idx = key(types, regime)
|
|
cols = [(w * (idx == c)[:, :, None]).sum(1) for c in range(n_key)] # each (N,2)
|
|
oid = offset(types, regime)
|
|
for c in range(n_off): # a free 2-vector offset per class
|
|
sel = (oid == c).float()
|
|
zero = torch.zeros_like(sel)
|
|
cols += [torch.stack([sel, zero], -1), torch.stack([zero, sel], -1)]
|
|
X.append(torch.stack(cols, -1).reshape(-1, len(cols)))
|
|
Y.append(det.reshape(-1))
|
|
Yn.append(target.reshape(-1))
|
|
return torch.cat(X).double(), torch.cat(Y).double(), torch.cat(Yn).double()
|
|
|
|
|
|
T = ParticleConfig().n_types
|
|
|
|
CEILINGS = [
|
|
("A perfect: (regime, t_i, t_j)",
|
|
lambda t, g: (g * T * T + t[:, None] * T + t[None, :]).long(),
|
|
lambda t, g: torch.zeros_like(t).long()),
|
|
("B regime-blind, pair-aware (t_i, t_j)",
|
|
lambda t, g: (t[:, None] * T + t[None, :]).long(),
|
|
lambda t, g: t.long()),
|
|
("C regime oracle (regime, t_j)",
|
|
lambda t, g: (g * T + t[None, :]).expand(len(t), len(t)).long(),
|
|
lambda t, g: (g * T + t).long()),
|
|
("D no oracle (t_j)",
|
|
lambda t, g: t[None, :].expand(len(t), len(t)).long(),
|
|
lambda t, g: t.long()),
|
|
]
|
|
|
|
|
|
def ceilings(steps: int = 1200, seeds: tuple[int, ...] = (0, 1, 2)) -> dict[str, tuple[float, float]]:
|
|
out = {}
|
|
for label, key, off in CEILINGS:
|
|
dets, obss = [], []
|
|
for seed in seeds:
|
|
cfg = ParticleConfig(seed=seed)
|
|
X, Y, Yn = design(collect(cfg, steps), cfg, key, off)
|
|
pred = (X @ torch.linalg.lstsq(X, Y.unsqueeze(1)).solution).squeeze(1)
|
|
dets.append(((pred - Y) ** 2).mean().item())
|
|
obss.append(((pred - Yn) ** 2).mean().item())
|
|
out[label] = (statistics.fmean(dets), statistics.fmean(obss))
|
|
return out
|
|
|
|
|
|
def main() -> None:
|
|
steps = int(sys.argv[1]) if len(sys.argv) > 1 else 1200
|
|
seeds = tuple(int(s) for s in sys.argv[2].split(",")) if len(sys.argv) > 2 else (0, 1, 2)
|
|
cfg = ParticleConfig()
|
|
res = ceilings(steps, seeds)
|
|
print(f"steps={steps} seeds={','.join(map(str, seeds))} noise^2 = {cfg.noise ** 2:.3e}\n")
|
|
print(f"{'information set':<40}{'MSE(det part)':>15}{'MSE(vs target)':>16}")
|
|
print("-" * 71)
|
|
for label, (d, o) in res.items():
|
|
print(f"{label:<40}{d:>15.3e}{o:>16.3e}")
|
|
c, d = res["C regime oracle (regime, t_j)"], res["D no oracle (t_j)"]
|
|
print(f"\noracle prize D->C: {d[0] / c[0]:.2f}x on the deterministic part, "
|
|
f"{d[1] / c[1]:.2f}x against the noisy target")
|
|
|
|
a = res["A perfect: (regime, t_i, t_j)"]
|
|
assert a[0] < 1e-15, f"row A must span the dynamics exactly, got {a[0]:.3e}"
|
|
assert abs(a[1] - cfg.noise ** 2) < 0.02 * cfg.noise ** 2, \
|
|
f"row A vs target must equal noise^2={cfg.noise ** 2:.3e}, got {a[1]:.3e}"
|
|
print("self-check: row A spans the dynamics and lands on the noise floor.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|