From f325f3f78d6287108137ea3c08c13da069af024b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:33:21 +0800 Subject: [PATCH 01/15] LSA-02H: Lean-authoritative recoverable off-reference state extractor with full proof certification --- .../ppt_gym/offpath_source.py | 366 ++++++++++++++++++ 1 file changed, 366 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/offpath_source.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py new file mode 100644 index 000000000..e9a4e1df3 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py @@ -0,0 +1,366 @@ +"""LSA-02H: Lean-authoritative *recoverable* off-reference proof trajectories. + +For frozen TRAIN theorems, sample at most two legal alternative tactics +that depart from the native shortest reference script. The candidate must +lead to a finite Lean-explored continuation that fits the remaining eight +tactic checks. Replay the entire alternate proof from the theorem root with +real Lean, check its terminal kernel receipt and compile every full script +as a standalone axiom-free declaration. + +Only correction states *after the deviation* can become training records. +They carry the same public packet / public action-menu / exact shortest +continuation label contract as the existing native teacher. A reference +path state is not counted as novel off-reference supervision. + +Unlike a model rollout, this controlled source selection has fixed public +tactic ordering and no dependence on model predictions or calibration data. +""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import hashlib +import json +from pathlib import Path +import time + +from lcgrt import config +from lcgrt.certify import certify, decl_name +from lcgrt.extract import explore, goal_key, optimal_script +from lcgrt.lean_repl import LeanRepl +from .data import canonical, sha256_file +from .live_lean import candidate_menu, fingerprint, public_state, state_input +from .live_suite import load_suite +from .native_train import ( + CHECKS, EVIDENCE, FRAME_SCHEMA, _load_teacher, + _reference_optimal_actions, _snapshot_trajectory, +) + + +SCHEMA = "lsa02h.recoverable_offreference_train.v1" +ROW_SCHEMA = "lsa02h.offreference_correction_frame.v1" +MAX_DEVIATIONS_PER_ROOT = 2 + + +def _json(path: Path, payload: dict) -> None: + path.write_text(canonical(payload) + "\n", encoding="utf-8") + + +def _records(path: Path) -> list[dict]: + return [json.loads(s) for s in path.read_text(encoding="utf-8").splitlines() if s.strip()] + + +def _replay_from_root(repl, case, script: list[str]) -> tuple[dict, list[dict]]: + repl.reset() + state = repl.init(case.statement, pp=True) + frames = [] + for tactic in script: + if not state["goals"]: + raise ValueError("off-reference script continues after terminal closure") + frames.append(public_state(repl, state)) + if tactic not in candidate_menu(repl, state): + raise ValueError("off-reference proof uses tactic absent from public grammar") + step = repl.run(state["sid"], tactic) + if step.get("ok") is not True: + raise ValueError("Lean rejected an off-reference proof tactic") + state = step["state"] + return state, frames + + +def _completion_script(oracle: dict, pending: list[dict]) -> list[str] | None: + script = [] + for goal in pending: + key = goal_key(goal) + size = oracle["size"].get(key) + if not isinstance(size, int) or size < 1: + return None + script.extend(optimal_script(oracle["table"], oracle["size"], key)) + return script + + +def _collect_case(repl, case, oracle: dict, reference_frames: list[dict], + cap: int = MAX_DEVIATIONS_PER_ROOT) -> tuple[list[dict], list[tuple], dict]: + if not 1 <= cap <= 8: + raise ValueError("off-reference source exploration cap outside registry") + reference_actions = oracle["proof"]["script"] + original = {row["public_state_sha256"] for row in reference_frames} + census = { + "root": case.root, + "lineage": case.lineage, + "reference_size": len(reference_actions), + "alternative_public_menu_proposals": 0, + "alternatives_accepted_in_lean_graph": 0, + "alternative_finite_continuations": 0, + "candidate_within_eight_checks": 0, + "deviations_compiled_pending": 0, + "offreference_training_frames": 0, + "unreachable_or_over_budget": 0, + } + discoveries: list[dict] = [] + reference_proofs: list[tuple] = [] + repl.reset() + current = repl.init(case.statement, pp=True) + prefix: list[str] = [] + for pos, selected in enumerate(reference_actions): + if current["goals"] == []: + raise ValueError("native reference terminated before expected step") + front = goal_key(current["goals"][0]) + menu = candidate_menu(repl, current) + if selected not in menu: + raise ValueError("reference tactic outside public menu") + table = oracle["table"].get(front, {}) + alternatives = sorted(t for t in menu if t != selected) + for tactic in alternatives: + census["alternative_public_menu_proposals"] += 1 + if tactic not in table: + continue + census["alternatives_accepted_in_lean_graph"] += 1 + children = table[tactic] + if any(oracle["size"].get(k) is None for k in children): + census["unreachable_or_over_budget"] += 1 + continue + census["alternative_finite_continuations"] += 1 + # Reconstruct the complete alternate state *with Lean*, rather + # than projecting a one-goal graph cost onto a multi-goal proof. + base_state, _ = _replay_from_root(repl, case, prefix + [tactic]) + extra = _completion_script(oracle, base_state["goals"]) + if extra is None or pos + 1 + len(extra) > CHECKS: + census["unreachable_or_over_budget"] += 1 + continue + census["candidate_within_eight_checks"] += 1 + if len(discoveries) >= cap: + continue + if not extra: + # An alternate terminal proof has no *new decision state* + # and cannot provide the intended off-reference training. + continue + full = prefix + [tactic] + extra + seen = [] + repl.reset() + state = repl.init(case.statement, pp=True) + accepted = [] + new_frames = [] + for step_number, action in enumerate(full): + if not state["goals"]: + raise ValueError("off-reference path has premature terminal proof") + packet, public_sha = state_input( + repl, state, (), max(1, CHECKS - step_number), + ) + if step_number >= pos + 1 and public_sha not in original: + current_front = goal_key(state["goals"][0]) + observed_menu = candidate_menu(repl, state) + labels = _reference_optimal_actions( + current_front, observed_menu, oracle["table"], oracle["size"], + ) + if labels[observed_menu.index(action)] != 1: + raise ValueError("off-reference correction did not follow verified shortest continuation") + new_frames.append({ + "schema": ROW_SCHEMA, + "evidence": EVIDENCE, + "root": case.root, + "lineage": case.lineage, + "family": case.family, + "goal": packet, + "public_state_sha256": public_sha, + "candidates": list(observed_menu), + "labels": list(labels), + "checks_remaining": max(1, CHECKS - step_number), + "step": len(reference_frames) + pos * 100 + step_number, + "source_prefix_size": pos, + "deviation_tactic": tactic, + "deviation_pos": pos, + "correction_index": step_number - (pos + 1), + "remaining_proof_steps": len(full) - step_number, + "path_length": len(full), + "reference_root_size": len(reference_actions), + "label_semantics": "native_Lean_shortest_continuation_after_legal_recoverable_deviation", + "source_kind": "off_reference", + }) + outcome = repl.run(state["sid"], action) + if outcome.get("ok") is not True: + raise ValueError("native Lean rejected replayed alternate proof") + accepted.append(action) + state = outcome["state"] + if state["goals"]: + raise ValueError("native alternate proof left unfinished goals") + cert = repl.kernel(state["sid"]) + if cert.get("ok") is not True or cert.get("axioms") != []: + raise ValueError("native off-reference alternate proof failed terminal kernel") + if not new_frames: + continue + signature = hashlib.sha256(canonical(full).encode()).hexdigest()[:16] + proof_id = f"{case.tid}_off_{signature}" + discoveries.append({ + "proof_id": proof_id, + "script": full, + "deviation_pos": pos, + "deviation_tactic": tactic, + "correction_states": new_frames, + }) + reference_proofs.append((proof_id, case.theorem(), full)) + census["deviations_compiled_pending"] += 1 + census["offreference_training_frames"] += len(new_frames) + # Multiple alternative replays reset the proof server. Restore the + # canonical shortest prefix before stepping to its next state. + nxt, _ = _replay_from_root(repl, case, prefix + [selected]) + current = nxt + prefix.append(selected) + if current["goals"]: + raise ValueError("canonical reference proof no longer closes") + return discoveries, reference_proofs, census + + +def collect(suite: Path, teacher: Path, out: Path, *, roots: int = 64, + cap_per_root: int = MAX_DEVIATIONS_PER_ROOT, + max_seconds: float = 900.0, request_timeout: int = 60, + cert_timeout: int = 420) -> dict: + if out.exists() or roots not in range(1, 1025) or max_seconds <= 0: + raise ValueError("fresh offreference output and bounded source roots required") + native_frames, teacher_meta = _load_teacher(teacher) + cases, source = load_suite(suite, "train", roots) + if source["suite_manifest_sha256"] != teacher_meta["source"]["suite_manifest_sha256"]: + raise ValueError("teacher and off-reference source generator differ") + if teacher_meta["independent_lineages"] != roots: + raise ValueError("native training teacher source root census differs") + per_root_reference = defaultdict(list) + for frame in native_frames: + per_root_reference[frame["root"]].append(frame) + began = time.perf_counter() + out.mkdir(parents=True) + all_source_rows = [] + evidence = [] + census = [] + proof_records = [] + with LeanRepl( + timeout=request_timeout, exe=config.REPL_EXE, + cwd=config.LEAN_DIR, env=config.lean_env(), + ) as repl: + if str(repl.version) != "4.19.0": + raise ValueError("native offreference extraction needs Lean 4.19.0") + backend = fingerprint(config.REPL_EXE, config.LEAN_EXE, repl.version) + for case in cases: + if time.perf_counter() - began > max_seconds: + raise TimeoutError("native off-reference corpus source collection timed out") + oracle = explore(repl, case.theorem()) + reference = _snapshot_trajectory(repl, case, oracle) + expected = per_root_reference[case.root] + if [(r["goal"], r["candidates"], r["labels"]) for r in reference] != [ + (r["goal"], r["candidates"], r["labels"]) for r in expected + ]: + raise ValueError("off-reference generator changed frozen native reference teacher") + alternatives, proofs, root_report = _collect_case( + repl, case, oracle, reference, cap=cap_per_root, + ) + census.append(root_report) + proof_records.extend(proofs) + evidence.extend({ + "root": case.root, + "lineage": case.lineage, + "proof_id": x["proof_id"], + "script": x["script"], + "deviation_pos": x["deviation_pos"], + "deviation_tactic": x["deviation_tactic"], + "correction_states": len(x["correction_states"]), + } for x in alternatives) + all_source_rows.extend( + frame for x in alternatives for frame in x["correction_states"] + ) + receipt = {"status": {}, "passed": 0, "timed_out": False} + if proof_records: + receipt = certify(proof_records, timeout=cert_timeout, keep=out / "standalone.lean") + if receipt.get("timed_out") or any( + receipt.get("status", {}).get(decl_name(tid)) != "passed" + for tid, _, _ in proof_records + ): + raise ValueError("independent Lean compilation rejected off-reference correction path") + # Deduplicate public state+menu+remaining budget within a theorem. This + # preserves individual theorem as statistical unit and avoids repeated + # corrections with different original prefixes counting as more examples. + by_identity: dict[tuple, dict] = {} + for row in all_source_rows: + key = ( + row["root"], row["public_state_sha256"], + row["checks_remaining"], tuple(row["candidates"]), + ) + if key in by_identity: + if by_identity[key]["labels"] != row["labels"]: + raise ValueError("same public correction state has conflicting shortest labels") + continue + by_identity[key] = row + unique = list(by_identity.values()) + for index, row in enumerate(unique): + row["step"] = 1000 + index + row["source_proof_compiled"] = True + with (out / "offreference_frames.jsonl").open("x", encoding="utf-8") as writer: + for row in unique: + writer.write(canonical(row) + "\n") + with (out / "source_census.jsonl").open("x", encoding="utf-8") as writer: + for row in census: + writer.write(canonical(row) + "\n") + with (out / "alternate_proofs.jsonl").open("x", encoding="utf-8") as writer: + for item in evidence: + writer.write(canonical(item) + "\n") + _json(out / "compiler_receipt.json", receipt) + artifacts = ["offreference_frames.jsonl", "source_census.jsonl", + "alternate_proofs.jsonl", "compiler_receipt.json"] + if proof_records: + artifacts.append("standalone.lean") + result = { + "schema": SCHEMA, + "source_teacher_sha256": sha256_file(teacher / "manifest.json"), + "suite_manifest_sha256": source["suite_manifest_sha256"], + "backend": backend, + "train_split_only": True, + "training_lineages": len(cases), + "roots_with_recoverable_deviations": len({ + r["root"] for r in unique + }), + "novel_offreference_training_states": len(unique), + "all_candidate_offreference_states": len(all_source_rows), + "certified_alternate_full_proofs": len(proof_records), + "max_deviations_per_train_root": cap_per_root, + "alternative_public_menu_proposals": sum(c["alternative_public_menu_proposals"] for c in census), + "alternatives_accepted_in_lean_graph": sum(c["alternatives_accepted_in_lean_graph"] for c in census), + "alternative_finite_continuations": sum(c["alternative_finite_continuations"] for c in census), + "candidate_within_eight_checks": sum(c["candidate_within_eight_checks"] for c in census), + "unreachable_or_over_budget": sum(c["unreachable_or_over_budget"] for c in census), + "independent_compiler_passed": True, + "model_calls_during_collection": 0, + "locked_test_opened": False, + "scientific_eligible": False, + "claim": "native Lean witnessed recoverable legal deviations; source-only coverage not model competence", + "artifacts": {f: sha256_file(out / f) for f in artifacts}, + } + _json(out / "manifest.json", result) + return result + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--suite", type=Path, required=True) + p.add_argument("--teacher", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--roots", type=int, default=64) + p.add_argument("--cap-per-root", type=int, default=2) + p.add_argument("--max-seconds", type=float, default=900) + p.add_argument("--request-timeout", type=int, default=60) + p.add_argument("--cert-timeout", type=int, default=420) + args = p.parse_args(argv) + result = collect(args.suite, args.teacher, args.out, + roots=args.roots, cap_per_root=args.cap_per_root, + max_seconds=args.max_seconds, request_timeout=args.request_timeout, + cert_timeout=args.cert_timeout) + print(canonical({ + "roots": result["training_lineages"], + "novel_states": result["novel_offreference_training_states"], + "roots_with_deviations": result["roots_with_recoverable_deviations"], + "alternate_proofs": result["certified_alternate_full_proofs"], + "candidates": result["candidate_within_eight_checks"], + "unreachable_or_over_budget": result["unreachable_or_over_budget"], + "source_manifest_sha256": result["source_teacher_sha256"], + })) + return result + + +if __name__ == "__main__": + main() From 8ebfdf48612be7f0fe7a0e229e8a84a5f4ddda9a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:35:33 +0800 Subject: [PATCH 02/15] LSA-02H: same-host matched reference/offpath/sham CPU fit with exact duplicate tensors and source draws --- .../lean_cgrt_hrm400/ppt_gym/offpath_train.py | 368 ++++++++++++++++++ 1 file changed, 368 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/offpath_train.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py new file mode 100644 index 000000000..ca84e29e9 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py @@ -0,0 +1,368 @@ +"""LSA-02H: one-worker matched CPU fit on verified off-reference Lean states. + +Same frozen Plan B, pp96 public input, original 64 theorem roots, the exact +seeded source-root and in-root sampler, and 720 AdamW steps per arm. The sole +intervention is the type of a prespecified additional source record on an +identical root/switch draw: + + reference: the original verified shortest reference-path frame + offpath: verified novel correction state after a legal recoverable deviation + sham: another native shortest reference-path frame of the same root + +The offpath and sham arms have identical opportunities to replace the base +frame; the total number of optimizer steps, physical parameters and initial +tensors match. A state from a calibration or locked-test lineage is refused. +""" +from __future__ import annotations + +import argparse +from collections import defaultdict +from dataclasses import asdict +import hashlib +import json +import os +from pathlib import Path +import platform +import random +import sys +import time + +import torch + +from .core import Config, PlasticProofTransformer, supervised_loss +from .data import canonical, sha256_file +from .determinism_audit import _compare_checkpoints +from .native_train import _load_teacher, _model_fingerprint +from .offpath_source import SCHEMA as OFFPATH_SCHEMA, ROW_SCHEMA +from .typed_state import encode_public_packet, schema_for_view + + +SCHEMA = "lsa02h.matched_recoverable_offpath_cpu.v1" +SEEDS = (157, 163) +ARMS = ("reference", "offpath", "sham") +VIEW = "pp96" +STEPCOUNT = 720 +SWITCH_MODULUS = 2 + + +def _json(path: Path): + return json.loads(path.read_text(encoding="utf-8")) + + +def _rows(path: Path) -> list[dict]: + return [json.loads(s) for s in path.read_text(encoding="utf-8").splitlines() if s.strip()] + + +def _write(path: Path, value: dict) -> None: + path.write_text(canonical(value) + "\n", encoding="utf-8") + + +def _load_offpath(teacher: Path, pack: Path, native_frames: list[dict], + source_meta: dict) -> tuple[dict[str, list[dict]], dict]: + manifest = _json(pack / "manifest.json") + if not ( + manifest.get("schema") == OFFPATH_SCHEMA + and manifest.get("source_teacher_sha256") == sha256_file(teacher / "manifest.json") + and manifest.get("suite_manifest_sha256") == source_meta["source"]["suite_manifest_sha256"] + and manifest.get("backend", {}).get("actual_lean_process") is True + and manifest.get("independent_compiler_passed") is True + and manifest.get("train_split_only") is True + and manifest.get("model_calls_during_collection") == 0 + and manifest.get("locked_test_opened") is False + and manifest.get("training_lineages") == source_meta["independent_lineages"] + and manifest.get("certified_alternate_full_proofs", 0) > 0 + and manifest.get("novel_offreference_training_states", 0) > 0 + and manifest.get("roots_with_recoverable_deviations", 0) > 0 + ): + raise ValueError("native certified offreference training source is missing or empty") + for name, digest in manifest.get("artifacts", {}).items(): + if name != Path(name).name or sha256_file(pack / name) != digest: + raise ValueError("offreference artifact is missing or tampered") + frames = _rows(pack / "offreference_frames.jsonl") + if len(frames) != manifest["novel_offreference_training_states"]: + raise ValueError("novel correction frame count differs from source manifest") + authorized_roots = {r["root"]: r["lineage"] for r in native_frames} + original_by_root: dict[str, set] = defaultdict(set) + for row in native_frames: + original_by_root[row["root"]].add(row["public_state_sha256"]) + by_root: dict[str, list[dict]] = defaultdict(list) + seen = set() + for row in frames: + if ( + row.get("schema") != ROW_SCHEMA + or row.get("source_kind") != "off_reference" + or row.get("source_proof_compiled") is not True + or row.get("root") not in authorized_roots + or authorized_roots[row["root"]] != row.get("lineage") + or row.get("public_state_sha256") in original_by_root[row["root"]] + or row.get("remaining_proof_steps", 1000) > row.get("checks_remaining", 0) + ): + raise ValueError("offreference correction violates root ancestry, novelty or budget") + if row["step"] in seen: + raise ValueError("offreference per-run state ordinal duplicated") + seen.add(row["step"]) + if not ( + 1 <= len(row["candidates"]) <= 64 + and len(row["labels"]) == len(row["candidates"]) + and all(type(x) is int and x in (0,1) for x in row["labels"]) + and any(row["labels"]) + ): + raise ValueError("offreference tactic candidate labels are malformed") + by_root[row["root"]].append(row) + if len(by_root) != manifest["roots_with_recoverable_deviations"]: + raise ValueError("offreference occupied root counts differ") + return by_root, manifest + + +def _sample_roster(reference: list[dict], supplement: dict[str, list[dict]], + seed: int, steps: int) -> list[dict]: + by_root: dict[str, list[dict]] = defaultdict(list) + for row in reference: + by_root[row["root"]].append(row) + roots = sorted(by_root) + rng = random.Random(seed) + result = [] + for i in range(steps): + root = roots[rng.randrange(len(roots))] + index = rng.randrange(len(by_root[root])) + switched = rng.randrange(SWITCH_MODULUS) == 0 and root in supplement + result.append({ + "step": i + 1, + "root": root, + "ref_index": index, + "switched": switched, + "supplement_index": ( + rng.randrange(len(supplement[root])) if switched else -1 + ), + }) + return result + + +def _fit(teacher: Path, source: dict[str, list[dict]], refs: list[dict], + pack_meta: dict, destination: Path, *, seed: int, arm: str, steps: int, + max_seconds: float) -> dict: + if destination.exists() or arm not in ARMS or not 1 <= steps <= 5000: + raise ValueError("fresh matched offreference destination and registered arm required") + ref_by_root: dict[str, list[dict]] = defaultdict(list) + for row in refs: + ref_by_root[row["root"]].append(row) + schedule = _sample_roster(refs, source, seed, steps) + torch.manual_seed(seed) + cfg = Config(plan="b", width=32, heads=4, max_bytes=384).validate() + model = PlasticProofTransformer(cfg).cpu().float() + init_sha = _model_fingerprint(model) + optim = torch.optim.AdamW(model.parameters(), lr=0.001) + destination.mkdir(parents=True) + trace = [] + begun = time.perf_counter() + for draw in schedule: + if time.perf_counter() - begun > max_seconds: + raise TimeoutError("same-worker offreference fit exceeded registered CPU budget") + root = draw["root"] + base = ref_by_root[root][draw["ref_index"]] + chosen = base + kind = "reference" + if draw["switched"] and arm == "offpath": + chosen = source[root][draw["supplement_index"]] + kind = "off_reference" + elif draw["switched"] and arm == "sham": + # Matched root, distinct reference-frame when possible. A + # single-frame root necessarily duplicates the only reference. + base_index = (draw["ref_index"] + 1) % len(ref_by_root[root]) + chosen = ref_by_root[root][base_index] + kind = "reference_sham" + payload = encode_public_packet( + chosen["goal"], chosen["candidates"], + view=VIEW, max_bytes=cfg.max_bytes, + ) + out = model( + payload, chosen["candidates"], depth=2, + checks_remaining=chosen["checks_remaining"], + middle_order="ab", return_all=True, + ) + loss = supervised_loss(out, tuple(chosen["labels"])) + if not bool(torch.isfinite(loss)): + raise FloatingPointError("nonfinite offreference source loss") + optim.zero_grad(set_to_none=True) + loss.backward() + clip = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + if not bool(torch.isfinite(clip)): + raise FloatingPointError("nonfinite source gradients") + optim.step() + trace.append({ + **draw, "kind": kind, "chosen_step": chosen["step"], + "chosen_state_sha256": chosen["public_state_sha256"], + "loss": float(loss.detach()), + }) + model.eval() + path = destination / "checkpoint.pt" + torch.save({ + "schema": "ppt_gym.checkpoint.v1", + "config": asdict(cfg), + "weights": model.state_dict(), + "seed": seed, "train_steps": steps, "train_order": "ab", + "input_view": VIEW, "input_view_schema": schema_for_view(VIEW), + "native_teacher_sha256": sha256_file(teacher / "manifest.json"), + "source_manifest_sha256": pack_meta["suite_manifest_sha256"], + "source_evidence_class": "lean_kernel_verified_reference_path", + "offreference_training_mode": arm, + "offreference_source_manifest_sha256": sha256_file( + teacher.parent / "offreference" / "manifest.json" + ), + "offreference_source_schema": OFFPATH_SCHEMA, + }, path) + optimizer_steps = destination / "optimizer_steps.jsonl" + optimizer_steps.write_text( + "".join(canonical(x) + "\n" for x in trace), encoding="utf-8", + ) + return { + "schema": "lsa02h.offreference_cpu_fit.v1", + "seed": seed, "arm": arm, "view": VIEW, "train_order": "ab", + "native_teacher_sha256": sha256_file(teacher / "manifest.json"), + "offreference_source_manifest_sha256": sha256_file( + teacher.parent / "offreference" / "manifest.json" + ), + "source_manifest_sha256": pack_meta["suite_manifest_sha256"], + "optimizer_steps": len(trace), + "initial_weights_sha256": init_sha, + "final_weights_sha256": _model_fingerprint(model), + "checkpoint_sha256": sha256_file(path), + "optimizer_steps_sha256": sha256_file(optimizer_steps), + "parameter_count": model.parameter_count(), + "offreference_source_roots": len(source), + "offreference_source_frames": sum(len(x) for x in source.values()), + "matched_switch_opportunities": sum(r["switched"] for r in trace), + "actual_offreference_optimizer_draws": sum(r["kind"] == "off_reference" for r in trace), + "actual_sham_optimizer_draws": sum(r["kind"] == "reference_sham" for r in trace), + "mean_final_32_loss": sum(r["loss"] for r in trace[-32:])/min(len(trace),32), + "query_label_optimizer_updates": 0, + "scientific_eligible": False, + } + + +def run(teacher: Path, supplement: Path, out: Path, + *, seeds: tuple[int, ...] = SEEDS, steps: int = STEPCOUNT, + max_seconds_per_fit: float = 300) -> dict: + if out.exists() or not seeds or len(seeds) != len(set(seeds)): + raise ValueError("fresh same-worker output and unique model seeds required") + if steps != STEPCOUNT or max_seconds_per_fit <= 0: + raise ValueError("registered 720 CPU steps required") + original, teacher_meta = _load_teacher(teacher) + supplement_rows, pack_meta = _load_offpath( + teacher, supplement, original, teacher_meta, + ) + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + torch.backends.mkldnn.enabled = False + if torch.get_num_threads() != 1: + raise ValueError("one Torch worker-thread contract failed") + # Checkpoint embeds the explicit supplement location under the frozen + # teacher's sibling path; source selection is fixed before fitting. + if supplement.resolve() != (teacher.parent / "offreference").resolve(): + raise ValueError("supplement must be the manifest-attested teacher sibling") + out.mkdir(parents=True) + all_cells = [] + for seed in seeds: + init = set() + samplers = {} + for arm in ARMS: + base = out / "fits" / f"{seed}-{arm}" + duplicate = out / "replicas" / f"{seed}-{arm}" + base.parent.mkdir(parents=True, exist_ok=True) + duplicate.parent.mkdir(parents=True, exist_ok=True) + first = _fit( + teacher, supplement_rows, original, pack_meta, base, + seed=seed, arm=arm, steps=steps, + max_seconds=max_seconds_per_fit, + ) + repeated = _fit( + teacher, supplement_rows, original, pack_meta, duplicate, + seed=seed, arm=arm, steps=steps, + max_seconds=max_seconds_per_fit, + ) + identity = _compare_checkpoints(base / "checkpoint.pt", + duplicate / "checkpoint.pt") + if not ( + first["optimizer_steps"] == repeated["optimizer_steps"] == steps + and identity["all_tensors_bitwise_equal"] + and identity["full_checkpoint_bytes_equal"] + and first["optimizer_steps_sha256"] == repeated["optimizer_steps_sha256"] + and first["initial_weights_sha256"] == repeated["initial_weights_sha256"] + and first["final_weights_sha256"] == repeated["final_weights_sha256"] + ): + raise ValueError("offreference same-host fit duplicate failed exact equality") + records = _records(base / "optimizer_steps.jsonl") + samplers[arm] = [ + (r["step"],r["root"],r["ref_index"],r["switched"],r["supplement_index"]) + for r in records + ] + init.add(first["initial_weights_sha256"]) + all_cells.append(first) + if len(init) != 1 or any( + samplers[arm] != samplers[ARMS[0]] for arm in ARMS[1:] + ): + raise ValueError("matched offreference arms had different initial weights or sample schedule") + report = { + "schema": SCHEMA, + "teacher_manifest_sha256": sha256_file(teacher / "manifest.json"), + "offreference_manifest_sha256": sha256_file(supplement / "manifest.json"), + "suite_manifest_sha256": pack_meta["suite_manifest_sha256"], + "training_lineages": teacher_meta["independent_lineages"], + "train_reference_frames": len(original), + "train_novel_offreference_states": sum(len(r) for r in supplement_rows.values()), + "train_offreference_roots": len(supplement_rows), + "seed_roster": list(seeds), "arm_roster": list(ARMS), + "view": VIEW, "optimizer_steps_per_cell": steps, + "all_exact_duplicate_fits_passed": True, + "same_seed_identical_source_draws": True, + "same_seed_bitwise_initial_weights": True, + "one_cpu_worker": True, + "torch_threads": torch.get_num_threads(), + "torch_deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), + "mkldnn_enabled": torch.backends.mkldnn.enabled, + "torch_version": torch.__version__, + "torch_config_sha256": hashlib.sha256(torch.__config__.show().encode()).hexdigest(), + "python": sys.version, "platform": platform.platform(), + "process_env": {k:os.environ.get(k) for k in ( + "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", + "PYTHONHASHSEED", + )}, + "cells": all_cells, + "native_calibration_queried_during_fit": False, + "test_or_ood_opened": False, + "scientific_eligible": False, + } + _json(out / "manifest.json", report) + return report + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--teacher", type=Path, required=True) + p.add_argument("--supplement", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--steps", type=int, default=STEPCOUNT) + p.add_argument("--seeds", type=int, nargs="+", default=list(SEEDS)) + p.add_argument("--max-seconds-per-fit", type=float, default=300) + a = p.parse_args(argv) + result = run(a.teacher, a.supplement, a.out, + seeds=tuple(a.seeds), steps=a.steps, + max_seconds_per_fit=a.max_seconds_per_fit) + print(canonical({ + "schema": result["schema"], + "offreference_roots": result["train_offreference_roots"], + "offreference_states": result["train_novel_offreference_states"], + "train_schedules_matched": result["same_seed_identical_source_draws"], + "six_duplicate_fits_reproduced": result["all_exact_duplicate_fits_passed"], + "cells": [{ + "seed": x["seed"], "arm": x["arm"], + "offreference_draws": x["actual_offreference_optimizer_draws"], + "sham_draws": x["actual_sham_optimizer_draws"], + "checkpoint_sha256": x["checkpoint_sha256"], + } for x in result["cells"]], + })) + return result + + +if __name__ == "__main__": + main() From d610e7c1e41372e90b93ca87cdef3c62c990abcf Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:36:28 +0800 Subject: [PATCH 03/15] LSA-02H: native Lean evaluator authenticates offreference source proofs and disjoint training roots --- .../lean_cgrt_hrm400/ppt_gym/native_order.py | 41 ++++++++++++++++++- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/native_order.py b/research/lean_cgrt_hrm400/ppt_gym/native_order.py index 80a2da299..c5756088e 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/native_order.py +++ b/research/lean_cgrt_hrm400/ppt_gym/native_order.py @@ -84,7 +84,8 @@ def _interval(deltas: list[int]) -> list[float] | None: def _checkpoint_provenance(checkpoint: dict, training_pack: Path | None, cases, - native_teacher: Path | None = None) -> dict: + native_teacher: Path | None = None, + offpath_source: Path | None = None) -> dict: """Keep prior training ancestry independent of native query proof outcomes.""" result = { "checkpoint_evidence_class": checkpoint.get("source_evidence_class", "unknown"), @@ -129,6 +130,37 @@ def _checkpoint_provenance(checkpoint: dict, training_pack: Path | None, cases, result["native_teacher_manifest_sha256"] = sha256_file(native_teacher) result["training_lineages"] = len(lineages) result["training_evidence"] = "native Lean shortest-continuation labels" + if checkpoint.get("offreference_source_manifest_sha256") or offpath_source is not None: + if offpath_source is None: + raise ValueError("offreference checkpoint requires its attested source manifest") + pack = json.loads(offpath_source.read_text(encoding="utf-8")) + if ( + pack.get("schema") != "lsa02h.recoverable_offreference_train.v1" + or pack.get("source_teacher_sha256") != sha256_file(native_teacher) + or pack.get("suite_manifest_sha256") != teacher["source"]["suite_manifest_sha256"] + or pack.get("backend", {}).get("actual_lean_process") is not True + or pack.get("independent_compiler_passed") is not True + or pack.get("train_split_only") is not True + or pack.get("model_calls_during_collection") != 0 + or pack.get("locked_test_opened") is not False + or checkpoint.get("offreference_source_schema") != pack["schema"] + or checkpoint.get("offreference_source_manifest_sha256") != sha256_file(offpath_source) + ): + raise ValueError("offreference checkpoint source manifest or Lean proof custody differs") + for name, checksum in pack.get("artifacts", {}).items(): + if name != Path(name).name or sha256_file(offpath_source.parent / name) != checksum: + raise ValueError("offreference source artifact checksum changed") + off_rows = _rows(offpath_source.parent / "offreference_frames.jsonl") + if len(off_rows) != pack.get("novel_offreference_training_states"): + raise ValueError("offreference source count differs") + if not all(r["lineage"] in set(lineages) for r in off_rows): + raise ValueError("offreference state lineage crossed native training teacher") + if {r["lineage"] for r in off_rows} & {c.lineage for c in cases}: + raise ValueError("offreference source overlaps native query roots") + result["offreference_source_verified"] = True + result["offreference_states"] = len(off_rows) + result["offreference_manifest_sha256"] = sha256_file(offpath_source) + result["training_evidence"] += " + certified recoverable offreference states" return result if training_pack is None: return result @@ -213,6 +245,7 @@ def run( cert_timeout: int = 120, training_pack: Path | None = None, native_teacher: Path | None = None, + offpath_source: Path | None = None, certified_backend: bool = False, certifier=certify, ) -> dict: @@ -247,7 +280,9 @@ def run( training, _ = load_suite(suite, "train", 1024) if {c.lineage for c in training} & {c.lineage for c in selected}: raise ValueError("training suite lineages overlap queried Lean theorem roots") - provenance = _checkpoint_provenance(checkpoint, training_pack, selected, native_teacher) + provenance = _checkpoint_provenance( + checkpoint, training_pack, selected, native_teacher, offpath_source, + ) checkpoint_hash = sha256_file(checkpoint_path) initial_weights = _weight_fingerprint(model) out.mkdir(parents=True) @@ -525,6 +560,7 @@ def main(argv: list[str] | None = None): run_cmd.add_argument("--checkpoint", type=Path, required=True) run_cmd.add_argument("--training-pack", type=Path) run_cmd.add_argument("--native-teacher", type=Path, help="frozen native teacher manifest.json") + run_cmd.add_argument("--offpath-source", type=Path, help="compiled offreference supplement manifest.json") run_cmd.add_argument("--out", type=Path, required=True) run_cmd.add_argument("--split", choices=("calibration", "ordinary_test", "ood_family"), default="calibration") @@ -547,6 +583,7 @@ def main(argv: list[str] | None = None): depth=args.depth, max_seconds=args.max_seconds, cert_timeout=args.cert_timeout, training_pack=args.training_pack, native_teacher=args.native_teacher, + offpath_source=args.offpath_source, certified_backend=True, ) else: From 9a40853b7c555350d0c392017e58cf334c2a2de4 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:37:41 +0800 Subject: [PATCH 04/15] LSA-02H: simulate recoverable and dead alternative Lean branches, verify novel states and tactic-budget labels --- .../ppt_gym/tests/test_offpath_source.py | 138 ++++++++++++++++++ 1 file changed, 138 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py new file mode 100644 index 000000000..d9931a478 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py @@ -0,0 +1,138 @@ +"""LSA-02H negative and positive off-reference source contracts (synthetic only).""" +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path +import tempfile +import unittest + +import torch + +from ppt_gym.data import canonical, sha256_file +from ppt_gym.live_lean import candidate_menu +from ppt_gym.native_train import _snapshot_trajectory +from ppt_gym.offpath_source import _collect_case, _completion_script + + +CONTEXT = [ + {"name": f"P{i}", "type": {"sort": "Prop"}} for i in range(3) +] + [ + {"name": "h0", "type": {"a": "P0"}}, + {"name": "r0", "type": {"imp": [{"a": "P0"}, {"a": "P1"}]}}, + {"name": "r1", "type": {"imp": [{"a": "P2"}, {"a": "P1"}]}}, + {"name": "r2", "type": {"imp": [{"a": "P0"}, {"a": "P2"}]}}, +] + + +class SmallLean: + version = "SIMULATED ONLY" + def __init__(self): + self.contexts = {"ctx0": CONTEXT} + self.states = {} + self.nextid = 0 + + def reset(self): + self.states = {} + self.nextid = 0 + return {"ok": True} + + def _state(self, target): + self.nextid += 1 + goals = [] if target is None else [{ + "ctx": "ctx0", "pp": f"⊢ {target}", "target": {"a": target}, + }] + s = {"sid": self.nextid, "goals": goals} + self.states[self.nextid] = s + return s + + def init(self, statement, pp=True): + return self._state("P1") + + def run(self, sid, tactic): + target = self.states[sid]["goals"][0]["target"]["a"] + routes = { + ("P1", "apply r0"): "P0", + ("P1", "apply r1"): "P2", + ("P2", "apply r2"): "P0", + ("P0", "apply h0"): None, + } + if (target, tactic) not in routes: + return {"ok": False, "error": "not a proof"} + return {"ok": True, "state": self._state(routes[(target, tactic)])} + + def kernel(self, sid): + return {"ok": not self.states[sid]["goals"], "axioms": []} + + +@dataclass +class FakeCase: + root: str = "dummy_root" + lineage: str = "dummy_lineage" + family: str = "alt" + tid: str = "dummy_theorem" + statement: str = "synthetic" + + def theorem(self): + return object() + + +ORACLE = { + "proof": {"script": ["apply r0", "apply h0"], + "repl_kernel": {"ok": True, "axioms": []}}, + "table": { + "P1": {"apply r0": ["P0"], "apply r1": ["P2"]}, + "P2": {"apply r2": ["P0"]}, + "P0": {"apply h0": []}, + }, + "size": {"P0": 1, "P2": 2, "P1": 2}, +} + + +class OffReferenceSourceTests(unittest.TestCase): + def setUp(self): + torch.set_num_threads(1) + + def test_native_graph_alternative_reaches_novel_certified_correction(self): + lean = SmallLean() + case = FakeCase() + ref = _snapshot_trajectory(lean, case, ORACLE) + self.assertEqual(len(ref), 2) + extra, records, census = _collect_case(lean, case, ORACLE, ref) + self.assertEqual(len(extra), 1) + self.assertEqual(len(records), 1) + self.assertEqual(records[0][2], ["apply r1", "apply r2", "apply h0"]) + self.assertEqual(len(extra[0]["correction_states"]), 1) + state = extra[0]["correction_states"][0] + self.assertEqual(state["source_kind"], "off_reference") + self.assertEqual(state["candidates"], ["apply r2"]) + self.assertEqual(state["labels"], [1]) + self.assertEqual(state["checks_remaining"], 7) + self.assertEqual(state["remaining_proof_steps"], 2) + self.assertNotIn(state["public_state_sha256"], + {r["public_state_sha256"] for r in ref}) + self.assertEqual(census["candidate_within_eight_checks"], 1) + self.assertEqual(census["offreference_training_frames"], 1) + + def test_dead_alternative_is_counted_as_ineligible(self): + lean = SmallLean() + case = FakeCase() + ref = _snapshot_trajectory(lean, case, ORACLE) + alt = json.loads(canonical(ORACLE)) + alt["size"]["P2"] = None + new, scripts, census = _collect_case(lean, case, alt, ref) + self.assertEqual(new, []) + self.assertEqual(scripts, []) + self.assertEqual(census["unreachable_or_over_budget"], 1) + + def test_no_fake_full_proof_can_be_claimed_for_an_unprovable_goal(self): + self.assertIsNone(_completion_script( + ORACLE, [{"target": {"a": "P3"}}], + )) + self.assertEqual(_completion_script( + ORACLE, [{"target": {"a": "P2"}}], + ), ["apply r2", "apply h0"]) + + +if __name__ == "__main__": + unittest.main() From e1eb6d6d7603968c987555ae779e8e4d9efc26d0 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:40:08 +0800 Subject: [PATCH 05/15] LSA-02H: post-native Lean calibration of recoverable offpath states and root-paired proof contrasts --- .../lean_cgrt_hrm400/ppt_gym/offpath_eval.py | 515 ++++++++++++++++++ 1 file changed, 515 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py new file mode 100644 index 000000000..e3adf398a --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py @@ -0,0 +1,515 @@ +"""LSA-02H: post-scoring Lean reference and off-reference calibration. + +This job MUST depend on all native proof evaluation jobs in GitHub Actions. +Its fresh calibration-state labels are never available to source fitting. +Native Lean certifies complete reference and recoverable alternate scripts. +Frozen Plan B models are scored on the same reference-path and offpath states; +all statistics are paired by unique theorem lineage, not tactic frame count. +""" +from __future__ import annotations + +import argparse +from collections import defaultdict +import json +from pathlib import Path +import random + +import torch + +from lcgrt import config +from lcgrt.certify import certify, decl_name +from lcgrt.extract import explore +from lcgrt.lean_repl import LeanRepl +from .cli import checkpoint_load +from .data import canonical, sha256_file +from .live_lean import fingerprint +from .live_suite import load_suite +from .native_train import _load_teacher, _snapshot_trajectory +from .offpath_source import _collect_case +from .offpath_train import SCHEMA as TRAIN_SCHEMA, SEEDS, ARMS, VIEW, _load_offpath +from .uniform_baseline import SCHEMA as RANDOM_SCHEMA + + +SCHEMA = "lsa02h.native_offreference_calibration.v1" +BOOTSTRAPS = 2000 + + +def _read(path: Path) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def _rows(path: Path) -> list[dict]: + return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] + + +def _write(path: Path, value: dict) -> None: + path.write_text(canonical(value) + "\n", encoding="utf-8") + + +def _hash_artifacts(directory: Path, manifest: dict) -> None: + if not manifest: + raise ValueError("missing Lean compiler artifact custody") + for filename, checksum in manifest.items(): + if filename != Path(filename).name or sha256_file(directory / filename) != checksum: + raise ValueError("native corpus or replay artifact hash differs: " + filename) + + +def _bootstrap(values: list[float]) -> list[float] | None: + if len(values) < 2: + return None + rng = random.Random(20261130) + size = len(values) + means = sorted( + sum(values[rng.randrange(size)] for _ in range(size)) / size + for _ in range(BOOTSTRAPS) + ) + return [means[int(BOOTSTRAPS * .025)], means[int(BOOTSTRAPS * .975)-1]] + + +def collect(repl, suite: Path, teacher: Path, out: Path, *, + roots: int = 32, cert_timeout: int = 420, + certified_backend: bool = False) -> dict: + if out.exists() or roots != 32: + raise ValueError("fresh calibration reference with 32 independent roots required") + train_rows, teacher_meta = _load_teacher(teacher) + cases, suite_meta = load_suite(suite, "calibration", roots) + if teacher_meta["source"]["suite_manifest_sha256"] != suite_meta["suite_manifest_sha256"]: + raise ValueError("calibration reference changed training theorem suite") + if {r["lineage"] for r in train_rows} & {c.lineage for c in cases}: + raise ValueError("new calibration roots overlap original training source") + if certified_backend and ( + not isinstance(repl, LeanRepl) or repl.version != "4.19.0" + ): + raise ValueError("need pinned real Lean 4.19.0 for reference state authority") + all_refs, all_off, census, proofs = [], [], [], [] + for case in cases: + oracle = explore(repl, case.theorem()) + ref = _snapshot_trajectory(repl, case, oracle) + off, alt_proofs, source_counts = _collect_case(repl, case, oracle, ref) + ref_frames = [ + f for f in ref + if len(oracle["proof"]["script"]) <= 8 and len(f["labels"]) > 1 + and 0 < sum(f["labels"]) < len(f["labels"]) + ] + all_refs.extend(ref_frames) + for candidate in off: + all_off.extend(candidate["correction_states"]) + proofs.append((case.tid, case.theorem(), oracle["proof"]["script"])) + proofs.extend(alt_proofs) + census.append({ + "root": case.root, + "lineage": case.lineage, + "reference_size": len(oracle["proof"]["script"]), + "within_budget": len(oracle["proof"]["script"]) <= 8, + "reference_forks": len(ref_frames), + "offpath_correction_states": sum(len(a["correction_states"]) for a in off), + "offpath_discriminating_forks": sum( + len(r["labels"]) > 1 and 0 < sum(r["labels"]) < len(r["labels"]) + for a in off for r in a["correction_states"] + ), + "offpath_full_proofs": len(alt_proofs), + "source_alternatives_within_budget": source_counts["candidate_within_eight_checks"], + }) + out.mkdir(parents=True) + receipt = certify(proofs, timeout=cert_timeout, + keep=out / "standalone.lean") + if receipt.get("timed_out") or any( + receipt.get("status", {}).get(decl_name(tid)) != "passed" + for tid, _, _ in proofs + ): + raise ValueError("calibration reference or recoverable alternate proof failed standalone compilation") + for name, rows in (("reference_forks.jsonl", all_refs), + ("offreference_frames.jsonl", all_off), + ("calibration_census.jsonl", census)): + with (out / name).open("x", encoding="utf-8") as stream: + for row in rows: + stream.write(canonical(row) + "\n") + _write(out / "compiler_receipt.json", receipt) + report = { + "schema": "lsa02h.lean_calibration_state_evidence.v1", + "suite_manifest_sha256": suite_meta["suite_manifest_sha256"], + "teacher_manifest_sha256": sha256_file(teacher / "manifest.json"), + "backend": ( + fingerprint(config.REPL_EXE, config.LEAN_EXE, repl.version) + if certified_backend else {"actual_lean_process": False} + ), + "independent_calibration_roots": len(census), + "independently_compiled_reference_roots": len(cases), + "independently_compiled_recoverable_deviations": sum(r["offpath_full_proofs"] for r in census), + "reference_fork_frames": len(all_refs), + "reference_fork_roots": sum(r["reference_forks"] > 0 for r in census), + "offreference_correction_frames": len(all_off), + "offreference_correction_roots": sum(r["offpath_correction_states"] > 0 for r in census), + "offreference_discriminating_fork_frames": sum(r["offpath_discriminating_forks"] for r in census), + "offreference_discriminating_fork_roots": sum(r["offpath_discriminating_forks"] > 0 for r in census), + "source_labels_produced_after_native_model_runs": True, + "calibration_optimizer_updates": 0, + "locked_test_opened": False, + "artifacts": {name: sha256_file(out / name) for name in ( + "reference_forks.jsonl", "offreference_frames.jsonl", + "calibration_census.jsonl", "standalone.lean", "compiler_receipt.json", + )}, + } + _write(out / "manifest.json", report) + return report + + +def _score_forks(model, rows: list[dict], *, require_fork: bool) -> dict[str, dict]: + by_root = defaultdict(list) + with torch.no_grad(): + for row in rows: + labels = row["labels"] + fork = len(labels) > 1 and 0 < sum(labels) < len(labels) + if require_fork and not fork: + continue + if len(labels) == 0 or not any(labels): + raise ValueError("calibration state omitted a shortest continuation witness") + goal = model( + __import__("ppt_gym.typed_state", fromlist=["encode_public_packet"]).encode_public_packet( + row["goal"], row["candidates"], + view=VIEW, max_bytes=model.cfg.max_bytes, + ), + row["candidates"], depth=2, + checks_remaining=row["checks_remaining"], middle_order="ab", + )[-1]["logits"] + chosen = int(goal.argmax()) + by_root[row["root"]].append({ + "correct": int(labels[chosen] == 1), + "uniform": sum(labels) / len(labels), + "fork": fork, + }) + return { + root: { + "states": len(values), + "correct": sum(x["correct"] for x in values), + "accuracy": sum(x["correct"] for x in values)/len(values), + "uniform_optimal_accuracy": sum(x["uniform"] for x in values)/len(values), + } for root, values in by_root.items() + } + + +def aggregate(teacher: Path, supplement: Path, fits: Path, probes: Path, + random_pack: Path, cal_source: Path, out: Path) -> dict: + if out.exists(): + raise ValueError("fresh calibration aggregate output is required") + original, teacher_meta = _load_teacher(teacher) + off_pool, off_meta = _load_offpath( + teacher, supplement, original, teacher_meta, + ) + teacher_sha = sha256_file(teacher / "manifest.json") + off_sha = sha256_file(supplement / "manifest.json") + trained = _read(fits / "manifest.json") + calibration = _read(cal_source / "manifest.json") + _hash_artifacts(cal_source, calibration["artifacts"]) + cal_census = _rows(cal_source / "calibration_census.jsonl") + ref_frames = _rows(cal_source / "reference_forks.jsonl") + off_frames = _rows(cal_source / "offreference_frames.jsonl") + if not ( + calibration.get("schema") == "lsa02h.lean_calibration_state_evidence.v1" + and calibration.get("suite_manifest_sha256") == teacher_meta["source"]["suite_manifest_sha256"] + and calibration.get("teacher_manifest_sha256") == teacher_sha + and calibration.get("backend", {}).get("actual_lean_process") is True + and calibration.get("independent_calibration_roots") == 32 + and calibration.get("independently_compiled_reference_roots") == 32 + and calibration.get("source_labels_produced_after_native_model_runs") is True + and calibration.get("calibration_optimizer_updates") == 0 + and calibration.get("locked_test_opened") is False + and len(cal_census) == 32 + and len({r["lineage"] for r in cal_census}) == 32 + and len(ref_frames) == calibration["reference_fork_frames"] + and len(off_frames) == calibration["offreference_correction_frames"] + ): + raise ValueError("post-proof calibration reference/alternate state evidence invalid") + if {r["lineage"] for r in original} & {r["lineage"] for r in cal_census}: + raise ValueError("native training and calibration lineage overlap") + if not ( + trained.get("schema") == TRAIN_SCHEMA + and trained.get("teacher_manifest_sha256") == teacher_sha + and trained.get("offreference_manifest_sha256") == off_sha + and trained.get("suite_manifest_sha256") == teacher_meta["source"]["suite_manifest_sha256"] + and trained.get("training_lineages") == teacher_meta["independent_lineages"] + and trained.get("train_novel_offreference_states") == sum(len(r) for r in off_pool.values()) + and trained.get("seed_roster") == list(SEEDS) + and trained.get("arm_roster") == list(ARMS) + and trained.get("view") == VIEW + and trained.get("optimizer_steps_per_cell") == 720 + and trained.get("all_exact_duplicate_fits_passed") is True + and trained.get("same_seed_identical_source_draws") is True + and trained.get("same_seed_bitwise_initial_weights") is True + and trained.get("one_cpu_worker") is True + and trained.get("torch_threads") == 1 + and trained.get("torch_deterministic_algorithms") is True + and trained.get("mkldnn_enabled") is False + and trained.get("native_calibration_queried_during_fit") is False + and trained.get("test_or_ood_opened") is False + and len(trained["cells"]) == len(SEEDS) * len(ARMS) + ): + raise ValueError("offreference same-host fit evidence differs from source registry") + training_cells = {(c["seed"], c["arm"]): c for c in trained["cells"]} + all_roots = [] + cells = [] + frozen = {} + torch.set_num_threads(1) + for seed in SEEDS: + initial = set() + for arm in ARMS: + item = training_cells[(seed,arm)] + key = f"{seed}-{arm}" + folder = fits / "fits" / key + path = folder / "checkpoint.pt" + cp_sha = sha256_file(path) + cp = _read(folder / "checkpoint.json") if (folder / "checkpoint.json").exists() else {} + model, saved = checkpoint_load(path) + if not ( + item["checkpoint_sha256"] == cp_sha + and saved.get("seed") == seed + and saved.get("train_order") == "ab" + and saved.get("offreference_training_mode") == arm + and saved.get("offreference_source_manifest_sha256") == off_sha + and saved.get("native_teacher_sha256") == teacher_sha + and saved.get("input_view") == VIEW + and model.parameter_count() == 57475 + and model.cfg.max_bytes == 384 + and item["optimizer_steps"] == 720 + and item["query_label_optimizer_updates"] == 0 + ): + raise ValueError("checkpoint differs from the registered offreference source/model") + initial.add(item["initial_weights_sha256"]) + evaldir = probes / key + proofdir = evaldir / "lsa02h-proof" + receipt = _read(proofdir / "manifest.json") + replay = _read(evaldir / "lsa02h-replay" / "replay.json") + _hash_artifacts(proofdir, receipt["artifacts"]) + if not ( + receipt.get("schema") == "lsa02b.native_block_order.v1" + and receipt.get("status") == "complete" + and receipt.get("checkpoint_sha256") == cp_sha + and receipt.get("input_view") == VIEW + and receipt.get("paired_roots") == 32 + and receipt.get("standalone_reference_certificates") == 32 + and receipt.get("training_provenance", {}).get("offreference_source_verified") is True + and receipt.get("training_provenance", {}).get("offreference_manifest_sha256") == off_sha + and receipt.get("training_provenance", {}).get("source_lineages_disjoint") is True + and receipt.get("backend", {}).get("actual_lean_process") is True + and receipt.get("query_label_training_updates") == 0 + and replay.get("replay_passed") is True + and replay.get("independent_replay_episodes") == 96 + and replay.get("session_manifest_sha256") == sha256_file(proofdir / "manifest.json") + ): + raise ValueError("offreference native proof and replay custody mismatch") + roots = _rows(proofdir / "paired_roots.jsonl") + if len(roots) != 32 or len({r["lineage"] for r in roots}) != 32: + raise ValueError("native proof evaluation repeated theorem roots") + all_roots.append({r["root"] for r in roots}) + frozen[key] = { + "proofs": {r["root"]:r for r in roots}, + "off": _score_forks(model.eval(), off_frames, require_fork=False), + "off_forks": _score_forks(model.eval(), off_frames, require_fork=True), + "reference": _score_forks(model.eval(), ref_frames, require_fork=True), + } + cells.append({ + "seed": seed, "arm": arm, + "full_proofs": receipt["scores"]["ab"]["standalone_verified_closures"], + "native_attainable": receipt["reference_reachable_within_budget"], + "auto8_proofs": receipt["scores"]["auto8"]["standalone_verified_closures"], + "reference_fork_roots": len(frozen[key]["reference"]), + "reference_fork_root_mean_accuracy": ( + sum(s["accuracy"] for s in frozen[key]["reference"].values()) / + len(frozen[key]["reference"]) if frozen[key]["reference"] else None + ), + "offpath_state_roots": len(frozen[key]["off"]), + "offpath_state_root_mean_accuracy": ( + sum(s["accuracy"] for s in frozen[key]["off"].values()) / + len(frozen[key]["off"]) if frozen[key]["off"] else None + ), + "offpath_fork_roots": len(frozen[key]["off_forks"]), + "offpath_fork_root_mean_accuracy": ( + sum(s["accuracy"] for s in frozen[key]["off_forks"].values()) / + len(frozen[key]["off_forks"]) if frozen[key]["off_forks"] else None + ), + "offreference_optimizer_draws": item["actual_offreference_optimizer_draws"], + "sham_optimizer_draws": item["actual_sham_optimizer_draws"], + "checkpoint_sha256": cp_sha, + }) + if len(initial) != 1: + raise ValueError("offreference same-seed initial weights differ") + if any(roots != all_roots[0] for roots in all_roots[1:]): + raise ValueError("native proof cohorts differ by training arm") + if {r["root"] for r in cal_census} != all_roots[0]: + raise ValueError("native reference correction cohort differs from evaluated proof roots") + uniform = _read(random_pack / "manifest.json") + uniform_replay = _read(random_pack / "replay" / "replay.json") + _hash_artifacts(random_pack, uniform["artifacts"]) + if not ( + uniform.get("schema") == "lsa02f.uniform_menu_native.v1" + and uniform.get("source_teacher_sha256") == teacher_sha + and uniform.get("independent_calibration_roots") == 32 + and uniform.get("seed_roster") == [17,31,47,61,83] + and uniform.get("native_model_calls") == 0 + and uniform.get("all_replays_passed") is True + and uniform.get("backend", {}).get("actual_lean_process") is True + and uniform_replay.get("all_replays_passed") is True + and uniform_replay.get("verified_episodes") == 160 + and uniform_replay.get("session_manifest_sha256") == sha256_file(random_pack / "manifest.json") + ): + raise ValueError("independent uniform native reference lacks verified custody") + random_roots = _rows(random_pack / "root_scores.jsonl") + if len(random_roots) != 32 or {r["root"] for r in random_roots} != all_roots[0]: + raise ValueError("random-menu native theorem roster differs from neural cohort") + random_by_root = {r["root"]:r["mean_seed_closure"] for r in random_roots} + + root_table = [] + for row in cal_census: + root = row["root"] + seed_views = [] + for seed in SEEDS: + base = frozen[f"{seed}-reference"]["proofs"][root] + for arm in ARMS: + x = frozen[f"{seed}-{arm}"]["proofs"][root] + if ( + x["lineage"] != base["lineage"] + or x["reference_budget_attainable"] != base["reference_budget_attainable"] + or x["auto8_certified"] != base["auto8_certified"] + ): + raise ValueError("same-root native proof authority differs among arms") + seed_views.append({ + "seed": seed, + "proofs": {a:int(frozen[f"{seed}-{a}"]["proofs"][root]["ab_certified"]) for a in ARMS}, + "reference_forks": { + a:frozen[f"{seed}-{a}"]["reference"][root]["accuracy"] for a in ARMS + } if row["reference_forks"] else {}, + "offpath_states": { + a:frozen[f"{seed}-{a}"]["off"][root]["accuracy"] for a in ARMS + } if row["offpath_correction_states"] else {}, + "offpath_forks": { + a:frozen[f"{seed}-{a}"]["off_forks"][root]["accuracy"] for a in ARMS + } if row["offpath_discriminating_forks"] else {}, + }) + root_table.append({ + "root": root, "lineage": row["lineage"], + "random_mean": random_by_root[root], + "reference_within_budget": row["within_budget"], + "calibration_offreference_states": row["offpath_correction_states"], + "calibration_offreference_forks": row["offpath_discriminating_forks"], + "seed_views": seed_views, + }) + + def effect(field: str, arm: str = "offpath", control: str = "reference"): + deltas=[] + for row in root_table: + sample=[] + for entry in row["seed_views"]: + vals=entry[field] + if vals: + sample.append(vals[arm] - vals[control]) + if sample: + deltas.append(sum(sample)/len(sample)) + return { + "root_count": len(deltas), + "mean": sum(deltas)/len(deltas) if deltas else None, + "descriptive_root_bootstrap95": _bootstrap(deltas), + } + + proof_rate = { + arm: sum(c["full_proofs"] for c in cells if c["arm"] == arm)/(32*len(SEEDS)) + for arm in ARMS + } + off_count = calibration["offreference_discriminating_fork_frames"] + off_roots = calibration["offreference_discriminating_fork_roots"] + effects = { + "offpath_minus_reference_full_proof": effect("proofs"), + "offpath_minus_sham_full_proof": effect("proofs", control="sham"), + "offpath_minus_reference_on_offpath_forks": effect("offpath_forks"), + "offpath_minus_sham_on_offpath_forks": effect("offpath_forks", control="sham"), + "offpath_minus_reference_on_offpath_all": effect("offpath_states"), + "offpath_minus_reference_on_reference_forks": effect("reference_forks"), + } + eligible = off_count >= 16 and off_roots >= 8 + screen = bool( + eligible + and effects["offpath_minus_reference_on_offpath_forks"]["mean"] is not None + and effects["offpath_minus_sham_on_offpath_forks"]["mean"] is not None + and effects["offpath_minus_reference_on_offpath_forks"]["mean"] >= 0.05 + and effects["offpath_minus_sham_on_offpath_forks"]["mean"] >= 0.05 + and effects["offpath_minus_reference_full_proof"]["mean"] >= 0 + and effects["offpath_minus_sham_full_proof"]["mean"] >= 0 + ) + random_rate=uniform["uniform_mean_closure_rate"] + competence=max(proof_rate.values())>=.40 and max(proof_rate.values())-random_rate>=.10 + report = { + "schema": SCHEMA, + "teacher_sha256": teacher_sha, + "offreference_source_sha256": off_sha, + "native_calibration_source_sha256": sha256_file(cal_source / "manifest.json"), + "uniform_manifest_sha256": sha256_file(random_pack / "manifest.json"), + "training_manifest_sha256": sha256_file(fits / "manifest.json"), + "train_roots": teacher_meta["independent_lineages"], + "train_reference_frames": len(original), + "train_offreference_states": sum(len(r) for r in off_pool.values()), + "train_offreference_roots": len(off_pool), + "calibration_unique_roots": len(cal_census), + "calibration_reference_fork_roots": calibration["reference_fork_roots"], + "calibration_reference_forks": calibration["reference_fork_frames"], + "calibration_offreference_roots": calibration["offreference_correction_roots"], + "calibration_offreference_states": len(off_frames), + "calibration_offreference_fork_roots": off_roots, + "calibration_offreference_forks": off_count, + "offpath_screen_eligible": eligible, + "model_seeds": list(SEEDS), "arms":list(ARMS), "view":VIEW, + "native_close_rates": proof_rate, + "native_uniform_mean_rate": random_rate, + "random_seeds":uniform["seed_roster"], + "native_reference_attainable":sum(r["within_budget"] for r in cal_census), + "effects": effects, + "predeclared_development_screen_passed": screen, + "formal_competence_floor_met": competence, + "formal_competence_gate": ( + "NEEDS_NEW_SEALED_CONFIRMATION" if competence + else "BLOCKED_INCOMPETENT_CHECKPOINT" + ), + "cells":cells, "root_results":root_table, + "calibration_labels_collected_after_all_native_model_scoring": True, + "calibration_optimizer_updates":0, + "locked_test_or_ood_opened":False, + "scientific_eligible":False, + "architecture_promotion_eligible":False, + "caveat": "Native Lean recoverable off-reference training; all correction-state statistics are root-clustered. Sparse fork coverage fails closed.", + } + out.mkdir(parents=True) + _write(out / "matched_offreference.json", report) + return report + + +def main(argv=None): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument("--suite",type=Path,required=True) + p.add_argument("--teacher",type=Path,required=True) + p.add_argument("--supplement",type=Path,required=True) + p.add_argument("--fits",type=Path,required=True) + p.add_argument("--probes",type=Path,required=True) + p.add_argument("--uniform",type=Path,required=True) + p.add_argument("--reference",type=Path,required=True) + p.add_argument("--out",type=Path,required=True) + p.add_argument("--request-timeout",type=int,default=60) + a=p.parse_args(argv) + with LeanRepl(timeout=a.request_timeout,exe=config.REPL_EXE, + cwd=config.LEAN_DIR,env=config.lean_env()) as repl: + ref=collect(repl,a.suite,a.teacher,a.reference,certified_backend=True) + result=aggregate(a.teacher,a.supplement,a.fits,a.probes, + a.uniform,a.reference,a.out) + print(canonical({ + "calibration_roots":result["calibration_unique_roots"], + "offreference_states":result["calibration_offreference_states"], + "offreference_forks":result["calibration_offreference_forks"], + "offreference_fork_roots":result["calibration_offreference_fork_roots"], + "root_paired_proof_rates":result["native_close_rates"], + "uniform_native_rate":result["native_uniform_mean_rate"], + "screen_eligible":result["offpath_screen_eligible"], + "screen":result["predeclared_development_screen_passed"], + "effects":result["effects"], + })) + return result + + +if __name__=="__main__": + main() From 77ba410993372fe99e733217b94fdcb1131fbbfb Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:42:13 +0800 Subject: [PATCH 06/15] LSA-02H preregistration: certified recoverable deviations, same-root sham and calibration fork coverage gate --- docs/lsa02h_offpath_native_cpu_protocol.md | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 docs/lsa02h_offpath_native_cpu_protocol.md diff --git a/docs/lsa02h_offpath_native_cpu_protocol.md b/docs/lsa02h_offpath_native_cpu_protocol.md new file mode 100644 index 000000000..9670740fe --- /dev/null +++ b/docs/lsa02h_offpath_native_cpu_protocol.md @@ -0,0 +1,74 @@ +# LSA-02H: Native Lean recoverable off-reference proof states + +**Registration:** November 23, 2026. **Evidence scope:** development-only, CPU/RAM before a full gym. This study follows [LSA-02G](../reports/lsa02g_native_fork_competence_20261123.md), where 4× emphasis on training-reference forks failed the root-weighted Lean calibration fork-accuracy gate twice. The previous verified proof policies visited states outside their shortest-reference training trajectories, motivating a falsifiable *state-coverage* experiment. + +## Hypothesis and source validity + +**Hypothesis:** adding truly novel, independently certified **recoverable off-reference proof states** to training improves theorem completion and decision accuracy at such states more than an equal-compute control using another already-known reference-path state of the same theorem root. + +The existing native teacher derives shortest-continuation labels on the exact reference proof trajectory. LSA-02H takes a controlled, legal alternative tactic from that path. It uses the actual Lean 4.19 tactic prover to reach the alternative successor and then computes the shortest finite completion using the Lean-reported AND/OR action graph. The collector retains a correction state only if: + +- the alternative tactic is in the public menu and succeeds in real Lean; +- the full *root-to-correction-to-terminal* proof has a finite continuation requiring at most **eight tactic checks**; +- the public state fingerprint is absent from that theorem's certified reference trajectory; +- the model-visible action menu has at least one native shortest-continuation witness; +- the **entire altered theorem proof**, including the deviation, is replayed in Lean, kernel-closed, and compiled separately as an axiom-free Lean declaration. + +**Unrecoverable alternatives are recorded as misses.** We never manufacture success labels from the generator's private hints or treat an unprovable dead end as a solvable training example. An off-reference state is a controlled, recoverable deviation from a known shortest proof, not a claim that a particular neural model visited that state. This distinction remains explicit in every receipt. + +The source collector can retain **at most two** successful distinct alternative recovery scripts per training root. Repeated public state/menu/budget identities within a theorem are deduplicated before training. Reference-only states are not relabeled as off-reference. Native source hash, independent terminal certificate status, proof script and lineage are frozen into a supplemental dataset. + +## Fresh theorem roots + +Freeze a **new** Lean-CGRT Horn suite with generator seed `20261201` and 96 independent roots in each of its train, calibration, ordinary-test and OOD-family shards. Compile and freeze a reference-path training teacher from **all 96 training theorem roots**, then collect at most two recoverable legal alternatives per root. The source's precise coverage is a measured outcome. + +Reserve the first **32 independent calibration roots** for the development experiment. The model/native proof evaluation runs first; only when all six checkpoints have completed their Lean proof evaluations does a separate job use native Lean to discover correction states on those calibration roots. Its results are **read-only and never used for optimizer updates or model policy selection**. Ordinary-test and OOD proof outcomes remain sealed. + +A source corpus with zero independently certified novel states fails the training gate. The calibration audit permits a valid low-coverage negative result and registers the absence of independent off-reference forks explicitly. + +## Same-worker training controls + +All models share the original Plan B architecture: **57,475 parameters**, width 32, four attention heads, two AB tied recurrent passes, fixed 384-byte input and the **`pp96`** public typed-plus-pretty representation. Training seeds are **157 and 163**, each with 720 CPU FP32 AdamW updates, learning rate 0.001 and gradient clipping 1. Every seed receives the **identical starting parameter tensors and theorem-root/reference-index/switch sampling schedule** across arms. + +| Arm | Training state used | +| --- | --- | +| `reference` | Only the existing native shortest-reference trajectory frame | +| `offpath` | On a registered switch draw, a **novel certified correction state** from that same theorem root; otherwise the original frame | +| `sham` | On the identical registered switch draw, another certified **reference-trajectory frame from that same theorem root**; otherwise the original frame | + +The sampler picks a theorem root uniformly and then a reference-path index uniformly. A half-probability switch is eligible only when the root has certified off-reference corrections. Switch/supplement indices are selected from a source-only seeded RNG shared across all arms. The sham reproduces the *number and root locations of opportunities* for new state exposure while keeping supervision on the old reference support. For a single-reference-frame theorem, a sham draw necessarily duplicates that frame. + +Each of the six cells is fitted **twice consecutively on one physical GitHub-hosted CPU worker**: 12 fits. Torch deterministic algorithms, one CPU thread, pinned CPU Torch 2.5.1, disabled MKLDNN, and environment fingerprints accompany exact tensor, checkpoint-byte and optimizer-trace equality gates. All actual switched/novel/sham draws are counted. Cross-runner bitwise agreement is an outstanding separate issue and cannot be inferred from within-host duplication. + +## Native outcome authority + +Each trained model evaluates on the same **32 fresh calibration theorem roots** under the real pinned Lean 4.19 `lgym` toolchain, eight tactic attempts, no fine-tuning, and real kernel closure. All closed model proofs undergo independent standalone axiom-free compilation and a second model-free tactic replay. Frozen AB/BA and `auto8` policies are retained as controls, as is the native minimum-proof attainability ceiling. + +A registered five-stream **uniform live public-menu** policy on those same roots (seeds 17/31/47/61/83) supplies the independent model-free proof baseline. Its proof scripts are also kernel-checked, independently compiled and replayed; all policy decisions depend only on public state/menu/seed. + +**Only after these proof outcomes are frozen**, a separate Lean reference evaluator builds the calibration support corpus, independently certifying all 32 reference proofs and every recoverable alternate script. On these states, each checkpoint is scored by frozen AB argmax against native shortest-continuation labels. It reports: + +- **off-reference discriminating fork accuracy**, root weighted (primary state-coverage endpoint); +- **off-reference all-state accuracy**, including forced singleton menus, separately; +- reference-path discriminating fork accuracy, distinct from offpath support; +- complete root-level proof closure and signed paired contrasts to reference/sham. + +An eligible **off-reference discriminating fork** has a public menu with at least two tactics, with both optimal and nonoptimal verified continuations. Off-reference forced states must not inflate the primary endpoint. + +## Registered decision gates + +The primary development screen requires at least **16 independently certified off-reference fork frames spanning at least 8 independent calibration theorem roots**. If that coverage floor fails, the study reports `INSUFFICIENT_OFFPATH_FORK_COVERAGE` and does not claim a fork-action improvement, regardless of any whole-proof changes. + +When eligible, success requires the offpath-trained arm's root-weighted off-reference fork accuracy to exceed **both reference and sham by at least +5 absolute percentage points**, with nonnegative mean whole-proof effects against both. This is a development screen; every root-level contrast is accompanied by a **descriptive 2,000-draw theorem-root bootstrap** and the precise denominator. Seeds are paired within roots and do not increase the number of independent theorems. + +The separate **native competence floor** remains at least 32 independent roots, **≥40% standalone-verified full-proof closure**, and **≥+10 points over the finite native uniform-menu policy**. Only a passing competence preflight may justify registering fresh sealed confirmation and FSI-01, subject to external corpus-ancestry checks. It never directly authorizes architecture promotion or claims Mathlib transfer. + +The experiment does not equate synthetic or deterministic controlled deviations with model-policy on-policy rollout. If recoverable off-reference states are scarce or forced choices dominate them, that is the scientific finding, and the next research mechanism may require explicit backtracking or richer verifier feedback. + +## CPU GitHub Actions and provenance + +The [LSA-02H CI workflow](../.github/workflows/lsa02h-offpath-cpu.yml) runs public/unit tests, builds the frozen teacher, collects and certifies recoverable train-only branches, trains same-host reference/offpath/sham cells, scores independent native random and neural proof episodes, and **then** collects calibration reference/off-reference states for read-only root-paired scoring. + +It records the original native teacher hash, all alternative full-proof compiler certificates, exact lineage and public-state identities, budget adequacy, initial/final weights and source draws, full proof kernel receipts, independent replay receipts and random-menu baseline provenance. Any failed proof or lineage gate aborts the corresponding scientific result. GitHub Actions artifacts retain raw receipts for 14 days and a Markdown report should be committed after successful verification. + +No GPU, local private machine, paid inference, or sealed evaluation is needed. From 8aabfb5a50d957a7f6c8a67f4d3078d619aa431f Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:42:57 +0800 Subject: [PATCH 07/15] LSA-02H test matched root/switch schedules and same-start offreference/sham CPU controls --- .../ppt_gym/tests/test_offpath_train.py | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py new file mode 100644 index 000000000..9eba234b4 --- /dev/null +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py @@ -0,0 +1,93 @@ +"""LSA-02H frozen source-sampler and same-root control tests, synthetic only.""" +from __future__ import annotations + +from dataclasses import dataclass +import json +from pathlib import Path +import tempfile +import unittest + +import torch + +from ppt_gym.data import canonical, sha256_file +from ppt_gym.offpath_train import _fit, _sample_roster +from ppt_gym.tests.test_offpath_source import CONTEXT, SmallLean +from ppt_gym.native_train import _snapshot_trajectory +from ppt_gym.live_lean import state_input +from ppt_gym.tests.test_offpath_source import FakeCase, ORACLE + + +class OffpathCPUFixtures(unittest.TestCase): + def setUp(self): + torch.set_num_threads(1) + + def _rows(self): + repl, case = SmallLean(), FakeCase() + reference = _snapshot_trajectory(repl, case, ORACLE) + repl.reset() + state = repl.init(case.statement, pp=True) + next_state = repl.run(state["sid"], "apply r1")["state"] + goal, sha = state_input(repl, next_state, (), 7) + off = { + "root": case.root, "lineage": case.lineage, + "step": 1000, "goal": goal, "candidates": ["apply r2"], + "labels": [1], "checks_remaining": 7, + "public_state_sha256": sha, + "source_kind": "off_reference", + "remaining_proof_steps": 2, + } + return reference, {case.root: [off]} + + def test_seeded_source_root_and_switch_draws_are_matched(self): + reference, supplement = self._rows() + schedule = _sample_roster(reference, supplement, 157, 60) + self.assertEqual(schedule, _sample_roster(reference, supplement, 157, 60)) + self.assertNotEqual(schedule, _sample_roster(reference, supplement, 163, 60)) + self.assertTrue(any(d["switched"] for d in schedule)) + self.assertEqual({r["root"] for r in schedule}, {"dummy_root"}) + self.assertTrue(all(d["supplement_index"] in (-1, 0) for d in schedule)) + + def test_three_arms_use_same_start_and_switch_opportunities(self): + reference, supplement = self._rows() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + teacher = base / "teacher" + teacher.mkdir() + (teacher / "manifest.json").write_text('{"synthetic":true}') + offpath = base / "offreference" + offpath.mkdir() + (offpath / "manifest.json").write_text('{"synthetic":true}') + receipts=[] + for arm in ("reference", "offpath", "sham"): + output = base / arm + data = _fit( + teacher, supplement, reference, + {"suite_manifest_sha256": "synthetic_fixture"}, + output, seed=157, arm=arm, steps=4, + max_seconds=40, + ) + receipts.append(data) + self.assertEqual(data["optimizer_steps"], 4) + self.assertEqual(data["query_label_optimizer_updates"], 0) + self.assertEqual(data["parameter_count"], 57475) + self.assertTrue((output / "checkpoint.pt").is_file()) + self.assertEqual(len({x["initial_weights_sha256"] for x in receipts}),1) + self.assertEqual(len({x["matched_switch_opportunities"] for x in receipts}),1) + self.assertEqual(receipts[1]["actual_offreference_optimizer_draws"], + receipts[1]["matched_switch_opportunities"]) + self.assertEqual(receipts[2]["actual_sham_optimizer_draws"], + receipts[2]["matched_switch_opportunities"]) + def core(p): + return [tuple((r[k] for k in ( + "step", "root", "ref_index", + "switched", "supplement_index", + ))) for r in ( + json.loads(x) for x in + (p / "optimizer_steps.jsonl").read_text().splitlines() + )] + self.assertEqual(core(base / "reference"), core(base / "offpath")) + self.assertEqual(core(base / "reference"), core(base / "sham")) + + +if __name__ == "__main__": + unittest.main() From 820e69cd471a0255da02f8ce59615b1a13b7efa9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:43:15 +0800 Subject: [PATCH 08/15] LSA-02H: use direct public state encoder in frozen calibration scorer --- research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py index e3adf398a..6c3322d05 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py @@ -28,6 +28,7 @@ from .offpath_source import _collect_case from .offpath_train import SCHEMA as TRAIN_SCHEMA, SEEDS, ARMS, VIEW, _load_offpath from .uniform_baseline import SCHEMA as RANDOM_SCHEMA +from .typed_state import encode_public_packet SCHEMA = "lsa02h.native_offreference_calibration.v1" @@ -165,7 +166,7 @@ def _score_forks(model, rows: list[dict], *, require_fork: bool) -> dict[str, di if len(labels) == 0 or not any(labels): raise ValueError("calibration state omitted a shortest continuation witness") goal = model( - __import__("ppt_gym.typed_state", fromlist=["encode_public_packet"]).encode_public_packet( + encode_public_packet( row["goal"], row["candidates"], view=VIEW, max_bytes=model.cfg.max_bytes, ), @@ -258,7 +259,6 @@ def aggregate(teacher: Path, supplement: Path, fits: Path, probes: Path, folder = fits / "fits" / key path = folder / "checkpoint.pt" cp_sha = sha256_file(path) - cp = _read(folder / "checkpoint.json") if (folder / "checkpoint.json").exists() else {} model, saved = checkpoint_load(path) if not ( item["checkpoint_sha256"] == cp_sha From 33b372b80cb960d461981c2fc70ee9e8f159fc65 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:44:52 +0800 Subject: [PATCH 09/15] LSA-02H CI: 96 train roots, independently compiled offpath proofs, matched CPU fits and post-native calibration --- .github/workflows/lsa02h-offpath-cpu.yml | 391 +++++++++++++++++++++++ 1 file changed, 391 insertions(+) create mode 100644 .github/workflows/lsa02h-offpath-cpu.yml diff --git a/.github/workflows/lsa02h-offpath-cpu.yml b/.github/workflows/lsa02h-offpath-cpu.yml new file mode 100644 index 000000000..01dcca685 --- /dev/null +++ b/.github/workflows/lsa02h-offpath-cpu.yml @@ -0,0 +1,391 @@ +name: LSA-02H certified off-reference Lean CPU pre-gym study +on: + pull_request: + paths: + - 'research/lean_cgrt_hrm400/ppt_gym/offpath_source.py' + - 'research/lean_cgrt_hrm400/ppt_gym/offpath_train.py' + - 'research/lean_cgrt_hrm400/ppt_gym/offpath_eval.py' + - 'research/lean_cgrt_hrm400/ppt_gym/native_order.py' + - 'research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py' + - 'research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py' + - 'docs/lsa02h_offpath_native_cpu_protocol.md' + - '.github/workflows/lsa02h-offpath-cpu.yml' + workflow_dispatch: +permissions: + contents: read +concurrency: + group: lsa02h-recovery-${{ github.ref }} + cancel-in-progress: false + +jobs: + unit: + name: Simulated legal and dead deviations plus matched CPU controls + runs-on: ubuntu-latest + timeout-minutes: 12 + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install pinned CPU-only PyTorch + run: python -m pip install 'torch==2.5.1' --index-url https://download.pytorch.org/whl/cpu + - name: Run exact source, correction-budget, and matched CPU controls + working-directory: research/lean_cgrt_hrm400 + run: | + python -m compileall -q ppt_gym/offpath_source.py ppt_gym/offpath_train.py ppt_gym/offpath_eval.py ppt_gym/native_order.py + python -m unittest ppt_gym.tests.test_offpath_source -v + python -m unittest ppt_gym.tests.test_offpath_train -v + python -m unittest ppt_gym.tests.test_native_order -v + + source: + name: Freeze and certify 96 fresh Lean roots and recoverable offpath proofs + runs-on: ubuntu-latest + timeout-minutes: 29 + needs: [unit] + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: 'research/lean_cgrt_hrm400/lean' + auto-config: false + build: true + test: false + use-mathlib-cache: false + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install pinned CPU-only PyTorch + run: python -m pip install 'torch==2.5.1' --index-url https://download.pytorch.org/whl/cpu + - name: Register frozen splits and compile native shortest teacher + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.live_cli freeze --out runs/lsa02h-suite \ + --seed 20261201 --per-split 96 + python -m ppt_gym.native_train collect --suite runs/lsa02h-suite \ + --out runs/lsa02h-teacher --roots 96 \ + --request-timeout 60 --max-seconds 720 --cert-timeout 420 + python - <<'PY' + import json + x=json.load(open('runs/lsa02h-teacher/manifest.json')) + assert x['backend']['actual_lean_process'] and x['source_compiler_passed'] + assert x['reference_proofs_compiled']==96 and x['independent_lineages']==96 + assert x['query_roots_exposed_to_fit']==0 and not x['locked_test_opened'] + print('LSA02H_NATIVE_TEACHER',x['reference_proofs_compiled'], + 'frames',x['train_examples'], + 'attainable',x['roots_with_eight_check_reference']) + PY + - name: Extract only certified, within-budget off-reference correction states + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.offpath_source --suite runs/lsa02h-suite \ + --teacher runs/lsa02h-teacher --out runs/offreference \ + --roots 96 --cap-per-root 2 --max-seconds 900 \ + --request-timeout 60 --cert-timeout 420 + python - <<'PY' + import json + x=json.load(open('runs/offreference/manifest.json')) + assert x['schema']=='lsa02h.recoverable_offreference_train.v1' + assert x['backend']['actual_lean_process'] + assert x['training_lineages']==96 and x['independent_compiler_passed'] + assert not x['locked_test_opened'] and x['model_calls_during_collection']==0 + print('LSA02H_RECOVERABLE_SOURCE', + x['roots_with_recoverable_deviations'], + x['novel_offreference_training_states'], + x['certified_alternate_full_proofs'], + x['unreachable_or_over_budget']) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lsa02h-native-source + path: | + research/lean_cgrt_hrm400/runs/lsa02h-suite/ + research/lean_cgrt_hrm400/runs/lsa02h-teacher/ + research/lean_cgrt_hrm400/runs/offreference/ + retention-days: 14 + if-no-files-found: warn + + train: + name: One-worker twelve deterministic CPU fits with root-matched sham + runs-on: ubuntu-latest + needs: [source] + timeout-minutes: 20 + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + OPENBLAS_NUM_THREADS: '1' + PYTHONHASHSEED: '0' + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: lsa02h-native-source + path: research/lean_cgrt_hrm400/runs + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install pinned CPU-only PyTorch + run: python -m pip install 'torch==2.5.1' --index-url https://download.pytorch.org/whl/cpu + - name: Matched reference/offpath/sham training on same verified source roots + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.offpath_train --teacher runs/lsa02h-teacher \ + --supplement runs/offreference --out runs/lsa02h-train \ + --steps 720 --seeds 157 163 --max-seconds-per-fit 300 + python - <<'PY' + import json + x=json.load(open('runs/lsa02h-train/manifest.json')) + assert x['schema']=='lsa02h.matched_recoverable_offpath_cpu.v1' + assert x['training_lineages']==96 and x['train_offreference_roots']>0 + assert x['train_novel_offreference_states']>0 + assert x['seed_roster']==[157,163] + assert x['arm_roster']==['reference','offpath','sham'] and x['view']=='pp96' + assert x['all_exact_duplicate_fits_passed'] and x['same_seed_bitwise_initial_weights'] + assert x['same_seed_identical_source_draws'] and x['torch_threads']==1 + assert not x['mkldnn_enabled'] and x['torch_deterministic_algorithms'] + assert len(x['cells'])==6 + assert all(c['optimizer_steps']==720 for c in x['cells']) + assert all(c['query_label_optimizer_updates']==0 for c in x['cells']) + print('LSA02H_MATCHED_CPU',x['train_offreference_roots'], + x['train_novel_offreference_states'], + [(c['seed'],c['arm'],c['actual_offreference_optimizer_draws'], + c['actual_sham_optimizer_draws']) for c in x['cells']]) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lsa02h-one-worker-checkpoints + path: research/lean_cgrt_hrm400/runs/lsa02h-train/ + retention-days: 14 + if-no-files-found: warn + + uniform: + name: Five-seed independent native Lean random-menu proof baseline + runs-on: ubuntu-latest + needs: [source] + timeout-minutes: 25 + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: lsa02h-native-source + path: research/lean_cgrt_hrm400/runs + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: 'research/lean_cgrt_hrm400/lean' + auto-config: false + build: true + test: false + use-mathlib-cache: false + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install pinned CPU-only PyTorch + run: python -m pip install 'torch==2.5.1' --index-url https://download.pytorch.org/whl/cpu + - name: Run and replay 160 model-free native proof episodes + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.uniform_baseline run --suite runs/lsa02h-suite \ + --teacher runs/lsa02h-teacher --out runs/lsa02h-uniform \ + --roots 32 --checks 8 --seeds 17 31 47 61 83 \ + --max-seconds 900 --cert-timeout 420 + python -m ppt_gym.uniform_baseline replay --suite runs/lsa02h-suite \ + --session runs/lsa02h-uniform --out runs/lsa02h-uniform/replay + python - <<'PY' + import json + x=json.load(open('runs/lsa02h-uniform/manifest.json')) + r=json.load(open('runs/lsa02h-uniform/replay/replay.json')) + assert x['complete_episodes']==160 and x['independent_calibration_roots']==32 + assert x['native_model_calls']==0 and x['all_replays_passed'] + assert x['backend']['actual_lean_process'] + assert r['all_replays_passed'] and r['verified_episodes']==160 + assert not x['heldout_test_opened'] + print('LSA02H_UNIFORM_NATIVE',x['standalone_verified_closures'], + x['uniform_mean_closure_rate'],x['per_seed_closures']) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lsa02h-uniform-native + path: research/lean_cgrt_hrm400/runs/lsa02h-uniform/ + retention-days: 14 + if-no-files-found: warn + + probe: + name: Native Lean proof evaluation seed ${{ matrix.seed }} arm ${{ matrix.arm }} + runs-on: ubuntu-latest + timeout-minutes: 25 + needs: [source, train] + strategy: + fail-fast: false + max-parallel: 2 + matrix: + seed: [157,163] + arm: [reference,offpath,sham] + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: lsa02h-native-source + path: research/lean_cgrt_hrm400/runs + - uses: actions/download-artifact@v4 + with: + name: lsa02h-one-worker-checkpoints + path: research/lean_cgrt_hrm400/runs/lsa02h-train + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: 'research/lean_cgrt_hrm400/lean' + auto-config: false + build: true + test: false + use-mathlib-cache: false + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install pinned CPU-only PyTorch + run: python -m pip install 'torch==2.5.1' --index-url https://download.pytorch.org/whl/cpu + - name: Frozen native Lean whole-proof search and independent replay + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.native_order run --suite runs/lsa02h-suite \ + --checkpoint runs/lsa02h-train/fits/${{ matrix.seed }}-${{ matrix.arm }}/checkpoint.pt \ + --native-teacher runs/lsa02h-teacher/manifest.json \ + --offpath-source runs/offreference/manifest.json \ + --split calibration --roots 32 --checks 8 --depth 2 \ + --max-seconds 720 --cert-timeout 360 --out runs/lsa02h-proof + python -m ppt_gym.native_order replay --suite runs/lsa02h-suite \ + --session runs/lsa02h-proof --out runs/lsa02h-replay + python - <<'PY' + import json + x=json.load(open('runs/lsa02h-proof/manifest.json')) + r=json.load(open('runs/lsa02h-replay/replay.json')) + assert x['status']=='complete' and x['paired_roots']==32 + assert x['input_view']=='pp96' and x['backend']['actual_lean_process'] + assert x['training_provenance']['training_source_verified'] + assert x['training_provenance']['offreference_source_verified'] + assert x['training_provenance']['source_lineages_disjoint'] + assert x['training_provenance']['training_lineages']==96 + assert x['standalone_reference_certificates']==32 + assert r['replay_passed'] and r['independent_replay_episodes']==96 + assert x['query_label_training_updates']==0 + assert not x['architecture_promotion_eligible'] + print('LSA02H_NATIVE_PROOF','${{ matrix.seed }}','${{ matrix.arm }}', + x['scores']['ab']['standalone_verified_closures'], + x['reference_reachable_within_budget']) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lsa02h-probe-${{ matrix.seed }}-${{ matrix.arm }} + path: | + research/lean_cgrt_hrm400/runs/lsa02h-proof/ + research/lean_cgrt_hrm400/runs/lsa02h-replay/ + retention-days: 14 + if-no-files-found: warn + + compare: + name: After all proof runs, native off-reference calibration and root-level decision audit + runs-on: ubuntu-latest + timeout-minutes: 29 + needs: [source, train, uniform, probe] + env: + OMP_NUM_THREADS: '1' + MKL_NUM_THREADS: '1' + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: lsa02h-native-source + path: research/lean_cgrt_hrm400/runs + - uses: actions/download-artifact@v4 + with: + name: lsa02h-one-worker-checkpoints + path: research/lean_cgrt_hrm400/runs/lsa02h-train + - uses: actions/download-artifact@v4 + with: + name: lsa02h-uniform-native + path: research/lean_cgrt_hrm400/runs/lsa02h-uniform + - uses: actions/download-artifact@v4 + with: + name: lsa02h-probe-157-reference + path: research/lean_cgrt_hrm400/runs/lsa02h-probes/157-reference + - uses: actions/download-artifact@v4 + with: + name: lsa02h-probe-157-offpath + path: research/lean_cgrt_hrm400/runs/lsa02h-probes/157-offpath + - uses: actions/download-artifact@v4 + with: + name: lsa02h-probe-157-sham + path: research/lean_cgrt_hrm400/runs/lsa02h-probes/157-sham + - uses: actions/download-artifact@v4 + with: + name: lsa02h-probe-163-reference + path: research/lean_cgrt_hrm400/runs/lsa02h-probes/163-reference + - uses: actions/download-artifact@v4 + with: + name: lsa02h-probe-163-offpath + path: research/lean_cgrt_hrm400/runs/lsa02h-probes/163-offpath + - uses: actions/download-artifact@v4 + with: + name: lsa02h-probe-163-sham + path: research/lean_cgrt_hrm400/runs/lsa02h-probes/163-sham + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: 'research/lean_cgrt_hrm400/lean' + auto-config: false + build: true + test: false + use-mathlib-cache: false + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install pinned CPU-only PyTorch + run: python -m pip install 'torch==2.5.1' --index-url https://download.pytorch.org/whl/cpu + - name: Certify the off-reference calibration states after model native scoring + working-directory: research/lean_cgrt_hrm400 + run: | + python -m ppt_gym.offpath_eval --suite runs/lsa02h-suite \ + --teacher runs/lsa02h-teacher --supplement runs/offreference \ + --fits runs/lsa02h-train --probes runs/lsa02h-probes \ + --uniform runs/lsa02h-uniform --reference runs/lsa02h-reference \ + --out runs/lsa02h-comparison + python - <<'PY' + import json + x=json.load(open('runs/lsa02h-comparison/matched_offreference.json')) + assert x['schema']=='lsa02h.native_offreference_calibration.v1' + assert x['train_roots']==96 and x['calibration_unique_roots']==32 + assert x['model_seeds']==[157,163] and x['arms']==['reference','offpath','sham'] + assert x['view']=='pp96' + assert x['calibration_labels_collected_after_all_native_model_scoring'] + assert not x['locked_test_or_ood_opened'] and x['calibration_optimizer_updates']==0 + assert not x['scientific_eligible'] and not x['architecture_promotion_eligible'] + print('LSA02H_FINAL',x['train_offreference_states'], + 'offpath_dev_forks',x['calibration_offreference_forks'], + 'reference_forks',x['calibration_reference_forks'], + 'prooffractions',x['native_close_rates'], + 'uniform',x['native_uniform_mean_rate'], + 'screen',x['predeclared_development_screen_passed'], + 'eligible',x['offpath_screen_eligible']) + PY + - uses: actions/upload-artifact@v4 + if: always() + with: + name: lsa02h-root-paired-offpath-evidence + path: | + research/lean_cgrt_hrm400/runs/lsa02h-reference/ + research/lean_cgrt_hrm400/runs/lsa02h-comparison/ + retention-days: 14 + if-no-files-found: warn From 2663bbb9492cf7c2fe40058e78ecfb43fe6a2bc6 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:45:27 +0800 Subject: [PATCH 10/15] Index Lean off-reference state coverage and native CPU competence protocol --- research/lean_cgrt_hrm400/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/research/lean_cgrt_hrm400/README.md b/research/lean_cgrt_hrm400/README.md index 7ccdd0a5e..4f5d4e70f 100644 --- a/research/lean_cgrt_hrm400/README.md +++ b/research/lean_cgrt_hrm400/README.md @@ -18,6 +18,7 @@ Start with these documents: - [LSA-02E typed-plus-pretty CPU experiment](../../docs/lsa02e_typed_pretty_cpu_protocol.md): fresh Lean proof roots, three matched 384-byte public input views, same-worker duplicate training, and native root-paired certification. - [LSA-02F pretty-text dosage and native uniform-menu CPU pilot](../../docs/lsa02f_pretty_dose_cpu_protocol.md): new Lean training/calibration roots, matched 0/48/96/160-byte view fits, independently compiled model-free random proof baseline and root-level competence gate. - [LSA-02G native Lean fork-choice competence pilot](../../docs/lsa02g_fork_competence_protocol.md): weighted train-only discriminating forks versus equal-mass shuffled sham, fresh verified reference-state fork decisions, and independently certified proof completion. +- [LSA-02H native recoverable off-reference CPU study](../../docs/lsa02h_offpath_native_cpu_protocol.md): Lean-verified alternate proof states, matched reference and same-root sham training, and separately certified calibration decision coverage. - [PPT-G03 live Lean search and verifier-checked data accretion](PPT_G03_RUNBOOK.md): native Lean 4.19 stepper, frozen theorem suites, independent compiled certificates, train-support DRAM updates and replay-gated export. - [PPT-G03B bounded backtracking gym](PPT_G03B_BACKTRACKING.md): saved Lean-state rollback on unprovable branches, separate tactic and host-cost accounting, and exact independent replay. - [`LOCAL_SCALING_RESULTS.md`](LOCAL_SCALING_RESULTS.md): campaign c1, Lean-certified results; From b3b056782e140f5603778cdba43f57dd1e170cd9 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:49:12 +0800 Subject: [PATCH 11/15] LSA-02H: filter unprovable native dead-end edges when reconstructing offpath shortest scripts --- .../ppt_gym/offpath_source.py | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py index e9a4e1df3..1714160f0 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_source.py @@ -26,7 +26,7 @@ from lcgrt import config from lcgrt.certify import certify, decl_name -from lcgrt.extract import explore, goal_key, optimal_script +from lcgrt.extract import explore, goal_key from lcgrt.lean_repl import LeanRepl from .data import canonical, sha256_file from .live_lean import candidate_menu, fingerprint, public_state, state_input @@ -67,6 +67,39 @@ def _replay_from_root(repl, case, script: list[str]) -> tuple[dict, list[dict]]: return state, frames +def _minimum_finite_script(table: dict, sizes: dict, key: str) -> list[str]: + """Construct native shortest script, ignoring Lean-reported dead edges. + + The original extractor's optimal_script assumes all action children have + finite size. The source graph deliberately includes accepted tactics that + lead to unprovable decoy goals, represented by None. Filter their edges + before scoring, then insist the selected tactic equals the exact native + finite size. Strict size decrease prevents cycles. + """ + size = sizes.get(key) + if not isinstance(size, int) or size < 1: + raise ValueError("offreference goal is not Lean-provable") + candidates = [] + for tactic, child in table.get(key, {}).items(): + costs = [sizes.get(g) for g in child] + if any(not isinstance(s, int) or s < 1 for s in costs): + continue + total = 1 + sum(costs) + if total == size: + candidates.append((tactic, child)) + if not candidates: + raise ValueError("native finite shortest proof has no matching admissible tactic") + tactic, children = min(candidates, key=lambda item: item[0]) + script = [tactic] + for child in children: + if sizes[child] >= size: + raise ValueError("finite native proof graph contains a nondecreasing cycle") + script.extend(_minimum_finite_script(table, sizes, child)) + if len(script) != size: + raise ValueError("native minimum completion length differs from reconstructed script") + return script + + def _completion_script(oracle: dict, pending: list[dict]) -> list[str] | None: script = [] for goal in pending: @@ -74,7 +107,7 @@ def _completion_script(oracle: dict, pending: list[dict]) -> list[str] | None: size = oracle["size"].get(key) if not isinstance(size, int) or size < 1: return None - script.extend(optimal_script(oracle["table"], oracle["size"], key)) + script.extend(_minimum_finite_script(oracle["table"], oracle["size"], key)) return script From 76f01173ad94fae4b79d3af211377726139a0887 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:49:32 +0800 Subject: [PATCH 12/15] LSA-02H: regression that finite shortest native script ignores accepted dead-decoy branches --- .../lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py index d9931a478..cda92b921 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_source.py @@ -125,6 +125,14 @@ def test_dead_alternative_is_counted_as_ineligible(self): self.assertEqual(scripts, []) self.assertEqual(census["unreachable_or_over_budget"], 1) + def test_native_dead_edge_is_excluded_from_finite_completion(self): + oracle = json.loads(canonical(ORACLE)) + oracle["table"]["P2"]["apply r3"] = ["P3"] + oracle["size"]["P3"] = None + self.assertEqual(_completion_script( + oracle, [{"target": {"a": "P2"}}], + ), ["apply r2", "apply h0"]) + def test_no_fake_full_proof_can_be_claimed_for_an_unprovable_goal(self): self.assertIsNone(_completion_script( ORACLE, [{"target": {"a": "P3"}}], From 4d609538df940114ea6b3be3ff8d951259386c29 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:53:33 +0800 Subject: [PATCH 13/15] LSA-02H: use defined optimizer-trace reader in same-worker matched sampling audit --- research/lean_cgrt_hrm400/ppt_gym/offpath_train.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py index ca84e29e9..d325efe9a 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py @@ -291,7 +291,7 @@ def run(teacher: Path, supplement: Path, out: Path, and first["final_weights_sha256"] == repeated["final_weights_sha256"] ): raise ValueError("offreference same-host fit duplicate failed exact equality") - records = _records(base / "optimizer_steps.jsonl") + records = _rows(base / "optimizer_steps.jsonl") samplers[arm] = [ (r["step"],r["root"],r["ref_index"],r["switched"],r["supplement_index"]) for r in records From 61b27b4369d77b608c2e7b11946aaae760487654 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:59:00 +0800 Subject: [PATCH 14/15] LSA-02H: persist completed one-worker checkpoint manifest through the source serializer --- research/lean_cgrt_hrm400/ppt_gym/offpath_train.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py b/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py index d325efe9a..9828ac5e5 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py +++ b/research/lean_cgrt_hrm400/ppt_gym/offpath_train.py @@ -332,7 +332,7 @@ def run(teacher: Path, supplement: Path, out: Path, "test_or_ood_opened": False, "scientific_eligible": False, } - _json(out / "manifest.json", report) + _write(out / "manifest.json", report) return report From 6f02959216cc8c3a55b2c6c894de08755b639441 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 23:59:34 +0800 Subject: [PATCH 15/15] LSA-02H: regression-test full same-worker receipt creation without synthetic proof claims --- .../ppt_gym/tests/test_offpath_train.py | 62 ++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py index 9eba234b4..e95b4b173 100644 --- a/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py +++ b/research/lean_cgrt_hrm400/ppt_gym/tests/test_offpath_train.py @@ -6,11 +6,12 @@ from pathlib import Path import tempfile import unittest +from unittest.mock import patch import torch from ppt_gym.data import canonical, sha256_file -from ppt_gym.offpath_train import _fit, _sample_roster +from ppt_gym.offpath_train import _fit, _sample_roster, run from ppt_gym.tests.test_offpath_source import CONTEXT, SmallLean from ppt_gym.native_train import _snapshot_trajectory from ppt_gym.live_lean import state_input @@ -47,6 +48,65 @@ def test_seeded_source_root_and_switch_draws_are_matched(self): self.assertEqual({r["root"] for r in schedule}, {"dummy_root"}) self.assertTrue(all(d["supplement_index"] in (-1, 0) for d in schedule)) + def test_full_one_worker_receipt_writer_and_source_roster(self): + # This is a synthetic orchestration fixture with all native loaders + # mocked; it certifies no theorem and performs no real optimizer fit. + reference, supplement = self._rows() + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + teacher = base / "lsa02h-teacher" + teacher.mkdir() + (teacher / "manifest.json").write_text('{"synthetic":true}') + offpath = base / "offreference" + offpath.mkdir() + (offpath / "manifest.json").write_text('{"synthetic":true}') + source = { + "source": {"suite_manifest_sha256": "synthetic_suite"}, + "independent_lineages": 1, + } + def fake_fit(teacher, supplements, refs, metadata, out, *, + seed, arm, steps, max_seconds): + out.mkdir(parents=True) + (out / "checkpoint.pt").write_text("synthetic-only") + (out / "optimizer_steps.jsonl").write_text( + canonical({ + "step": 1, "root": "dummy_root", "ref_index": 0, + "switched": True, "supplement_index": 0, + }) + "\n" + ) + return { + "seed": seed, "arm": arm, + "optimizer_steps": steps, + "initial_weights_sha256": "fake-start", + "final_weights_sha256": "fake-end", + "optimizer_steps_sha256": "fake-trace", + } + with ( + patch("ppt_gym.offpath_train._load_teacher", + return_value=(reference, source)), + patch("ppt_gym.offpath_train._load_offpath", + return_value=(supplement, { + "suite_manifest_sha256": "synthetic_suite", + })), + patch("ppt_gym.offpath_train._fit", side_effect=fake_fit), + patch("ppt_gym.offpath_train._compare_checkpoints", + return_value={ + "all_tensors_bitwise_equal": True, + "full_checkpoint_bytes_equal": True, + }), + ): + report = run( + teacher, offpath, base / "fitted", seeds=(157,), + steps=720, max_seconds_per_fit=20, + ) + self.assertEqual(report["schema"], + "lsa02h.matched_recoverable_offpath_cpu.v1") + self.assertTrue(report["same_seed_identical_source_draws"]) + self.assertTrue((base / "fitted" / "manifest.json").is_file()) + manifest = json.loads((base / "fitted" / "manifest.json").read_text()) + self.assertEqual(len(manifest["cells"]), 3) + self.assertTrue(manifest["all_exact_duplicate_fits_passed"]) + def test_three_arms_use_same_start_and_switch_opportunities(self): reference, supplement = self._rows() with tempfile.TemporaryDirectory() as tmp: