diff --git a/.github/workflows/roc01-evalmath.yml b/.github/workflows/roc01-evalmath.yml new file mode 100644 index 00000000..ba4d32bd --- /dev/null +++ b/.github/workflows/roc01-evalmath.yml @@ -0,0 +1,42 @@ +name: ROC-01 EvalMath observer type and evidence scorer +on: + push: + paths: + - 'research/observer_calculus/**' + - 'tests/test_roc01_evaluator.py' + - '.github/workflows/roc01-evalmath.yml' + pull_request: + paths: + - 'research/observer_calculus/**' + - 'tests/test_roc01_evaluator.py' + - '.github/workflows/roc01-evalmath.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + exact-intervention-separation: + runs-on: ubuntu-24.04 + timeout-minutes: 12 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Reject unverified ROC cards and score BPD-01 exact cover + env: + PYTHONPATH: src:. + run: | + python -m compileall -q research/observer_calculus + python -m unittest tests.test_roc01_evaluator -v + - name: Export hypothetical five-type intervention-card receipt + env: + PYTHONPATH: src:. + run: | + python - <<'PY' + import json + from research.observer_calculus.roc01_evaluator import idealized_example + r=idealized_example() + assert r["min_cost"]==3 + assert r["causal_identification_ready"] is False + print(json.dumps(r,sort_keys=True)) + PY diff --git a/research/observer_calculus/README.md b/research/observer_calculus/README.md new file mode 100644 index 00000000..1cd4eecb --- /dev/null +++ b/research/observer_calculus/README.md @@ -0,0 +1,61 @@ +# ROC-01 EvalMath: register and score causal observer interventions + +**Public MathCan source pin:** patrickdugan/MathCan at +37bbac210c175ccb98e0ff0d4aa8bdd2be0764e6, +branch research/roc01-unified-observer-card-20261116. +It includes Parts 0–4, report-card code, exact-rational counterexamples, +a Lean finite witness and source-derived NRF v0.4 partial cards. + +The canonical physical observer calculation lives in +MathCan/research/observer_calculus/observer_card.py. It measures A, B and C +from the computed-change Jacobian D=T-I and s from OLM-07's output +Gramian H. EvalMath's local roc01_evaluator.py scores the **declared +intervention hypothesis contract** through the existing BPD-01 exact +finite minimum-test-cover implementation. + +For five idealized mechanism exemplars, BPD-01 identifies one three-arm +minimum set as dark-to-observed, observed-to-dark and **observed-to-observed**. Two other size-three covers exist. Readout ablation remains mandatory as a +control even if omitted from one ideal separating set. Under a *physical* +freeze-U intervention, both A and B are removed together; the invariant +subspace and register signatures become indistinguishable. Thus the frozen +freeze-U four-arm table does not separate all five synthetic types. The +corrected selective within-observed arm and its exact KL allocation are +specified in MathCan's dated ROC01_AMENDMENT_2026-11-16C.md. These labels can overlap in actual nonlinear networks, so +this table is a synthetic protocol demonstration, not a measurement +of real trained weights. + +The audit_observer_card function also requires the rank-specific null median, +a six-direction Holm-corrected p-value family and a verified rank-relative +B penalty, as stipulated by amendment C. It refuses to certify a complete +report with +missing or blank per-state A/B/C/s/MSE, missing D/H norms, fewer than 100 +**distinct** rank-matched random bases, unpublished per-state rows, +unequal task-only training, absent norm-matched random intervention arms, +or an undeclared output. Existing NRF/SPC eight-way random controls fail +this gate. The function treats source publication and control counts as +caller attestations. The public source, checkpoint and null rows require +independent verification before a scientific claim. A categorical +intervention table can be separable while the observer card is incomplete, +so identify_types requires a complete card audit for causal promotion. + +Run exact small tests from EvalMath root: + + PYTHONPATH=src:. python -m unittest tests.test_roc01_evaluator -v + +For numeric card replay use the public MathCan script and exact source +inputs, including NRF's 1,584 per-state CSV rows and the per-seed paired +W_delta/rho_delta decomposition. The original checkpoint files are not +committed to public MathCan, and the new normalized card/closure sweep +cannot be credited with neural results from those missing inputs. + +## ROC-02 protocol boundary (amendment C, 2026-11-16) + +The original ROC-01 registration and Part 4 remain frozen for provenance. +Prospective ROC-02 uses ranks {1,2,3,4,7,8,12,16,32}, with SPC rank 7 +included explicitly. The new tag gate compares a,b,c,s against 128 +rank-matched null bases on the same frozen state, rather than applying the +old absolute thresholds. Null degeneracy returns unclassified, and the +penalty uses squared B divided by its own rank-conditioned median. +A checkpoint-free demonstration or a caller-attested complete card remains +synthetic until its per-state null rows, checkpoint, observer, H and decoder +measurements can be independently replayed. diff --git a/research/observer_calculus/roc01_evaluator.py b/research/observer_calculus/roc01_evaluator.py new file mode 100644 index 00000000..df65cd6d --- /dev/null +++ b/research/observer_calculus/roc01_evaluator.py @@ -0,0 +1,206 @@ +"""ROC-01: an EvalMath validation interface for the public MathCan card. + +The physical card is calculated in MathCan from T, U and output Jacobians. +EvalMath only scores the *declared* categorical intervention predictions: +it applies BPD-01's exact minimum-cost pair-separating cover, and refuses +a causal-confirmation flag when important measurement controls are absent. + +Idealized tables are tutorial fixtures, not neural experiments. +Source pin: patrickdugan/MathCan@37bbac210c175ccb98e0ff0d4aa8bdd2be0764e6 +""" +from __future__ import annotations + +from dataclasses import dataclass +from math import isfinite, isclose +from typing import Mapping, Sequence + +from spiral_ln.evaluation_bpd import ( + Probe, coverage, minimum_batch, adaptive_worst_cost, + identify_hypothesis, NO_HYPOTHESIS_FITS, +) + +MATHCAN_SOURCE="37bbac210c175ccb98e0ff0d4aa8bdd2be0764e6" +REQUIRED_METRICS=("A_normalized","B_normalized","C_normalized", + "s_causal","task_mse","D_frob","H_trace") +ALLOWED_ARMS=("dark_to_observed","observed_to_dark", + "observed_to_observed","ablate_readout") + + +@dataclass(frozen=True) +class InterventionObservation: + name: str + outcomes: tuple[int, ...] + cost: int + routed: bool + measured: bool + checkpoint_sha256: str + observer_sha256: str + next_readout: int + intervention_pass: int + norm_matched_random: bool + + def __post_init__(self): + if (self.name not in ALLOWED_ARMS + or len(self.outcomes)<2 + or any(type(x) is not int or x<0 for x in self.outcomes) + or type(self.cost) is not int or self.cost<1 + or type(self.routed) is not bool + or type(self.measured) is not bool + or type(self.norm_matched_random) is not bool + or not self.checkpoint_sha256 or not self.observer_sha256 + or type(self.intervention_pass) is not int + or type(self.next_readout) is not int + or self.intervention_pass<0 + or self.next_readout<=self.intervention_pass): + raise ValueError("Malformed source-bound ROC intervention") + + +def identify_types(rows: Sequence[InterventionObservation], + realized: Mapping[str,int|None]|None=None, + *, card_audit: Mapping|None=None) -> dict: + if not rows: raise ValueError("Nonempty mechanism arms required") + if len({r.name for r in rows})!=len(rows): + raise ValueError("Duplicate intervention names") + checkpoint={r.checkpoint_sha256 for r in rows} + observers={r.observer_sha256 for r in rows} + times={(r.intervention_pass,r.next_readout) for r in rows} + if len(checkpoint)!=1 or len(observers)!=1 or len(times)!=1: + raise ValueError("Source, observer and clock must stay frozen across probes") + if len({len(x.outcomes) for x in rows})!=1: + raise ValueError("Mechanism hypothesis family must be fixed") + probes=tuple(Probe(r.name,r.outcomes,r.cost,r.routed) for r in rows) + cov=coverage(probes) + minset=minimum_batch(probes) + result={ + "source_mathcan_sha":MATHCAN_SOURCE, + "covered_pairs":cov["separated_pairs"], + "unresolved_pairs":cov["unresolved_pairs"], + "equivalence_classes":cov["equivalence_classes"], + "min_cost":minset[0] if minset is not None else None, + "min_arms":list(minset[1]) if minset is not None else None, + "adaptive_worst_cost":adaptive_worst_cost(probes), + "measured":all(r.measured for r in rows), + "all_norm_matched":all(r.norm_matched_random for r in rows), + "intervention_arms_complete":set(r.name for r in rows)==set(ALLOWED_ARMS), + } + result["finite_intervention_separation_ready"]=bool( + result["measured"] and result["all_norm_matched"] + and result["intervention_arms_complete"] + and not result["unresolved_pairs"] + ) + # A finite type table can be source-consistent yet lack the causal Gram, + # same-state task loss, checkpoint record or 128 valid null bases. + # Do not promote its categorical separation alone into a full observer claim. + result["causal_identification_ready"]=bool( + result["finite_intervention_separation_ready"] + and card_audit is not None + and card_audit.get("complete") is True + and card_audit.get("source_mathcan_sha")==MATHCAN_SOURCE + ) + if realized is not None: + result["realized"]=identify_hypothesis(probes,realized) + return result + + +def audit_observer_card(card: Mapping, *, random_count:int, + task_only_equal_budget:bool, + every_intervention_norm_matched:bool, + output_declared:bool, + distinct_random_bases:int|None=None, + per_state_rows_public:bool=False, + null_calibration:Mapping|None=None) -> dict: + """Fail closed for incomplete or nonnumeric ROC measurements. + + Control flags are caller attestations and must be independently audited + against the pinned public source receipts. In particular, 128 attempts at + a unique readout-containing rank-k basis are not 128 distinct null bases. + """ + absent=[] + invalid=[] + for key in REQUIRED_METRICS: + value=card.get(key) + if value is None or value=="": + absent.append(key) + continue + if type(value) not in (int,float) or not isfinite(value) or value<0: + invalid.append(key) + continue + if key in ("A_normalized","B_normalized","C_normalized","s_causal") and value>1+1e-8: + invalid.append(key) + if ("s_causal" not in absent and "s_causal" not in invalid + and "H_trace" not in absent and "H_trace" not in invalid + and card["H_trace"]<=0): + invalid.append("s_causal_with_zero_H") + unique_ok=bool( + type(random_count) is int and random_count>=100 + and type(distinct_random_bases) is int + and 100<=distinct_random_bases<=random_count + ) + # ROC-02 supersedes absolute tag cutoffs with rank-conditional null + # medians and a fixed six-direction Holm family. Counts alone cannot + # certify the new diagnostic or the leakage-penalty denominator. + cal=null_calibration + directions={"a_small","b_small","c_small","b_large","s_high","s_low"} + null_ok=False + if isinstance(cal,Mapping): + med=cal.get("null_medians") + raw=cal.get("one_sided_p") + adj=cal.get("holm_adjusted_p") + penalty=cal.get("b_penalty_ratio_squared") + if (cal.get("schema")=="roc01.null_relative_six_direction.v1" + and cal.get("tag_status")=="null_calibrated" + and type(cal.get("distinct_null_subspaces")) is int + and cal.get("distinct_null_subspaces")==distinct_random_bases + and isinstance(med,Mapping) and isinstance(raw,Mapping) + and isinstance(adj,Mapping) + and set(raw)==directions and set(adj)==directions + and type(med.get("B_normalized")) in (int,float) + and isfinite(med["B_normalized"]) and med["B_normalized"]>0 + and type(penalty) in (int,float) and isfinite(penalty) + and penalty>=0 and type(card.get("B_normalized")) in (int,float)): + p_ok=all( + type(raw[k]) in (int,float) and type(adj[k]) in (int,float) + and isfinite(raw[k]) and isfinite(adj[k]) + and 0<=raw[k]<=adj[k]<=1 for k in directions + ) + expected=(card["B_normalized"]/med["B_normalized"])**2 + null_ok=bool(p_ok and isfinite(expected) + and isclose(penalty,expected,rel_tol=1e-8, + abs_tol=1e-10)) + required=bool( + null_ok and unique_ok and task_only_equal_budget + and every_intervention_norm_matched and output_declared + and per_state_rows_public and not absent and not invalid + ) + return {"source_mathcan_sha":MATHCAN_SOURCE, + "complete":required,"missing_metrics":absent, + "invalid_metrics":invalid, + "random_count":random_count, + "distinct_random_bases":distinct_random_bases, + "random_rank_valid":unique_ok, + "rank_null_calibration_valid":null_ok, + "task_only_equal_budget":task_only_equal_budget, + "norm_matched_interventions":every_intervention_norm_matched, + "output_declared":output_declared, + "per_state_rows_public":per_state_rows_public, + "trust_boundary":"caller control attestation; independently verify pinned public Git blobs"} + + +IDEAL_TABLE={ + "dark_to_observed":(0,1,0,1,0), + "observed_to_dark":(1,0,1,0,0), + "observed_to_observed":(1,1,0,0,0), + "ablate_readout":(1,1,1,1,0), +} +IDEAL_LABELS=("closed_quotient","invariant_subspace", + "latched_memory","output_register","irrelevant") + + +def idealized_example()->dict: + rows=[InterventionObservation( + name,tuple(outcome),1,True,False,"synthetic","synthetic",2,1,False) + for name,outcome in IDEAL_TABLE.items()] + out=identify_types(rows) + out["source_type"]="hypothetical_finite_signatures_not_neural_evidence" + out["mechanism_labels"]=IDEAL_LABELS + return out diff --git a/tests/test_roc01_evaluator.py b/tests/test_roc01_evaluator.py new file mode 100644 index 00000000..cb765b06 --- /dev/null +++ b/tests/test_roc01_evaluator.py @@ -0,0 +1,148 @@ +"""ROC-01 EvalMath T1 bridge tests from a publicly pinned MathCan card schema.""" +import unittest +from pathlib import Path +import sys + +# Repository-wide installed-package pytest excludes the source root. +# Make the public source-only review package importable in that job. +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from research.observer_calculus.roc01_evaluator import ( + IDEAL_TABLE, InterventionObservation, identify_types, idealized_example, + audit_observer_card, MATHCAN_SOURCE +) +from spiral_ln.evaluation_bpd import NO_HYPOTHESIS_FITS + +DIRECTIONS=("a_small","b_small","c_small","b_large","s_high","s_low") + + +def fake_calibration(card): + """Synthetic caller attestation; independent public receipts still needed.""" + return { + "schema":"roc01.null_relative_six_direction.v1", + "tag_status":"null_calibrated", + "distinct_null_subspaces":128, + "null_medians":{"B_normalized":1.0}, + "b_penalty_ratio_squared":0.0, + "one_sided_p":{k:1.0 for k in DIRECTIONS}, + "holm_adjusted_p":{k:1.0 for k in DIRECTIONS}, + } + + +def audit_with_calibration(card, **kwargs): + return audit_observer_card(card,null_calibration=fake_calibration(card),**kwargs) + + + +def arm(name,outcomes,*,measured=False,norm=False,routed=True): + return InterventionObservation( + name,tuple(outcomes),1,routed,measured,"checkpoint","basis",2,1,norm) + + +class ROC01EvaluatorTest(unittest.TestCase): + def test_old_freeze_arm_and_uncalibrated_card_fail(self): + with self.assertRaises(ValueError): + arm("freeze_U",(1,1,0,1,0)) + c={k:0.0 for k in ("A_normalized","B_normalized", + "C_normalized","s_causal","task_mse","D_frob","H_trace")} + c["H_trace"]=1.0 + args=dict(random_count=128,distinct_random_bases=128, + per_state_rows_public=True,task_only_equal_budget=True, + every_intervention_norm_matched=True,output_declared=True) + self.assertFalse(audit_observer_card(c,**args)["complete"]) + self.assertFalse(audit_observer_card(c,**args)["rank_null_calibration_valid"]) + bad=fake_calibration(c) + bad["b_penalty_ratio_squared"]=2 + self.assertFalse(audit_observer_card( + c,null_calibration=bad,**args)["complete"]) + + + def test_ideal_five_exemplars_need_three_arms(self): + out=idealized_example() + self.assertEqual(out["min_cost"],3) + self.assertEqual(out["min_arms"], + ["dark_to_observed","observed_to_dark","observed_to_observed"]) + self.assertEqual(out["covered_pairs"],10) + self.assertFalse(out["causal_identification_ready"]) + self.assertEqual(out["source_mathcan_sha"],MATHCAN_SOURCE) + + def test_unknown_route_remains_missing(self): + rows=[arm(k,v,routed=k=="ablate_readout") + for k,v in IDEAL_TABLE.items()] + out=identify_types(rows) + self.assertIsNone(out["min_cost"]) + self.assertTrue(out["unresolved_pairs"]) + self.assertFalse(out["causal_identification_ready"]) + + def test_no_hypothesis_fits_is_explicit(self): + rows=[arm(k,v) for k,v in IDEAL_TABLE.items()] + out=identify_types(rows,{"dark_to_observed":2}) + self.assertEqual(out["realized"],NO_HYPOTHESIS_FITS) + + def test_valid_complete_card_gates(self): + c={k:0.0 for k in ("A_normalized","B_normalized", + "C_normalized","s_causal","task_mse","D_frob","H_trace")} + c["H_trace"]=1.0 + passed=audit_with_calibration(c,random_count=128, + distinct_random_bases=128,per_state_rows_public=True, + task_only_equal_budget=True, + every_intervention_norm_matched=True, + output_declared=True) + self.assertTrue(passed["complete"]) + insufficient=audit_with_calibration(c,random_count=8, + distinct_random_bases=8,per_state_rows_public=True, + task_only_equal_budget=True, + every_intervention_norm_matched=True, + output_declared=True) + self.assertFalse(insufficient["complete"]) + self.assertFalse(insufficient["random_rank_valid"]) + missing=audit_with_calibration({k:None for k in c}, + random_count=128,distinct_random_bases=128, + per_state_rows_public=True,task_only_equal_budget=True, + every_intervention_norm_matched=True,output_declared=True) + self.assertFalse(missing["complete"]) + self.assertEqual(len(missing["missing_metrics"]),7) + blank={**c,"B_normalized":""} + self.assertIn("B_normalized",audit_with_calibration( + blank,random_count=128,distinct_random_bases=128, + per_state_rows_public=True,task_only_equal_budget=True, + every_intervention_norm_matched=True, + output_declared=True)["missing_metrics"]) + self.assertFalse(audit_with_calibration( + c,random_count=128,distinct_random_bases=1, + per_state_rows_public=True,task_only_equal_budget=True, + every_intervention_norm_matched=True,output_declared=True)["complete"]) + self.assertFalse(audit_with_calibration( + c,random_count=128,distinct_random_bases=128, + per_state_rows_public=False,task_only_equal_budget=True, + every_intervention_norm_matched=True,output_declared=True)["complete"]) + + def test_unmeasured_missing_controls_not_promoted(self): + rows=[arm(k,v,measured=True,norm=True) for k,v in IDEAL_TABLE.items()] + self.assertTrue(identify_types(rows)["finite_intervention_separation_ready"]) + self.assertFalse(identify_types(rows)["causal_identification_ready"]) + c={k:0.0 for k in ("A_normalized","B_normalized", + "C_normalized","s_causal","task_mse","D_frob","H_trace")} + c["H_trace"]=1.0 + audit=audit_with_calibration( + c,random_count=128,distinct_random_bases=128, + per_state_rows_public=True,task_only_equal_budget=True, + every_intervention_norm_matched=True,output_declared=True) + self.assertTrue(identify_types(rows,card_audit=audit)["causal_identification_ready"]) + changed=rows[:2]+[arm("observed_to_observed",IDEAL_TABLE["observed_to_observed"],norm=False, + measured=True)]+rows[3:] + self.assertFalse(identify_types(changed)["causal_identification_ready"]) + with self.assertRaises(ValueError): + identify_types(rows[:1]+[arm("dark_to_observed",(0,1,0,1,0))]) + + def test_disparate_checkpoint_or_clock_rejected(self): + rows=[arm(k,v) for k,v in IDEAL_TABLE.items()] + bad=list(rows) + bad[0]=InterventionObservation( + bad[0].name,bad[0].outcomes,1,True,False, + "different","basis",2,1,False) + with self.assertRaises(ValueError): + identify_types(bad) + +if __name__=="__main__": + unittest.main()