diff --git a/.github/workflows/bpd-lg02-kernel.yml b/.github/workflows/bpd-lg02-kernel.yml new file mode 100644 index 00000000..d6f30c35 --- /dev/null +++ b/.github/workflows/bpd-lg02-kernel.yml @@ -0,0 +1,43 @@ +name: BPD-LG-02 counterfactual Lean kernel and refutation audit + +on: + push: + paths: + - 'experiments/bpd_lean_curriculum_v2/**' + - '.github/workflows/bpd-lg02-kernel.yml' + pull_request: + paths: + - 'experiments/bpd_lean_curriculum_v2/**' + - '.github/workflows/bpd-lg02-kernel.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + six-file-kernel-audit: + runs-on: ubuntu-24.04 + timeout-minutes: 18 + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Independently audit every finite model and export source + run: | + python -m unittest experiments.bpd_lean_curriculum_v2.test_generate -v + python -m experiments.bpd_lean_curriculum_v2.generate --out /tmp/bpd-lg02 + - name: Install pinned Lean 4.19.0 + run: | + curl --fail --location --retry 3 https://github.com/leanprover/lean4/releases/download/v4.19.0/lean-4.19.0-linux.tar.zst -o /tmp/lean.tar.zst + tar --zstd -xf /tmp/lean.tar.zst -C /tmp + echo '/tmp/lean-4.19.0-linux/bin' >> "$GITHUB_PATH" + - name: Kernel-check all 192 proof witnesses and 192 negative refutations + run: | + python -m experiments.bpd_lean_curriculum_v2.verify_kernel --source-dir /tmp/bpd-lg02 + - name: Archive source, all six axiom outputs and exact receipts + if: always() + uses: actions/upload-artifact@v4 + with: + name: bpd-lg02-six-file-lean-${{ github.run_id }} + path: /tmp/bpd-lg02/ + retention-days: 30 + if-no-files-found: warn diff --git a/experiments/bpd_lean_curriculum_v2/KERNEL_AUDIT.md b/experiments/bpd_lean_curriculum_v2/KERNEL_AUDIT.md new file mode 100644 index 00000000..ccb91bf8 --- /dev/null +++ b/experiments/bpd_lean_curriculum_v2/KERNEL_AUDIT.md @@ -0,0 +1,22 @@ +# BPD-LG-02 independent six-file Lean kernel audit + +**Date:** 2026-11-15. **Evidence:** [EvalMath CI run 43705790859](https://github.com/MoralityLabAI/EvalMath/actions/runs/43705790859). Public independent replay of the same generator blobs committed in the private LoopedTransformers branch. + +- Exact source: EvalMath branch commit `a3032ba2055bd4847075bf8531fa133daecb18fb`. +- Lean: `Lean (version 4.19.0, x86_64-unknown-linux-gnu, commit 6caaee842e94, Release)`. +- All 7 independent Python source tests passed. +- 384 generated examples: 256 train, 64 dev, 64 test. +- **192 positive theorem scripts** and **192 negative refutation theorems** kernel-checked, six Lean source files. +- **384/384 empty axiom inventories**, each checked individually with `#print axioms`. +- All structural-role digests were unique across cases and no digest/group crossed the train/dev/test boundary under the generator's declared normalization. This does **not** establish general graph-isomorphism or semantic disjointness. +- The negative theorem has the form `¬ (∀ parameters, premises → goal)`, witnessed by an explicit satisfying assignment that falsifies the goal. This gives a Lean kernel-checked negation for the original universal claim, not a proof of irrelevance of a particular model component. + +| Split | Positive proofs | Negative refutations | Positive source SHA-256 | Refutation source SHA-256 | +|---|---:|---:|---|---| +| train | 128 | 128 | `cfc85e99132c536d29e3c63751446f746068c8c012f2647c8a8f1c56e5fd21fe` | `ad52ba622b846f9b8da54779c6e51e5b3eb41eda673d7402812569be82430ef8` | +| dev | 32 | 32 | `63d7c17ecdd0319a3a2ef582dd958c39caf84a066de4bcad7d59de58eaf687e8` | `0b148f8b033cb515e625c10ea86bef3c4ccd6961f991fa3dcec51d5f3a85654c` | +| test | 32 | 32 | `05cdfa2c84286c32c91205dc373ffcae757067a794c168c83b5098270dcbd407` | `99bfb562599a200fb8a3a58c72a51a58bfcb6c0255624da3f7c0860d8447807f` | + +The first CI attempt caught a missing parenthesis around the final `rcases` conjunct. The second revealed a negative-induction theorem parser defect and an unwanted use of `propext` by `simp` in the refutation witnesses. Both issues were repaired before this independent successful replay. Negative refutations now use constructive proof terms built from `True.intro`, `False.elim`, `And.intro`, and `rfl`. + +**Research boundary:** finite Horn/equality reasoning proofs are kernel-certified. The curriculum has never trained a BPD/VPD neural decomposition and cannot distinguish latent mechanisms without measured model interventions. The exact symbolic graph algorithm is an expected 100% baseline. The original BPD-LG-01 training/test split remained defective despite an earlier successful Lean proof audit. diff --git a/experiments/bpd_lean_curriculum_v2/README.md b/experiments/bpd_lean_curriculum_v2/README.md new file mode 100644 index 00000000..6905351a --- /dev/null +++ b/experiments/bpd_lean_curriculum_v2/README.md @@ -0,0 +1,58 @@ +# BPD-LG-02: independent structural audit and repair of the Lean curriculum + +**Status, 2026-11-15:** generator, finite-model checker, split audit, and seven independent CPU tests passed. [Independent Lean 4.19.0 replay](https://github.com/MoralityLabAI/EvalMath/actions/runs/43705790859) kernel-checked **192 positive proofs and 192 negative refutations**, with **384 empty axiom inventories**. See [KERNEL_AUDIT.md](KERNEL_AUDIT.md) for source hashes and claim boundaries. No neural training, BPD decomposition, or capability result is asserted. + +## Why this exists + +Fable's review of BPD-01 identified a failure in the original BPD-LG-01 corpus: its six roots per template varied only in binder names, the label was a directly accessible `critical` generator toggle, depth was irrelevant to `rw` and `induction` proof scripts, and the nuisance was an unused `(noise : Nat)` binder. The original kernel audit was valid for those synthetic statements and remains archived. The earlier corpus is **a failed mechanism-separation benchmark** even though its proofs compiled. + +This successor builds distinct typed *premise graphs*, preserves multiple deceptive but valid hypotheses, and exports student-visible statements in a separate file from host-only labels and witnesses. Every negative replaces **an interior dependency** of a real proof chain and is accompanied by a fully enumerated satisfying interpretation of the premises with a false target. Some positive examples also lack the straightforward path and require an active detour through a distractor node. Every split contains both kinds of positive proof structures. + +## Corpus contract + +Four tactic-witness families are covered, with nominal depth 3–6 and six graph shapes per family/depth. For each shape the generator emits positive/negative minimal contrasts with two nuisance-graph variants: **384 cases** (192 label-positive and 192 label-negative), divided **256/64/64** train/dev/test. The split is by a digest of the **role-labelled structural scaffold**, before constructing minimal pairs. Every one of 96 structural groups stays in exactly one partition. Each source formula's role-labelled premise-graph digest is audited against every other split, producing 384 distinct fingerprints and zero cross-split duplicates in the present deterministic set. + +The graph digest ignores theorem identifiers, renamed propositional/Nat variables and shuffled hypothesis binders. It preserves the source/target and dependency relation. This is a **conservative role-labelled structural normalization**, not a complete decision procedure for logical equivalence or arbitrary graph isomorphism. Do not claim the grammar is out-of-distribution in meaning without testing alternative structural baselines. + +- `exact` uses a computed chain of real implications. +- `rw` uses a `calc` proof that rewrites each required equality; the number of rewrites grows with path length. +- `rcases` deconstructs a nested conjunction of shuffled implication premises before rebuilding the dependency chain. +- `induction` proves a property of arbitrary Nat-indexed predicates. The base case requires actual Horn-chain propagation, and the successor case uses a recurrent step from the prior proof; longer chains require more proof applications. + +The visible payload has just `case_id` and `lean_statement`. It exposes no generator `critical`, `variant`, nuisance, or gold label flags. Host-only JSONL includes targets, finite countermodels, proofs, original role-graphs, and structural fingerprints. Model input code must read only `*_public.jsonl`, and any selection/evaluation process must treat `*_host.jsonl` as privileged scorer data. + +No claim of tactic-family uniqueness is made. The family is one witness, and another tactic or a symbolic graph algorithm can solve these tasks. A straightforward BFS/union-find oracle has 100% correctness on this deterministic Horn/equality fragment. It is an **essential strong zero-neural baseline**; the generator itself computes such a label. + +## Negative certificates + +A positive Lean theorem is saved to `*_positives.lean`. Each negative's original universal claim is separately refuted in `*_refutations.lean`: an explicit interpretation of every theorem parameter satisfies its hypotheses while making its goal false. Proving the negation of a universal theorem is stronger evidence than checking only a Python Boolean countermodel. All six generated Lean files need independent kernel replay and axiom inventory checks. + +For induction, the finite model assigns every Nat-indexed predicate a constant truth value. This is an explicit countermodel for **all** natural numbers rather than a bounded simulation of the induction statement. The finite proof generator still has to pass the Lean kernel before it can be called certified. + +## Mechanism separation and the next experiment + +The mathematical BPD-01 minimax and set-cover results remain correct. Their use as a decomposition claim depends on measured interventions. The original curriculum's contrast was insufficient to distinguish proof-chain following from noticing the only critical premise. BPD-LG-02 addresses obvious corpus shortcuts but **does not yet establish T1 separation of any two trained mechanisms**. + +For a genuinely discriminative neural experiment, prespecify a base/unrolled-VPD/lookup/rotation-null comparison and a **fourth-family-held-out** test. Fit components from three of `exact`, `rw`, `rcases`, `induction`, then predict single-cut and joint-cut intervention effects on the fourth. Freeze per-pass readout labels at the *next readout*, track source and state separately, and run a cue-conflict swap: perturb carried state with input fixed, then perturb input with carried state fixed. Hold matched compute and rank; compare component stability across seeds. Preregister tolerances for continuous-state matching and report held-out predictive error over a tolerance sweep. The trivial discrete fibre-error floor from T3 is only a diagnostic of a specified information interface. + +For an open-set decomposition, include an explicit `none of the candidates` outcome, measure whether the intervention coordinates are comparable, and require parsimony within each observational equivalence class. If routing depends on mechanism, treat the route as an observable response or a measured missingness channel. + +FC-12's separate original MathCan training-incidence data and held-out source proofs remain unchanged. The Hall deficit applies to quota feasibility for *verified positive tactic edges*, whereas BPD-01's mechanism-pair cover optimizes causal distinguishability. Its 117 suggestions are unknown compiler outcomes and carry no estimated success rate from the current graph. + +## Reproduce (without Lean) + +```bash +python -m unittest experiments.bpd_lean_curriculum_v2.test_generate -v +python -m experiments.bpd_lean_curriculum_v2.generate --out /tmp/bpd-lg02 +``` + +Then, with Lean 4.19.0 installed: + +```bash +for s in train dev test; do + lean "/tmp/bpd-lg02/${s}_positives.lean" + lean "/tmp/bpd-lg02/${s}_refutations.lean" +done +``` + +The CI validator should also append `#print axioms` for each declaration to a *second* file and require every statement to be axiom-free. CI must report success by split and by sign, and archive original generated source digests, stdout/stderr, and failure receipts. diff --git a/experiments/bpd_lean_curriculum_v2/generate.py b/experiments/bpd_lean_curriculum_v2/generate.py new file mode 100644 index 00000000..21fde848 --- /dev/null +++ b/experiments/bpd_lean_curriculum_v2/generate.py @@ -0,0 +1,462 @@ +"""BPD-LG-02: source-first, reachable-obligation, finite-model curriculum. + +Four tactic witnesses are generated independently of their withheld labels. +A row is labelled by reachability/equality connectivity of its actual source +hypotheses, not by a generator toggle. The negative certificate is a finite +semantic interpretation checked independently by evaluating every hypothesis. +No generated model has been trained or run here. +""" +from __future__ import annotations + +import argparse +from collections import defaultdict, deque +from dataclasses import dataclass +import hashlib +import json +from pathlib import Path +import random + +SCHEMA = 'BPD-LG-02-v1' +SEED = 2026111518 +FAMILIES = ('exact', 'rw', 'rcases', 'induction') +DEPTHS = (3, 4, 5, 6) +SHAPES = tuple(range(6)) +SPLITS = ('train', 'dev', 'test') + + +def canonical(value) -> str: + return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True) + + +def digest(value) -> str: + return hashlib.sha256(canonical(value).encode()).hexdigest() + + +def node(kind: str, i: int) -> str: + return ('X' if kind == 'rw' else 'P') + str(i) + + +def directed_path(start: str, target: str, edges: list[tuple[str,str]]) -> list[tuple[str,str]] | None: + """Independent shortest-path witness search for explicit proof terms.""" + pending=deque([start]); predecessor={start:None} + while pending: + cur=pending.popleft() + if cur==target: + path=[] + while predecessor[cur] is not None: + prev=predecessor[cur] + path.append((prev,cur));cur=prev + return path[::-1] + for a,b in edges: + if a==cur and b not in predecessor: + predecessor[b]=cur;pending.append(b) + return None + + +def graph_spec(family: str, depth: int, shape: int, nuisance: int, variant: int) -> dict: + """Return graph with binder roles independent of theorem/variable names. + + The first `depth` edges form a potential source-to-goal chain. A changed + *interior* edge is redirected to a fresh decoy node, preserving the number + and type of premises. Distractors also include reachable and dead-end + implications/equalities. Only traversal determines the label. + """ + if family not in FAMILIES or depth not in DEPTHS or shape not in SHAPES or nuisance not in (0,1) or variant not in (0,1): + raise ValueError('unsupported family/depth/shape/nuisance/variant') + rng = random.Random(SEED + 100003*FAMILIES.index(family) + 1009*depth + 137*shape + 17*nuisance) + # Different decoy graph sizes make each structural shape distinct, including + # between train and held-out shape families. + n_decoys = 4 + shape*2 + main = [node(family, i) for i in range(depth+1)] + aux = ['D'+str(i) for i in range(n_decoys)] + cut = 1 + ((shape+depth) % (depth-2)) # strictly interior edge + # Shuffle the polarity of the counterfactual variant, so variant=0 is not + # uniformly positive (and the variant is never model-visible anyway). + intact_variant = (shape + depth + FAMILIES.index(family)) % 2 + intact = (variant == intact_variant) + use_detour = (shape + depth) % 2 == 1 + core = [] + for i in range(depth): + # Half the structural roots need an alternate bridge; the main chain + # is absent for positive as well as negative examples in that stratum. + dst = aux[-1] if i == cut and (use_detour or not intact) else main[i+1] + core.append((main[i], dst)) + # The dead-end branch into the goal has no incoming path from the start. + distractors = [(main[0], aux[0]), (main[0], aux[1])] + distractors += [(aux[j], aux[j+1]) for j in range(1, n_decoys-3)] + distractors.append((aux[-2], main[-1])) + # A detour requires a distinct bridge rule, but only on the positive. + # Replacing that rule by a dead-end premise is a one-edge counterfactual. + distractors.append((aux[-1], main[cut+1]) if (use_detour and intact) + else (aux[-1], aux[0])) + # Nuisance is a real typed rule that can fire, but it does not bridge the + # missing source-to-goal cut. No dummy unreferenced binder is introduced. + distractors.append((main[0], aux[1]) if nuisance else (aux[-3], aux[0])) + all_edges = core + distractors + order = list(range(len(all_edges))) + rng.shuffle(order) + edges = [all_edges[i] for i in order] + edge_ids = ['h'+str(i) for i in range(len(edges))] + # Kernel witnesses use actual dependency paths, including detours. + walk = directed_path(main[0], main[-1], edges) if intact else None + witness_indices = [next(j for j,e in enumerate(edges) if e==link) for link in walk] if walk is not None else None + public_names={role:'v'+format(rng.randrange(1<<44),'011x') for role in main+aux} + assert len(set(public_names.values()))==len(public_names) + sig = {'family': family, 'depth': depth, 'main_count': len(main), + 'decoy_count': n_decoys, 'edges': sorted(edges), + 'source': main[0], 'target': main[-1], + 'loop': family == 'induction'} + return {'family':family,'depth':depth,'shape':shape,'nuisance':nuisance, + 'variant':variant, 'main':main,'aux':aux,'cut':cut,'public_names':public_names, + 'edges':edges,'edge_ids':edge_ids,'witness_indices':witness_indices,'use_detour':use_detour, + 'signature':sig, 'alpha_hash':digest(sig)} + + +def reachability(start: str, edges: list[tuple[str,str]]) -> set[str]: + todo = [start] + visited = {start} + out: dict[str,list[str]] = defaultdict(list) + for src,dst in edges: + out[src].append(dst) + while todo: + cur = todo.pop() + for nxt in out[cur]: + if nxt not in visited: + visited.add(nxt) + todo.append(nxt) + return visited + + +def connectivity(start: str, edges: list[tuple[str,str]]) -> set[str]: + undirected = edges + [(b,a) for a,b in edges] + return reachability(start, undirected) + + +def semantic_label(spec: dict) -> bool: + edges=spec['edges'] + reachable = (connectivity(spec['main'][0],edges) if spec['family']=='rw' + else reachability(spec['main'][0],edges)) + return spec['main'][-1] in reachable + + +def model(spec: dict) -> dict: + fam=spec['family'] + nodes = spec['main']+spec['aux'] + reachable = (connectivity(spec['main'][0],spec['edges']) if fam=='rw' + else reachability(spec['main'][0],spec['edges'])) + if fam=='rw': + # Union-connectivity components are given distinct Nat values; source + # and goal are in different components exactly for negative cases. + comps = {} + values={} + for x in nodes: + c=frozenset(connectivity(x,spec['edges'])) + if c not in comps: comps[c]=len(comps) + values[x]=comps[c] + result={'domain':'Nat','assignments':values,'goal_false':values[nodes[0]]!=values[spec['main'][-1]]} + else: + # Induction predicates are constant across Nat: P_i(n) is either True + # or False. The recurrence is satisfied because its head Pd is False. + values={x:x in reachable for x in nodes} + result={'domain':'Nat -> Prop' if fam=='induction' else 'Prop', + 'assignments':values,'goal_false':not values[spec['main'][-1]]} + if not result['goal_false']: + return {} + return result + + +def verify_model(spec: dict, witness: dict) -> bool: + if semantic_label(spec): + return witness == {} + assignments=witness.get('assignments',{}) + if set(assignments) != set(spec['main']+spec['aux']): + return False + if spec['family']=='rw': + ok=all(assignments[a]==assignments[b] for a,b in spec['edges']) + return ok and assignments[spec['main'][0]]!=assignments[spec['main'][-1]] + ok=bool(assignments[spec['main'][0]]) + ok=ok and all(not assignments[a] or assignments[b] for a,b in spec['edges']) + if spec['family']=='induction': + # For every Nat n, Pd(n) implies P0(n+1). Both are constant predicates. + ok=ok and (not assignments[spec['main'][-1]] or assignments[spec['main'][0]]) + return ok and not assignments[spec['main'][-1]] + + +def edge_expr(fam: str, a: str, b: str) -> str: + if fam=='rw': return f'{a} = {b}' + if fam=='induction': return f'∀ n : Nat, {a} n → {b} n' + return f'{a} → {b}' + + +def chain_term(spec: dict, start_term: str, index_term: str='') -> str: + inner=start_term + for step in spec['witness_indices']: + h=spec['edge_ids'][step] + inner = f'({h} {index_term} {inner})' if spec['family']=='induction' else f'({h} {inner})' + return inner + + +def right_conj(parts: list[str]) -> str: + if len(parts)==1: return '('+parts[0]+')' + return '(('+parts[0]+') ∧ '+right_conj(parts[1:])+')' + + +def source(spec: dict, name: str) -> tuple[str, str|None]: + family=spec['family']; nodes=spec['main']+spec['aux']; edges=spec['edges'] + render=lambda n:spec.get('public_names',{}).get(n,n) + names=' '.join(render(n) for n in nodes) + if family=='rw': + header=f'theorem {name} ({names} : Nat)' + elif family=='induction': + header=f'theorem {name} ({names} : Nat → Prop)' + else: + header=f'theorem {name} ({names} : Prop)' + if family=='rcases': + # Bundle contains shuffled real and decoy edges so deconstruction + # must recover the actual dependency order. + bundle=right_conj([edge_expr(family,render(a),render(b)) for a,b in edges]) + header+=f' (hs : {render(spec["main"][0])}) (bundle : {bundle})' + else: + if family!='rw': header+=f' (hs : {render(spec["main"][0])}' + (' 0)' if family=='induction' else ')') + for h,(a,b) in zip(spec['edge_ids'],edges): + header+=f' ({h} : {edge_expr(family,render(a),render(b))})' + if family=='induction': + header+=f' (hloop : ∀ n : Nat, {render(spec["main"][-1])} n → {render(spec["main"][0])} (Nat.succ n))' + goal=f'∀ n : Nat, {render(spec["main"][-1])} n' + elif family=='rw': + goal=f'{render(spec["main"][0])} = {render(spec["main"][-1])}' + else: + goal=render(spec['main'][-1]) + declaration=header+' : '+goal+' := by' + if not semantic_label(spec): + return declaration, None + if family=='exact': + script=' exact '+chain_term(spec,'hs') + elif family=='rw': + # The chain is the unique witness despite shuffled decoys. + path=directed_path(spec['main'][0],spec['main'][-1],spec['edges']) + assert path is not None + index_by_edge={e:i for i,e in enumerate(spec['edges'])} + lines=[' calc'] + for i,(a,b) in enumerate(path): + lines.append(f' {render(a) if i==0 else "_"} = {render(b)} := by rw [{spec["edge_ids"][index_by_edge[a,b]]}]') + script='\n'.join(lines) + elif family=='rcases': + n=len(edges) + # Each rcases step peels one piece of the nested conjunction. The last + # binder is a rule itself, with no further destructuring. + lines=[] + rest='bundle' + for i in range(n-1): + tail=f'tail{i}' + lines.append(f' rcases {rest} with ⟨{spec["edge_ids"][i]}, {tail}⟩') + rest=tail + lines.append(f' have {spec["edge_ids"][-1]} := {rest}') + lines.append(' exact '+chain_term(spec,'hs')) + script='\n'.join(lines) + else: + base=chain_term(spec,'hs','0') + step=chain_term(spec,'(hloop n ih)','(Nat.succ n)') + script=(' intro n\n induction n with\n' + f' | zero =>\n exact {base}\n' + f' | succ n ih =>\n exact {step}') + return declaration, script + + +def refutation_certificate(spec: dict, name: str) -> str | None: + """A constructively checked closed refutation of an invalid statement. + + Premises are built from True.intro, False.elim, And.intro and rfl, so the + negative witnesses do not require Classical.choice or propext. + """ + if semantic_label(spec): return None + declaration,_=source(spec,name) + statement=declaration.removesuffix(' := by') + fam=spec['family'] + if fam=='induction': + head,tail=statement.rsplit(' : ∀ n : Nat, ',1) + goal='∀ n : Nat, '+tail + else: + head,goal=statement.rsplit(' : ',1) + binders=head.removeprefix('theorem '+name+' ') + assignments=model(spec)['assignments'] + nodes=spec['main']+spec['aux'] + if fam=='rw': + vals=[str(assignments[n]) for n in nodes] + elif fam=='induction': + vals=[f'(fun _ : Nat => {"True" if assignments[n] else "False"})' for n in nodes] + else: + vals=['True' if assignments[n] else 'False' for n in nodes] + + def term_for_arrow(a: str, b: str) -> str: + if fam=='rw': + assert assignments[a]==assignments[b] + return 'rfl' + if assignments[b]: + return '(fun _ _ => True.intro)' if fam=='induction' else '(fun _ => True.intro)' + assert not assignments[a] + return '(fun _ h => False.elim h)' if fam=='induction' else '(False.elim)' + + terms=[term_for_arrow(a,b) for a,b in spec['edges']] + if fam=='rcases': + def and_term(parts: list[str]) -> str: + if len(parts)==1: return parts[0] + return '(And.intro '+parts[0]+' '+and_term(parts[1:])+')' + assumptions=['True.intro', and_term(terms)] + elif fam=='rw': + assumptions=terms + else: + assumptions=['True.intro']+terms + if fam=='induction': + # The constant interpretation makes P0 true and Pd false. + assumptions+=['(fun _ _ => True.intro)'] + app='hall '+' '.join(vals+assumptions) + if fam=='induction': app='('+app+') 0' + if fam=='rw': + pair=f'{assignments[spec["main"][0]]} = {assignments[spec["main"][-1]]}' + body=f' intro hall\n have absurd_eq : {pair} := {app}\n cases absurd_eq' + else: + body=f' intro hall\n have hFalse : False := {app}\n exact hFalse' + return f'theorem neg_{name} : ¬ (∀ {binders}, {goal}) := by\n{body}' + + +def group_signature(family: str, depth: int, shape: int) -> dict: + # Ignore labels/nuisance while grouping all intervention variants of one + # structural recipe. Contains no root index or theorem names. + s=graph_spec(family,depth,shape,0,0) + return {'family':family,'depth':depth, 'decoy_count':len(s['aux']), + 'edge_count':len(s['edges']), 'loop':family=='induction'} + + +def assign_groups() -> dict[tuple[str,int,int],str]: + output={} + for family in FAMILIES: + for depth in DEPTHS: + scored=sorted((digest(group_signature(family,depth,shape)),shape) for shape in SHAPES) + assert len({h for h,_ in scored}) == len(SHAPES) + for i,(_,shape) in enumerate(scored): + output[family,depth,shape]='train' if i<4 else ('dev' if i==4 else 'test') + return output + + +def roster() -> list[dict]: + groups=assign_groups() + rows=[] + for family in FAMILIES: + for depth in DEPTHS: + for shape in SHAPES: + for nuisance in (0,1): + for variant in (0,1): + spec=graph_spec(family,depth,shape,nuisance,variant) + label=semantic_label(spec) + cm=model(spec) + assert label or verify_model(spec,cm) + assert label == (spec['witness_indices'] is not None) + group_hash=digest(group_signature(family,depth,shape)) + cid='bpd2_'+digest((family,depth,shape,nuisance,variant))[:16] + decl,proof=source(spec,'thm_'+cid) + if label: assert proof is not None + rows.append({ + 'schema':SCHEMA,'case_id':cid,'split':groups[family,depth,shape], + 'root_group':group_hash, 'alpha_hash':spec['alpha_hash'], + 'family':family,'structural_depth':depth, + 'public':{'case_id':cid,'lean_statement':decl.removesuffix(' := by')}, + 'host_only':{'solvable':label,'countermodel':cm if not label else None, + 'proof_witness':proof,'source_edges':spec['edges'], + 'source_node':spec['main'][0],'target_node':spec['main'][-1], + 'cut_edge':spec['cut'] if not label else None, + 'model_signature':spec['signature'], 'public_names':spec['public_names']}, + 'kernel_status':'pending_independent_lean', + }) + return rows + + +def audit(rows: list[dict]) -> dict: + if len(rows)!=384 or len({r['case_id'] for r in rows})!=len(rows): + raise AssertionError('roster cardinality or duplicated case ID') + by_split={s:[r for r in rows if r['split']==s] for s in SPLITS} + if {s:len(rows) for s,rows in by_split.items()}!={'train':256,'dev':64,'test':64}: + raise AssertionError('split mismatch') + group_splits=defaultdict(set) + alpha_splits=defaultdict(set) + labels=defaultdict(int) + for row in rows: + group_splits[row['root_group']].add(row['split']) + alpha_splits[row['alpha_hash']].add(row['split']) + labels[row['split'],row['host_only']['solvable']]+=1 + # The learner never receives the label or generator toggle in public. + assert set(row['public'])=={'case_id','lean_statement'} + assert not any(key in row['public'] for key in ('critical','nuisance','solvable','variant')) + if any(len(v)>1 for v in group_splits.values()): + raise AssertionError('structural groups leak between splits') + if any(len(v)>1 for v in alpha_splits.values()): + raise AssertionError('alpha-normalized statements leak between splits') + # Each root/group is two positive and two negative matched observations. + for group in group_splits: + r=[x for x in rows if x['root_group']==group] + if len(r)!=4 or sum(x['host_only']['solvable'] for x in r)!=2: + raise AssertionError('root matched contrasts missing') + return {'cases':len(rows),'split_counts':{s:len(by_split[s]) for s in SPLITS}, + 'positive_cases':sum(r['host_only']['solvable'] for r in rows), + 'negative_finite_models':sum(not r['host_only']['solvable'] for r in rows), + 'distinct_alpha_hashes':len(alpha_splits), + 'distinct_root_groups':len(group_splits), + 'cross_split_alpha_collisions':sum(len(v)>1 for v in alpha_splits.values()), + 'cross_split_group_collisions':sum(len(v)>1 for v in group_splits.values()), + 'labels':{s:{'positive':labels[s,True],'negative':labels[s,False]} for s in SPLITS}, + 'claim_boundary':'source-first synthetic Horn/equality curriculum, no neural training; kernel separately audited'} + + +def export(out: Path) -> dict: + rows=roster() + report=audit(rows) + out.mkdir(parents=True,exist_ok=True) + for s in SPLITS: + subset=[r for r in rows if r['split']==s] + # Publish model inputs without scorer labels or generator mechanics. + (out/f'{s}_public.jsonl').write_text( + ''.join(canonical(r['public'])+'\n' for r in subset)) + # Host-only evidence is a separate file; only trusted scoring code + # may load this label/countermodel/proof manifest. + (out/f'{s}_host.jsonl').write_text( + ''.join(canonical({k:v for k,v in r.items() if k!='public'})+'\n' for r in subset)) + proofs=[] + negative_certs=[] + for r in subset: + if r['host_only']['solvable']: + proof=r['host_only']['proof_witness'] + proofs.append(r['public']['lean_statement']+' := by\n'+proof) + else: + spec=r['host_only']['model_signature'] + # The graph can be reconstructed from the host-only structure + # without the generator's hidden polarity flag. + edges=[tuple(e) for e in r['host_only']['source_edges']] + role_nodes=[f'X{i}' if r['family']=='rw' else f'P{i}' for i in range(r['structural_depth']+1)] + decoys=[f'D{i}' for i in range(spec['decoy_count'])] + complete={'family':r['family'],'main':role_nodes,'aux':decoys,'edges':edges, + 'edge_ids':['h'+str(i) for i in range(len(edges))], + 'witness_indices':None,'public_names':r['host_only']['public_names']} + neg=refutation_certificate(complete,'thm_'+r['case_id']) + if neg is None: raise AssertionError('missing negative proof witness') + negative_certs.append(neg) + (out/f'{s}_positives.lean').write_text( + '/- BPD-LG-02 generated positive proof candidates; Lean 4.19.0 -/\n\n'+ + '\n\n'.join(proofs)+'\n') + (out/f'{s}_refutations.lean').write_text( + '/- BPD-LG-02 closed negative certificates; Lean 4.19.0 -/\n\n'+ + '\n\n'.join(negative_certs)+'\n') + report.update({'schema':SCHEMA,'seed':SEED, + 'sha256':{p.name:hashlib.sha256(p.read_bytes()).hexdigest() + for p in sorted(out.glob('*.jsonl'))+sorted(out.glob('*.lean'))}}) + (out/'manifest.json').write_text(json.dumps(report,sort_keys=True,indent=2)+'\n') + return report + + +def main(): + p=argparse.ArgumentParser() + p.add_argument('--out',type=Path,required=True) + a=p.parse_args() + print(json.dumps(export(a.out),sort_keys=True)) + + +if __name__=='__main__': main() diff --git a/experiments/bpd_lean_curriculum_v2/test_generate.py b/experiments/bpd_lean_curriculum_v2/test_generate.py new file mode 100644 index 00000000..0da44f63 --- /dev/null +++ b/experiments/bpd_lean_curriculum_v2/test_generate.py @@ -0,0 +1,102 @@ +"""Independent, adversarial finite audit of BPD-LG-02 source generation.""" +import json +from pathlib import Path +import tempfile +import unittest +from collections import defaultdict + +from experiments.bpd_lean_curriculum_v2 import generate as g + + +class BpdLg02(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.rows = g.roster() + + def test_counts_and_source_feature_isolation(self): + m=g.audit(self.rows) + self.assertEqual((m['cases'],m['positive_cases'],m['negative_finite_models']), (384,192,192)) + self.assertEqual(m['split_counts'], {'train':256,'dev':64,'test':64}) + self.assertEqual(m['cross_split_alpha_collisions'],0) + self.assertEqual(m['cross_split_group_collisions'],0) + self.assertEqual(m['distinct_alpha_hashes'],384) + self.assertTrue(all(set(r['public'])=={'case_id','lean_statement'} for r in self.rows)) + self.assertTrue(all('critical' not in r['public']['lean_statement'] and + 'noise : Nat' not in r['public']['lean_statement'] for r in self.rows)) + + def test_pair_metadata_not_a_public_label(self): + by_group=defaultdict(list) + for row in self.rows: by_group[row['root_group']].append(row) + for group,items in by_group.items(): + self.assertEqual((len(items),sum(r['host_only']['solvable'] for r in items)),(4,2)) + self.assertEqual(len({r['split'] for r in items}),1) + self.assertEqual(len({r['alpha_hash'] for r in items}),4) + # Every group contains one-label-only edge differences, with + # equal premise counts in positive and negative instances. + positive=[r for r in items if r['host_only']['solvable']] + negative=[r for r in items if not r['host_only']['solvable']] + for a in positive: + self.assertTrue(any(len(a['host_only']['source_edges']) == + len(b['host_only']['source_edges']) for b in negative)) + + def test_independent_transitive_closure(self): + """Warshall-style reachable sets separate from generator DFS and BFS.""" + for row in self.rows: + d=row['host_only'];sig=d['model_signature']; nodes=[f'X{i}' if row['family']=='rw' else f'P{i}' + for i in range(row['structural_depth']+1)] + [f'D{i}' for i in range(sig['decoy_count'])] + relation={(a,b) for a,b in d['source_edges']}|{(n,n) for n in nodes} + if row['family']=='rw':relation|={(b,a) for a,b in d['source_edges']} + for pivot in nodes: + left=[a for a in nodes if (a,pivot) in relation] + right=[b for b in nodes if (pivot,b) in relation] + relation|={(a,b) for a in left for b in right} + self.assertEqual((nodes[0],nodes[row['structural_depth']]) in relation, + d['solvable']) + + def test_every_negative_has_satisfying_finite_model(self): + for row in self.rows: + d=row['host_only'];sig=d['model_signature'];depth=row['structural_depth'] + role_nodes=['X'+str(i) if row['family']=='rw' else 'P'+str(i) for i in range(depth+1)] + spec={'family':row['family'],'main':role_nodes,'aux':['D'+str(i) for i in range(sig['decoy_count'])], + 'edges':[tuple(e) for e in d['source_edges']]} + if d['solvable']: + self.assertIsNone(d['countermodel']) + else: + self.assertTrue(g.verify_model(spec,d['countermodel'])) + self.assertTrue(d['countermodel']['goal_false']) + + def test_half_of_positives_use_a_real_detour(self): + direct,detour=0,0 + for row in self.rows: + if not row['host_only']['solvable']:continue + d=row['host_only'];main=[('X' if row['family']=='rw' else 'P')+str(i) + for i in range(row['structural_depth']+1)] + direct_flag=all((main[i],main[i+1]) in map(tuple,d['source_edges']) + for i in range(len(main)-1)) + direct+=direct_flag;detour+=not direct_flag + self.assertGreaterEqual(d['proof_witness'].count('rw' if row['family']=='rw' else + 'rcases' if row['family']=='rcases' else + 'induction' if row['family']=='induction' else 'h'),1) + self.assertEqual((direct,detour),(96,96)) + + def test_export_determinism_and_certificate_cardinality(self): + with tempfile.TemporaryDirectory() as p, tempfile.TemporaryDirectory() as q: + a=g.export(Path(p));b=g.export(Path(q)) + self.assertEqual(a,b) + for split,pos,neg in (('train',128,128),('dev',32,32),('test',32,32)): + self.assertEqual((Path(p)/f'{split}_positives.lean').read_text().count('theorem thm_bpd2_'),pos) + self.assertEqual((Path(p)/f'{split}_refutations.lean').read_text().count('theorem neg_thm_bpd2_'),neg) + source=(Path(p)/f'{split}_positives.lean').read_text()+'\n'+(Path(p)/f'{split}_refutations.lean').read_text() + for forbidden in ('sorry','admit','native_decide','axiom '): + self.assertNotIn(forbidden,source) + + def test_completeness_of_source_normalization_not_claimed(self): + # The checksum covers role-labelled premise graphs, not equivalence + # under arbitrary graph automorphisms or logical simplification. + self.assertEqual(g.graph_spec('exact',3,0,0,0)['alpha_hash'], + g.graph_spec('exact',3,0,0,0)['alpha_hash']) + self.assertNotEqual(g.graph_spec('exact',3,0,0,0)['alpha_hash'], + g.graph_spec('exact',3,1,0,0)['alpha_hash']) + + +if __name__=='__main__':unittest.main() diff --git a/experiments/bpd_lean_curriculum_v2/verify_kernel.py b/experiments/bpd_lean_curriculum_v2/verify_kernel.py new file mode 100644 index 00000000..a5e06a8e --- /dev/null +++ b/experiments/bpd_lean_curriculum_v2/verify_kernel.py @@ -0,0 +1,71 @@ +"""Independent Lean kernel/axiom audit of all six generated BPD-LG-02 files. + +A successful exit requires 192 positive and 192 negative declarations, and +requires Lean to report an empty axiom inventory for every one of them. +""" +from __future__ import annotations +import argparse +from hashlib import sha256 +import json +from pathlib import Path +import re +import subprocess +import sys + +POSITIVES = {'train': 128, 'dev': 32, 'test': 32} +FORBIDDEN = re.compile(r'\b(sorry|admit|native_decide|axiom|unsafe)\b') + + +def audit(root: Path, executable: str = 'lean') -> dict: + version = subprocess.check_output([executable, '--version'], text=True).strip() + if 'version 4.19.0' not in version: + raise RuntimeError(f'unsupported Lean version: {version}') + receipt = {'schema':'BPD-LG-02-KERNEL-v1', 'lean_version': version, + 'by_split':{},'positive_proofs':0,'negative_refutations':0, + 'axiom_free':0,'all_passed':False} + try: + allnames=set() + for split, size in POSITIVES.items(): + for polarity,suffix in (('positive','positives'),('negative','refutations')): + count=size + original=root/f'{split}_{suffix}.lean' + source=original.read_text() + names=re.findall(r'^theorem (\w+)',source,re.M) + if len(names)!=count or len(set(names))!=count or allnames.intersection(names): + raise RuntimeError(f'{split} {suffix}: declaration count or duplicate failure: {len(names)}') + if FORBIDDEN.search(source): + raise RuntimeError(f'{split} {suffix}: forbidden proof declaration') + allnames.update(names) + audited=root/f'{split}_{suffix}_axioms.lean' + audited.write_text(source+'\n'+'\n'.join(f'#print axioms {n}' for n in names)+'\n') + run=subprocess.run([executable,str(audited)],capture_output=True,text=True,timeout=300) + (root/f'{split}_{suffix}_stdout.log').write_text(run.stdout) + (root/f'{split}_{suffix}_stderr.log').write_text(run.stderr) + if run.returncode!=0: + raise RuntimeError(f'{split} {suffix} failed kernel elaboration: '\ + f'exit {run.returncode}\n{run.stdout[-7000:]}\n{run.stderr[-7000:]}') + empty=run.stdout.count('does not depend on any axioms') + if empty != count: + raise RuntimeError(f'{split} {suffix}: empty axiom count {empty}/{count}; output {run.stdout[-3000:]}') + receipt['by_split'][f'{split}_{polarity}']={ + 'declarations': count,'axiom_free':empty, + 'sha256':sha256(original.read_bytes()).hexdigest()} + receipt['positive_proofs' if polarity=='positive' else 'negative_refutations']+=count + receipt['axiom_free']+=empty + if receipt['positive_proofs'] != 192 or receipt['negative_refutations'] != 192: + raise RuntimeError('incomplete signed certificate coverage') + receipt['all_passed']=True + finally: + (root/'kernel_receipt.json').write_text(json.dumps(receipt,sort_keys=True,indent=2)+'\n') + return receipt + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument('--source-dir',type=Path,required=True) + parser.add_argument('--lean',default='lean') + args=parser.parse_args() + report=audit(args.source_dir,args.lean) + print(json.dumps(report,sort_keys=True)) + +if __name__=='__main__':main() diff --git a/paper/bpd_01_fable_review_errata.md b/paper/bpd_01_fable_review_errata.md new file mode 100644 index 00000000..9e815ce3 --- /dev/null +++ b/paper/bpd_01_fable_review_errata.md @@ -0,0 +1,27 @@ +# BPD-01 / BPD-LG-01: adversarial-review corrections (2026-11-15) + +## Evidence disposition + +BPD-01/T1 and T2 are valid finite decision-theoretic identities under a declared deterministic observation table. The minimum-weight pair cover and minimax adaptive decision tree are established formulations, not proofs of learned neural decomposition. T3 is the weighted majority-error identity for finite feature fibres. Continuous hidden states generally produce singleton fibres, giving a vacuous zero floor without a separately justified matching protocol. T4 is a synthetic refresh counterexample; the original `refill_witness` tabulates trajectories rather than executing an independently specified recurrent transition. A real cue-conflict intervention is needed. + +**BPD-LG-01 is retained as a failed mechanism-separation benchmark.** It kernel-checked 192 synthetic positive proof scripts, but the six roots within each family/depth differed only by renamed binders. Its critical-promise deletion controlled the labels, the nuisance was an unused Nat binder, and some tactic scripts did not change with depth. Therefore the train/dev/test assignment did not protect against alpha-renamed statement reuse. Kernel validity certifies a proposition/proof pair; it does not certify a generalization split or causal mechanism distinction. + +## Terminology and scope + +Goodfire's method is **adVersarial Parameter Decomposition (VPD)** ([Goodfire paper](https://www.goodfire.com/research/interpreting-lm-parameters)), correcting the earlier informal expansion “Vector Parameter Decomposition.” + +A finite table of mechanism hypotheses H is a **closed-world identifiability interface**. For an unknown mechanism outside H, an experiment can return an observation incompatible with every member, but a zero-error open-set guarantee needs an explicit alternative class and its observation kernels. Lookup-table explanations satisfy finite behavioural fidelity; interpretable decomposition requires a separate simplicity/minimality prior and consistent parameter/activation coordinates. + +For hypothesis-dependent routing, route selection belongs in the observation alphabet when the routing result is observed. When missingness is latent, model the missingness mechanism and its selection bias. In a stochastic setting, discrimination is controlled by KL divergences across joint route/output distributions, under stated absolute continuity and sequential sampling assumptions. The binary-bandit QI-02 bound addresses two specified worlds. + +The exact finite T3 fibre floor is a **diagnostic of an observation interface**, not a learned-state metric. For continuous recurrent states, preregister a tolerance sweep, held-out predictive accuracy, intervention labels at the next readout, and matched remaining iteration budgets. A source/carry cue-conflict swap is needed to test reconstruction versus persistence: perturb the carried component with source fixed, then source with state fixed, and jointly cut candidate backup paths. + +The FC-12 Hall deficit concerns feasibility of assigning **verified positive** tactic labels under quotas. BPD-01 pair cover concerns **distinguishing declared mechanisms**. Of 204 training state-family cells, 39 have positive compiler evidence and 165 remain unknown; none of the untested cells is a verified failure, and the 117 proposed critical edges have no current success probability estimate. + +## Successor and acceptance gates + +The source-first BPD-LG-02 corpus lives at `MoralityLabAI/LoopedTransformers/experiments/bpd_lean_curriculum_v2` and is independently mirrored on this branch for hosted Lean kernel replay. It uses distinct role-labelled premise graphs, interior-link counterfactuals, active type-correct decoys, 96 structural groups, balanced labels, and a separate model-visible record. Role-graph fingerprints ignore variable names but do not certify arbitrary semantic or graph-isomorphism uniqueness. The four tactic families still share a narrow synthetic logic grammar. + +Future BPD mechanism claims require held-out **intervention** predictions on an unseen tactic family, a strong symbolic/taxonomy control, matched unrolled VPD and rotation nulls, joint-ablation prediction from single edits, and recurrence across decomposition seeds. Reporting the positive/negative Lean kernel results is a separate gate from measuring any neural capability or mechanistic gain. + +Original review supplied by Fable; corrections and experiment design recorded separately from the original paper to preserve provenance.