From ac10bbca4e9bda9ac9878bd2903e8e5393573dd4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 7 Sep 2026 18:12:53 -0500 Subject: [PATCH] feat: psi as a continuous kernel axis -- the deciding test Teacher changes the kernel's shape with psi (valence rotates the frequency, arousal widens the envelope), never its gain, guarded by a test checked against a teacher deliberately reduced to a gain. The CPPN answers for withheld psi at 1.18x its trained-psi error from 720 parameters. A binned table plus interpolation along psi matches it on 6 seeds of 6 using 57,600. Not a sample-budget artefact: the largest table at 4x the steps fits three times better and generalises not at all better. The bare tables' 19x failure is arithmetic -- their bin never saw gradient -- and is labelled as scale rather than evidence, which is why the interp arms exist at all. Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_01HCydQraDSoZ9WoTm2v23Eb --- psi.py | 261 +++++++++++++++++++++++++++++++++++++++ results/psi.md | 109 ++++++++++++++++ results/rp_properties.md | 29 +++-- tests/test_psi.py | 81 ++++++++++++ 4 files changed, 470 insertions(+), 10 deletions(-) create mode 100644 psi.py create mode 100644 results/psi.md create mode 100644 tests/test_psi.py diff --git a/psi.py b/psi.py new file mode 100644 index 0000000..589ac85 --- /dev/null +++ b/psi.py @@ -0,0 +1,261 @@ +"""psi as a continuous kernel axis: the one place a lookup cannot be built. + +Where the argument stands after `scale.md` and `unseen.md`: variable N and permutation +equivariance are shared with any GNN, identity-in-the-kernel is the same statement as indexing a +lookup by type as well as offset, and generating weights from geometry is real but bounded to +relation spaces that cannot be enumerated. What is left is parameter compression where the +relation space is NOT enumerable -- and psi is the only genuinely continuous axis this +architecture has. A table over (offset x valence x arousal) has to bin the last two. + +This is claim A2 of the paper arriving from the front rather than as a later chapter. + +TWO MEASUREMENTS, because accuracy alone did not separate the arms in `unseen.md` and there is +no reason to expect it to here: + + 1. ACCURACY on a region of psi space held out of training. A binned table can interpolate + across psi bins exactly as it interpolated across offset cells, so this is expected to be + close and is not the headline. + 2. COST to get there -- parameters, and samples. The CPPN shares statistical strength across + the psi axis by construction; a binned table cannot, and pays for every bin separately. + Kernel parameters: CPPN ~720 regardless of resolution; table 3600 * B^2. + +THE NEGATIVE BRANCH, worth as much: if a COARSE table (B=2) plus interpolation matches the CPPN +at a fraction of the parameters, then psi-continuity buys nothing either, and the RP has no +distinguishing claim left against a GNN. That outcome ends a line of argument, which is why it +is written down before the run rather than after. + +The teacher changes the kernel's SHAPE with psi, not its gain: valence rotates the spatial +frequency and arousal widens the envelope. A gain would be reproducible by scaling one shared +kernel, which is the failure mode `chess_reach.md` measured for piece type. +""" +from __future__ import annotations + +import argparse +import json +import math +import statistics +from pathlib import Path + +import torch +from torch import nn + +from unseen import ATTR, CELLS, D, G, R, cell_of + +# The interior box of psi space withheld from training, both axes. Aligned to the bin grid: +# psi in [-1,1] split into B bins puts edges at multiples of 2/B, so [0, 0.5] is exactly one bin +# at B=4 and exactly two at B=8. +# +# A TABLE CANNOT WITHHOLD ANYTHING FINER THAN ITS OWN BIN, and this favours the coarse arms +# rather than the CPPN. At B=1 the box is not held out at all -- that arm ignores psi entirely +# and its "unseen" column is just its ordinary error. At B=2 the box is half of a bin whose +# other half is trained, so the entry it reads has seen data. Only B>=4 withholds it honestly. +# Stated here rather than corrected for: correcting it would mean a different box per arm, and +# then the arms would no longer be answering the same question. +HELD = (0.0, 0.5) + + +def psi_offsets() -> torch.Tensor: + ys, xs = torch.meshgrid(torch.arange(-R, R + 1), torch.arange(-R, R + 1), indexing="ij") + return torch.stack([xs, ys], -1).reshape(CELLS, 2).float() + + +class PsiTeacher(nn.Module): + """W*(r, psi): valence rotates the frequency, arousal widens the envelope. + + Both are shape changes. A psi that only scaled the kernel would be satisfiable by any model + with a gain on its output and would make the experiment vacuous. + """ + def __init__(self, seed: int = 0, kfreq: float = 0.35): + super().__init__() + g = torch.Generator().manual_seed(seed) + self.register_buffer("r", psi_offsets()) + self.register_buffer("k", torch.randn(D, 2, generator=g) * kfreq) + self.register_buffer("phi", torch.rand(D, generator=g) * 2 * math.pi) + + def kernel(self, psi: torch.Tensor) -> torch.Tensor: + val, aro = psi[0], psi[1] + th = val * (math.pi / 2) + rot = torch.stack([torch.stack([torch.cos(th), -torch.sin(th)]), + torch.stack([torch.sin(th), torch.cos(th)])]) + k = self.k @ rot.T # (D,2) frequency rotated by valence + sigma = 3.0 * (1.0 + 0.4 * aro) # envelope widened by arousal + env = torch.exp(-(self.r * self.r).sum(-1) / (2 * sigma * sigma))[:, None] + return env * torch.cos(self.r @ k.T + self.phi) # (CELLS, D) + + def forward(self, r, edge_onehot, context): + return self.kernel(context)[cell_of(r)] + + +class BinnedTable(nn.Module): + """A lookup over (psi bin, offset cell): what a GNN has to do with a continuous axis. + + B=1 is a table that ignores psi entirely -- the floor for this experiment, and the shape a + plain edge-type lookup actually has. + """ + def __init__(self, bins: int): + super().__init__() + self.bins = bins + self.w = nn.Parameter(torch.randn(bins * bins, CELLS, D) * 0.1) + + def bin_of(self, psi: torch.Tensor) -> int: + i, j = (((psi.clamp(-1, 1) + 1) / 2 * self.bins).long().clamp(0, self.bins - 1)).tolist() + return i * self.bins + j + + def forward(self, r, edge_onehot, context): + return self.w[self.bin_of(context)][cell_of(r)] + + +def make(arm: str, seed: int, omega: float = 2.0) -> nn.Module: + from ailed.core import RelationalPerceptron + torch.manual_seed(seed) + rp = RelationalPerceptron(ATTR, 2, 1, 2, hidden_dim=D, cppn_hidden=32, omega=omega) + if arm.startswith("table"): + rp.cppn = BinnedTable(int(arm.split("_")[1])) # "table_4" and "table_4_interp" alike + return nn.ModuleDict({"rp": rp, "out": nn.Linear(D, D)}) + + +def untrained_bins(bins: int) -> torch.Tensor: + """(bins*bins,) bool: bins lying wholly inside the withheld box, so never gradient-updated. + + A bin only partly inside the box still sees training psi from its other part, which is why + B=1 and B=2 have nothing to fill and their `unseen` column is not really held out. + """ + t = BinnedTable(bins) + out = torch.zeros(bins * bins, dtype=torch.bool) + lo, hi = HELD + eps = 1e-4 + for i in range(bins): + for j in range(bins): + x0, x1 = -1 + 2 * i / bins + eps, -1 + 2 * (i + 1) / bins - eps + y0, y1 = -1 + 2 * j / bins + eps, -1 + 2 * (j + 1) / bins - eps + corners = [torch.tensor([x, y]) for x in (x0, x1) for y in (y0, y1)] + if all(in_held(c) for c in corners): + out[t.bin_of(corners[0])] = True + return out + + +@torch.no_grad() +def fill_bins_by_diffusion(table: BinnedTable, held: torch.Tensor) -> None: + """THE CONTROL THAT DECIDES WHAT THIS MEASURES, and the same one `unseen.md` needed. + + A bin that never received gradient sits at its initialisation, so a table failing on the + withheld psi region is arithmetic rather than evidence. Filling those bins from their + trained neighbours in psi space asks the question that matters: does generating the kernel + from a continuous psi beat a lookup plus the obvious smoothing along the same axis? + """ + B = table.bins + grid = table.w.data.view(B, B, -1).clone() + know = (~held).view(B, B).clone() + while not know.all(): + acc = torch.zeros_like(grid) + cnt = torch.zeros(B, B) + for dy, dx in ((-1, 0), (1, 0), (0, -1), (0, 1)): + src_v = torch.roll(grid * know[..., None], shifts=(dy, dx), dims=(0, 1)) + src_k = torch.roll(know.float(), shifts=(dy, dx), dims=(0, 1)) + if dy: # do not wrap around the psi range + (src_v[0] if dy > 0 else src_v[-1]).zero_() + (src_k[0] if dy > 0 else src_k[-1]).zero_() + if dx: + (src_v[:, 0] if dx > 0 else src_v[:, -1]).zero_() + (src_k[:, 0] if dx > 0 else src_k[:, -1]).zero_() + acc += src_v + cnt += src_k + newly = (~know) & (cnt > 0) + if not newly.any(): + break + grid[newly] = acc[newly] / cnt[newly][:, None] + know |= newly + table.w.data.copy_(grid.view(B * B, CELLS, D)) + + +def teacher(seed: int) -> nn.Module: + m = make("rp", seed + 1000) + m["rp"].cppn = PsiTeacher(seed) + for p in m.parameters(): + p.requires_grad_(False) + return m + + +def in_held(psi: torch.Tensor) -> bool: + lo, hi = HELD + return bool(((psi >= lo) & (psi <= hi)).all()) + + +def sample_psi(want_held: bool, gen: torch.Generator) -> torch.Tensor: + while True: + psi = torch.rand(2, generator=gen) * 2 - 1 + if in_held(psi) == want_held: + return psi + + +def batch(want_held: bool, gen: torch.Generator, size=24, n_lo=2, n_hi=5): + out = [] + for _ in range(size): + n = int(torch.randint(n_lo, n_hi + 1, (1,), generator=gen)) + 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), sample_psi(want_held, gen))) + return out + + +def run(model, a, r, mask, psi): + edge = torch.ones(a.shape[0], a.shape[0], 1) + return model["out"](model["rp"](a, r, edge, mask, psi)) + + +def evaluate(model, tea, data): + with torch.no_grad(): + err = sum(((run(model, *d) - run(tea, *d)) ** 2).sum().item() for d in data) + ys = torch.cat([run(tea, *d) for d in data]) + n = sum(d[0].shape[0] * D for d in data) + return err / n, ((ys - ys.mean(0)) ** 2).mean().item() + + +def one_seed(arm, steps, seed, omega): + tea, gen = teacher(seed), torch.Generator().manual_seed(seed) + model = make(arm, seed, omega) + opt = torch.optim.Adam(model.parameters(), lr=3e-3) + for _ in range(steps): + data = batch(False, gen) + loss = sum(((run(model, *d) - run(tea, *d)) ** 2).mean() for d in data) / len(data) + opt.zero_grad(); loss.backward(); opt.step() + + if arm.endswith("_interp"): + fill_bins_by_diffusion(model["rp"].cppn, untrained_bins(model["rp"].cppn.bins)) + + ev = torch.Generator().manual_seed(seed + 5000) + seen, floor_s = evaluate(model, tea, batch(False, ev, size=64)) + unseen, floor_u = evaluate(model, tea, batch(True, ev, size=64)) + return {"seed": seed, "arm": arm, "seen": seen, "unseen": unseen, "floor": floor_u, + "kernel_params": sum(p.numel() for p in model["rp"].cppn.parameters())} + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--arms", default="rp,table_1,table_2,table_4") + ap.add_argument("--omega", type=float, default=2.0) + ap.add_argument("--steps", type=int, default=2500) + ap.add_argument("--seeds", default="0,1,2,3,4,5") + ap.add_argument("--out", default="results/psi.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.steps, s, args.omega)) + r = rows[-1] + print(f"{arm:9s} seed {s} seen {r['seen']:.5f} unseen {r['unseen']:.5f}" + f" params {r['kernel_params']}", flush=True) + + print(f"\npsi held out: box [{HELD[0]},{HELD[1]}]^2, omega={args.omega}") + print(f"{'arm':9s} {'seen':>9s} {'unseen':>9s} {'floor':>9s} {'kernel params':>14s}") + for arm in args.arms.split(","): + a = [r for r in rows if r["arm"] == arm] + print(f"{arm:9s} {statistics.mean([r['seen'] for r in a]):9.5f} " + f"{statistics.mean([r['unseen'] for r in a]):9.5f} " + f"{statistics.mean([r['floor'] for r in a]):9.5f} {a[0]['kernel_params']:14d}") + Path(args.out).write_text(json.dumps({"args": vars(args), "rows": rows}, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/results/psi.md b/results/psi.md new file mode 100644 index 0000000..7d0902e --- /dev/null +++ b/results/psi.md @@ -0,0 +1,109 @@ +# psi as a continuous kernel axis — the deciding test, and it decided against + +After `unseen.md` and `scale.md` the RP's distinguishing claim against a lookup had narrowed to +one thing: **parameter compression where the relation space cannot be enumerated.** psi is the +only genuinely continuous axis this architecture has — a table over (offset × valence × arousal) +must bin the last two — so this was the experiment that would settle whether the CPPN is a +capability or a parameterisation. + +**It is a parameterisation.** A binned table plus interpolation along psi matches the CPPN's +accuracy on withheld psi, on 6 seeds out of 6, using 80× to 320× more parameters. What the CPPN +buys is size, not answers. + +The negative branch was written into `psi.py` before the run: *"if a coarse table plus +interpolation matches the CPPN, then psi-continuity buys nothing either, and the RP has no +distinguishing claim left against a GNN."* It is recorded here as it was predicted. + +## Setup + +Teacher kernel changes **shape** with psi, not gain: valence rotates the spatial frequency, +arousal widens the envelope. A psi that only scaled the kernel would be satisfiable by any model +with a gain on its output — the failure mode `chess_reach.md` measured for piece type — and is +guarded by `test_teacher_kernel_changes_shape_with_psi_not_only_gain`, which was checked against +a teacher deliberately reduced to a gain. + +Withheld: the box psi ∈ [0, 0.5]², aligned to the bin grid. `omega=2`, the measured optimum from +`omega.md`. 6 seeds. Arms share `RelationalPerceptron`'s forward with the kernel swapped. + +## Results + +``` +arm steps seen unseen u/s vs rp kernel params +rp 2500 0.00032 0.00038 1.18 1.00x 720 +table_1 2500 0.00091 0.00081 0.89 2.11x 3600 +table_2 2500 0.00042 0.00070 1.64 1.81x 14400 +table_4 2500 0.00022 0.00733 32.87 19.12x 57600 +table_4_interp 2500 0.00022 0.00034 1.54 0.90x 57600 +table_8 2500 0.00025 0.00746 29.52 19.47x 230400 +table_8 10000 0.00009 0.00691 80.75 18.04x 230400 +table_8_interp 2500 0.00025 0.00033 1.32 0.87x 230400 +floor 0.00656 + +table_4_interp - rp: -0.00004 +/- 0.00002 table better on 6/6 seeds +table_8_interp - rp: -0.00005 +/- 0.00003 table better on 5/6 seeds +``` + +## What this establishes + +**1. The CPPN does answer for psi it never saw.** 0.00038 against 0.00032 on trained psi — a +1.18x cost, at 6% of the floor, from 720 parameters. The property is real. + +**2. And a binned table with the gaps filled does it at least as well.** `table_4_interp` reads +0.00034 and beats the CPPN on 6 seeds of 6. The margin is small in absolute terms and outside +one paired se, so it is readable, but the direction is what matters: **there is no accuracy +advantage to generating the kernel from a continuous psi.** + +**3. The bare tables' failure is arithmetic, and was labelled so before the run.** `table_4` and +`table_8` read ~19x the CPPN on withheld psi because the bin covering the box never received +gradient and sat at its initialisation. Reporting that as evidence would have been the same +tautology `unseen.md` avoided, and it is the reason the interpolation arms exist. + +**4. It is not a sample-budget artefact.** `table_8` at 4x the steps fits trained psi three times +better (0.00025 → 0.00009) and generalises **not at all** better (0.00746 → 0.00691, floor +0.00656). More training buys memorisation and nothing else. Under-training a baseline is the +mirror image of tuning one until it catches up, and this rules it out. + +**5. Resolution in psi and generalisation over psi are opposed in a table.** The arms that +generalise without help (`table_1`, `table_2`) do so by being blind to psi or by having half +their bin trained; the arms that can actually resolve psi are the ones that fail. Only the +explicit fill breaks the trade-off. The CPPN has no such trade-off, which is a structural +difference — it just is not an accuracy one. + +## What is left of the claim + +Parameters. 720 against 57,600 and 230,400 — 80x and 320x — at equal accuracy. That is a real +engineering property and it is now quantified rather than asserted, and its shape matters more +than its size here: **the table's cost is B^(number of continuous axes) × cells × channels, and +the CPPN's is constant.** At two psi axes and B=8 that is already 320x. At four it would be +4096 bins. The compression advantage grows exponentially in the number of continuous inputs and +the CPPN's does not grow at all. + +That is the honest form of what the RP buys, and it is smaller than "a capability a lookup does +not have". Nothing measured in this project distinguishes the RP from a lookup **in what it can +represent**. What distinguishes it is what that representation costs. + +## What this does not establish + +Two continuous axes, one teacher family, a smooth dependence on psi by construction (a rotation +and an envelope width, both continuous and monotone). A psi dependence that was *not* smooth — +discontinuous, or high frequency in psi — is the case where interpolation between bins should +fail and the CPPN should not, and it has not been run. That is the sharpest remaining version of +this question and it is the natural sibling of the deferred capacity sweep, which asks the same +thing along the offset axis. + +The interpolation control also needs to know which bins are untrained. That is realistic — a +system knows which regions it has seen — but it is an extra piece of machinery the CPPN does not +require, and at higher axis counts building it is the exponential above. + +## Reproduce + +``` +uv run python psi.py --arms rp,table_1,table_2,table_4,table_8 --omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi.json +uv run python psi.py --arms table_8 --omega 2 --steps 10000 --seeds 0,1,2,3,4,5 --out results/psi_table8_long.json +uv run python psi.py --arms table_4_interp,table_8_interp --omega 2 --steps 2500 --seeds 0,1,2,3,4,5 --out results/psi_interp.json +``` + +Tests: `tests/test_psi.py`. Both silent-failure risks are defended and both defences were checked +against deliberately broken versions: a teacher reduced to a psi-gain fails the shape test, and +the bin bookkeeping (`untrained_bins`) is asserted exactly rather than approximately, because an +interp arm quietly filling bins that had data would look like a result. diff --git a/results/rp_properties.md b/results/rp_properties.md index 5dc37f6..3379847 100644 --- a/results/rp_properties.md +++ b/results/rp_properties.md @@ -131,22 +131,31 @@ 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 +## Where the argument stands, after three deciding experiments -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, +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`). +table plus a blur competes (`unseen.md`). ψ was the last place a lookup could not be built, and +`psi.md` found that it can: bin it and interpolate, and it matches the CPPN on 6 seeds of 6. -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. +**Nothing measured in this project distinguishes the RP from a lookup in what it can represent.** +What distinguishes it is what that representation costs: 720 parameters against 57,600 and +230,400 at equal accuracy. And the shape of that cost is the part worth keeping — the table +scales as B^(continuous axes) × cells × channels while the CPPN is constant, so the advantage is +80-320× at two continuous axes and grows exponentially with the number of them. + +That is a smaller claim than the one the project was carrying, and it is the one the evidence +supports. It is also not nothing: a parameterisation that is exponentially smaller in the number +of continuous inputs is a real property, now quantified instead of assumed. ## What is open, in order -1. **ψ as a continuous kernel axis** (A2). The one place a lookup cannot be built. Decisive. +1. **A kernel that is NOT smooth in its inputs.** Every measurement here used a smooth teacher, + and smoothness is exactly what lets the table's blur compete. A dependence that is + discontinuous or high-frequency — in ψ, or in the relation, where a knight's L is eight + isolated cells — is where interpolation should fail and the CPPN should not. This is now the + sharpest open question, and the deferred capacity sweep is its sibling along the offset axis. 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 diff --git a/tests/test_psi.py b/tests/test_psi.py new file mode 100644 index 0000000..2ddece3 --- /dev/null +++ b/tests/test_psi.py @@ -0,0 +1,81 @@ +"""The withheld psi region is the experiment, and a leak would be silent as usual. + +Plus the property that makes the experiment non-vacuous: the teacher's kernel must change SHAPE +with psi, not gain. A psi that only scaled the kernel would be satisfiable by any model with a +gain on its output, and every arm would pass for the wrong reason. +""" +import torch + +import psi as P + + +def test_training_psi_never_lands_in_the_held_box(): + gen = torch.Generator().manual_seed(0) + for *_, p in P.batch(False, gen, size=256): + assert not P.in_held(p) + + +def test_eval_psi_is_always_inside_the_held_box(): + gen = torch.Generator().manual_seed(1) + for *_, p in P.batch(True, gen, size=128): + assert P.in_held(p) + + +def test_teacher_kernel_changes_shape_with_psi_not_only_gain(): + # The same check the library makes for the CPPN's context input, applied to the teacher: + # if psi were a gain the ratio between two kernels would be constant. + tea = P.PsiTeacher(0) + a = tea.kernel(torch.tensor([-0.8, 0.0])) + b = tea.kernel(torch.tensor([0.8, 0.0])) + assert (b / (a + 1e-9)).std() > 1e-2 + c = tea.kernel(torch.tensor([0.0, -0.9])) + d = tea.kernel(torch.tensor([0.0, 0.9])) + assert (d / (c + 1e-9)).std() > 1e-2 # arousal too, not just valence + + +def test_bins_partition_psi_and_the_box_aligns_at_b4(): + t4 = P.BinnedTable(4) + lo, hi = P.HELD + inside = {t4.bin_of(torch.tensor([x, y])) + for x in (lo + 0.01, hi - 0.01) for y in (lo + 0.01, hi - 0.01)} + assert len(inside) == 1 # the held box is exactly one bin at B=4 + outside = t4.bin_of(torch.tensor([-0.9, -0.9])) + assert outside not in inside + + +def test_table_1_ignores_psi_entirely(): + # The floor arm: it must be unable to represent any psi dependence, or it is not a floor. + t = P.BinnedTable(1) + r = torch.randint(-3, 4, (3, 3, 2)).float() + a = t(r, None, torch.tensor([-0.9, -0.9])) + b = t(r, None, torch.tensor([0.9, 0.9])) + assert torch.equal(a, b) + + +def test_untrained_bins_are_exactly_the_ones_inside_the_box(): + # At B=4 the withheld box is exactly one bin; at B=2 it is half of one, so nothing is + # wholly untrained and there is nothing for the control to fill. If this drifted, the + # interp arm would quietly be filling bins that had data. + assert int(P.untrained_bins(4).sum()) == 1 + assert int(P.untrained_bins(8).sum()) == 4 + assert int(P.untrained_bins(2).sum()) == 0 + assert int(P.untrained_bins(1).sum()) == 0 + + +def test_diffusion_fills_held_bins_only_from_trained_ones(): + # Trained bins all hold 1, untrained hold 0: after filling, every bin must be 1. A 0 left + # anywhere means an untrained bin was used as a source. + t = P.BinnedTable(4) + held = P.untrained_bins(4) + t.w.data.fill_(1.0) + t.w.data[held] = 0.0 + P.fill_bins_by_diffusion(t, held) + assert torch.allclose(t.w.data, torch.ones_like(t.w.data), atol=1e-6) + + +def test_diffusion_leaves_trained_bins_untouched(): + t = P.BinnedTable(4) + held = P.untrained_bins(4) + before = t.w.data.clone() + P.fill_bins_by_diffusion(t, held) + assert torch.equal(t.w.data[~held], before[~held])