From d95383f8a2a48a91b95e19990a24e719a88b708c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 7 Sep 2026 17:45:41 -0500 Subject: [PATCH] feat: omega curve and unseen-N, the two steps before psi omega.md: a plateau at [1,4] that does not track the domain across a 4.7x range, so the bandwidth is a knob that was set wrong rather than a defect to design around. omega=8 is an optimisation cliff, not a mis-tune. The project default of 10 is outside the plateau. scale.md: one parameter set works at an entity count it never trained on -- trained on N<=16 it beats the oracle at N=32 -- and a lookup table does it too. Read against an oracle because the mse/floor ratio is not comparable across N, which is asserted as a test rather than claimed in prose. The cost runs large->small only, at 2.28x, which makes it the pooling's 1/deg dilution rather than a degree-distribution shift. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb --- analyse_scale.py | 46 +++++++++++++++ analyse_sweep.py | 39 ++++++++++++ results/omega.md | 88 +++++++++++++++++++++++++++ results/rp_properties.md | 37 ++++++++---- results/scale.md | 86 +++++++++++++++++++++++++++ scale.py | 124 +++++++++++++++++++++++++++++++++++++++ tests/test_scale.py | 44 ++++++++++++++ unseen.py | 22 ++++--- 8 files changed, 467 insertions(+), 19 deletions(-) create mode 100644 analyse_scale.py create mode 100644 analyse_sweep.py create mode 100644 results/omega.md create mode 100644 results/scale.md create mode 100644 scale.py create mode 100644 tests/test_scale.py diff --git a/analyse_scale.py b/analyse_scale.py new file mode 100644 index 0000000..6a6ebe2 --- /dev/null +++ b/analyse_scale.py @@ -0,0 +1,46 @@ +"""Does one parameter set still WORK at an entity count it never trained on? + +Read against the ORACLE, never down the N axis. `y_i` is a mean over neighbours, so the target's +variance falls as N rises and any error-over-floor ratio climbs with N for a model that is doing +nothing wrong. The oracle -- trained over the full range [2,32] -- absorbs all of that: at each +N, `forward / oracle` is the cost of never having seen that entity count, and nothing else. + +Both directions are reported. A cost in BOTH is the degree distribution shifting under the mean +pooling; a cost in ONE is the extrapolation that was actually asked for. +""" +import json, statistics as st + + +def load(tag, arm): + rs = json.load(open(f"results/scale_{tag}.json"))["rows"] + return [r for r in rs if r["arm"] == arm] + + +def per_n(rows, n): + return st.mean([r["per_n"][str(n)]["mse"] for r in rows]) + + +def paired(a, b, n): + d = [x["per_n"][str(n)]["mse"] - y["per_n"][str(n)]["mse"] for x, y in zip(a, b)] + return st.mean(d), st.stdev(d) / len(d) ** 0.5, sum(1 for v in d if v > 0), len(d) + + +NS = [2, 4, 8, 12, 16, 20, 24, 28, 32] + +for arm in ("rp", "table"): + fwd, rev, orc = (load(t, arm) for t in ("forward", "reverse", "oracle")) + print(f"\n{'=' * 78}\n{arm.upper()} raw MSE, and cost against the oracle trained on [2,32]\n{'=' * 78}") + print(f"{'N':>4} {'fwd[2,16]':>10} {'rev[17,32]':>11} {'oracle':>10} " + f"{'fwd/orc':>8} {'rev/orc':>8} trained on N?") + for n in NS: + f, r, o = per_n(fwd, n), per_n(rev, n), per_n(orc, n) + tag = "fwd" if n <= 16 else "rev" + print(f"{n:>4} {f:10.5f} {r:11.5f} {o:10.5f} {f / o:8.2f} {r / o:8.2f} {tag} only") + print() + for label, arms_, ns in (("forward, unseen N (17-32)", fwd, [20, 24, 28, 32]), + ("reverse, unseen N (2-16)", rev, [2, 4, 8, 12])): + ms = [paired(orc, arms_, n) for n in ns] + tot = st.mean([m for m, _, _, _ in ms]) + won = sum(w for _, _, w, _ in ms) + print(f" {label}: mean cost over oracle {tot:+.5f} " + f"{won}/{sum(k for _, _, _, k in ms)} seed-points worse than oracle") diff --git a/analyse_sweep.py b/analyse_sweep.py new file mode 100644 index 0000000..f305600 --- /dev/null +++ b/analyse_sweep.py @@ -0,0 +1,39 @@ +"""The omega curve. Prints all of it, which is the point. + +omega sets the CPPN's bandwidth. `unseen.md` found a 17x swing between two hand-picked values +and every chess number sits at one of them, unexamined. This decides which of two things that +is: a knob that was set wrong (broad plateau -> document it, choose per domain, leave +AffectiveCPPN alone) or an architectural defect (narrow, domain-dependent optimum -> a learned +or multi-scale frequency is a mechanism question worth asking). + +THE TRAP, stated so it cannot be walked into: this reports the whole curve. Picking the omega +that beats table+interp and quoting that number would be tuning a mechanism until it wins, +which is the move AGENTS.md exists to forbid. +""" +import glob, json, re, statistics as st + +REF = {"random": 0.00016, "band": 0.00006} # table+interp, from unseen.md + + +def load(path): + return [r for r in json.load(open(path))["rows"] if r["arm"] == "rp"] + + +for kind in ("random", "band"): + files = sorted(glob.glob(f"results/sweep_{kind}_w*.json"), + key=lambda f: float(re.search(r"_w([\d.]+)\.json", f).group(1))) + if not files: + print(f"{kind}: nothing yet") + continue + print(f"\n{'=' * 78}\n{kind.upper()} hold-out — omega curve, 8 seeds" + f" (table+interp reference: {REF[kind]:.5f})\n{'=' * 78}") + print(f"{'omega':>6} {'seen':>10} {'unseen':>10} {'u/s':>6} {'vs ref':>8} " + f"{'seeds10} per-seed unseen") + for f in files: + w = float(re.search(r"_w([\d.]+)\.json", f).group(1)) + rs = load(f) + seen, uns = st.mean([r["seen"] for r in rs]), st.mean([r["unseen"] for r in rs]) + beat = sum(1 for r in rs if r["unseen"] < REF[kind]) + per = " ".join(f"{r['unseen']:.5f}" for r in sorted(rs, key=lambda r: r["seed"])) + print(f"{w:>6g} {seen:10.5f} {uns:10.5f} {uns / seen:6.2f} " + f"{uns / REF[kind]:8.2f}x {beat:>7}/8 {per}") diff --git a/results/omega.md b/results/omega.md new file mode 100644 index 0000000..c2708ee --- /dev/null +++ b/results/omega.md @@ -0,0 +1,88 @@ +# omega: a knob that was set wrong, not a defect to design around + +`unseen.md` found a 17x swing in held-out error between two hand-picked values of `omega`, the +CPPN's bandwidth, and noted that every chess number in this project sits at one of them without +anyone having examined it. This file decides which of two things that is: + +- a **knob** that wants a value per domain — document it, choose it, leave `AffectiveCPPN` alone; +- a **defect** — a narrow optimum that moves with the domain, in which case a learned or + multi-scale frequency is a mechanism question worth asking rather than a tune. + +The answer is the first one, and the reason the code already gave for it is measured **false**. + +## The curve, one domain, 8 seeds + +MSE on held-out relations, `unseen.py`, teacher bandwidth `kfreq=0.35`. + +``` + omega 0.25 0.5 1 2 4 8 16 + random 0.00052 0.00016 0.00008 0.00006 0.00007 0.00112 0.00019 + band 0.00087 0.00034 0.00014 0.00008 0.00007 0.00064 0.00028 + (seen) 0.00044 0.00012 0.00007 0.00006 0.00006 0.00024 0.00011 +``` + +A plateau at **omega ∈ [1,4]**, in the same place for both hold-out structures. The project's +default of 10 sits outside it, 7-11x worse than the optimum. `omega=1`, which `unseen.md` ran +at and which was picked without measuring, is not the optimum either — 2 is. That result was +obtained by luck, and it is recorded as luck. + +**omega=8 is unstable, not merely mis-tuned.** Per seed: 0.00028, 0.00425, 0.00016, 0.00127, +0.00037, 0.00159, 0.00043, 0.00059. `seen` degrades with it (0.00024), so this is optimisation +breaking down rather than a bandwidth mismatch — and 16 recovers to 0.00019. The curve has a +cliff in the middle, not a single valley, and a sweep of three points could have missed it. + +## Does the optimum move with the domain? No. + +The deciding axis. `kfreq` is the **domain's** spatial frequency, `omega` the **model's**. +6 seeds, random hold-out, MSE on held-out relations. + +``` + kfreq \ omega 0.5 1 2 4 8 best + 0.15 0.00006 0.00003 0.00003 0.00003 0.00138 4 + 0.35 0.00017 0.00009 0.00006 0.00006 0.00132 2 + 0.70 0.00118 0.00046 0.00028 0.00020 0.00143 4 +``` + +The optimum sits at 2-4 across a domain bandwidth that varies by 4.7x. It does not track the +domain. What *does* change with the domain is the **penalty for being under-banded**: at +`kfreq=0.7` an `omega` of 0.5 costs 6x the optimum, at `kfreq=0.15` only 2x. And `omega=8` +fails at ~0.0013-0.0014 for every domain tested, which confirms the cliff is a property of the +model, not of what it is fitting. + +**This contradicts the comment in `core.py`**, which states that omega "is a calibration knob +that wants tuning against the domain's length scale". That was a plausible assumption and it is +now measured false over the range tested: a fixed value in [2,4] is near-optimal for every +domain bandwidth here. The comment should say what the measurement says. + +## What follows + +**Do not rework `AffectiveCPPN`.** There is a broad plateau, it does not move, and a learned or +multi-scale frequency would be solving a problem that was not found. That option stays available +if a domain ever turns up whose optimum is outside [1,4]; none has. + +**The default is a footgun and the debt is recorded rather than paid here.** Every chess number +in this project was produced at `omega=10`, outside the plateau. Those results are comparisons +at a *fixed* omega, so the comparisons remain fair and nothing in `chess_reach.md`, +`chess_rules.md` or `chess_dist.md` is invalidated — but their absolute levels come from a +badly calibrated kernel, and how much of the gap to the rule-knowing control was bandwidth is +unknown. Re-running the chess arc in the plateau belongs to the chess arc, which is parked. + +## What this does not establish + +Three domain bandwidths over one order of magnitude, one teacher family (Gabor), one hold-out +structure for the grid, 6 seeds. The grid's resolution in omega is 2x, so a shift in the optimum +smaller than that would not show. "The optimum does not move" is a statement about this range, +and the honest form of it is: nothing was found that would justify redesigning the kernel's +frequency, which is a weaker claim than nothing exists. + +## Reproduce + +``` +for w in 0.25 0.5 1 2 4 8 16; do for k in random band; do + uv run python unseen.py --holdout $k --arms rp --omega $w --steps 2500 \ + --seeds 0,1,2,3,4,5,6,7 --out results/sweep_${k}_w${w}.json; done; done +for kf in 0.15 0.35 0.70; do for w in 0.5 1 2 4 8; do + uv run python unseen.py --holdout random --arms rp --omega $w --kfreq $kf --steps 2500 \ + --seeds 0,1,2,3,4,5 --out results/grid_k${kf}_w${w}.json; done; done +uv run python analyse_sweep.py +``` diff --git a/results/rp_properties.md b/results/rp_properties.md index 0b20b82..5dc37f6 100644 --- a/results/rp_properties.md +++ b/results/rp_properties.md @@ -19,7 +19,7 @@ measure has already been assumed away. No MLP is trained anywhere in this file. | # | Property | Status | Evidence | |---|----------|--------|----------| -| 1 | **One parameter set, any N** | **Defined: asserted.** Generalises: *untested* | `test_rp_same_parameters_any_n`. ~9k params served N=2..32 throughout the chess arc | +| 1 | **One parameter set, any N** | **Measured. Holds — and a GNN has it too** | `scale.md`, `test_rp_same_parameters_any_n` | | 2 | **Permutation equivariance** | **Asserted, sabotage-verified** | `test_rp_permutation_equivariance`, `test_organism_permutation_equivariance_with_memory` | | 3 | **Weights generated from the relation** | **Measured. Real, and smaller than assumed** | `unseen.md` | | 4 | **Translation invariance** | **Asserted, and its cost measured** | `test_rp_translation_invariance`; `chess_rules.md` | @@ -36,8 +36,16 @@ dimension is N·d (or N²·d for pairs) and has to be chosen before training. Ch different model, not a different input. That is the cleanest statement of what the RP buys, and it is structural — no run establishes it and no run can refute it. -What *is* open is a separate claim that the wording invites confusion with: that the RP still -**works** at an N it never trained on. Defined ≠ competent. Untested (`≤16 → 17-32`). +What the wording invites confusion with is a separate claim: that the RP still **works** at an N +it never trained on. Measured in `scale.md`, and it holds strongly — a model trained on N ≤ 16 +scores 0.84 of the oracle's error at N=32, i.e. *better* than the model that trained there. + +Two qualifications, both from that file. **A lookup table does the same** (0.86-0.90): neither +has a parameter tied to entity count, so this separates the RP from a perceptron and from +nothing else. And the cost that does exist runs the other way — training on N ∈ [17,32] and +evaluating at N=2 costs 2.28x, because mean pooling dilutes each pair's contribution by 1/deg +and the kernel is learned less sharply at large N. **The RP's pooling is a low-pass filter on +the learning signal, strength 1/N**; the cheap curriculum is to train small and deploy large. ### 2. Permutation equivariance @@ -123,16 +131,23 @@ The RP earns its cost where at least one of these is load-bearing: And it is the wrong tool where the law is anchored to absolute position (row 4), which has to be patched in through attributes. +## Where the argument now stands + +Rows 1 and 2 are **shared with any GNN** — measured, not assumed (`scale.md`). Row 5, identity +in the kernel, is the same statement as indexing a lookup by type as well as by offset. Row 3, +generating weights from geometry, is real but bounded: where relations are few and discrete, a +table plus a blur competes (`unseen.md`). + +So the RP's remaining distinguishing claim is **parameter compression in a relation space that +cannot be enumerated** — and in this architecture the one genuinely continuous axis is **ψ**. A +table over (offset × type × valence × arousal) has no cells to interpolate between on the last +two. That makes ψ the deciding experiment rather than a later chapter, and it is claim A2 of the +paper arriving from the front. + ## What is open, in order -1. **Unseen N** (row 1, second half). Train ≤16 entities, evaluate 17-32. Now the first item: - after `unseen.md`, row 1 is the RP's least qualified distinguishing property. -2. **Unseen relations in a CONTINUOUS space** (row 3, second half). The measured result is - bounded by the relation space having been enumerable. Where it is not, the table control - cannot be built and the comparison changes shape. -3. **`omega`.** Raised by `unseen.md` and not on this card before: the bandwidth is a free knob - that moved a result 17x, and every chess number was produced at one unexamined value. -4. **Kernel capacity and interference.** How many distinct kernels fit before they collide, and +1. **ψ as a continuous kernel axis** (A2). The one place a lookup cannot be built. Decisive. +2. **Kernel capacity and interference.** How many distinct kernels fit before they collide, and which pairs collide first. The pawn/colour result is one measured point of this curve; the sweep makes similarity an independent variable instead of an accident of chess. Deliberately last: how far a mechanism stretches is only worth measuring once it is known what it is for. diff --git a/results/scale.md b/results/scale.md new file mode 100644 index 0000000..f67c324 --- /dev/null +++ b/results/scale.md @@ -0,0 +1,86 @@ +# One parameter set, an entity count it never trained on + +Row 1 of `rp_properties.md`, second half. That the RP is *defined* at any N is structural and +asserted in the library's tests — a fixed-weight layer is not worse there, it has no input +dimension to use. Whether it still **works** at an N it never saw is a different claim, and +defined is not competent. + +Two things come out, and the second is the more useful one. + +## Read against an oracle, never down the N axis + +`y_i` is a mean over neighbours, so raising N averages more terms, the target's variance falls, +and any error-over-floor ratio climbs with N for a model doing nothing wrong. This was found in +the smoke run and is asserted in `tests/test_scale.py::test_floor_shrinks_as_n_grows` rather +than left in prose. + +What makes the axis comparable is an oracle: a model trained over the full range [2,32] and +evaluated at the same N. Three runs, `omega=2` (the measured optimum from `omega.md`, not the +value picked by hand for `unseen.md`), 8 seeds, both arms: + +- `forward` trained on N ∈ [2,16] — large N unseen +- `reverse` trained on N ∈ [17,32] — small N unseen +- `oracle` trained on N ∈ [2,32] + +The reverse direction is a control, not symmetry: mean pooling means degree rises with N, so a +cost at large N could be the pooled statistics shifting rather than a failure to generalise over +entity count. A cost in **both** directions would be the degree distribution; a cost in **one** +is the extrapolation actually asked for. + +## Result: generalising over N is free, and the table does it too + +Ratio to the oracle at the same N. Below 1 means *better* than the model that trained there. + +``` + N 2 4 8 12 16 20 24 28 32 +rp fwd/orc 0.75 0.71 0.76 0.80 0.78 0.80 0.80 0.82 0.84 +rp rev/orc 2.28 1.26 0.91 0.87 0.84 0.83 0.82 0.84 0.84 +table fwd/orc 0.86 0.76 0.84 0.86 0.86 0.86 0.86 0.91 0.90 +table rev/orc 1.82 1.27 1.10 1.06 1.04 0.97 0.98 1.03 1.00 + | unseen for forward -> + <- unseen for reverse | +``` + +**The property holds, strongly.** A model that never saw more than 16 entities is not merely +competent at 32: at 0.84 it beats the oracle that trained there. + +**And it does not distinguish the RP from a GNN.** The lookup table shows the same pattern +(0.86-0.90 forward). Neither has a parameter tied to the entity count, so neither needs to. Row +1 separates the RP from a *perceptron*, for which variable N is undefined, and from nothing +else. The property card already said this; it is now measured rather than argued. + +## The asymmetry is the finding + +The cost appears in **one** direction only — large→small, 2.28x at N=2 and 1.26x at N=4, gone by +N=8. Small→large is free and better than free. + +The mechanism is the pooling. `h_i = tanh(mean_j m_ij ⊙ W p_j + b)`, so a single pair's +contribution to the target is diluted by 1/deg. Training at N=32 dilutes every kernel value by +~1/32 before the gradient sees it, and the kernel is learned less sharply; that imprecision is +invisible at large N, where averaging hides it, and shows up immediately at N=2, where it does +not. **The RP's mean pooling is a low-pass filter on the learning signal, with strength 1/N.** + +That is actionable and it is the opposite of the intuition that more entities means more signal: +the cheap curriculum is to train on few entities and deploy on many. It is also a statement +about relational architectures rather than about this domain, which is the kind this project is +for. The table arm showing the same asymmetry (1.82x at N=2) confirms it is the pooling and not +the kernel. + +## What this does not establish + +One domain, one teacher family, N from 2 to 32 on an 8x8 lattice, so density rises with N and is +confounded with count — at N=32 half the squares are occupied and the displacement distribution +is not the same as at N=2. Separating count from density needs a board that grows with N, and +that was not run. The 2.28x at N=2 is the point where that confound is largest. + +## Reproduce + +``` +uv run python scale.py --train 2,16 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_forward.json +uv run python scale.py --train 17,32 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_reverse.json +uv run python scale.py --train 2,32 --omega 2 --steps 2000 --seeds 0,1,2,3,4,5,6,7 --out results/scale_oracle.json +uv run python analyse_scale.py +``` + +Tests: `tests/test_scale.py`. The training range is the experiment and a leak would be silent; +the range check was run against a deliberately widened sampler and failed there. diff --git a/scale.py b/scale.py new file mode 100644 index 0000000..66f2349 --- /dev/null +++ b/scale.py @@ -0,0 +1,124 @@ +"""One parameter set, an entity count it never trained on. + +Row 1 of `rp_properties.md`, second half. That the RP is *defined* at any N is structural and +already asserted in the library's tests; a fixed-weight layer is not worse there, it has no +input dimension to use. What is not established is whether it still WORKS at an N it never saw, +and defined is not competent. + +THE TABLE ARM IS HERE ON PURPOSE. A lookup kernel generalises over N for the same reason the +CPPN does -- neither has a parameter tied to the entity count. If it holds up, this property +separates the RP from a perceptron and NOT from a GNN, which is what the property card already +claims and what should be measured rather than argued. + +THE CONFOUND THIS IS BUILT TO SEPARATE. `h_i` is a mean over neighbours, so raising N raises the +degree and changes the pooled statistics. Degradation at large N could be that, not a failure to +generalise over entity count. Hence the reverse direction: train large and evaluate small. A +failure in BOTH directions is about the degree distribution shifting; a failure in one is about +the direction it was asked to extrapolate. + +MEASUREMENT NOTE, found in the smoke run and worth more than the run that found it. Dividing by +a per-N floor does NOT make the axis comparable. `y_i` is a mean over neighbours, so raising N +averages more terms, the target's variance falls, the floor falls with it, and the ratio climbs +even for a model that is doing fine. The ratio is reported because it is informative WITHIN one +N, across arms -- never read down a column as a trend. + +What makes the axis comparable is an ORACLE, which is this repo's rule anyway: a model trained +over the FULL range [2,32] and evaluated at the same N. Degradation from an unseen entity count +is then (model trained on [2,16]) against (model trained on [2,32]) at the same N, and every +N-dependent difficulty cancels. Three runs, compared in `analyse_scale.py`: + + --train 2,16 forward: small seen, large unseen + --train 17,32 reverse: large seen, small unseen + --train 2,32 the oracle both are read against +""" +from __future__ import annotations + +import argparse +import json +import statistics +from pathlib import Path + +import torch + +from unseen import ATTR, D, make_model, run_model, teacher + + +def configs(n: int, count: int, gen: torch.Generator): + out = [] + for _ in range(count): + c = torch.randint(0, 8, (n, 2), generator=gen).float() + out.append((torch.randn(n, ATTR, generator=gen), c[None, :, :] - c[:, None, :], + torch.ones(n, n))) + return out + + +def mixed_batch(lo: int, hi: int, gen: torch.Generator, size=24): + out = [] + for _ in range(size): + n = int(torch.randint(lo, hi + 1, (1,), generator=gen)) + out += configs(n, 1, gen) + return out + + +def evaluate(model, tea, data): + with torch.no_grad(): + err = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).sum().item() + for a, r, m in data) + ys = torch.cat([run_model(tea, a, r, m) for a, r, m in data]) + n = sum(a.shape[0] * D for a, _, _ in data) + return err / n, ((ys - ys.mean(0)) ** 2).mean().item() + + +def one_seed(arm, lo, hi, evals, steps, seed, omega): + tea = teacher(seed) + gen = torch.Generator().manual_seed(seed) + model = make_model(arm, seed, omega) + opt = torch.optim.Adam(model.parameters(), lr=3e-3) + for _ in range(steps): + data = mixed_batch(lo, hi, gen) + loss = sum(((run_model(model, a, r, m) - run_model(tea, a, r, m)) ** 2).mean() + for a, r, m in data) / len(data) + opt.zero_grad(); loss.backward(); opt.step() + + ev = torch.Generator().manual_seed(seed + 5000) + per_n = {} + for n in evals: + mse, floor = evaluate(model, tea, configs(n, 24, ev)) + per_n[n] = {"mse": mse, "floor": floor, "ratio": mse / floor} + return {"seed": seed, "arm": arm, "omega": omega, "train_lo": lo, "train_hi": hi, + "per_n": per_n} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--train", default="2,16", help="lo,hi entity count seen in training") + ap.add_argument("--evals", default="2,4,8,12,16,20,24,28,32") + ap.add_argument("--arms", default="rp,table") + ap.add_argument("--omega", type=float, default=1.0) + ap.add_argument("--steps", type=int, default=2000) + ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7") + ap.add_argument("--out", default="results/scale.json") + args = ap.parse_args() + + lo, hi = (int(x) for x in args.train.split(",")) + evals = [int(x) for x in args.evals.split(",")] + rows = [] + for arm in args.arms.split(","): + for s in (int(x) for x in args.seeds.split(",")): + rows.append(one_seed(arm, lo, hi, evals, args.steps, s, args.omega)) + print(f"{arm:6s} seed {s} " + " ".join( + f"N{n}:{rows[-1]['per_n'][n]['ratio']:.4f}" for n in evals), flush=True) + + print(f"\ntrained on N in [{lo},{hi}], omega={args.omega} (mse / per-N floor)") + print(f"{'arm':6s} " + " ".join(f"{('N' + str(n)) + ('*' if lo <= n <= hi else ''):>9s}" + for n in evals)) + for arm in args.arms.split(","): + a = [r for r in rows if r["arm"] == arm] + print(f"{arm:6s} " + " ".join( + f"{statistics.mean([r['per_n'][n]['ratio'] for r in a]):9.4f}" for n in evals)) + print("* = inside the training range") + Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/tests/test_scale.py b/tests/test_scale.py new file mode 100644 index 0000000..7cee0e0 --- /dev/null +++ b/tests/test_scale.py @@ -0,0 +1,44 @@ +"""The training range is the experiment. If an unseen N appears in training, nothing complains. + +Same silent-failure shape as the held-out cells in test_unseen: every arm still trains and every +number still prints, and `unseen N` quietly becomes `seen N`. +""" +import torch + +import scale + + +def test_training_never_sees_an_n_outside_its_range(): + gen = torch.Generator().manual_seed(0) + for lo, hi in ((2, 16), (17, 32)): + ns = {a.shape[0] for a, _, _ in scale.mixed_batch(lo, hi, gen, size=200)} + assert ns and min(ns) >= lo and max(ns) <= hi + + +def test_training_range_actually_varies_n(): + # A range that collapsed to a single N would make the whole axis meaningless while still + # satisfying the bounds check above. + gen = torch.Generator().manual_seed(1) + ns = {a.shape[0] for a, _, _ in scale.mixed_batch(2, 16, gen, size=200)} + assert len(ns) > 8 + + +def test_one_parameter_set_evaluates_at_every_n(): + # The property under test: the same object, unchanged, runs at any entity count. + model = scale.make_model("rp", 0, 1.0) + before = [p.clone() for p in model.parameters()] + gen = torch.Generator().manual_seed(2) + for n in (2, 7, 16, 25, 32): + for a, r, m in scale.configs(n, 1, gen): + assert scale.run_model(model, a, r, m).shape == (n, scale.D) + assert all(torch.equal(x, y) for x, y in zip(before, model.parameters())) + + +def test_floor_shrinks_as_n_grows(): + # The measurement note in scale.py depends on this being true, so it is checked rather + # than asserted in prose: pooling more neighbours lowers the target's variance, which is + # why the mse/floor ratio must not be read as a trend down the N axis. + tea = scale.teacher(0) + gen = torch.Generator().manual_seed(3) + floors = [scale.evaluate(tea, tea, scale.configs(n, 32, gen))[1] for n in (2, 8, 32)] + assert floors[0] > floors[1] > floors[2] diff --git a/unseen.py b/unseen.py index a63f119..89c6c5a 100644 --- a/unseen.py +++ b/unseen.py @@ -48,7 +48,7 @@ def cell_of(r: torch.Tensor) -> torch.Tensor: return dy * G + dx -def gabor_kernel(sigma: float = 3.0, seed: int = 0) -> torch.Tensor: +def gabor_kernel(sigma: float = 3.0, seed: int = 0, kfreq: float = 0.35) -> torch.Tensor: """(CELLS, D) true kernel: a smooth, band-limited function of the displacement. Smooth on purpose. A CPPN that cannot interpolate THIS has not failed a hard case, it has @@ -57,7 +57,7 @@ def gabor_kernel(sigma: float = 3.0, seed: int = 0) -> torch.Tensor: g = torch.Generator().manual_seed(seed) ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij") r = torch.stack([xs, ys], -1).reshape(CELLS, 2).float() - k = torch.randn(D, 2, generator=g) * 0.35 # spatial frequencies, low by design + k = torch.randn(D, 2, generator=g) * kfreq # spatial frequencies of the domain phi = torch.rand(D, generator=g) * 6.2831853 env = torch.exp(-(r * r).sum(-1) / (2 * sigma * sigma))[:, None] return env * torch.cos(r @ k.T + phi) @@ -120,10 +120,14 @@ def fill_by_diffusion(w: torch.Tensor, held: torch.Tensor) -> None: w.copy_(grid.view(CELLS, D)) -def teacher(seed: int) -> nn.Module: +def teacher(seed: int, kfreq: float = 0.35) -> nn.Module: + """kfreq is the DOMAIN's length scale, not the model's. Sweeping it against the CPPN's omega + is what separates a knob that wants calibrating per domain from a defect in the + architecture: if the best omega tracks kfreq, core.py's own comment was right all along and + nobody had calibrated it; if it sits still, the default can simply be corrected.""" m = make_model("table", seed + 1000) with torch.no_grad(): - m["rp"].cppn.w.copy_(gabor_kernel(seed=seed)) + m["rp"].cppn.w.copy_(gabor_kernel(seed=seed, kfreq=kfreq)) for p in m.parameters(): p.requires_grad_(False) return m @@ -209,8 +213,9 @@ def floor_mse(tea, data) -> float: return ((ys - ys.mean(0)) ** 2).mean().item() -def one_seed(arm: str, kind: str, frac: float, steps: int, seed: int, omega: float = 1.0) -> dict: - tea = teacher(seed) +def one_seed(arm: str, kind: str, frac: float, steps: int, seed: int, omega: float = 1.0, + kfreq: float = 0.35) -> dict: + tea = teacher(seed, kfreq) held = holdout_cells(kind, frac, seed) gen = torch.Generator().manual_seed(seed) model = make_model(arm, seed, omega) @@ -228,7 +233,7 @@ def one_seed(arm: str, kind: str, frac: float, steps: int, seed: int, omega: flo ev = torch.Generator().manual_seed(seed + 5000) seen = pair_batch(held, False, ev) unseen = pair_batch(held, True, ev) - return {"seed": seed, "arm": arm, "omega": omega, "seen": evaluate(model, tea, seen), + return {"seed": seed, "arm": arm, "omega": omega, "kfreq": kfreq, "seen": evaluate(model, tea, seen), "unseen": evaluate(model, tea, unseen), "floor_seen": floor_mse(tea, seen), "floor_unseen": floor_mse(tea, unseen), "n_held": int(held.sum())} @@ -242,13 +247,14 @@ def main(): ap.add_argument("--seeds", default="0,1,2,3,4,5,6,7") ap.add_argument("--arms", default="rp,table") ap.add_argument("--omega", type=float, default=1.0) + ap.add_argument("--kfreq", type=float, default=0.35, help="the DOMAIN's spatial frequency") ap.add_argument("--out", default="results/unseen.json") args = ap.parse_args() rows = [] for arm in args.arms.split(","): for s in (int(x) for x in args.seeds.split(",")): - rows.append(one_seed(arm, args.holdout, args.frac, args.steps, s, args.omega)) + rows.append(one_seed(arm, args.holdout, args.frac, args.steps, s, args.omega, args.kfreq)) r = rows[-1] print(f"{arm:6s} seed {s} seen {r['seen']:.5f} unseen {r['unseen']:.5f}" f" floor {r['floor_unseen']:.5f}", flush=True)