diff --git a/.github/workflows/bpd-learned-rlt-exit.yml b/.github/workflows/bpd-learned-rlt-exit.yml new file mode 100644 index 00000000..4b33ecdb --- /dev/null +++ b/.github/workflows/bpd-learned-rlt-exit.yml @@ -0,0 +1,63 @@ +name: BPD pretrained TRM learned RLT exit + +on: + push: + branches: + - research/rlt-learned-exit-20261121 + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/learned_exit_controller.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_learned_exit_controller.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py" + - ".github/workflows/bpd-learned-rlt-exit.yml" + pull_request: + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/learned_exit_controller.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_learned_exit_controller.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py" + - ".github/workflows/bpd-learned-rlt-exit.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: learned-rlt-exit-${{ github.ref }} + cancel-in-progress: true + +jobs: + cpu-training: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + OMP_NUM_THREADS: "2" + OPENBLAS_NUM_THREADS: "1" + MKL_NUM_THREADS: "2" + PYTHONDONTWRITEBYTECODE: "1" + HF_HUB_DISABLE_TELEMETRY: "1" + HF_HUB_DISABLE_XET: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install CPU dependencies + 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: Test logits-only controller and native recurrent continuation + run: python -m unittest mechinterp.bpd.experiments.inkling_reader_v0.test_learned_exit_controller -v + - name: Execute pinned pretrained training/calibration/development experiment + if: github.event_name == 'push' + run: | + timeout --signal=TERM --kill-after=15s 850s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.learned_exit_controller \ + --model gaoxin492 --train-roots 96 --cal-roots 48 --dev-roots 48 \ + --holes 50 --out runs/rlt_learned_exit_20261121 + - name: Retain complete development and training receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: bpd-rlt-learned-exit-first-dev + path: runs/rlt_learned_exit_20261121/ + if-no-files-found: warn + retention-days: 7 diff --git a/.github/workflows/bpd-rlt-exit-audit-export.yml b/.github/workflows/bpd-rlt-exit-audit-export.yml new file mode 100644 index 00000000..4424a20f --- /dev/null +++ b/.github/workflows/bpd-rlt-exit-audit-export.yml @@ -0,0 +1,60 @@ +name: RLT learned exit independent audit and DataGoblin train export + +on: + push: + branches: + - research/rlt-learned-exit-20261121 + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/export_datagoblin.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_export_datagoblin.py" + - ".github/workflows/bpd-rlt-exit-audit-export.yml" + pull_request: + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/export_datagoblin.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_export_datagoblin.py" + - ".github/workflows/bpd-rlt-exit-audit-export.yml" + workflow_dispatch: + +permissions: + contents: read + actions: read + +jobs: + audit-and-export: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Test verifier and training custody fixtures without Torch + run: | + python -m unittest discover -s mechinterp/bpd/experiments/inkling_reader_v0 -p 'test_export_datagoblin.py' -v + python -m py_compile mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py + - name: Fetch original SHA-bound pretrained learned-exit receipts + uses: actions/download-artifact@v4 + with: + name: bpd-rlt-learned-exit-first-dev + path: runs/source + run-id: 44911864342 + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Audit independent roots and all policy decisions + run: | + python mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py \ + --source runs/source --out runs/independent_audit.json + - name: Export verifier-grounded TRAIN-only corpus to DataGoblin + run: | + python mechinterp/bpd/experiments/inkling_reader_v0/export_datagoblin.py \ + --source runs/source --out runs/datagoblin_train + - name: Archive evidence and training corpus + uses: actions/upload-artifact@v4 + with: + name: bpd-learned-rlt-exit-audited-dg-train + path: | + runs/independent_audit.json + runs/datagoblin_train/ + if-no-files-found: error + retention-days: 30 diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/LEARNED_EXIT_DEV_RESULTS_20261121.md b/mechinterp/bpd/experiments/inkling_reader_v0/LEARNED_EXIT_DEV_RESULTS_20261121.md new file mode 100644 index 00000000..126f705e --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/LEARNED_EXIT_DEV_RESULTS_20261121.md @@ -0,0 +1,104 @@ +# RLT-EXIT-02: logits-only learned recurrent stopping on pretrained 7M TRM + +Date 2026-11-21. Evidence: **development-only real pretrained inference, with independent receipt replay**. +The original hosted CPU campaign is [Actions #44911864342](https://github.com/MoralityLabAI/BPD/actions/runs/44911864342), +artifact [bpd-rlt-learned-exit-first-dev #14710246746](https://github.com/MoralityLabAI/BPD/actions/runs/44911864342/artifacts/14710246746). +The separate stdlib [cross-audit and DataGoblin export](https://github.com/MoralityLabAI/BPD/actions/runs/44912385166) +passed and retained a second artifact with audit results and TRAIN-only rollout examples. + +This is a **real trained STOP controller** over learned recurrent Sudoku-model outputs. +The underlying 7M Attention-TRM is pretrained upstream; the stop controller +itself is a small deterministic six-feature regularized logistic model. +Neither network implements Inkling's cross-loop Attention Residual Q/K/V/MoE readers. + +## Data and model identity + +- Upstream model: gaoxin492/TinyRecursiveModels-Sudoku-Extreme-att at pinned + model checksum 932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3. +- Fresh source-root seeds: TRAIN 20261211, CALIBRATION 20261212, DEVELOPMENT 20261213; + each consecutive root advances the corresponding seed by 101. +- Train: 96 unique Sudoku questions with 50 blanks. First-pass exact valid 50, + second-pass 95, with 45 newly repaired after one additional outer step. +- Calibration: 48 independent roots, 26 valid at first pass and 47 at second. + The threshold was frozen at 0.5656608144205763 to maximize calibration + first-step exits with zero false exits. It stopped 22/48. +- Development: 48 further independent roots with no reused questions. + First-step exact valid 24, second-pass 47. Neither source nor outcomes + were used to fit weights or set the threshold. +- Checkpoint, root IDs, generation seeds, solution verification, step logits, + timing, logistic coefficients and original source/data SHA hashes are retained + in the original artifact. + +Only six numbers summarizing first-step digit logits reach the STOP controller: +mean, minimum, tenth percentile and median blank-cell top-two logit margins; +mean blank-cell categorical entropy; and mean top-token probability. +At inference it receives no Sudoku validity bit, planted target or +future-step result. The exact Sudoku checker supplies labels during +TRAIN and threshold CALIBRATION and serves as the separate oracle-quality +baseline. + +## Independent original development result + +| Stopping policy | Solved/48 | Outer model steps | Native model CPU sec | Bad early exits | +| --- | ---: | ---: | ---: | ---: | +| Fixed depth 2 | 47 | 96 | 22.288943 | 0 | +| Exact Sudoku verifier | 47 | 72 | 16.693023 | 0 | +| Learned logits-only threshold | **47** | **75** | **17.284104** | **0** | +| Random gate (CAL rate 22/48) | 37 | 77 | 17.713731 | 11 | + +The learned gate stopped 21/48 after the first recurrent step. +It saved 21 of 96 recurrent steps (21.875%) and 22.45% of measured +native model CPU time versus the fixed-two-step policy, retaining +the same 47/48 complete-solution count on this independent +DEVELOPMENT cohort. The exact verifier saved 24 steps (25.0%). +The random gate was seeded independently per root at the frozen +CAL stop probability of 0.4583333333333333 and made 11 wrong +first-step exits, reducing final solves to 37. + +The regularized logistic fit reached 89.58% first-step training +accuracy at probability 0.5. TRAIN class counts were 50 valid, +46 invalid. The CAL threshold was chosen by the declared +zero-false-stop rule and was NOT adjusted on the 48 development +outcomes. All full-model recurrent hidden states genuinely +continued between first and second outer steps. The entire +run, including collection, took 165.457 seconds on a hosted CPU +runner after dependencies were installed. + +## Cross-audited provenance + +The stdlib audit independently rechecked all TRAIN/CAL/DEV questions, +fresh root identity and disjointness, Sudoku validity for first and +second responses, supplied feature arrays, logistic score replay, +calibration threshold, learned and seeded random stop decisions, +and model-step/time sums. It revalidated the report against +input SHA-256 dda473da08434484f4d67e8f0e6fa77b4296d9fa1489a810f529c699dc94a7e1. +It did not reexecute pretrained model weights; the original +native execution was completed in the first Actions campaign. + +The DataGoblin corpus export independently screened its input +for train-only lineage custody and verifier agreement. It generated +96 verified stop/continue SFT rows, 96 future-outcome rows, +and 45 verified first-to-second-pass repair preferences. +Zero CAL or DEV examples entered those training exports. +All source and output file hashes are in its manifest. +These are supervised STOP and repair examples, **not** fabricated +hidden reasoning chains or actual Inkling teacher samples. + +## Scientific scope and next controls + +This is one exposed development study on one fixed Sudoku-trained model. +No uncertainty interval or predeclared minimum meaningful difference +supports a general efficiency claim beyond the measured source roots. +The zero observed wrong early exits is a small-sample observation, +not proof that the future false-stop rate is zero. A separately powered, +fresh confirmation root cohort and paired model-accuracy/cost inference +would be needed for that claim. + +A general RLT controller should train on multiple independently checked +task families and learn a conditional value of further computation. +For exact proof/Sudoku tasks, the environment checker can be a reliable +stopping source. For other gyms, compare learned stop decisions against +verified correctness, matched-cost random and constant-depth baselines, +with explicit error penalties and no reuse of held-out labels. +The native Inkling cross-loop routing and Goodfire coordinate-2027 +hypotheses remain distinct, untested research questions. diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py b/mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py new file mode 100644 index 00000000..24c3884b --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/audit_learned_exit.py @@ -0,0 +1,282 @@ +"""Independent stdlib audit of BPD learned recurrent exit outcomes. + +Recomputes exact Sudoku verifier labels, lineage custody, logistic scores, +calibration selection, deterministic random controls and policy outcome totals +from archived JSON. Does not rerun native model weights or certify generalization. +""" + +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" +SPLITS = ("train", "calibration", "development") +POLICIES = ("fixed2", "exact_verifier", "learned", "random_matched") + + +def _digest(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def _sha(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _rows(path: Path) -> list[dict[str, Any]]: + if path.stat().st_size > 24_000_000: + raise ValueError("oversized evidence file") + rows = [] + for line in path.read_text(encoding="utf-8").splitlines(): + if line.strip(): + record = json.loads(line) + if not isinstance(record, dict): + raise ValueError("evidence row must be an object") + rows.append(record) + return rows + + +def _verify_sudoku(q: str, candidate: str) -> bool: + if not isinstance(q, str) or not isinstance(candidate, str): + return False + if len(q) != 81 or len(candidate) != 81: + return False + if any(c not in "123456789." for c in q): + return False + if any(c not in "123456789" for c in candidate): + return False + if any(c != "." and candidate[i] != c for i, c in enumerate(q)): + return False + for r in range(9): + if {candidate[r * 9 + c] for c in range(9)} != set("123456789"): + return False + for c in range(9): + if {candidate[r * 9 + c] for r in range(9)} != set("123456789"): + 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) + } != set("123456789"): + return False + return True + + +def _score(features: list[float], training: dict[str, Any]) -> float: + weights = training["weights"] + mean = training["mean"] + scale = training["scale"] + if any(len(seq) != len(features) for seq in (weights, mean, scale)): + raise ValueError("classifier dimensionality mismatch") + z = training["bias"] + for x, w, mu, sigma in zip(features, weights, mean, scale, strict=True): + if not all(math.isfinite(v) for v in (x, w, mu, sigma)) or sigma <= 0: + raise ValueError("invalid logistic feature/weight") + z += ((x - mu) / sigma) * w + z = min(40, max(-40, z)) + return 1 / (1 + math.exp(-z)) + + +def audit(source: Path) -> dict[str, Any]: + meta_path = source / "report.json" + meta = json.loads(meta_path.read_text(encoding="utf-8")) + if ( + meta.get("schema_version") != "bpd.trm_learned_exit.v1" + or meta.get("evidence_class") != "native_pretrained_development_learned_exit" + or meta.get("model_sha256") != MODEL_SHA + ): + raise ValueError("unrecognized experiment model or evidence class") + feature_count = len(meta["feature_names"]) + if feature_count != 6: + raise ValueError("expected six logits-only features") + stages = {} + roots = set() + questions = set() + for split in SPLITS: + path = source / f"{split}.jsonl" + if meta["data_sha256"].get(path.name) != _sha(path): + raise ValueError(f"{split} source checksum mismatch") + rows = _rows(path) + if len(rows) != meta["root_counts"][split]: + raise ValueError(f"{split} root-count mismatch") + for index, row in enumerate(rows): + q = row.get("question") + root = row.get("root_id") + expected_root = f"{split}-sudoku-{meta['source_seeds'][split] + 101 * index}" + if root != expected_root or root in roots or row.get("split") != split: + raise ValueError("duplicate or mismatched source-root lineage") + roots.add(root) + if not isinstance(q, str) or q.count(".") != meta["holes"] or q in questions: + raise ValueError("duplicate or invalid source question") + questions.add(q) + if row.get("task_digest") != _digest({"question": q}): + raise ValueError("task digest mismatch") + if row.get("model_sha256") != MODEL_SHA: + raise ValueError("row uses different checkpoint") + if row.get("training_eligible") is not (split == "train"): + raise ValueError("train/cal/development custody mismatch") + if row.get("oracle_target_visible_to_controller") is not False or ( + row.get("future_step_visible_to_controller") is not False + ): + raise ValueError("controller-observation provenance invalid") + first = _verify_sudoku(q, row.get("first_candidate")) + second = _verify_sudoku(q, row.get("second_candidate")) + if ( + row.get("first_pass_verified") is not first + or row.get("second_pass_verified") is not second + or row.get("second_pass_rescue") is not (second and not first) + ): + raise ValueError("recomputed Sudoku outcome disagrees with row") + feature = row.get("features") + if ( + not isinstance(feature, list) or len(feature) != feature_count + or any(type(v) not in {int, float} or not math.isfinite(v) for v in feature) + ): + raise ValueError("invalid logits feature row") + stages[split] = rows + + training = meta["training"] + if training["train_count"] != len(stages["train"]) or training["train_positive"] != sum( + row["first_pass_verified"] for row in stages["train"] + ): + raise ValueError("trained-model label counters inconsistent") + train_predictions = [ + _score(row["features"], training) >= 0.5 for row in stages["train"] + ] + train_accuracy = sum( + pred == row["first_pass_verified"] + for pred, row in zip(train_predictions, stages["train"], strict=True) + ) / len(stages["train"]) + if not math.isclose(train_accuracy, training["train_accuracy_at_half"], abs_tol=1e-10): + raise ValueError("training accuracy disagrees with frozen classifier") + + cal = meta["calibration"] + candidates = [1.000001] + sorted( + {_score(row["features"], training) for row in stages["calibration"]}, reverse=True + ) + best = (1.000001, 0) + for t in candidates: + stopped = [ + row for row in stages["calibration"] if _score(row["features"], training) >= t + ] + if all(row["first_pass_verified"] for row in stopped) and len(stopped) > best[1]: + best = (t, len(stopped)) + if ( + not math.isclose(cal["threshold"], best[0], abs_tol=1e-10) + or cal["stop_count"] != best[1] + or cal["false_stops"] != 0 + or cal["calibration_cases"] != len(stages["calibration"]) + or cal["calibration_valid_first"] != sum( + row["first_pass_verified"] for row in stages["calibration"] + ) + or not math.isclose(cal["random_stop_probability"], best[1] / len(stages["calibration"]), + abs_tol=1e-12) + ): + raise ValueError("calibration zero-false-stop selection does not replay") + + eval_path = source / "evaluation.jsonl" + if meta["data_sha256"].get(eval_path.name) != _sha(eval_path): + raise ValueError("development policy evidence checksum mismatch") + evaluations = _rows(eval_path) + if len(evaluations) != len(stages["development"]): + raise ValueError("incomplete evaluation root matrix") + totals = { + name: {"solved": 0, "total_outer_steps": 0, "stopped_after_first": 0, + "incorrect_early_exits": 0, "native_seconds": 0.0} + for name in POLICIES + } + for index, (row, recorded) in enumerate(zip(stages["development"], evaluations, strict=True)): + if ( + recorded.get("root_id") != row["root_id"] + or recorded.get("task_digest") != row["task_digest"] + or recorded.get("split") != "development" + or recorded.get("training_eligible") is not False + or set(recorded.get("policies", {})) != set(POLICIES) + ): + raise ValueError("evaluation source root/custody mismatch") + score = _score(row["features"], training) + if not math.isclose(recorded["learned_score"], score, abs_tol=1e-10): + raise ValueError("learned probability receipt mismatch") + if not math.isclose(recorded["calibrated_threshold"], cal["threshold"], abs_tol=1e-12): + raise ValueError("learned threshold differs from frozen calibration") + rand = random.Random((meta["source_seeds"]["development"] + 101 * index) ^ 0xF107) + random_stop = rand.random() < cal["random_stop_probability"] + decisions = { + "fixed2": False, + "exact_verifier": row["first_pass_verified"], + "learned": score >= cal["threshold"], + "random_matched": random_stop, + } + for policy in POLICIES: + actual = recorded["policies"][policy] + step_count = 1 if decisions[policy] else 2 + correct = row["first_pass_verified"] if step_count == 1 else row["second_pass_verified"] + candidate = row["first_candidate"] if step_count == 1 else row["second_candidate"] + if ( + actual.get("visits") != step_count + or actual.get("correct") is not correct + or actual.get("final_candidate") != candidate + or actual.get("first_candidate") != row["first_candidate"] + ): + raise ValueError(f"{policy} decision/continuation does not replay") + secs = actual.get("native_seconds") + if type(secs) not in {int, float} or not math.isfinite(secs) or secs < 0: + raise ValueError("invalid native execution time") + totals[policy]["solved"] += int(correct) + totals[policy]["total_outer_steps"] += step_count + totals[policy]["stopped_after_first"] += int(step_count == 1) + totals[policy]["incorrect_early_exits"] += int(step_count == 1 and not correct) + totals[policy]["native_seconds"] += secs + for policy, computed in totals.items(): + registered = meta["evaluation"]["scores"][policy] + for field in ("solved", "total_outer_steps", "stopped_after_first", "incorrect_early_exits"): + if computed[field] != registered[field]: + raise ValueError(f"{policy} summary {field} differs from raw evidence") + if not math.isclose(computed["native_seconds"], registered["native_seconds"], abs_tol=0.001): + raise ValueError(f"{policy} timing differs from raw evidence") + + return { + "schema_version": "bpd.learned_exit_independent_audit.v1", + "source_report_sha256": _sha(meta_path), + "training_count": len(stages["train"]), + "calibration_count": len(stages["calibration"]), + "development_count": len(stages["development"]), + "calibration_threshold_replayed": best[0], + "calibration_zero_false_stops": True, + "policy_totals": totals, + "source_lineage_disjoint": True, + "independent_sudoku_grade_replay": True, + "model_is_reexecuted_by_this_auditor": False, + "evidence_class": "native_pretrained_development_independent_receipt_replay", + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.out.exists(): + parser.error("audit output exists") + result = audit(args.source) + args.out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({ + "training_roots": result["training_count"], + "development_roots": result["development_count"], + "learned_solves": result["policy_totals"]["learned"]["solved"], + "learned_steps": result["policy_totals"]["learned"]["total_outer_steps"], + "replayed": True, + }, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/export_datagoblin.py b/mechinterp/bpd/experiments/inkling_reader_v0/export_datagoblin.py new file mode 100644 index 00000000..772c8fff --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/export_datagoblin.py @@ -0,0 +1,223 @@ +"""Export verified, lineage-disjoint TRAIN controller rollouts into DataGoblin format. + +Do not export calibration or development labels. The exported targets are +Sudoku-verifier-backed stop/continue decisions, not hidden teacher thoughts. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +SOURCE_SCHEMA = "bpd.trm_learned_exit.v1" +SOURCE_ROW = "bpd.trm_exit_training_row.v1" +MODEL_SHA = "932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3" + + +def _hash(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 _rows(path: Path) -> list[dict[str, Any]]: + if path.stat().st_size > 24_000_000: + raise ValueError("oversized training corpus") + rows = [] + with path.open(encoding="utf-8") as source: + for line in source: + if line.strip(): + row = json.loads(line) + if not isinstance(row, dict): + raise ValueError("expected JSON object") + rows.append(row) + return rows + + +def _sudoku_valid(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(v not in "123456789." for v in question): + return False + if any(v not in "123456789" for v in candidate): + return False + if any(v != "." and candidate[i] != v for i, v in enumerate(question)): + return False + for r in range(9): + if {candidate[r * 9 + c] for c in range(9)} != set("123456789"): + return False + for c in range(9): + if {candidate[r * 9 + c] for r in range(9)} != set("123456789"): + 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) + } != set("123456789"): + return False + return True + + +def _jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(json.dumps(row, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n") + + +def export(source: Path, out: Path) -> dict[str, Any]: + manifest_path = source / "report.json" + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + if ( + manifest.get("schema_version") != SOURCE_SCHEMA + or manifest.get("model_sha256") != MODEL_SHA + or manifest.get("evidence_class") != "native_pretrained_development_learned_exit" + ): + raise ValueError("requires real, pinned pretrained model campaign") + all_rows = {} + all_roots = set() + all_digests = set() + for split in ("train", "calibration", "development"): + path = source / f"{split}.jsonl" + if manifest["data_sha256"].get(path.name) != _hash(path): + raise ValueError(f"{split} digest mismatch") + rows = _rows(path) + if len(rows) != manifest["root_counts"][split]: + raise ValueError(f"{split} root count mismatch") + for row in rows: + if row.get("schema_version") != SOURCE_ROW or row.get("split") != split: + raise ValueError("row split/schema mismatch") + if row.get("model_sha256") != MODEL_SHA: + raise ValueError("row checkpoint mismatch") + if row.get("training_eligible") is not (split == "train"): + raise ValueError("training data custody mismatch") + if row.get("oracle_target_visible_to_controller") is not False: + raise ValueError("controller observed target oracle") + if row.get("future_step_visible_to_controller") is not False: + raise ValueError("controller observed future step") + if type(row.get("root_id")) is not str or not row["root_id"]: + raise ValueError("root ID required") + if row["root_id"] in all_roots: + raise ValueError("root reused across splits") + all_roots.add(row["root_id"]) + q = row.get("question") + if not isinstance(q, str) or len(q) != 81: + raise ValueError("invalid question") + digest = _digest({"question": q}) + if row.get("task_digest") != digest or digest in all_digests: + raise ValueError("duplicate or mismatched lineage") + all_digests.add(digest) + for step in ("first", "second"): + candidate = row.get(f"{step}_candidate") + outcome = row.get(f"{step}_pass_verified") + if type(outcome) is not bool or _sudoku_valid(q, candidate) is not outcome: + raise ValueError("verifier label does not replay") + if row.get("second_pass_rescue") is not ( + row["second_pass_verified"] and not row["first_pass_verified"] + ): + raise ValueError("rescue label mismatch") + features = row.get("features") + if ( + not isinstance(features, list) or len(features) != len(manifest["feature_names"]) + or any(type(v) not in {int, float} or not math.isfinite(v) for v in features) + ): + raise ValueError("nonfinite or incomplete feature array") + all_rows[split] = rows + # Evaluation/online policy records are not eligible training examples. + eval_path = source / "evaluation.jsonl" + if manifest["data_sha256"].get(eval_path.name) != _hash(eval_path): + raise ValueError("evaluation digest mismatch") + if len(_rows(eval_path)) != manifest["root_counts"]["development"]: + raise ValueError("incomplete development policy outcomes") + if out.exists(): + raise ValueError("output must be a new directory") + out.mkdir(parents=True) + sft, repair, outcomes = [], [], [] + for row in all_rows["train"]: + base = { + "root_id": row["root_id"], "task_digest": row["task_digest"], + "model_sha256": MODEL_SHA, "family": "sudoku9", + "split": "train", "training_eligible": True, + "source_sha256": _hash(source / "train.jsonl"), + "source_model": "pretrained_gaoxin492_trm", + "teacher_hidden_state_access": False, + } + sft.append({ + "schema_version": "rlt_gym.controller_sft.v1", **base, + "kind": "verified_stop_decision", + "input": { + "task_question": row["question"], + "first_candidate": row["first_candidate"], + "logits_only_feature_names": manifest["feature_names"], + "logits_only_features": row["features"], + }, + "target": {"decision": "stop" if row["first_pass_verified"] else "continue"}, + "verification": {"first_pass_verified": row["first_pass_verified"]}, + }) + outcomes.append({ + "schema_version": "rlt_gym.controller_outcome.v1", **base, + "kind": "future_verifier_outcome", + "first_pass_verified": row["first_pass_verified"], + "second_pass_verified": row["second_pass_verified"], + "second_pass_rescue": row["second_pass_rescue"], + "observed_second_candidate": row["second_candidate"], + }) + if row["second_pass_rescue"]: + repair.append({ + "schema_version": "rlt_gym.controller_preference.v1", **base, + "kind": "verified_repair", + "input": {"task_question": row["question"]}, + "rejected": {"candidate": row["first_candidate"]}, + "chosen": {"candidate": row["second_candidate"]}, + "verification": {"chosen": True, "rejected": False}, + }) + _jsonl(out / "controller_sft.jsonl", sft) + _jsonl(out / "outcomes.jsonl", outcomes) + _jsonl(out / "repairs.jsonl", repair) + report = { + "schema_version": "rlt_gym.pretrained_trm_train_export.v1", + "model_sha256": MODEL_SHA, + "source_report_sha256": _hash(manifest_path), + "source_train_sha256": _hash(source / "train.jsonl"), + "source_calibration_sha256": _hash(source / "calibration.jsonl"), + "source_development_sha256": _hash(source / "development.jsonl"), + "source_evaluation_sha256": _hash(eval_path), + "training_root_count": len(sft), "verified_repair_pairs": len(repair), + "train_only": True, "development_rows_exported": 0, + "files_sha256": { + n: _hash(out / n) for n in ("controller_sft.jsonl", "outcomes.jsonl", "repairs.jsonl") + }, + "claim_boundary": ( + "Fresh TRAIN source roots only, exact independent Sudoku verification and " + "logits-derived controller features. No exposed CAL/DEV labels in this training export." + ), + } + (out / "manifest.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", + encoding="utf-8") + return report + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + report = export(args.source, args.out) + print(json.dumps({"training_roots": report["training_root_count"], + "repair_pairs": report["verified_repair_pairs"], + "train_only": True}, sort_keys=True)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/learned_exit_controller.py b/mechinterp/bpd/experiments/inkling_reader_v0/learned_exit_controller.py new file mode 100644 index 00000000..57dcad00 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/learned_exit_controller.py @@ -0,0 +1,349 @@ +"""Learned logits-only exit controller for real pretrained 7M TRM recurrence. + +Fit train-only first-visit correctness, choose threshold on separate calibration +roots, and evaluate genuine resumed model execution on new development roots. +All material is a research pilot; no sealed confirmation data is accessed. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import random +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.native_trm_exit import native_rollout +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot import ( + _permute_sudoku, verify_sudoku, +) +from mechinterp.loopscope02.scripts.trm_sudoku import TRM_CHECKPOINTS, PureSudokuTRM + +SCHEMA = "bpd.trm_learned_exit.v1" +FEATURES = ( + "mean_blank_logit_margin", "min_blank_logit_margin", + "p10_blank_logit_margin", "median_blank_logit_margin", + "mean_blank_entropy", "mean_blank_top_probability", +) +SPLIT_SEEDS = {"train": 20261211, "calibration": 20261212, "development": 20261213} +DEFAULT_COUNTS = {"train": 96, "calibration": 48, "development": 48} + + +def _sha(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def _features(obs: dict[str, Any]) -> list[float]: + values = [obs[name] for name in FEATURES] + if any(type(x) not in (int, float) or not math.isfinite(x) for x in values): + raise ValueError("invalid logits-only feature") + return [float(x) for x in values] + + +def _logit_model(features: np.ndarray, params: dict[str, Any]) -> np.ndarray: + mu, scale = np.array(params["mean"]), np.array(params["scale"]) + weights = np.array(params["weights"]) + x = (features - mu) / scale + z = np.clip(x @ weights + params["bias"], -40, 40) + return 1 / (1 + np.exp(-z)) + + +def fit_logistic(rows: list[dict[str, Any]], *, epochs: int = 500, ridge: float = 0.08) -> dict[str, Any]: + """Deterministic six-dimensional logistic, optimizing only train-root labels.""" + if not rows or any(item["split"] != "train" for item in rows): + raise ValueError("logistic training requires TRAIN rows exclusively") + roots = [item["root_id"] for item in rows] + if len(roots) != len(set(roots)): + raise ValueError("duplicate training roots") + x = np.array([row["features"] for row in rows], dtype=np.float64) + y = np.array([float(row["first_pass_verified"]) for row in rows], dtype=np.float64) + if not (np.any(y == 0) and np.any(y == 1)): + raise ValueError("training requires positive and negative labels") + if x.ndim != 2 or x.shape[1] != len(FEATURES) or not np.isfinite(x).all(): + raise ValueError("invalid feature array") + mu, scale = x.mean(axis=0), x.std(axis=0) + scale = np.maximum(scale, 1e-6) + x = (x - mu) / scale + w = np.zeros(len(FEATURES), dtype=np.float64) + bias = 0.0 + for epoch in range(epochs): + z = np.clip(x @ w + bias, -40, 40) + error = 1 / (1 + np.exp(-z)) - y + eta = 0.3 / (1 + epoch / 200) + w -= eta * ((x.T @ error) / len(rows) + ridge * w) + bias -= eta * float(error.mean()) + scores = 1 / (1 + np.exp(-np.clip(x @ w + bias, -40, 40))) + return { + "features": list(FEATURES), "mean": mu.tolist(), "scale": scale.tolist(), + "weights": w.tolist(), "bias": bias, + "ridge": ridge, "epochs": epochs, + "train_count": len(rows), "train_positive": int(y.sum()), + "train_accuracy_at_half": float(((scores >= 0.5) == y).mean()), + "source_only": "logits_features_without_checker_or_oracle", + } + + +def calibrate(rows: list[dict[str, Any]], params: dict[str, Any]) -> dict[str, Any]: + """Choose maximum calibration stops subject to zero observed false stops.""" + if not rows or any(row["split"] != "calibration" for row in rows): + raise ValueError("calibration must use disjoint CAL roots") + x = np.array([row["features"] for row in rows], dtype=np.float64) + scores = _logit_model(x, params) + labels = np.array([row["first_pass_verified"] for row in rows], dtype=bool) + # No valid threshold always stops incorrectly less often than an unsafe one. + candidates = [1.000001] + [float(s) for s in sorted(set(scores), reverse=True)] + chosen = {"threshold": 1.000001, "stop_count": 0, "false_stops": 0} + for cutoff in candidates: + should_stop = scores >= cutoff + false_stops = int((should_stop & ~labels).sum()) + stop_count = int(should_stop.sum()) + if false_stops == 0 and stop_count > chosen["stop_count"]: + chosen = {"threshold": cutoff, "stop_count": stop_count, "false_stops": 0} + return { + **chosen, "calibration_cases": len(rows), + "calibration_valid_first": int(labels.sum()), + "random_stop_probability": chosen["stop_count"] / len(rows), + "threshold_selection": "maximum_calibration_stops_with_zero_false_stops", + "calibration_is_scientific_confirmation": False, + } + + +def _root_seed(split: str, index: int) -> int: + return SPLIT_SEEDS[split] + 101 * index + + +def _row( + split: str, idx: int, q: str, trace: list[dict[str, Any]], checkpoint_sha: str, +) -> dict[str, Any]: + if len(trace) != 2: + raise ValueError("two-depth source required for first-step valuation") + first, second = trace + return { + "schema_version": "bpd.trm_exit_training_row.v1", + "root_id": f"{split}-sudoku-{_root_seed(split, idx)}", + "task_digest": _sha({"question": q}), + "split": split, + "model_sha256": checkpoint_sha, + "question": q, + "features": _features(first), + "first_pass_verified": bool(first["sudoku_checker_passed"]), + "second_pass_verified": bool(second["sudoku_checker_passed"]), + "second_pass_rescue": bool(second["sudoku_checker_passed"] and not first["sudoku_checker_passed"]), + "first_candidate": first["candidate"], + "second_candidate": second["candidate"], + "training_eligible": split == "train", + "oracle_target_visible_to_controller": False, + "future_step_visible_to_controller": False, + } + + +def _fixed_rows(model: PureSudokuTRM, *, split: str, n: int, holes: int, sha: str) -> list[dict[str, Any]]: + rows = [] + for idx in range(n): + q, solution = _permute_sudoku(_root_seed(split, idx), holes=holes) + trace, _ = native_rollout(model, q, max_outer_steps=2, stop_when_verified=False) + if any(v["sudoku_checker_passed"] != (v["candidate"] == solution) for v in trace): + raise ValueError("task oracle and exact verifier disagree") + rows.append(_row(split, idx, q, trace, sha)) + if len({row["task_digest"] for row in rows}) != len(rows): + raise ValueError("duplicate task source inside split") + return rows + + +def _metrics(traces: list[tuple[str, list[dict[str, Any]], dict[str, Any]]]) -> dict[str, Any]: + solved = sum(steps[-1]["sudoku_checker_passed"] for _, steps, _ in traces) + invalid_exits = sum(len(steps) == 1 and not steps[0]["sudoku_checker_passed"] + for _, steps, _ in traces) + return { + "solved": solved, "total": len(traces), + "total_outer_steps": sum(len(steps) for _, steps, _ in traces), + "stopped_after_first": sum(len(steps) == 1 for _, steps, _ in traces), + "incorrect_early_exits": invalid_exits, + "native_seconds": round(sum(step["native_step_seconds"] for _, steps, _ in traces + for step in steps), 6), + "checker_seconds": round(sum(step["exact_check_seconds"] for _, steps, _ in traces + for step in steps), 6), + } + + +def evaluate( + model: PureSudokuTRM, + rows: list[dict[str, Any]], + params: dict[str, Any], + calibration: dict[str, Any], +) -> tuple[dict[str, Any], list[dict[str, Any]]]: + """Execute policies independently with real model-state continuation.""" + if any(row["split"] != "development" or row["training_eligible"] for row in rows): + raise ValueError("test evaluation requires development-only new roots") + policies = ("fixed2", "exact_verifier", "learned", "random_matched") + traces: dict[str, list[tuple[str, list[dict[str, Any]], dict[str, Any]]]] = { + name: [] for name in policies + } + records = [] + cutoff = calibration["threshold"] + p_random = calibration["random_stop_probability"] + for index, row in enumerate(rows): + q = row["question"] + model_outputs = {} + # Rotate execution order deterministically across roots. + order = policies[index % len(policies):] + policies[:index % len(policies)] + for policy in order: + if policy == "fixed2": + steps, result = native_rollout(model, q, max_outer_steps=2, stop_when_verified=False) + elif policy == "exact_verifier": + steps, result = native_rollout(model, q, max_outer_steps=2, stop_when_verified=True) + elif policy == "learned": + def decide(features: dict[str, float]) -> bool: + vector = np.array([features[name] for name in FEATURES], dtype=np.float64) + return bool(_logit_model(vector, params) >= cutoff) + steps, result = native_rollout( + model, q, max_outer_steps=2, stop_when_verified=False, stop_decider=decide, + ) + else: + control_rng = random.Random(_root_seed("development", index) ^ 0xF107) + random_decision = control_rng.random() < p_random + steps, result = native_rollout( + model, q, max_outer_steps=2, stop_when_verified=False, + stop_decider=lambda _features, s=random_decision: s, + ) + model_outputs[policy] = (steps, result) + traces[policy].append((row["root_id"], steps, result)) + fixed_steps = model_outputs["fixed2"][0] + for policy, (steps, _) in model_outputs.items(): + if steps[0]["candidate"] != fixed_steps[0]["candidate"]: + raise ValueError("first-visit model output differs between paired policies") + if len(steps) == 2 and steps[1]["candidate"] != fixed_steps[1]["candidate"]: + raise ValueError("second-visit continuation changed across policies") + records.append({ + "root_id": row["root_id"], "task_digest": row["task_digest"], + "split": "development", "training_eligible": False, + "first_step_valid": row["first_pass_verified"], + "second_step_valid": row["second_pass_verified"], + "learned_score": float(_logit_model(np.array(row["features"]), params)), + "calibrated_threshold": cutoff, "execution_order": list(order), + "policies": { + name: { + "visits": len(steps), "correct": bool(steps[-1]["sudoku_checker_passed"]), + "first_candidate": steps[0]["candidate"], + "final_candidate": steps[-1]["candidate"], + "stop_reason": result["stop_reason"], + "native_seconds": round(sum(x["native_step_seconds"] for x in steps), 6), + } for name, (steps, result) in model_outputs.items() + }, + }) + scores = {name: _metrics(traces[name]) for name in policies} + return { + "scores": scores, + "learned_vs_fixed_steps_saved": 1 - scores["learned"]["total_outer_steps"] / scores["fixed2"]["total_outer_steps"], + "learned_vs_fixed_correct_delta": scores["learned"]["solved"] - scores["fixed2"]["solved"], + "verifier_vs_fixed_steps_saved": 1 - scores["exact_verifier"]["total_outer_steps"] / scores["fixed2"]["total_outer_steps"], + "independent_root_count": len(rows), + }, records + + +def run( + model: PureSudokuTRM, + *, + sha: str, + pretrained: bool, + counts: dict[str, int] | None = None, + holes: int = 50, +) -> tuple[dict[str, Any], dict[str, list[dict[str, Any]]]]: + counts = dict(counts or DEFAULT_COUNTS) + if set(counts) != set(SPLIT_SEEDS) or any(type(n) is not int or not 4 <= n <= 160 + for n in counts.values()): + raise ValueError("counts must be train/calibration/development with 4-160 roots") + seen = set() + started = time.monotonic() + stages = {} + for split in ("train", "calibration", "development"): + rows = _fixed_rows(model, split=split, n=counts[split], holes=holes, sha=sha) + overlap = seen & {r["task_digest"] for r in rows} + if overlap: + raise ValueError("cross-split duplicated root questions") + seen.update(r["task_digest"] for r in rows) + stages[split] = rows + parameters = fit_logistic(stages["train"]) + calibration = calibrate(stages["calibration"], parameters) + results, records = evaluate(model, stages["development"], parameters, calibration) + for row in stages["development"]: + row["training_eligible"] = False + report = { + "schema_version": SCHEMA, + "evidence_class": "native_pretrained_development_learned_exit" if pretrained else "untrained_smoke", + "model_sha256": sha, "source_seeds": dict(SPLIT_SEEDS), + "root_counts": counts, "holes": holes, + "feature_names": list(FEATURES), + "training": parameters, "calibration": calibration, + "evaluation": results, + "seconds_total_including_data_collection": round(time.monotonic() - started, 3), + "claim_boundary": ( + "Real pretrained TRM with a learned logits-only stop model; exact verifier labels " + "supervise TRAIN and CAL but are not provided to the learned controller at inference. " + "Evaluation remains development only and is not a sealed scientific confirmation." + ), + } + return report, {**stages, "evaluation": records} + + +def _save_rows(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(json.dumps(row, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--model", choices=("mini", "gaoxin492"), default="mini") + parser.add_argument("--train-roots", type=int, default=96) + parser.add_argument("--cal-roots", type=int, default=48) + parser.add_argument("--dev-roots", type=int, default=48) + parser.add_argument("--holes", type=int, default=50) + args = parser.parse_args() + if args.out.exists(): + parser.error("create-only output directory required") + torch.set_num_threads(2) + if args.model == "gaoxin492": + model = load_pretrained_trm("gaoxin492", dtype=torch.float32, verify_sha256=True) + sha = TRM_CHECKPOINTS["gaoxin492"]["sha256"] + pretrained = True + 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) + sha = _sha({"untrained_mini_seed": 43}) + pretrained = False + report, rows = run( + model, sha=sha, pretrained=pretrained, + counts={"train": args.train_roots, "calibration": args.cal_roots, "development": args.dev_roots}, + holes=args.holes, + ) + args.out.mkdir(parents=True) + paths = {} + for key, values in rows.items(): + target = args.out / f"{key}.jsonl" + _save_rows(target, values) + paths[target.name] = hashlib.sha256(target.read_bytes()).hexdigest() + report["data_sha256"] = paths + report["source_sha256"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + (args.out / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8") + print(json.dumps({ + "out": str(args.out), "evidence_class": report["evidence_class"], + "calibration": report["calibration"], + "evaluation": report["evaluation"], + }, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py b/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py index ff16c8d2..7b64019b 100644 --- a/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py +++ b/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py @@ -15,7 +15,7 @@ import time from collections import Counter from pathlib import Path -from typing import Any +from typing import Any, Callable import torch from torch import Tensor @@ -36,8 +36,11 @@ def native_rollout( *, max_outer_steps: int, stop_when_verified: bool, + stop_decider: Callable[[dict[str, float]], bool] | None = None, ) -> tuple[list[dict[str, Any]], dict[str, Any]]: """One uninterrupted recurrence; later steps reuse the preceding state.""" + if stop_when_verified and stop_decider is not None: + raise ValueError("exact and learned exits require separate policies") if type(max_outer_steps) is not int or not 1 <= max_outer_steps <= 8: raise ValueError("max_outer_steps must be in 1..8") if len(question) != 81 or "." not in question: @@ -48,6 +51,7 @@ def native_rollout( blank = [index for index, value in enumerate(question) if value == "."] observations: list[dict[str, Any]] = [] start = time.perf_counter() + stopped_by_decider = False for step in range(1, max_outer_steps + 1): began = time.perf_counter() z_h, z_l = model.act_step(z_h, z_l, embedded) @@ -59,20 +63,36 @@ def native_rollout( check_sec = time.perf_counter() - verify_started margin = torch.topk(logits[blank], k=2, dim=-1).values margins = (margin[:, 0] - margin[:, 1]).tolist() + sorted_margins = sorted(margins) + probabilities = torch.softmax(logits[blank], dim=-1) + entropies = -(probabilities * probabilities.clamp_min(1e-12).log()).sum(dim=-1) + features = { + "mean_blank_logit_margin": sum(margins) / len(margins), + "min_blank_logit_margin": min(margins), + "p10_blank_logit_margin": sorted_margins[int(0.1 * (len(margins) - 1))], + "median_blank_logit_margin": sorted_margins[len(margins) // 2], + "mean_blank_entropy": float(entropies.mean()), + "mean_blank_top_probability": float(probabilities.max(dim=-1).values.mean()), + } observations.append({ "outer_step": step, "candidate": prediction, "sudoku_checker_passed": checked, - "mean_blank_logit_margin": sum(margins) / len(margins), - "min_blank_logit_margin": min(margins), + **features, "native_step_seconds": round(step_compute_sec, 6), "exact_check_seconds": round(check_sec, 6), }) if checked and stop_when_verified: break + if step < max_outer_steps and stop_decider is not None and bool(stop_decider(dict(features))): + stopped_by_decider = True + break return observations, { "realized_outer_steps": len(observations), - "stop_reason": "verified" if observations[-1]["sudoku_checker_passed"] else "depth_budget", + "stop_reason": ( + "learned_exit" if stopped_by_decider else + "verified" if observations[-1]["sudoku_checker_passed"] else "depth_budget" + ), "elapsed_seconds": round(time.perf_counter() - start, 6), } diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_export_datagoblin.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_export_datagoblin.py new file mode 100644 index 00000000..935ef9b1 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_export_datagoblin.py @@ -0,0 +1,130 @@ +"""Synthetic custody fixtures for train-only DataGoblin RLT export.""" + +from __future__ import annotations + +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from export_datagoblin import MODEL_SHA, _digest, _hash, export + + +def _solution(index: int) -> str: + return "".join( + str(((r * 3 + r // 3 + c + index) % 9) + 1) + for r in range(9) for c in range(9) + ) + + +def _row(split: str, index: int, first_valid: bool) -> dict: + solved = _solution(index) + q = "." + solved[1:] + return { + "schema_version": "bpd.trm_exit_training_row.v1", + "root_id": f"{split}-sudoku-root-{index}", + "task_digest": _digest({"question": q}), + "model_sha256": MODEL_SHA, "split": split, "question": q, + "features": [1.0 + index] * 6, + "first_pass_verified": first_valid, + "second_pass_verified": True, + "second_pass_rescue": not first_valid, + "first_candidate": solved if first_valid else "1" * 81, + "second_candidate": solved, + "training_eligible": split == "train", + "oracle_target_visible_to_controller": False, + "future_step_visible_to_controller": False, + } + + +def make_source(root: Path) -> Path: + source = root / "model_run" + source.mkdir(parents=True) + rows = { + "train": [_row("train", 0, True), _row("train", 1, False)], + "calibration": [_row("calibration", 2, True), _row("calibration", 3, True)], + "development": [_row("development", 4, False), _row("development", 5, False)], + "evaluation": [{"root_id": "development-4"}, {"root_id": "development-5"}], + } + digests = {} + for split, values in rows.items(): + path = source / f"{split}.jsonl" + path.write_text( + "".join(json.dumps(v, sort_keys=True, separators=(",", ":")) + "\n" for v in values), + encoding="utf-8", + ) + digests[path.name] = _hash(path) + report = { + "schema_version": "bpd.trm_learned_exit.v1", + "model_sha256": MODEL_SHA, "evidence_class": "native_pretrained_development_learned_exit", + "root_counts": {"train": 2, "calibration": 2, "development": 2}, + "feature_names": [ + "mean_blank_logit_margin", "min_blank_logit_margin", + "p10_blank_logit_margin", "median_blank_logit_margin", + "mean_blank_entropy", "mean_blank_top_probability", + ], + "data_sha256": digests, + } + (source / "report.json").write_text(json.dumps(report), encoding="utf-8") + return source + + +def reseal(source: Path) -> None: + report = json.loads((source / "report.json").read_text()) + for split in ("train", "calibration", "development", "evaluation"): + name = f"{split}.jsonl" + report["data_sha256"][name] = _hash(source / name) + (source / "report.json").write_text(json.dumps(report), encoding="utf-8") + + +class TrainExportTests(unittest.TestCase): + def test_train_only_export_and_verified_repairs(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + source = make_source(folder) + result = export(source, folder / "out") + self.assertEqual(result["training_root_count"], 2) + self.assertEqual(result["verified_repair_pairs"], 1) + self.assertEqual(result["development_rows_exported"], 0) + records = [ + json.loads(line) for line in (folder / "out" / "controller_sft.jsonl").read_text().splitlines() + ] + self.assertEqual(len(records), 2) + self.assertEqual( + [r["target"]["decision"] for r in records], ["stop", "continue"], + ) + self.assertTrue(all(r["training_eligible"] and r["split"] == "train" for r in records)) + content = (folder / "out" / "controller_sft.jsonl").read_text() + self.assertNotIn("development-sudoku-root", content) + + def test_reject_altered_verifier_label_despite_resealed_hash(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + source = make_source(folder) + path = source / "train.jsonl" + rows = [json.loads(line) for line in path.read_text().splitlines()] + rows[0]["first_pass_verified"] = False + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + reseal(source) + with self.assertRaisesRegex(ValueError, "verifier label"): + export(source, folder / "out") + + def test_reject_cross_split_duplicates_and_changed_source_bytes(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + source = make_source(folder) + path = source / "calibration.jsonl" + rows = [json.loads(line) for line in path.read_text().splitlines()] + rows[0]["question"] = _solution(0)[0:1].replace("1", ".") + _solution(0)[1:] + rows[0]["task_digest"] = _digest({"question": rows[0]["question"]}) + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + with self.assertRaisesRegex(ValueError, "digest mismatch"): + export(source, folder / "out") + reseal(source) + with self.assertRaisesRegex(ValueError, "lineage"): + export(source, folder / "out") + + +if __name__ == "__main__": + unittest.main() diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_learned_exit_controller.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_learned_exit_controller.py new file mode 100644 index 00000000..2b33ba0d --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_learned_exit_controller.py @@ -0,0 +1,103 @@ +"""Separate TRAIN/CAL roots and real recurrent-state policy-path controls.""" + +from __future__ import annotations + +import math +import unittest + +import numpy as np +import torch + +from mechinterp.bpd.adapters.trm import build_mini_trm +from mechinterp.bpd.experiments.inkling_reader_v0.learned_exit_controller import ( + FEATURES, _fixed_rows, _logit_model, calibrate, evaluate, fit_logistic, +) +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_exit import native_rollout +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot import _permute_sudoku + + +def fake_rows(split: str = "train") -> list[dict]: + return [ + { + "root_id": f"{split}-{i}", "split": split, + "features": [float(i), i / 2, i / 3, i / 4, 2 / (i + 1), i / 10], + "first_pass_verified": i >= 6, + } + for i in range(12) + ] + + +class LearnedExitTest(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, + ) + + def test_training_calibration_and_feature_contract(self) -> None: + params = fit_logistic(fake_rows(), epochs=200) + self.assertEqual(len(params["weights"]), len(FEATURES)) + self.assertGreater(params["train_accuracy_at_half"], 0.8) + cal = calibrate(fake_rows("calibration"), params) + self.assertEqual(cal["false_stops"], 0) + self.assertGreater(cal["stop_count"], 0) + self.assertLessEqual(cal["stop_count"], cal["calibration_valid_first"]) + scores = _logit_model(np.array([r["features"] for r in fake_rows()]), params) + self.assertGreater(scores[-1], scores[0]) + + def test_split_custody_prohibits_training_on_dev(self) -> None: + with self.assertRaisesRegex(ValueError, "TRAIN"): + fit_logistic(fake_rows("development")) + with self.assertRaisesRegex(ValueError, "CAL"): + calibrate(fake_rows("train"), { + "weights": [0.0] * len(FEATURES), "bias": 0.0, + "mean": [0.0] * len(FEATURES), "scale": [1.0] * len(FEATURES), + }) + duplicated = fake_rows() + duplicated[1]["root_id"] = duplicated[0]["root_id"] + with self.assertRaisesRegex(ValueError, "duplicate"): + fit_logistic(duplicated) + + def test_hidden_checker_not_available_to_callback(self) -> None: + q, _ = _permute_sudoku(3333, holes=22) + features_seen = [] + fixed, _ = native_rollout(self.model, q, max_outer_steps=2, stop_when_verified=False) + stopped, receipt = native_rollout( + self.model, q, max_outer_steps=2, stop_when_verified=False, + stop_decider=lambda features: (features_seen.append(dict(features)), True)[1], + ) + self.assertEqual(len(stopped), 1) + self.assertEqual(stopped[0]["candidate"], fixed[0]["candidate"]) + self.assertEqual(receipt["stop_reason"], "learned_exit") + self.assertEqual(len(features_seen), 1) + self.assertEqual(set(features_seen[0]), set(FEATURES)) + self.assertTrue(all(math.isfinite(v) for v in features_seen[0].values())) + with self.assertRaisesRegex(ValueError, "separate"): + native_rollout( + self.model, q, max_outer_steps=2, stop_when_verified=True, + stop_decider=lambda _: True, + ) + + def test_real_mini_forward_paired_policy_traces(self) -> None: + sha = "0" * 64 + rows = _fixed_rows(self.model, split="development", n=4, holes=22, sha=sha) + params = { + "weights": [0.0] * len(FEATURES), "bias": 0.0, + "mean": [0.0] * len(FEATURES), "scale": [1.0] * len(FEATURES), + } + results, details = evaluate( + self.model, rows, params, + {"threshold": 1.000001, "random_stop_probability": 0.0}, + ) + self.assertEqual(results["independent_root_count"], 4) + self.assertEqual(results["scores"]["fixed2"]["total_outer_steps"], 8) + self.assertEqual(results["scores"]["learned"]["total_outer_steps"], 8) + self.assertEqual(len(details), 4) + self.assertTrue(all(not r["training_eligible"] for r in rows)) + self.assertTrue(all(len(r["policies"]) == 4 for r in details)) + + +if __name__ == "__main__": + unittest.main()