diff --git a/.github/workflows/bpd-pinned-kernel.yml b/.github/workflows/bpd-pinned-kernel.yml new file mode 100644 index 00000000..54a1eead --- /dev/null +++ b/.github/workflows/bpd-pinned-kernel.yml @@ -0,0 +1,94 @@ +name: BPD-LG-01 pinned Lean kernel validation +on: + push: + paths: + - 'fixtures/bpd_lean_curriculum_pinned/**' + - '.github/workflows/bpd-pinned-kernel.yml' + pull_request: + paths: + - 'fixtures/bpd_lean_curriculum_pinned/**' + - '.github/workflows/bpd-pinned-kernel.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + kernel: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Regenerate pinned BPD-LG-01 corpus and verify hashes + run: | + python - <<'PY' + import hashlib, json, subprocess + from pathlib import Path + path = Path("fixtures/bpd_lean_curriculum_pinned/generate.py") + assert hashlib.sha256(path.read_bytes()).hexdigest() == "3b474850e3aac9c6958be8c7d33ae16b2448fbf8ef6fac965d7d795fb2f830fe" + out = Path("/tmp/bpd-lg01") + subprocess.run(["python", str(path), "--out", str(out)], check=True) + m = json.loads((out/"manifest.json").read_text()) + assert m["cases"] == 384 + assert m["positive_templates"] == m["negative_finite_countermodels"] == 192 + assert m["split_counts"] == {"train": 256, "dev": 64, "test": 64} + assert {k:m["sha256"][k] for k in ("train_positives.lean","dev_positives.lean","test_positives.lean")} == { + "train_positives.lean": "c688fc711817e33633c9065569e11cafcabfca665c29013c6b5704cec43fbdab", + "dev_positives.lean": "bb2329e9745c966e529cbf8f591276228df707c04b0f6471e291602d8ed2607f", + "test_positives.lean": "e2376bb1cef30eb78ab93dc13853b682a740bc6f3daa12560fd010fd23a8048f" + } + PY + - name: Install pinned Lean 4.19.0 + run: | + curl --fail --location --retry 3 https://github.com/leanprover/lean4/releases/download/v4.19.0/lean-4.19.0-linux.tar.zst -o /tmp/lean.tar.zst + tar --zstd -xf /tmp/lean.tar.zst -C /tmp + echo '/tmp/lean-4.19.0-linux/bin' >> "$GITHUB_PATH" + - name: Kernel typecheck all positives and reject axiom dependencies + run: | + python - <<'PY' + import hashlib, json, re, subprocess + from pathlib import Path + root = Path("/tmp/bpd-lg01") + version = subprocess.check_output(["lean","--version"], text=True).strip() + assert "version 4.19.0" in version, version + receipt = {"source_repo":"MoralityLabAI/LoopedTransformers", + "source_commit":"ebdd76e3acacb5d68d4d736d6dc49417f26f166f", + "generator_sha256":"3b474850e3aac9c6958be8c7d33ae16b2448fbf8ef6fac965d7d795fb2f830fe", + "lean_version":version, "by_split":{}, "kernel_checked":0, "axiom_free":False} + try: + seen=set() + for split,count in (("train",128),("dev",32),("test",32)): + original=root/f"{split}_positives.lean" + content=original.read_text() + names=re.findall(r"^theorem (thm_bpd_[A-Za-z0-9_]+)\b",content,re.M) + assert len(names)==len(set(names))==count + assert not seen.intersection(names) + seen.update(names) + assert not re.search(r"\b(?:axiom|sorry|admit|native_decide|unsafe)\b",content) + audited=root/f"{split}_axiom_audit.lean" + audited.write_text(content+"\n"+"\n".join("#print axioms "+n for n in names)+"\n") + p=subprocess.run(["lean",str(audited)],capture_output=True,text=True,timeout=180) + (root/f"{split}_stdout.log").write_text(p.stdout) + (root/f"{split}_stderr.log").write_text(p.stderr) + if p.returncode: + raise RuntimeError(f"{split}: Lean exit {p.returncode}\n"+p.stdout[-6000:]+p.stderr[-6000:]) + if p.stdout.count("does not depend on any axioms")!=count: + raise RuntimeError(f"{split}: axiom audit count mismatch\n"+p.stdout[-6000:]) + receipt["by_split"][split]={"theorems":count,"axiom_free":count, + "source_sha256":hashlib.sha256(original.read_bytes()).hexdigest()} + receipt["kernel_checked"]+=count + assert receipt["kernel_checked"]==192 + receipt["axiom_free"]=True + finally: + (root/"kernel_audit_receipt.json").write_text(json.dumps(receipt,sort_keys=True,indent=2)+"\n") + print("BPD-LG-01 KERNEL:",json.dumps(receipt,sort_keys=True)) + PY + - name: Archive generated sources and independent kernel receipt + if: always() + uses: actions/upload-artifact@v4 + with: + name: bpd-lg01-kernel-pinned-${{ github.run_id }} + path: /tmp/bpd-lg01/ + retention-days: 30 + if-no-files-found: warn diff --git a/README.md b/README.md index e351c155..9a142e98 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,8 @@ and `PYTHONPATH=src python scripts/verify_cryptomania_audit.py`. Reviewers: see [`REVIEW.md`](REVIEW.md). +**New (BPD-01, 2026-11-15):** [interventional separation and looped Lean curriculum](paper/bpd_interventional_separation.md) formalizes routed mechanism-pair coverage, optimal fixed/adaptive probes, clock-versus-state observability floors and a recurrence-repair counterexample. Exact 512-matrix and 96 seeded audits are source-hashed in `output/evaluation_bpd/bpd_01.json`. Reproduce via `python scripts/check_receipts.py --only bpd`. It supplies design mathematics, not a neural decomposition result. + ## Self-designed evaluation and FRC The [HRC-FRC-01 extension](paper/frc_harmonic_self_evaluation.md) studies diff --git a/fixtures/bpd_lean_curriculum_pinned/generate.py b/fixtures/bpd_lean_curriculum_pinned/generate.py new file mode 100644 index 00000000..4f7bf766 --- /dev/null +++ b/fixtures/bpd_lean_curriculum_pinned/generate.py @@ -0,0 +1,156 @@ +"""BPD-LG-01: reproducible source-owned Lean witness/countermodel task family. + +Generated source is a conjectured Lean syntax fixture until a pinned `lean` +compiler actually checks the positive theorem scripts. Negative cases are +independently witnessed by finite countermodels, never emitted as sorry. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +SCHEMA = "BPD-LG-01-v1" +FAMILIES = ("exact", "rw", "rcases", "induction") +DEPTHS = (1, 2, 3, 4) +ROOTS = tuple(range(6)) + + +def split_of(root: int) -> str: + if root in (0, 1, 2, 3): + return "train" + return "dev" if root == 4 else "test" + + +def mk_case(family: str, depth: int, root: int, critical: bool, nuisance: bool) -> dict: + if family not in FAMILIES or depth not in DEPTHS or root not in ROOTS: + raise ValueError("unsupported family/depth/root") + stem = f"bpd_{family}_d{depth}_r{root}_{int(critical)}_{int(nuisance)}" + name = "thm_" + stem + extra = " (noise : Nat)" if nuisance else "" + proof = None + countermodel = None + if family == "exact": + props = " ".join(f"P{i}" for i in range(depth + 1)) + hyps = "" if not critical else " (h0 : P0)" + hyps += "".join(f" (h{i} : P{i-1} → P{i})" for i in range(1, depth + 1)) + statement = f"theorem {name} ({props} : Prop){hyps}{extra} : P{depth} := by" + if critical: + term = "h0" + for i in range(1, depth + 1): + term = f"h{i} ({term})" + proof = " exact " + term + else: + countermodel = {"P_values": [False] * (depth + 1), "goal": False} + elif family == "rw": + a, b = "a", "b" + for _ in range(depth): + a, b = f"Nat.succ ({a})", f"Nat.succ ({b})" + hyp = " (hEq : a = b)" if critical else "" + statement = f"theorem {name} (a b : Nat){hyp}{extra} : {a} = {b} := by" + if critical: + proof = " rw [hEq]" + else: + countermodel = {"a": 0, "b": 1, "goal": False} + elif family == "rcases": + props = " ".join(f"P{i}" for i in range(depth + 1)) + nested = f"P{depth}" + for j in reversed(range(depth)): + nested = f"(P{j} ∧ {nested})" + hyp = f" (h : {nested})" if critical else "" + statement = f"theorem {name} ({props} : Prop){hyp}{extra} : P{depth} := by" + if critical: + lines = [] + previous = "h" + for i in range(depth): + nxt = f"tail{i}" + lines.append(f" rcases {previous} with ⟨_, {nxt}⟩") + previous = nxt + proof = "\n".join(lines + [f" exact {previous}"]) + else: + countermodel = {"P_values": [False] * (depth + 1), "goal": False} + else: + fn = "fn_" + stem + initial = "0" if critical else "1" + definition = (f"private def {fn} : Nat → Nat\n" + f" | 0 => {initial}\n" + f" | n + 1 => Nat.succ ({fn} n)\n") + expr = "n" + for _ in range(depth): + expr = f"{fn} ({expr})" + statement = f"theorem {name}{extra} : ∀ n : Nat, {expr} = n := by" + if critical: + proof = (f" intro n\n induction n with\n" + f" | zero => rfl\n" + f" | succ n ih =>\n" + f" simpa only [{fn}] using congrArg Nat.succ ih") + else: + countermodel = {"n": 0, "actual_at_zero": depth, "goal": False} + statement = definition + "\n" + statement + return { + "schema": SCHEMA, "case_id": stem, + "root_id": f"{family}-d{depth}-r{root}", "split": split_of(root), + "family": family, "structural_depth": depth, + "critical": critical, "nuisance": nuisance, + "public_goal_source": statement.removesuffix(" := by"), + "lean_theorem": statement + "\n" + (proof or " -- Negative: no theorem is sent for Lean proof checking"), + "gold_proof": proof, "countermodel": countermodel, + "host_label": "positive_proof_template" if critical else "negative_countermodel", + "kernel_verified": False, + } + + +def roster() -> list[dict]: + return [mk_case(f, d, r, critical, nuisance) + for f in FAMILIES for d in DEPTHS for r in ROOTS + for critical in (True, False) for nuisance in (False, True)] + + +def check_countermodel(row: dict) -> bool: + if row["critical"]: + return row["countermodel"] is None and row["gold_proof"] is not None + w = row["countermodel"] + d = row["structural_depth"] + if row["family"] in ("exact", "rcases"): + return all(v is False for v in w["P_values"]) and w["goal"] is False + if row["family"] == "rw": + return w == {"a": 0, "b": 1, "goal": False} and (w["a"] + d != w["b"] + d) + return w == {"n": 0, "actual_at_zero": d, "goal": False} and d > 0 + + +def export(out: Path) -> dict: + cases = roster() + out.mkdir(parents=True, exist_ok=True) + by_split = {s: [c for c in cases if c["split"] == s] for s in ("train", "dev", "test")} + for split, rows in by_split.items(): + (out / f"{split}.jsonl").write_text( + "".join(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n" for row in rows)) + proofs = [c["lean_theorem"] for c in rows if c["critical"]] + (out / f"{split}_positives.lean").write_text( + "/- BPD-LG-01 generated positive proof candidates; compile with Lean 4.19.0 -/\n\n" + + "\n\n".join(proofs) + "\n") + assert all(check_countermodel(row) for row in cases) + roots = {s: {r["root_id"] for r in rows} for s, rows in by_split.items()} + assert not roots["train"] & roots["dev"] and not roots["train"] & roots["test"] + assert not roots["dev"] & roots["test"] + report = { + "schema": SCHEMA, "cases": len(cases), + "split_counts": {k: len(v) for k, v in by_split.items()}, + "positive_templates": sum(c["critical"] for c in cases), + "negative_finite_countermodels": sum(not c["critical"] for c in cases), + "families": list(FAMILIES), "depths": list(DEPTHS), + "all_countermodels_verified": True, + "kernel_status": "not_run_by_export; require CI pinned Lean compiler", + "sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(out.glob("*.lean")) + sorted(out.glob("*.jsonl"))}, + } + (out / "manifest.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") + return report + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(export(args.out), sort_keys=True)) diff --git a/output/evaluation_bpd/bpd_01.json b/output/evaluation_bpd/bpd_01.json new file mode 100644 index 00000000..d69f0ca5 --- /dev/null +++ b/output/evaluation_bpd/bpd_01.json @@ -0,0 +1,72 @@ +{ + "binary_matrices": 512, + "branched_witness": { + "adaptive_cost": 2, + "batch_cost": 3 + }, + "checks": { + "adaptive_strict_example": true, + "all_binary_matrices_independent": true, + "clock_fibre_gap": true, + "early_repair_obscures_final": true, + "routing_collision": true, + "visible_fibre_collision": true, + "weighted_multiway_independent": true + }, + "clock_witness": { + "state_clock": 0, + "state_only": 1, + "visible_only": 1 + }, + "evidence": "finite exact deterministic oracle; mathematical proof in paper; no neural or Lean model measurements", + "refill_witness": { + "baseline": [ + 1, + 1, + 1, + 1 + ], + "persistent_cut_final": 0, + "single_cut_final": [ + 1, + 1, + 1, + 0 + ], + "single_cut_trajectories": [ + [ + 0, + 1, + 1, + 1 + ], + [ + 1, + 0, + 1, + 1 + ], + [ + 1, + 1, + 0, + 1 + ], + [ + 1, + 1, + 1, + 0 + ] + ], + "terminal_blind_early_cuts": 3 + }, + "schema": "BPD-01-v1", + "source_sha256": { + "paper/bpd_interventional_separation.md": "a1738c49c47bf1efa1aa2ce177305711ce93852b8d4fef47b57d3bf2f18fd7ac", + "scripts/verify_evaluation_bpd.py": "a43cbbb642fe3b8d1283f1f4b8b91fbcebef3e50f6079f30b46f98bba54bc835", + "src/spiral_ln/evaluation_bpd.py": "9c0e1d386dd2335ab43b970e604e073c72afc3e2e4512a1f75a0cb0a1c6a8062", + "tests/test_evaluation_bpd.py": "76ba84ca0930e89ae5534a72d6688c5c80f3dc9462c1bdc924bf899a4b045412" + }, + "weighted_categorical_cases": 96 +} diff --git a/paper/bpd_interventional_separation.md b/paper/bpd_interventional_separation.md new file mode 100644 index 00000000..ad4000b3 --- /dev/null +++ b/paper/bpd_interventional_separation.md @@ -0,0 +1,104 @@ +# BPD-01: Interventional separation for behavioral parameter decomposition and looped Lean gyms + +**Status (2026-11-15):** mathematical proofs for a finite deterministic interface; independent exhaustive CPU checks; synthetic examples. No model weights, candidate VPD dictionaries, Lean kernel, or physical interventions were evaluated here. This note extends the *experiment design* side of [MP-02](metaprune_set_cover.md) and [QI-02](active_quotient_information_budget.md); it does not imply an existing neural decomposition works. + +## 1. The question the dataset must answer + +A behavioral parameter decomposition (BPD) proposes mechanisms or rival explanations \(H=\{h_0,\ldots,h_{n-1}\}\). An evaluation cell \(e\) is an **item plus a precisely specified intervention, target expert, recurrent pass and readout**. For now each cell has a deterministic known outcome \(y_e(h)\) in a finite categorical alphabet, a positive integer measurement cost \(w_e\), and a fixed routing bit \(r_e\). Only cells with \(r_e=1\) are usable. The routing bit is fixed across hypotheses; a routing failure is **missing data**, never evidence of an unchanged outcome. If expert routing depends on the hidden mechanism, it must be modeled as a separately observed stochastic channel rather than silently treated as a binary failure. + +Let \(P=\{\{h_i,h_j\}:i1} +\left[w_e+\max_{B\in\Pi_e(A)}D(B)\right], +\tag{BPD-3} +\] + +where \(\Pi_e(A)\) partitions \(A\) by the observed categorical response. The value is infinite if no informative cell exists. This recurrence equals optimal worst-case identification cost for deterministic adaptive policies. **Proof.** Every valid decision tree chooses some informative first cell and must solve its realized response class. Condition on the first response for the lower bound; attach optimal subtrees for the upper bound. Strictly smaller response classes make the recursion well founded. Consequently \(D(H)\le C_{\rm batch}\), with strict inequality possible. + +A four-mechanism witness has three unit-cost probes with outcome rows + +| Probe | h0 | h1 | h2 | h3 | +|---|---:|---:|---:|---:| +| root | 0 | 0 | 1 | 1 | +| left | 0 | 1 | 0 | 0 | +| right | 0 | 0 | 0 | 1 | + +A fixed separating batch needs all three. Querying `root`, then only `left` or `right` according to the answer, needs at most two. Turning off routing for `left` makes \(h_0,h_1\) indistinguishable; both optimizers correctly return infeasibility. + +## 2. Clock and visibility as measurable finite fibres + +To compare causal-importance predictors, collect **intervention labels** on records indexed by `(case, component, intervention type, state, pass, visible)`. The binary label is a declared intervention outcome, such as a thresholded change in the exact proof-checker result. It is not silently replaced by a final-answer correctness label. For any feature projection \(\phi\), let \(F_z=\{i:\phi(i)=z\}\) be the resulting finite fibres, with integer weights \(a_i>0\) and binary labels \(b_i\). + +**BPD-01/T3 (finite feature-fibre error floor, algebraic identity).** Among all deterministic binary predictors allowed to inspect only \(\phi(i)\), the minimum weighted 0-1 error is exactly + +\[ +L^*(\phi)=\sum_z \min\!\left(\sum_{i\in F_z:b_i=0}a_i,\sum_{i\in F_z:b_i=1}a_i\right). +\tag{BPD-4} +\] + +**Proof.** A deterministic predictor must issue one label per fibre. Choosing the majority label minimizes errors independently on each fibre; summing achieves the lower bound. Ties admit either choice. This result needs no statistical model and is exact even if all component labels are wrong; causal interpretation requires separately validated interventions. + +Compare three projections with `case`, `component` and `intervention` always fixed: + +- **state-only:** add the carried-state identifier; +- **state + clock:** add the same state identifier and pass index; +- **visible-only:** add the projected head-readable identifier. + +The state + clock projection refines state-only, so \(L^*_{\mathrm{state+clock}}\le L^*_{\mathrm{state}}\). A strict gap **certifies that the observed labelled records cannot be fit by a deterministic state-only importance rule**. A visible-only gap certifies loss of information relative to the tested richer interface only when comparing on the same cases and labels. It does not establish that the hidden representation is intrinsically uninterpretable or that clocks cause differences without controlled trajectory matching. + +A finite test contains two records at the same carried state and component, at passes 0 and 1, with labels 0 and 1. Adding the clock reduces the irreducible error from one to zero. A third record changes full state while preserving visible readout, exhibiting the visible collision. Identical state IDs must be produced by a calibrated matching protocol; rounded embedding hashes do not certify exact state equality. + +## 3. Refill makes final-only importance underestimate path importance + +**BPD-01/T4 (synthetic counterexample).** Let a loop refresh a one-bit carried component from an input bit \(x=1\) at each of \(T\ge2\) boundaries. Erasing the component at any boundary \(t dict: + checked = 0 + for pattern in product(range(8), repeat=3): + probes = tuple(Probe(str(i), tuple((bit >> j) & 1 for j in range(3))) + for i, bit in enumerate(pattern)) + dp = minimum_batch(probes) + brute = exhaustive_batch(probes) + assert dp == brute + adaptive = adaptive_worst_cost(probes) + assert (dp is None) == (adaptive is None) + if dp is not None: + assert adaptive <= dp[0] + checked += 1 + rng = random.Random(11617) + weighted = 0 + for _ in range(96): + n = rng.randrange(2, 6) + probes = tuple(Probe(str(i), tuple(rng.randrange(3) for _ in range(n)), + rng.randrange(1, 5), rng.choice((True, False, True))) + for i in range(rng.randrange(1, 7))) + dp = minimum_batch(probes) + assert dp == exhaustive_batch(probes) + adaptive = adaptive_worst_cost(probes) + assert (dp is None) == (adaptive is None) + if dp is not None: + assert adaptive <= dp[0] + weighted += 1 + branch = (Probe("root", (0, 0, 1, 1)), Probe("left", (0, 1, 0, 0)), + Probe("right", (0, 0, 0, 1))) + switched = (branch[0], Probe("left", branch[1].outcomes, routed=False), branch[2]) + samples = [ + {"case": "g", "component": "c", "intervention": "single", "state": "s0", "visible": "v", "pass": 0, "label": 0}, + {"case": "g", "component": "c", "intervention": "single", "state": "s0", "visible": "v", "pass": 1, "label": 1}, + {"case": "g", "component": "c", "intervention": "single", "state": "s1", "visible": "v", "pass": 2, "label": 1}, + ] + floor = clock_visibility_floors(samples) + witness = refill_witness(4, 1) + checks = { + "all_binary_matrices_independent": checked == 512, + "weighted_multiway_independent": weighted == 96, + "adaptive_strict_example": minimum_batch(branch)[0] == 3 and adaptive_worst_cost(branch) == 2, + "routing_collision": coverage(switched)["separated_pairs"] == 5 and minimum_batch(switched) is None, + "clock_fibre_gap": (floor["state_only"]["minimum_errors"],floor["state_clock"]["minimum_errors"]) == (1, 0), + "visible_fibre_collision": floor["visible_only"]["minimum_errors"] == 1, + "early_repair_obscures_final": witness["terminal_blind_early_cuts"] == 3 and witness["persistent_cut_final"] == 0, + } + assert all(checks.values()) + return { + "schema": "BPD-01-v1", + "evidence": "finite exact deterministic oracle; mathematical proof in paper; no neural or Lean model measurements", + "binary_matrices": checked, + "weighted_categorical_cases": weighted, + "branched_witness": {"batch_cost": 3, "adaptive_cost": 2}, + "clock_witness": {key: value["minimum_errors"] for key, value in floor.items()}, + "refill_witness": witness, + "checks": checks, + "source_sha256": {p: sha256((ROOT / p).read_bytes()).hexdigest() for p in SOURCE_FILES}, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=ROOT / "output/evaluation_bpd/bpd_01.json") + args = parser.parse_args() + result = verify() + path = args.output + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(f"BPD-01 {result['binary_matrices']} exhaustive + {result['weighted_categorical_cases']} seeded; {len(result['checks'])} checks passed") + + +if __name__ == "__main__": + main() diff --git a/src/spiral_ln/evaluation_bpd.py b/src/spiral_ln/evaluation_bpd.py new file mode 100644 index 00000000..cd6945c8 --- /dev/null +++ b/src/spiral_ln/evaluation_bpd.py @@ -0,0 +1,221 @@ +"""BPD-01: exact finite observability and curriculum probe selection. + +The rows describe hypothetical deterministic mechanism outcomes, not measured +neural components. Unrouted rows have zero information. A missing outcome is +not interpreted as a negative. All optimization costs are positive integers. +""" +from __future__ import annotations + +from dataclasses import dataclass +from functools import lru_cache +from itertools import combinations +from collections import defaultdict, Counter +from typing import Iterable + + +@dataclass(frozen=True) +class Probe: + name: str + outcomes: tuple[int, ...] + cost: int = 1 + routed: bool = True + + +def validate(probes: Iterable[Probe]) -> tuple[tuple[Probe, ...], int]: + rows = tuple(probes) + if not rows or not all(isinstance(e, Probe) for e in rows): + raise ValueError("nonempty sequence of Probe records required") + n = len(rows[0].outcomes) + if n < 2 or len({p.name for p in rows}) != len(rows): + raise ValueError("at least two hypotheses and unique probe names required") + for p in rows: + if (not isinstance(p.name, str) or not p.name or type(p.cost) is not int + or p.cost <= 0 or type(p.routed) is not bool + or len(p.outcomes) != n or any(type(x) is not int or x < 0 + for x in p.outcomes)): + raise ValueError("invalid probe shape, cost, routing or categorical outcome") + return rows, n + + +def pairs(n: int) -> tuple[tuple[int, int], ...]: + return tuple(combinations(range(n), 2)) + + +def masks(probes: Iterable[Probe]) -> tuple[tuple[int, ...], tuple[tuple[int, int], ...]]: + rows, n = validate(probes) + ps = pairs(n) + return (tuple(sum(1 << k for k, (i, j) in enumerate(ps) + if p.routed and p.outcomes[i] != p.outcomes[j]) + for p in rows), ps) + + +def quotient(probes: Iterable[Probe]) -> tuple[tuple[int, ...], ...]: + """Observational equivalence classes of candidate mechanisms.""" + rows, n = validate(probes) + classes: dict[tuple[int, ...], list[int]] = defaultdict(list) + for i in range(n): + classes[tuple(p.outcomes[i] for p in rows if p.routed)].append(i) + return tuple(sorted((tuple(v) for v in classes.values()), key=lambda x: x[0])) + + +def coverage(probes: Iterable[Probe]) -> dict: + rows, n = validate(probes) + ms, ps = masks(rows) + cover = 0 + for m in ms: + cover |= m + return { + "hypotheses": n, + "probes": len(rows), + "routed_probes": sum(p.routed for p in rows), + "total_pairs": len(ps), + "separated_pairs": cover.bit_count(), + "unresolved_pairs": [list(p) for k, p in enumerate(ps) if not (cover >> k & 1)], + "equivalence_classes": [list(c) for c in quotient(rows)], + } + + +def minimum_batch(probes: Iterable[Probe]) -> tuple[int, tuple[str, ...]] | None: + """Exact minimum-cost NONADAPTIVE set of probes separating every pair.""" + rows, n = validate(probes) + ms, ps = masks(rows) + full = (1 << len(ps)) - 1 + if full & ~_union(ms): + return None + + @lru_cache(None) + def solve(missing: int) -> tuple[int, tuple[int, ...]] | None: + if missing == 0: + return (0, ()) + pivot = missing & -missing + best = None + for j, m in enumerate(ms): + if not m & pivot: + continue + sub = solve(missing & ~m) + if sub is None: + continue + candidate = (rows[j].cost + sub[0], tuple(sorted((j,) + sub[1]))) + if best is None or candidate < best: + best = candidate + return best + + answer = solve(full) + return (answer[0], tuple(rows[i].name for i in answer[1])) if answer else None + + +def _union(values: Iterable[int]) -> int: + r = 0 + for x in values: + r |= x + return r + + +def exhaustive_batch(probes: Iterable[Probe]) -> tuple[int, tuple[str, ...]] | None: + """Independent exhaustive subsets, intentionally not using minimum_batch's DP.""" + rows, n = validate(probes) + if len(rows) > 20: + raise ValueError("exhaustive oracle supports <=20 probes") + ps = pairs(n) + answer = None + for r in range(len(rows) + 1): + for ids in combinations(range(len(rows)), r): + signatures = {tuple(rows[j].outcomes[i] for j in ids if rows[j].routed) + for i in range(n)} + if len(signatures) == n: + candidate = (sum(rows[j].cost for j in ids), ids) + if answer is None or candidate < answer: + answer = candidate + return (answer[0], tuple(rows[i].name for i in answer[1])) if answer else None + + +def adaptive_worst_cost(probes: Iterable[Probe]) -> int | None: + """Optimal worst-case tree depth in cost units, identifying ALL hypotheses.""" + rows, n = validate(probes) + + @lru_cache(None) + def solve(worlds: tuple[int, ...]) -> int | None: + if len(worlds) <= 1: + return 0 + best = None + for probe in rows: + if not probe.routed: + continue + branch: dict[int, list[int]] = defaultdict(list) + for world in worlds: + branch[probe.outcomes[world]].append(world) + if len(branch) < 2: + continue + children = [solve(tuple(v)) for v in branch.values()] + if any(x is None for x in children): + continue + cost = probe.cost + max(children) + if best is None or cost < best: + best = cost + return best + + return solve(tuple(range(n))) + + +def fibre_floor(samples: Iterable[dict], features: tuple[str, ...]) -> dict: + """Exact minimum 0-1 errors for ANY deterministic predictor of `features`. + + Rows sharing an identical feature tuple must receive one prediction. Labels + are 0/1; optional weight is a positive integer. Keys are explicit, so the + caller must include task, intervention, component and observed state IDs. + """ + rows = tuple(samples) + if not rows or not features or len(set(features)) != len(features): + raise ValueError("nonempty samples and unique feature keys required") + fibres: dict[tuple, Counter] = defaultdict(Counter) + for row in rows: + if (row.get("label") not in (0, 1) or type(row.get("label")) is not int + or type(row.get("weight", 1)) is not int or row.get("weight", 1) <= 0): + raise ValueError("binary labels and positive integer weights required") + if any(key not in row or not isinstance(row[key], (str, int)) + or isinstance(row[key], bool) for key in features): + raise ValueError("missing or invalid feature") + fibres[tuple(row[key] for key in features)][row["label"]] += row.get("weight", 1) + disagreements = [(key, min(counts[0], counts[1])) + for key, counts in fibres.items() if counts[0] and counts[1]] + return { + "minimum_errors": sum(v for _, v in disagreements), + "total_weight": sum(sum(c.values()) for c in fibres.values()), + "fibres": len(fibres), + "conflicting_fibres": len(disagreements), + "first_conflict": list(sorted(disagreements, key=lambda x: repr(x[0]))[0][0]) + if disagreements else None, + } + + +def clock_visibility_floors(samples: Iterable[dict]) -> dict: + """Fit bounds, not actual probe accuracy or causal importance estimates.""" + rows = tuple(samples) + base = ("case", "component", "intervention") + return { + "state_only": fibre_floor(rows, base + ("state",)), + "state_clock": fibre_floor(rows, base + ("state", "pass")), + "visible_only": fibre_floor(rows, base + ("visible",)), + } + + +def refill_witness(passes: int = 4, source_bit: int = 1) -> dict: + """Synthetic repeated refresh: early single-pass erasure is rebuilt.""" + if type(passes) is not int or passes < 2 or source_bit not in (0, 1): + raise ValueError("requires >=2 passes and a bit-valued source") + baseline = (source_bit,) * passes + single_final = [] + single_trajectories = [] + for cut in range(passes): + path = list(baseline) + path[cut] = 0 + single_trajectories.append(path) + single_final.append(path[-1]) + persistent = (0,) * passes + return { + "baseline": list(baseline), + "single_cut_final": single_final, + "single_cut_trajectories": single_trajectories, + "persistent_cut_final": persistent[-1], + "terminal_blind_early_cuts": sum(final == source_bit for final in single_final[:-1]), + } diff --git a/tests/test_evaluation_bpd.py b/tests/test_evaluation_bpd.py new file mode 100644 index 00000000..db7e57e3 --- /dev/null +++ b/tests/test_evaluation_bpd.py @@ -0,0 +1,113 @@ +"""BPD-01 independent exhaustive optimizer and schedule-fibre audits.""" +import itertools +import random +import unittest + +from spiral_ln.evaluation_bpd import ( + Probe, adaptive_worst_cost, clock_visibility_floors, coverage, + exhaustive_batch, fibre_floor, minimum_batch, quotient, refill_witness, +) + + +class BpdTests(unittest.TestCase): + def test_branched_adaptive_strict_gain(self): + # Root separates branches; conditional selectors are disjoint. + ps = (Probe("root", (0, 0, 1, 1)), + Probe("left", (0, 1, 0, 0)), + Probe("right", (0, 0, 0, 1))) + self.assertEqual(coverage(ps)["separated_pairs"], 6) + self.assertEqual(minimum_batch(ps), (3, ("root", "left", "right"))) + self.assertEqual(exhaustive_batch(ps), minimum_batch(ps)) + self.assertEqual(adaptive_worst_cost(ps), 2) + + def test_routing_removes_information(self): + ps = (Probe("root", (0, 0, 1, 1)), + Probe("left", (0, 1, 0, 0), routed=False), + Probe("right", (0, 0, 0, 1))) + self.assertEqual(coverage(ps)["separated_pairs"], 5) + self.assertEqual(quotient(ps), ((0, 1), (2,), (3,))) + self.assertIsNone(minimum_batch(ps)) + self.assertIsNone(adaptive_worst_cost(ps)) + self.assertIsNone(exhaustive_batch(ps)) + + def test_exhaustive_binary_cases(self): + checked = 0 + for code in itertools.product(range(8), repeat=3): + ps = tuple(Probe(f"p{i}", tuple(m >> j & 1 for j in range(3))) + for i, m in enumerate(code)) + self.assertEqual(minimum_batch(ps), exhaustive_batch(ps)) + batches = minimum_batch(ps) + cost = adaptive_worst_cost(ps) + self.assertEqual(batches is None, cost is None) + if batches is not None: + self.assertLessEqual(cost, batches[0]) + checked += 1 + self.assertEqual(checked, 512) + + def test_seeded_weights_multiway(self): + rng = random.Random(11617) + for _ in range(96): + n = rng.randrange(2, 6) + ps = tuple(Probe(str(i), tuple(rng.randrange(3) for _ in range(n)), + rng.randrange(1, 5), rng.choice((True, False, True))) + for i in range(rng.randrange(1, 7))) + self.assertEqual(minimum_batch(ps), exhaustive_batch(ps)) + ans = minimum_batch(ps) + adaptive = adaptive_worst_cost(ps) + self.assertEqual(ans is None, adaptive is None) + if ans is not None: + self.assertLessEqual(adaptive, ans[0]) + + def test_clock_and_visibility_collision(self): + records = [ + {"case": "g1", "component": "c7", "intervention": "single", + "state": "s0", "visible": "v0", "pass": 0, "label": 0}, + {"case": "g1", "component": "c7", "intervention": "single", + "state": "s0", "visible": "v0", "pass": 1, "label": 1}, + {"case": "g1", "component": "c7", "intervention": "single", + "state": "s1", "visible": "v0", "pass": 2, "label": 1}, + ] + got = clock_visibility_floors(records) + self.assertEqual(got["state_only"]["minimum_errors"], 1) + self.assertEqual(got["state_clock"]["minimum_errors"], 0) + self.assertEqual(got["visible_only"]["minimum_errors"], 1) + self.assertEqual(got["visible_only"]["total_weight"], 3) + + def test_weighted_fibre_and_missing_inputs(self): + rows = [{"s": "x", "label": 0, "weight": 3}, + {"s": "x", "label": 1, "weight": 4}, + {"s": "y", "label": 1, "weight": 2}] + self.assertEqual(fibre_floor(rows, ("s",))["minimum_errors"], 3) + with self.assertRaises(ValueError): + fibre_floor([{"s": "x", "label": 1, "weight": 0}], ("s",)) + with self.assertRaises(ValueError): + fibre_floor([{"s": "x", "label": True}], ("s",)) + with self.assertRaises(ValueError): + fibre_floor([{"label": 1}], ("s",)) + + def test_early_repair_masks_terminal(self): + w = refill_witness(4) + self.assertEqual(w["baseline"], [1, 1, 1, 1]) + self.assertEqual(w["single_cut_final"], [1, 1, 1, 0]) + self.assertEqual(w["persistent_cut_final"], 0) + self.assertEqual(w["terminal_blind_early_cuts"], 3) + self.assertEqual(refill_witness(2, 0)["terminal_blind_early_cuts"], 1) + with self.assertRaises(ValueError): + refill_witness(1) + + def test_reject_invalid_probe_shapes(self): + bad = [ + (Probe("same", (0, 1)), Probe("same", (1, 0))), + (Probe("one", (0,)),), + (Probe("cost", (0, 1), cost=0),), + (Probe("bool", (False, True)),), + (Probe("badroute", (0, 1), routed=1),), + (Probe("mismatch", (0, 1)), Probe("other", (0, 1, 2))), + ] + for ps in bad: + with self.assertRaises(ValueError): + coverage(ps) + + +if __name__ == "__main__": + unittest.main()