diff --git a/.github/workflows/bpd-rlt-exit-support-guard.yml b/.github/workflows/bpd-rlt-exit-support-guard.yml new file mode 100644 index 00000000..fde60f79 --- /dev/null +++ b/.github/workflows/bpd-rlt-exit-support-guard.yml @@ -0,0 +1,82 @@ +name: BPD pretrained learned exit difficulty support guard + +on: + push: + branches: + - research/rlt-exit-support-guard-20261121 + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/exit_support_guard.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard_audit.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/audit_exit_support_guard.py" + - ".github/workflows/bpd-rlt-exit-support-guard.yml" + pull_request: + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/exit_support_guard.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard_audit.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/audit_exit_support_guard.py" + - ".github/workflows/bpd-rlt-exit-support-guard.yml" + workflow_dispatch: + +permissions: + contents: read + actions: read + +concurrency: + group: bpd-exit-support-guard-${{ github.ref }} + cancel-in-progress: true + +jobs: + guard-eval: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + OPENBLAS_NUM_THREADS: "1" + OMP_NUM_THREADS: "2" + MKL_NUM_THREADS: "2" + HF_HUB_DISABLE_TELEMETRY: "1" + HF_HUB_DISABLE_XET: "1" + PYTHONDONTWRITEBYTECODE: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install CPU model runtime + run: | + python -m pip install "torch==2.5.1+cpu" --index-url https://download.pytorch.org/whl/cpu + python -m pip install "numpy>=1.24,<3" "huggingface_hub>=0.24,<1" + - name: Verify cutoff rule, native state continuation and fresh roots + run: python -m unittest mechinterp.bpd.experiments.inkling_reader_v0.test_exit_support_guard -v + - name: Check independent source-only verifier and resealed tamper controls + run: python -m unittest mechinterp.bpd.experiments.inkling_reader_v0.test_exit_support_guard_audit -v + - name: Fetch immutable original controller + uses: actions/download-artifact@v4 + with: + name: bpd-rlt-learned-exit-first-dev + path: runs/frozen + run-id: 44911864342 + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Predeclared fresh 40/52 blank support-guard comparison + if: github.event_name == 'push' + run: | + timeout --signal=TERM --kill-after=15s 850s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.exit_support_guard \ + --source runs/frozen --model gaoxin492 --roots-per-panel 24 \ + --out runs/rlt_exit_support_guard + - name: Independent replay of exact board grades and frozen stopping decisions + if: github.event_name == 'push' + run: | + python -m mechinterp.bpd.experiments.inkling_reader_v0.audit_exit_support_guard \ + --source runs/rlt_exit_support_guard \ + --frozen runs/frozen/report.json \ + --out runs/rlt_exit_support_guard/independent_audit.json + - name: Retain real paired verifier-grade and timing receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: bpd-rlt-exit-support-guard-new-roots + path: runs/rlt_exit_support_guard/ + if-no-files-found: warn + retention-days: 14 diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/EXIT_SUPPORT_GUARD_DEV_20261121.md b/mechinterp/bpd/experiments/inkling_reader_v0/EXIT_SUPPORT_GUARD_DEV_20261121.md new file mode 100644 index 00000000..e3ed5385 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/EXIT_SUPPORT_GUARD_DEV_20261121.md @@ -0,0 +1,100 @@ +# RLT-EXIT-04: support-aware stopping on fresh 40/52-blank Sudoku roots + +**Date:** 2026-11-21. **Status:** development evidence, real 7M pretrained +Attention-TRM execution with frozen source-only learned stop model. +Original [GitHub Actions run #44914654368](https://github.com/MoralityLabAI/BPD/actions/runs/44914654368) +and independent cross-replayed [run #44915182662](https://github.com/MoralityLabAI/BPD/actions/runs/44915182662) +both succeeded. Full run including the independent offline audit is retained +in artifact bpd-rlt-exit-support-guard-new-roots #14712000093. + +## Registration and source custody + +The original 50-blank controller was trained and calibrated in merged BPD +PR #140, using TRAIN/CAL/DEV source roots distinct from this experiment. +Controller model and threshold were loaded from frozen report SHA-256 +dda473da08434484f4d67e8f0e6fa77b4296d9fa1489a810f529c699dc94a7e1. +The pretrained 7M Attention-TRM checkpoint SHA-256 remains +932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3. + +Merged BPD PR #141 recorded an incorrect learned early stop at 52 blanks. +After seeing that failure, this new support guard was designed using a +public input property. It allows the originally frozen logits-only learned +stop threshold when Sudoku has **at most 50 blanks**; otherwise it runs the +fixed two-step model. The rule is posthoc with respect to the original +difficulty-failure finding and was frozen before collecting the following +fresh development roots. + +- Fresh easy cohort: 24 uniquely solvable 40-blank puzzles, seeds + 20261411 + 101*i. +- Fresh hard cohort: 24 uniquely solvable 52-blank puzzles, seeds + 20261412 + 101*i. +- Input question, both independently checked candidate boards, six + logits-derived features, full checkpoint/threshold/source hashes, + per-policy decision, measured native CPU time, and physical visit + count are saved for every root. +- No pretrained weights, learned logistic coefficients, or threshold + were updated. All prior TRAIN/CAL/DEV roots were excluded by digest; + the previous transfer cohort's registered seeds were excluded. + No protected BPD confirmation/sealed data were opened. + +## Final measured and independently audited outcomes + +The first run and the cross-audited replication produced identical +counts of correct boards, stops and incorrect exits. CPU times varied +slightly with runner scheduling. + +| Cohort/policy | Correct boards | Recurrent outer steps | Native time (audit run) | Wrong early exits | +| --- | ---: | ---: | ---: | ---: | +| 40-blank, fixed 2 | 24/24 | 48 | 11.886519 s | 0 | +| 40-blank, exact verifier exit | 24/24 | 24 | 5.930708 s | 0 | +| 40-blank, original learned exit | 24/24 | 25 | 6.314108 s | 0 | +| 40-blank, **support-guarded learned exit** | **24/24** | **25** | **6.151625 s** | **0** | +| 40-blank, rate-matched random | 24/24 | 39 | 9.807077 s | 0 | +| 52-blank, fixed 2 | 22/24 | 48 | 11.943368 s | 0 | +| 52-blank, exact verifier exit | 22/24 | 41 | 10.159272 s | 0 | +| 52-blank, original learned exit | 22/24 | 42 | 10.495693 s | 0 | +| 52-blank, **support-guarded learned exit** | **22/24** | **48** | **11.774915 s** | **0** | +| 52-blank, rate-matched random | 17/24 | 39 | 9.637505 s | 7 | + +For 40 blanks, the guard conserved 23/48 recurrent outer steps (47.92%) +while retaining 24/24 exact boards. Measured native CPU step time was +48.25% below fixed-two under this runner sample. One first-step +valid board fell just below the original learned classifier threshold, +so the gate executed an unnecessary second step. + +For 52 blanks, the guard necessarily uses the full two-step budget. +It spent six more recurrent steps than the unguarded learned policy, +which happened to make **no incorrect stops on this new 24-root cohort**. +Consequently this new sample demonstrates the guard's adherence to +its frozen support rule and cost, without observing an accuracy gain +from the guard. A distinct older 52-blank cohort did contain one +incorrect learned stop. Preserve both observations; their difference +is finite-sample heterogeneity. + +## Verification and audit scope + +[Independent audit code](audit_exit_support_guard.py) replays the entire +written Sudoku input and candidate board, root lineage, correctness +at each pass, known public difficulty guard, frozen threshold, and +six-feature original trained classifier score. It also recomputes +the deterministic random-control decisions and every aggregate +verifier/cost count, rejecting changed scores and candidates even if +someone has resealed the input file digests. + +The independent audit passed 48/48 roots in the reproducible GitHub +Actions run. Saved report SHA-256: +b5f8d716db1b9b1b069513793fa80afd5d1a787718c50a30ed32a80821444364. +It does **not** reexecute the 7M pretrained neural weights from saved +activations. The original hosted CPU run executed genuine native TRM +recurrence; the replay verifies its archived outputs and policy decisions. + +The scientific claim remains bounded to this posthoc-designed, +development-only support rule. Zero observed false stops across +48 new roots cannot certify a future-zero risk. A prospective +source-root sample with a prespecified acceptable false-stop margin, +paired compute/accuracy inference and cross-task verifiers is required +to claim controlled generalization. + +The TRM's recurrent H/L states are distinct from Inkling's +Attention Residual cross-loop readers. This experiment does not claim +an Inkling feature or Goodfire coordinate-2027 mechanism. diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/audit_exit_support_guard.py b/mechinterp/bpd/experiments/inkling_reader_v0/audit_exit_support_guard.py new file mode 100644 index 00000000..028fb19b --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/audit_exit_support_guard.py @@ -0,0 +1,246 @@ +"""Independently replay exact Sudoku outcomes and policy decisions in RLT-EXIT-04. + +Uses archived text/data and immutable originally trained controller parameters. +This rechecks saved receipts; it does not reexecute pretrained TRM weights. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import random +from pathlib import Path +from typing import Any + +MODEL_SHA = "932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3" +FROZEN_SHA = "dda473da08434484f4d67e8f0e6fa77b4296d9fa1489a810f529c699dc94a7e1" +FEATURE_COUNT = 6 +SUPPORT_MAX_HOLES = 50 +PANELS = ((40, 20261411), (52, 20261412)) +POLICIES = ("fixed2", "exact_verifier", "learned", "random_matched") + + +def _sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _digest(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def valid_sudoku(question: str, candidate: str) -> bool: + if not isinstance(question, str) or not isinstance(candidate, str): + return False + if len(question) != 81 or len(candidate) != 81: + return False + if any(x not in "123456789." for x in question): + return False + if any(x not in "123456789" for x in candidate): + return False + if any(x != "." and candidate[i] != x for i, x in enumerate(question)): + return False + digits = set("123456789") + for r in range(9): + if {candidate[r * 9 + c] for c in range(9)} != digits: + return False + for c in range(9): + if {candidate[r * 9 + c] for r in range(9)} != digits: + return False + for r in (0, 3, 6): + for c in (0, 3, 6): + if {candidate[(r + dr) * 9 + c + dc] for dr in range(3) for dc in range(3)} != digits: + return False + return True + + +def _probability(values: list[float], controller: dict[str, Any]) -> float: + if not isinstance(values, list) or len(values) != FEATURE_COUNT: + raise ValueError("wrong frozen controller feature count") + arrays = [controller[name] for name in ("mean", "scale", "weights")] + if any(not isinstance(a, list) or len(a) != FEATURE_COUNT for a in arrays): + raise ValueError("invalid controller parameters") + z = controller["bias"] + for x, mu, scale, weight in zip(values, *arrays, strict=True): + if any(type(v) not in (int, float) or not math.isfinite(v) for v in (x, mu, scale, weight)): + raise ValueError("nonfinite classifier features") + if scale <= 0: + raise ValueError("classifier scale must be positive") + z += ((x - mu) / scale) * weight + z = min(40.0, max(-40.0, z)) + return 1 / (1 + math.exp(-z)) + + +def _expected_visits(policy: str, *, first_valid: bool, score: float, threshold: float, + index: int, random_rate: float) -> int: + if policy == "fixed2": + return 2 + if policy == "exact_verifier": + return 1 if first_valid else 2 + if policy == "learned": + return 1 if score >= threshold else 2 + if policy == "random_matched": + # Retain the historical development-index seed to replay its controls. + mask = random.Random((20261213 + 101 * index) ^ 0xF107).random() < random_rate + return 1 if mask else 2 + raise ValueError("unrecognized comparator policy") + + +def audit(source: Path, frozen_report: Path) -> dict[str, Any]: + if _sha(frozen_report) != FROZEN_SHA: + raise ValueError("frozen controller artifact changed") + frozen = json.loads(frozen_report.read_text(encoding="utf-8")) + result_path = source / "report.json" + if result_path.stat().st_size > 1_000_000: + raise ValueError("oversized summary") + result = json.loads(result_path.read_text(encoding="utf-8")) + if ( + result.get("schema_version") != "bpd.trm_exit_support_guard.v1" + or result.get("model_sha256") != MODEL_SHA + or result.get("frozen_controller_report_sha256") != FROZEN_SHA + or result.get("evidence_class") != "posthoc_registered_support_guard_fresh_development_roots" + or result.get("guard_rule_frozen_before_new_sources") != "holes <= 50 else fixed_2" + or not math.isclose(result.get("frozen_threshold"), frozen["calibration"]["threshold"], abs_tol=1e-12) + ): + raise ValueError("source/model/support rule mismatch") + threshold = frozen["calibration"]["threshold"] + random_rate = frozen["calibration"]["random_stop_probability"] + controller = frozen["training"] + expected_panels = {holes: seed for holes, seed in PANELS} + if {p.get("holes"): p.get("seed") for p in result["panels"]} != expected_panels: + raise ValueError("wrong registered cohort roster") + seen_roots, seen_questions = set(), set() + reports = [] + for panel in result["panels"]: + holes, seed, n = panel["holes"], panel["seed"], panel["roots"] + path = source / f"guard_h{holes}.jsonl" + if path.stat().st_size > 16 * 1024 * 1024 or _sha(path) != result["files_sha256"][path.name]: + raise ValueError("source evidence digest/size mismatch") + rows = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + if len(rows) != n or type(n) is not int or not 1 <= n <= 64: + raise ValueError("incomplete cohort") + grade = { + key: {"solved": 0, "steps": 0, "incorrect_early_exits": 0, "native_seconds": 0.0} + for key in (*POLICIES, "support_guarded") + } + first_solves = 0 + for index, row in enumerate(rows): + expected_root = f"transfer-h{holes}-s{seed + 101 * index}" + q = row["question"] + if ( + row.get("root_id") != expected_root or expected_root in seen_roots + or not isinstance(q, str) or q.count(".") != holes or q in seen_questions + or row.get("split") != "development" or row.get("training_eligible") is not False + or row.get("holes") != holes or row.get("controller_support_max_holes") != SUPPORT_MAX_HOLES + or row.get("task_digest") != _digest({"question": q}) + ): + raise ValueError("root, task, or development custody mismatch") + seen_roots.add(expected_root) + seen_questions.add(q) + first, second = row["first_pass_candidate"], row["second_pass_candidate"] + first_valid, second_valid = valid_sudoku(q, first), valid_sudoku(q, second) + if row["first_pass_verified"] is not first_valid or row["second_pass_verified"] is not second_valid: + raise ValueError("independent Sudoku grade differs from source") + first_solves += int(first_valid) + score = row["frozen_controller_score"] + if type(score) not in (int, float) or not math.isfinite(score): + raise ValueError("invalid controller output") + recomputed_score = _probability(row.get("first_step_features"), controller) + if not math.isclose(score, recomputed_score, abs_tol=1e-10): + raise ValueError("frozen trained classifier score does not replay") + if not math.isclose(score, row["reference_learned_score"], abs_tol=1e-12): + raise ValueError("inconsistent frozen controller score") + policies = row["reference_policies"] + if not isinstance(policies, dict) or set(policies) != set(POLICIES): + raise ValueError("incomplete policy matrix") + for policy in POLICIES: + visits = _expected_visits( + policy, first_valid=first_valid, score=score, + threshold=threshold, index=index, random_rate=random_rate, + ) + selected = first if visits == 1 else second + source_row = policies[policy] + outcome = first_valid if visits == 1 else second_valid + if ( + source_row.get("visits") != visits + or source_row.get("correct") is not outcome + or source_row.get("first_candidate") != first + or source_row.get("final_candidate") != selected + ): + raise ValueError(f"{policy} output disagrees with verifier replay") + cost = source_row.get("native_seconds") + if type(cost) not in (int, float) or not math.isfinite(cost) or cost < 0: + raise ValueError("missing actual native seconds") + metrics = grade[policy] + metrics["steps"] += visits + metrics["solved"] += int(outcome) + metrics["incorrect_early_exits"] += int(visits == 1 and not outcome) + metrics["native_seconds"] += cost + guard_visits = 2 if holes > SUPPORT_MAX_HOLES else ( + 1 if score >= threshold else 2 + ) + guard_pass = first_valid if guard_visits == 1 else second_valid + if ( + row.get("guarded_outer_steps") != guard_visits + or row.get("guarded_correct") is not guard_pass + ): + raise ValueError("guarded outcome violates frozen threshold/support rule") + native_seconds = row.get("guarded_native_seconds") + if type(native_seconds) not in (int, float) or not math.isfinite(native_seconds) or native_seconds < 0: + raise ValueError("invalid guard execution cost") + gm = grade["support_guarded"] + gm["steps"] += guard_visits + gm["solved"] += int(guard_pass) + gm["incorrect_early_exits"] += int(guard_visits == 1 and not guard_pass) + gm["native_seconds"] += native_seconds + for key, totals in grade.items(): + reported = panel["support_guarded"] if key == "support_guarded" else panel[ + {"fixed2": "fixed_2", "exact_verifier": "exact_verifier", + "learned": "original_frozen_learned", "random_matched": "calibration_rate_random"}[key] + ] + report_steps = reported["outer_steps"] if key == "support_guarded" else reported["total_outer_steps"] + if (report_steps != totals["steps"] or reported["solved"] != totals["solved"] + or reported["incorrect_early_exits"] != totals["incorrect_early_exits"] + or not math.isclose(reported["native_seconds"], totals["native_seconds"], abs_tol=0.0002)): + raise ValueError(f"{key} aggregate differs from source outcomes and timing") + reports.append({ + "holes": holes, "roots": n, "first_pass_solved": first_solves, + "verified_policy_totals": grade, + }) + return { + "schema_version": "bpd.rlt_exit_support_guard_audit.v1", + "source_report_sha256": _sha(result_path), + "pinned_controller_sha256": FROZEN_SHA, + "checkpoint_sha256": MODEL_SHA, + "unique_source_roots": len(seen_roots), + "panels": reports, + "independent_exact_checker_replay": True, + "learned_stop_policy_replay": True, + "limitation": ( + "Rechecks written Sudoku candidate outputs and policy decisions from native run; " + "does not reexecute pretrained TRM weights or certify cross-task generalization." + ), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--frozen", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.out.exists(): + parser.error("output exists") + report = audit(args.source, args.frozen) + args.out.write_text(json.dumps(report, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8") + print(json.dumps({"checked_roots": report["unique_source_roots"], + "all_passed": report["independent_exact_checker_replay"]}, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/exit_support_guard.py b/mechinterp/bpd/experiments/inkling_reader_v0/exit_support_guard.py new file mode 100644 index 00000000..67ae3aaa --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/exit_support_guard.py @@ -0,0 +1,215 @@ +"""Predeclared support guard for the frozen 50-blank trained TRM exit controller. + +A difficulty shift to 52 blanks produced an unsafe exit in RLT-EXIT-03. +This posthoc-designed guard allows learned stopping only for <=50 blanks +and evaluates it on NEW development source roots, without refitting. +""" + +from __future__ import annotations + +import argparse +import json +import time +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from mechinterp.bpd.adapters.trm import build_mini_trm, load_pretrained_trm +from mechinterp.bpd.experiments.inkling_reader_v0.exit_difficulty_transfer import ( + BASELINE_REPORT_SHA256, COHORTS as OLD_COHORTS, MODEL_SHA256, + generate_verified_rows, load_frozen, sha, +) +from mechinterp.bpd.experiments.inkling_reader_v0.learned_exit_controller import ( + FEATURES, _logit_model, evaluate, +) +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_exit import native_rollout +from mechinterp.loopscope02.scripts.trm_sudoku import TRM_CHECKPOINTS + +SCHEMA = "bpd.trm_exit_support_guard.v1" +EASY_HOLES = 40 +HARD_HOLES = 52 +ALLOWED_HOLES = 50 +FRESH_COHORTS = ((EASY_HOLES, 20261411), (HARD_HOLES, 20261412)) + + +def _policy_details( + model: torch.nn.Module, rows: list[dict[str, Any]], + frozen: dict[str, Any], *, holes: int, +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + params, calibration = frozen["training"], frozen["calibration"] + threshold = calibration["threshold"] + records = [] + for row in rows: + q = row["question"] + + def guarded_stop(features: dict[str, float]) -> bool: + if holes > ALLOWED_HOLES: + return False + feature = np.array([features[name] for name in FEATURES], dtype=np.float64) + return bool(_logit_model(feature, params) >= threshold) + + trace, receipt = native_rollout( + model, q, max_outer_steps=2, stop_when_verified=False, + stop_decider=guarded_stop, + ) + if trace[0]["candidate"] != row["first_candidate"]: + raise ValueError("guarded first visit diverged from frozen task") + if len(trace) == 2 and trace[1]["candidate"] != row["second_candidate"]: + raise ValueError("guarded second visit changed fixed-depth trajectory") + if holes > ALLOWED_HOLES and len(trace) != 2: + raise ValueError("out-of-support case stopped early") + valid = trace[-1]["sudoku_checker_passed"] + if valid != ( + row["first_pass_verified"] if len(trace) == 1 else row["second_pass_verified"] + ): + raise ValueError("guarded output disagrees with independent Sudoku check") + records.append({ + "root_id": row["root_id"], + "task_digest": row["task_digest"], + "question": q, + "split": "development", + "training_eligible": False, + "holes": holes, + "controller_support_max_holes": ALLOWED_HOLES, + "first_pass_verified": row["first_pass_verified"], + "second_pass_verified": row["second_pass_verified"], + "first_pass_candidate": row["first_candidate"], + "second_pass_candidate": row["second_candidate"], + "first_step_features": row["features"], + "frozen_controller_score": float(_logit_model( + np.array(row["features"], dtype=np.float64), params, + )), + "guarded_outer_steps": len(trace), + "guarded_correct": valid, + "guarded_native_seconds": round(sum(s["native_step_seconds"] for s in trace), 6), + "guarded_checker_seconds": round(sum(s["exact_check_seconds"] for s in trace), 6), + "guarded_stop_reason": receipt["stop_reason"], + }) + return records, { + "solved": sum(row["guarded_correct"] for row in records), + "roots": len(records), + "outer_steps": sum(row["guarded_outer_steps"] for row in records), + "native_seconds": round(sum(row["guarded_native_seconds"] for row in records), 6), + "incorrect_early_exits": sum( + row["guarded_outer_steps"] == 1 and not row["guarded_correct"] for row in records + ), + "stopped_after_first": sum(row["guarded_outer_steps"] == 1 for row in records), + "support_rule": f"learned_exit_if_holes_lte_{ALLOWED_HOLES}_else_fixed_2", + } + + +def run( + model: torch.nn.Module, frozen: dict[str, Any], prohibited: set[str], + *, roots_per_panel: int = 24, + cohorts: tuple[tuple[int, int], ...] = FRESH_COHORTS, +) -> tuple[dict[str, Any], dict[int, list[dict[str, Any]]]]: + if set(holes for holes, _ in cohorts) != {EASY_HOLES, HARD_HOLES}: + raise ValueError("both predeclared ease/hardness arms are required") + if any(seed in {s for _, s in OLD_COHORTS} for _, seed in cohorts): + raise ValueError("cannot reuse the prior difficulty-shift seeds") + used = set(prohibited) + report_rows = {} + panel_summaries = [] + started = time.monotonic() + for holes, seed in cohorts: + rows = generate_verified_rows( + model, sha256=MODEL_SHA256, holes=holes, seed=seed, + roots=roots_per_panel, prohibited=used, + ) + used.update(r["task_digest"] for r in rows) + unguarded, seen = evaluate( + model, rows, frozen["training"], frozen["calibration"], + ) + if len(seen) != len(rows): + raise ValueError("unguarded policy matrix incomplete") + guarded_rows, guard = _policy_details(model, rows, frozen, holes=holes) + for index, receipt in enumerate(guarded_rows): + reference = seen[index] + if receipt["root_id"] != reference["root_id"]: + raise ValueError("guard and policy comparison source roots differ") + receipt["reference_policies"] = reference["policies"] + receipt["reference_learned_score"] = reference["learned_score"] + scores = unguarded["scores"] + report_rows[holes] = guarded_rows + panel_summaries.append({ + "holes": holes, "seed": seed, "roots": len(rows), + "original_frozen_learned": scores["learned"], + "fixed_2": scores["fixed2"], + "exact_verifier": scores["exact_verifier"], + "calibration_rate_random": scores["random_matched"], + "support_guarded": guard, + "guarded_vs_fixed_steps_saved": ( + 1 - guard["outer_steps"] / scores["fixed2"]["total_outer_steps"] + ), + "guarded_vs_fixed_native_time_saved": ( + 1 - guard["native_seconds"] / scores["fixed2"]["native_seconds"] + ), + }) + return { + "schema_version": SCHEMA, + "evidence_class": "posthoc_registered_support_guard_fresh_development_roots", + "model_sha256": MODEL_SHA256, + "frozen_controller_report_sha256": BASELINE_REPORT_SHA256, + "frozen_threshold": frozen["calibration"]["threshold"], + "guard_rule_frozen_before_new_sources": "holes <= 50 else fixed_2", + "root_counts": roots_per_panel, + "panels": panel_summaries, + "source_train_cal_dev_roots_excluded": len(prohibited), + "total_wall_seconds": round(time.monotonic() - started, 4), + "claim_boundary": ( + "The guard is a posthoc response to the already observed 52-blank failure. " + "It is evaluated on new independent development source seeds with no " + "retraining or new threshold tuning. No preregistered scientific confirmation." + ), + }, report_rows + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--model", choices=("gaoxin492", "mini"), default="gaoxin492") + parser.add_argument("--roots-per-panel", type=int, default=24) + args = parser.parse_args() + if args.out.exists(): + parser.error("output exists") + torch.set_num_threads(2) + original, seen = load_frozen(args.source) + if args.model == "gaoxin492": + model = load_pretrained_trm("gaoxin492", dtype=torch.float32, verify_sha256=True) + if TRM_CHECKPOINTS["gaoxin492"]["sha256"] != MODEL_SHA256: + raise ValueError("pretrained checkpoint changed") + else: + model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, + h_cycles=2, l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=43, + ) + report, rows = run(model, original, seen, roots_per_panel=args.roots_per_panel) + if args.model == "mini": + report["evidence_class"] = "untrained_mini_plumbing" + report["model_sha256"] = "mini_untrained_43" + args.out.mkdir(parents=True) + digests = {} + for holes, data in rows.items(): + p = args.out / f"guard_h{holes}.jsonl" + p.write_text( + "".join(json.dumps(row, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n" + for row in data), encoding="utf-8", + ) + digests[p.name] = sha(p) + report["files_sha256"] = digests + report["source_sha256"] = sha(Path(__file__)) + (args.out / "report.json").write_text( + json.dumps(report, indent=2, sort_keys=True, allow_nan=False) + "\n", encoding="utf-8", + ) + print(json.dumps({ + "panels": report["panels"], + "output": str(args.out), + }, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard.py new file mode 100644 index 00000000..483d017b --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard.py @@ -0,0 +1,67 @@ +"""Posthoc support guard keeps harder tasks at fixed depth on new source roots.""" + +from __future__ import annotations + +import unittest + +import torch + +from mechinterp.bpd.adapters.trm import build_mini_trm +from mechinterp.bpd.experiments.inkling_reader_v0.exit_difficulty_transfer import MODEL_SHA256 +from mechinterp.bpd.experiments.inkling_reader_v0.exit_support_guard import run + + +class DifficultyGuardTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + torch.set_num_threads(2) + cls.model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, h_cycles=2, + l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=43, + ) + cls.frozen = { + "model_sha256": MODEL_SHA256, + "training": { + "features": [ + "mean_blank_logit_margin", "min_blank_logit_margin", + "p10_blank_logit_margin", "median_blank_logit_margin", + "mean_blank_entropy", "mean_blank_top_probability", + ], + "weights": [0.0] * 6, "mean": [0.0] * 6, + "scale": [1.0] * 6, "bias": 20.0, + }, + "calibration": { + "threshold": 0.5656608144205763, + "random_stop_probability": 0.4583333333333333, + }, + } + + def test_fixed_support_cutoff_is_applied_online(self) -> None: + report, rows = run( + self.model, self.frozen, set(), + roots_per_panel=2, + ) + self.assertEqual(sorted(rows), [40, 52]) + per = {p["holes"]: p for p in report["panels"]} + self.assertEqual(per[40]["support_guarded"]["outer_steps"], 2) + self.assertEqual(per[52]["support_guarded"]["outer_steps"], 4) + self.assertEqual(per[52]["support_guarded"]["incorrect_early_exits"], 0) + self.assertEqual(per[52]["original_frozen_learned"]["total_outer_steps"], 2) + self.assertEqual(report["guard_rule_frozen_before_new_sources"], "holes <= 50 else fixed_2") + self.assertTrue(all(not row["training_eligible"] for group in rows.values() for row in group)) + + def test_old_seeds_and_missing_cohorts_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "both predeclared"): + run( + self.model, self.frozen, set(), roots_per_panel=2, + cohorts=((40, 20261411),), + ) + with self.assertRaisesRegex(ValueError, "reuse"): + run( + self.model, self.frozen, set(), roots_per_panel=2, + cohorts=((40, 20261311), (52, 20261312)), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard_audit.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard_audit.py new file mode 100644 index 00000000..c376b0a1 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_exit_support_guard_audit.py @@ -0,0 +1,104 @@ +"""Independent verifier guard-audit smoke and sealed-tamper checks.""" + +from __future__ import annotations + +import hashlib +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import torch + +from mechinterp.bpd.adapters.trm import build_mini_trm +from mechinterp.bpd.experiments.inkling_reader_v0 import audit_exit_support_guard as auditor +from mechinterp.bpd.experiments.inkling_reader_v0.exit_support_guard import run + + +class GuardReceiptReplayTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + torch.set_num_threads(2) + cls.model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, h_cycles=2, + l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=43, + ) + cls.frozen = { + "model_sha256": auditor.MODEL_SHA, + "training": { + "features": [ + "mean_blank_logit_margin", "min_blank_logit_margin", + "p10_blank_logit_margin", "median_blank_logit_margin", + "mean_blank_entropy", "mean_blank_top_probability", + ], + "weights": [0.0] * 6, "mean": [0.0] * 6, + "scale": [1.0] * 6, "bias": 20.0, + }, + "calibration": { + "threshold": 0.5656608144205763, + "random_stop_probability": 0.4583333333333333, + }, + } + + def _write(self, base: Path) -> tuple[Path, Path, str]: + original_path = base / "frozen.json" + original_path.write_text(json.dumps(self.frozen, sort_keys=True) + "\n") + digest = hashlib.sha256(original_path.read_bytes()).hexdigest() + report, cohorts = run(self.model, self.frozen, set(), roots_per_panel=2) + report["frozen_controller_report_sha256"] = digest + out = base / "source" + out.mkdir() + hashes = {} + for holes, rows in cohorts.items(): + target = out / f"guard_h{holes}.jsonl" + target.write_text("".join(json.dumps(row, sort_keys=True) + "\n" for row in rows)) + hashes[target.name] = hashlib.sha256(target.read_bytes()).hexdigest() + report["files_sha256"] = hashes + (out / "report.json").write_text(json.dumps(report, sort_keys=True) + "\n") + return out, original_path, digest + + def test_replay_all_logged_policies_and_raw_sudoku(self) -> None: + with tempfile.TemporaryDirectory() as temp: + out, original, digest = self._write(Path(temp)) + with patch.object(auditor, "FROZEN_SHA", digest): + report = auditor.audit(out, original) + self.assertEqual(report["unique_source_roots"], 4) + self.assertTrue(report["independent_exact_checker_replay"]) + self.assertTrue(report["learned_stop_policy_replay"]) + self.assertEqual(sorted(item["holes"] for item in report["panels"]), [40, 52]) + + def test_mutated_classifier_score_detected_even_if_resealed(self) -> None: + with tempfile.TemporaryDirectory() as temp: + out, original, digest = self._write(Path(temp)) + filename = out / "guard_h40.jsonl" + data = [json.loads(line) for line in filename.read_text().splitlines()] + data[0]["frozen_controller_score"] = 0.03 + data[0]["reference_learned_score"] = 0.03 + filename.write_text("".join(json.dumps(v, sort_keys=True) + "\n" for v in data)) + report_path = out / "report.json" + manifest = json.loads(report_path.read_text()) + manifest["files_sha256"][filename.name] = hashlib.sha256(filename.read_bytes()).hexdigest() + report_path.write_text(json.dumps(manifest) + "\n") + with patch.object(auditor, "FROZEN_SHA", digest): + with self.assertRaisesRegex(ValueError, "classifier score"): + auditor.audit(out, original) + + def test_mutated_candidate_detected_even_if_resealed(self) -> None: + with tempfile.TemporaryDirectory() as temp: + out, original, digest = self._write(Path(temp)) + filename = out / "guard_h52.jsonl" + data = [json.loads(line) for line in filename.read_text().splitlines()] + data[0]["first_pass_candidate"] = "1" * 81 + filename.write_text("".join(json.dumps(v, sort_keys=True) + "\n" for v in data)) + report_path = out / "report.json" + manifest = json.loads(report_path.read_text()) + manifest["files_sha256"][filename.name] = hashlib.sha256(filename.read_bytes()).hexdigest() + report_path.write_text(json.dumps(manifest) + "\n") + with patch.object(auditor, "FROZEN_SHA", digest): + with self.assertRaisesRegex(ValueError, "output disagrees"): + auditor.audit(out, original) + + +if __name__ == "__main__": + unittest.main()