diff --git a/.github/workflows/bpd-inkling-reader-source.yml b/.github/workflows/bpd-inkling-reader-source.yml new file mode 100644 index 00000000..3f32a073 --- /dev/null +++ b/.github/workflows/bpd-inkling-reader-source.yml @@ -0,0 +1,32 @@ +name: BPD Inkling reader source checks +on: + push: + branches: + - research/inkling-cross-loop-causal-20261121 + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/**" + - ".github/workflows/bpd-inkling-reader-source.yml" + pull_request: + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/**" + - ".github/workflows/bpd-inkling-reader-source.yml" + workflow_dispatch: +permissions: + contents: read +jobs: + source-test: + runs-on: ubuntu-latest + timeout-minutes: 8 + strategy: + fail-fast: false + matrix: + python-version: ['3.10', '3.12'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Run source-only unittest fixtures + run: | + python -m unittest discover -s mechinterp/bpd/experiments/inkling_reader_v0 -p 'test_reader_probe.py' -v + python -m unittest discover -s mechinterp/bpd/experiments/inkling_reader_v0 -p 'test_positive_control_audit.py' -v diff --git a/.github/workflows/bpd-native-trm-inkling-pilot.yml b/.github/workflows/bpd-native-trm-inkling-pilot.yml new file mode 100644 index 00000000..d4c88419 --- /dev/null +++ b/.github/workflows/bpd-native-trm-inkling-pilot.yml @@ -0,0 +1,101 @@ +name: Pretrained 7M TRM native boundary pilot + +on: + push: + branches: + - research/inkling-cross-loop-causal-20261121 + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/native_trm_pilot.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_pilot.py" + - ".github/workflows/bpd-native-trm-inkling-pilot.yml" + pull_request: + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/native_trm_pilot.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_pilot.py" + - ".github/workflows/bpd-native-trm-inkling-pilot.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: native-trm-${{ github.ref }} + cancel-in-progress: true + +jobs: + cpu-model: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + HF_HUB_DISABLE_TELEMETRY: "1" + HF_HUB_DISABLE_XET: "1" + OMP_NUM_THREADS: "2" + OPENBLAS_NUM_THREADS: "1" + MKL_NUM_THREADS: "2" + PYTHONDONTWRITEBYTECODE: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install CPU-only runtime + run: | + python -m pip install --upgrade pip + python -m pip install "torch==2.5.1+cpu" --index-url https://download.pytorch.org/whl/cpu + python -m pip install "numpy>=1.24,<3" "huggingface_hub>=0.24,<1" + - name: Unit-test native recurrence and dose checks + run: >- + python -m unittest + mechinterp.bpd.experiments.inkling_reader_v0.test_native_trm_pilot -v + - name: Run SHA-pinned pretrained pilot and harder paired development cohort + if: github.event_name == 'push' + run: | + set -euo pipefail + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot \ + --model gaoxin492 --roots 1 --holes 22 --outer-steps 1 \ + --out runs/inkling_native_trm_pilot_20261121.json + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot \ + --model gaoxin492 --roots 24 --holes 40 --outer-steps 1 \ + --relative-dose 0.5 --patch-h-cycle 1 \ + --out runs/inkling_native_trm_hard_early_20261121.json + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot \ + --model gaoxin492 --roots 24 --holes 40 --outer-steps 1 \ + --relative-dose 0.5 --patch-h-cycle 2 \ + --out runs/inkling_native_trm_hard_late_20261121.json + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot \ + --model gaoxin492 --roots 24 --holes 40 --outer-steps 2 \ + --relative-dose 0.5 --patch-h-cycle 1 \ + --out runs/inkling_native_trm_hard_depth2_20261121.json + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot \ + --model gaoxin492 --roots 24 --seed 20261122 --holes 50 --outer-steps 1 \ + --relative-dose 0.5 --patch-h-cycle 1 \ + --out runs/inkling_native_trm_50blank_depth1_20261122.json + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot \ + --model gaoxin492 --roots 24 --seed 20261122 --holes 50 --outer-steps 2 \ + --relative-dose 0.5 --patch-h-cycle 1 \ + --out runs/inkling_native_trm_50blank_depth2_20261122.json + - name: Independently replay Sudoku outcomes and raw dose receipts + if: github.event_name == 'push' + run: | + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_receipt_audit \ + runs/inkling_native_trm_pilot_20261121.json \ + runs/inkling_native_trm_hard_early_20261121.json \ + runs/inkling_native_trm_hard_late_20261121.json \ + runs/inkling_native_trm_hard_depth2_20261121.json \ + runs/inkling_native_trm_50blank_depth1_20261122.json \ + runs/inkling_native_trm_50blank_depth2_20261122.json \ + --out runs/inkling_native_trm_receipt_audit.json + - name: Retain native model evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: bpd-native-trm-cpu-pilot + path: runs/inkling_native_trm_*.json + if-no-files-found: warn + retention-days: 7 diff --git a/.github/workflows/bpd-native-trm-verifier-exit.yml b/.github/workflows/bpd-native-trm-verifier-exit.yml new file mode 100644 index 00000000..d0a96f57 --- /dev/null +++ b/.github/workflows/bpd-native-trm-verifier-exit.yml @@ -0,0 +1,73 @@ +name: Pretrained TRM native verifier-gated recurrence + +on: + push: + branches: + - research/inkling-cross-loop-causal-20261121 + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit.py" + - ".github/workflows/bpd-native-trm-verifier-exit.yml" + pull_request: + paths: + - "mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py" + - "mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit.py" + - ".github/workflows/bpd-native-trm-verifier-exit.yml" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: native-trm-exit-${{ github.ref }} + cancel-in-progress: true + +jobs: + native-exit: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + HF_HUB_DISABLE_TELEMETRY: "1" + HF_HUB_DISABLE_XET: "1" + OMP_NUM_THREADS: "2" + OPENBLAS_NUM_THREADS: "1" + MKL_NUM_THREADS: "2" + PYTHONDONTWRITEBYTECODE: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + - name: Install CPU-only inference dependencies + run: | + python -m pip install --upgrade pip + python -m pip install "torch==2.5.1+cpu" --index-url https://download.pytorch.org/whl/cpu + python -m pip install "numpy>=1.24,<3" "huggingface_hub>=0.24,<1" + - name: Run native recurrent state and verifier unit tests + run: >- + python -m unittest + mechinterp.bpd.experiments.inkling_reader_v0.test_native_trm_exit -v + - name: Run independent 24-root 50-blank pretrained adaptive exit comparison + if: github.event_name == 'push' + run: | + timeout --signal=TERM --kill-after=15s 780s \ + python -m mechinterp.bpd.experiments.inkling_reader_v0.native_trm_exit \ + --model gaoxin492 --roots 24 --seed 20261123 --holes 50 \ + --wall-limit 600 \ + --out runs/trm_online_adaptive_50blank_20261123.json + - name: Independent offline receipt audit and adversarial test fixtures + run: | + python -m unittest mechinterp.bpd.experiments.inkling_reader_v0.test_native_trm_exit_audit -v + if [ -f runs/trm_online_adaptive_50blank_20261123.json ]; then + python -m mechinterp.bpd.experiments.inkling_reader_v0.audit_native_trm_exit \ + --input runs/trm_online_adaptive_50blank_20261123.json \ + --out runs/trm_online_adaptive_50blank_20261123.audit.json + fi + - name: Retain signed source-level development evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: bpd-trm-native-verifier-exit + path: runs/trm_online_adaptive_50blank_20261123*.json + if-no-files-found: warn + retention-days: 7 diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/NATIVE_TRM_DEV_RESULTS_20261121.md b/mechinterp/bpd/experiments/inkling_reader_v0/NATIVE_TRM_DEV_RESULTS_20261121.md new file mode 100644 index 00000000..82198419 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/NATIVE_TRM_DEV_RESULTS_20261121.md @@ -0,0 +1,44 @@ +# Native pretrained 7M Attention-TRM: fresh development root campaign + +Date: 2026-11-21. The [successful GitHub Actions run](https://github.com/MoralityLabAI/BPD/actions/runs/44902293753) includes the complete JSON evidence in artifact [14706930611](https://github.com/MoralityLabAI/BPD/actions/runs/44902293753/artifacts/14706930611). + +Pretrained checkpoint: gaoxin492/TinyRecursiveModels-Sudoku-Extreme-att, step_21700. The checkpoint's expected and checked SHA-256 is +932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3. +The recorded code SHA-256 begins 2544738749cc757d. The test uses genuine pretrained recurrent attention/MLP blocks and a raw z_H hidden-state patch after an H-cycle commit. It does NOT exercise Inkling's Attention Residual cross-loop block reader. + +## Frozen development surface + +24 Sudoku roots were deterministically generated using seeds 20261121 + 101*i for i=0..23. Each problem has 40 blanks and was checked as having exactly one legal solution before model inference. A second independent backtracking enumerator confirmed 24/24 uniquely solvable puzzles after the run. This is a development cohort, with fresh generated examples but no prospective confirmation claim. + +The source model has three H cycles and six L cycles per outer step. A patch is applied at the FIRST blank cell, before observing that model's answer, after H-cycle 1 or 2 on the first outer step. The remaining learned recurrence runs to completion. The head-direction vector is the fixed difference between two digit-head rows; the comparison is a seeded random direction, normalized to the same physical L2 dose. Zero-patch and clean runs are additional controls. + +The per-sample physical dose is 0.5 × pre-patch state L2 norm, approximately 11.3137. The clean hand-unrolled recurrence reproduces the model's act_step forward exactly (maximum difference 0.0). + +## Original results + +| Scenario | Clean boards | Head direction | Random direction | +| --- | ---: | ---: | ---: | +| 40 blanks, outer 1, patch H1 | 23/24 | 23/24 | 23/24 | +| 40 blanks, outer 1, patch H2 | 23/24 | 23/24 | 23/24 | +| 40 blanks, outer 2, patch H1 | 24/24 | 24/24 | 24/24 | + +| Scenario | Mean absolute digit-logit change, head | Random sham | +| --- | ---: | ---: | +| Outer 1, patch H1 | 0.08677565 | 0.12443353 | +| Outer 1, patch H2 | 0.06420392 | 0.06798894 | +| Outer 2, patch H1 | 0.01284373 | 0.01633112 | + +Each mean is across the same 24 source roots and their 81×9 output digit logits. One-step clean failure occurs at root source-sudoku-20263141, cell 35: predicted 5 instead of 2. The H1 intervention changes a different predicted digit at cell 33, while the selected patch cell was index 0. This is evidence of nonlocal downstream dependence on this development example. Two outer steps recovered the correct complete board on every tested root and intervention arm. + +The comparison at the same patch phase across outer steps indicates roughly 85.2% reduction in mean absolute head-direction logit change and roughly 86.9% for the random-direction arm. A similar reduction for random noise implies recurrent attenuation rather than a uniquely identified head-direction mechanism. The exact-board endpoint is near ceiling with only one susceptible root. + +## Evidence and reproducibility + +- Hardware: GitHub hosted CPU, bounded run; no local RTX 5080 allocation. +- Measured execution durations: 21.12 s for H1 one-step, 21.41 s for H2 one-step and 42.34 s for H1 two-step, excluding environment setup and weights download. +- 24 independent source roots, 96 rows per panel, 288 harder-panel observations; four additional one-root smoke rows. +- Complete per-root model identity, input puzzle, exact target, patch site, nominal and realized L2, all digit predictions, selected-cell logits and other output receipts are in the archived JSON files. +- The earlier 22-blank smoke with relative dose 0.2 produced 81/81 correct for all arms and head/random mean-logit changes 0.0602/0.0395. Preserve separately. +- All zero-patch outputs exactly match clean outputs, and no sealed BPD or EvalMath cohorts were opened. + +Scientific classification: native pretrained DEVELOPMENT evidence showing reproducible state-dependent output sensitivity, a single nonlocal cell effect, and attenuation across recurrent computation. The experiment did not identify a reusable sparse mechanistic direction above random controls, and did not test the Inkling attention-residual reader. A new preregistered source population with adequate sham power and a memory-suitable native Inkling checkpoint is the appropriate successor. diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/NATIVE_TRM_VERIFIER_EXIT_RESULTS_20261123.md b/mechinterp/bpd/experiments/inkling_reader_v0/NATIVE_TRM_VERIFIER_EXIT_RESULTS_20261123.md new file mode 100644 index 00000000..cb9857ec --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/NATIVE_TRM_VERIFIER_EXIT_RESULTS_20261123.md @@ -0,0 +1,113 @@ +# BPD RLT-EXIT-01: online verifier-gated native pretrained TRM recurrence + +**First original result:** development-only, real SHA-pinned pretrained recurrent attention model, +November 21, 2026. [GitHub Actions #44903527858](https://github.com/MoralityLabAI/BPD/actions/runs/44903527858), +[raw artifact #14706404454](https://github.com/MoralityLabAI/BPD/actions/runs/44903527858/artifacts/14706404454). + +- Model: gaoxin492/TinyRecursiveModels-Sudoku-Extreme-att, pretrained + checkpoint SHA-256 932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3. +- Source: native_trm_exit.py SHA-256 + 2fd754ce38506787fdf724952ae8c64c1eedb78412b6c6746bd2f5fa9f0a7634. +- Raw original JSON SHA-256 + c621861c5fc0b950d23cd30ae4de5ea677d07b893e53ecbfbd0b73b84259f948. + All per-root candidate grids, runtime records, source IDs and model settings + remain in the original Actions artifact. +- Fresh **development** cohort: 24 separate, uniquely solvable 9x9 Sudoku + questions with 50 blanks, seed 20261123 + 101*i for each root. + Prior 40-blank and 50-blank cohorts used seeds 20261121 and 20261122. +- Fixed policy: run two real outer recurrent steps using continued z_H / z_L + states, then grade. Adaptive policy: run one outer step, run an exact Sudoku + clue/row/column/box verifier, and stop immediately when complete. + Otherwise run the second outer step and check again. +- Match controls: identical checkpoint, same 24 tasks, same generated states + from each initialization and first-step candidate string, alternating + policy order across roots to moderate execution-order timing effects. + The verifier only sees the candidate and original question, never the + planted solution. Independent receipt review recomputed Sudoku legality + and per-root depth policy behavior. + +## Original measurements + +| Metric | Fixed 2 | Online verifier exit | +| --- | ---: | ---: | +| Cases solved completely | 23/24 | 23/24 | +| First outer step solved | 15/24 | 15/24 | +| Additional roots solved on second step | 8 | 8 | +| Subsequent regressions on earlier correct grids | 0 | 0 (stopped) | +| Total outer steps | 48 | 33 | +| Mean outer steps per task | 2.000 | 1.375 | +| Native model forward seconds, total | 10.133934 | 6.974778 | +| End-to-end policy seconds, total | 10.147272 | 6.983677 | +| Exact verifier seconds, total | 0.003163 | 0.002071 | + +Result: **31.25% fewer outer recurrent steps**, 31.174% lower measured +native forward seconds, 31.177% lower policy-level elapsed seconds. +These are sums over sequential model calls on a hosted GitHub CPU runner, +not amortized parallel serving, GPU inference throughput or watt-hours. +Each outer step involves three H-cycles with seven L_level calls per +H-cycle (six L followed by one H): 21 calls per step. Across the cohort, +that is 1,008 L_level calls at fixed depth versus 693 with verifier exit. + +Exactly 15 roots halted after the first verifier-valid Sudoku grid. +Eight more were successfully completed after two; one remained unsolved +at the permitted depth. The fixed model also solved 23, with zero +observed late-depth regressions among its first-step correct roots. + +## Claim boundary + +The trained recurrent model is **TRM**, not the native 26B Inkling 2 Mini +Attention Residual architecture. This experiment demonstrates that +task-verifier feedback can save real inference compute with preserved +Sudoku accuracy on a small, exposed development cohort. The model is +not learning an exit gate here. Its exact Sudoku checker is task-specific, +and a general language-model replacement would need externally +trustworthy verification or a calibrated learned stop controller. + +One run on 24 roots is not a prospectively powered scientific confirmation. +No additional protected BPD NC09/AMM cohorts were accessed; all historical +gates and verdicts remain unchanged. No model weights were committed. + +### Next scientific experiment + +Fit a tiny exit-policy predictor on disjoint development roots using +the first-step logit margins, state-change norms, and future verified +outcomes. Compare learned routing to exact-verifier stop and fixed +depth under the same compute budget, with source-root bootstrap and +sham-calibrated minimum effect in EvalMath. Preserve the exact verifier +as an upper-quality source of labels, avoid exposing held-out outcomes +to controller selection, and test the stopping logic across other +reasoning task families. Native Inkling cross-loop readers still require +a separate instrumented checkpoint and memory-suitable runner. + + +## Independent replay and timing replication + +An unchanged-root **development replication** reran the online policy +from the same pinned pretrained checkpoint, with a new source-level +independent receipt audit and adversarial audit unit tests: +[Actions #44903755773](https://github.com/MoralityLabAI/BPD/actions/runs/44903755773), +[artifact #14707545104](https://github.com/MoralityLabAI/BPD/actions/runs/44903755773/artifacts/14707545104). + +The retried 24 roots again produced 15 first-step valid puzzles, +23/24 final correct, 48 fixed versus 33 adaptive recurrent steps, +and no first-valid answer regressions. This time the native model +used **6.621843 seconds fixed versus 4.590264 seconds adaptive**, +a 30.67996% measured reduction. The policy wall totals were +6.636706 versus 4.600248 seconds, a 30.68477% reduction. The +runtime difference between the original and replication reflects +hosted-run timing variability; the checker and recurrence counts +agree exactly. + +The companion independent audit independently rechecked every +saved candidate's full Sudoku legality, first-step prefix identity, +stop correctness and step/time totals. Its replay verdict is PASS, +with input receipt SHA-256 +8945a80beb3ed3736a76b201cc42428c4463b61a32e0fbec4013b32b4eab1443. +This independent audit rechecks outputs and receipts without +reexecuting pretrained weights. Preserve the first and second run +as separate source-labeled development evidence. + +A DataGoblin adapter on branch research/inkling-varloop-distill-20261121 +can import this source/audit pair to emit train-INELIGIBLE +controller task-format traces for RLT gym prototyping, preserving +all 24 development roots outside the training corpus. diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/PROTOCOL.md b/mechinterp/bpd/experiments/inkling_reader_v0/PROTOCOL.md new file mode 100644 index 00000000..ad91cc06 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/PROTOCOL.md @@ -0,0 +1,145 @@ +# Inkling Reader-01: causal cross-loop routing, source-only phase + +Date: 2026-11-21. Status: source-only math and proposed native protocol. +No trained-model causal result. The NC09 Fixed12, AMM08/09 and all other +sealed BPD cohorts remain untouched, with their historical decisions intact. + +## Literature and hypothesis + +- Thinking Machines, Inkling 2 Mini (2026-11-20): + https://thinkingmachines.ai/news/inkling-2-mini/ +- Chen et al., Attention Residuals: + https://arxiv.org/abs/2603.15031 +- Goodfire, Interpreting Inkling 2 Mini: + https://www.goodfire.com/research/interpreting-inkling-2-mini/ +- Variable-loop model card: + https://thinkingmachines.ai/model-card/tml-d24-varloop-research/ + +Inkling repeats two middle six-layer blocks with a learned gate admitting +the previous pass's block representation. Its four cross-loop readers +(query, key, value and MoE) select from the preceding block 2/3 outputs. +Goodfire reports a conspicuous outlier coordinate 2027 in the released +FIXED three-pass model, not in the variable-loop research checkpoint. +At the measured block boundary it explains a large fraction of the +normalized activation and several routing score gaps. Correlation with +reader preference alone is insufficient for a causal mechanism claim. + +For block vectors v2, v3 and a frozen reader u, let + + s_i = dot(u, RMSNorm(v_i)) / sqrt(d) + beta3 = sigmoid(s3 - s2) + +The coordinate contribution u_j * (RMSNorm(v3)_j - RMSNorm(v2)_j) +divided by sqrt(d) is an exact additive decomposition of the frozen +score gap. A physical raw-coordinate patch changes RMSNorm, so +recompute the entire downstream state to measure an intervention. + +## Rival hypotheses + +H1: A selected routing direction causes a greater change in independently +verified serial-task success than dose-matched random interventions. + +H2: Routing probabilities change while correctness remains within the +matched-sham effect envelope. The direction may encode phase or punctuation. + +H3: A large attribution under a frozen-normalization decomposition +shrinks or reverses after physically patching the raw block vector and +recomputing RMSNorm. + +H4: Coda/tuned-lens decodability rises with recurrence without a +corresponding increase in verified task success. + +## Native experiment registration requirements + +- Freeze the checkpoint revision, tokenizer, actual operator, pass count, + cache-sharing mode, sampling seed, chosen layer and evaluation task root. + Check that the target model solves a positive-control algorithm. +- Discover outlier directions in a TRAIN-only split. Coordinate 2027 is + a hypothesis for the fixed three-pass checkpoint only. +- Select the reader and intervention direction on independent development + roots. One primary reader and one prespecified dose must be frozen + before any fresh confirmation readout. +- Patch the raw block 2 or 3 output at a named loop boundary (after + layers 12 or 18). Recompute complete model execution thereafter, + including normalization, all four readers, gates and the final head. +- Arms: untreated, zero patch, candidate direction, dose-matched random + coordinate, dose-matched Haar direction, shuffled donor, matched + unrelated donor, and clean/corrupted minimal-pair donor when available. +- Physical dose is ACTUAL raw-state L2 displacement, checked separately + from intended dose. Record full-head parity, future logits, clean/patched + KL, reader weights, layer state norms and per-token differences. +- Primary endpoint: independent verifier-confirmed task repair/corruption + rate under a fixed resource budget, not a reader score or a linear probe. + Secondary endpoints include first-valid visit and outlier propagation. +- Independent unit: source task root or separately trained checkpoint as + registered. Tokens, loop passes, directions and donor variants are + correlated measurements within one root. +- EvalMath preflight sets the minimum meaningful effect, shams, power and + Holm multiplicity plan. Calibrating a nonparametric 95/95 sham threshold + requires at least 59 independent sham roots even using the maximum. +- Evaluation uses a fresh sealed source-root population with explicit + access authorization and release protocol. Never reuse the NC09 or + AMM confirmation samples. + +## Failure gates and scientific scope + +Failure includes absent trained positive control, mismatched actual dose, +reconstruction/head-parity faults, source overlap, unregistered direction +selection, or a task effect within sham variability. All negative arms +and outcomes must be retained. Conclude observational feature detection +when a probe decodes state but native causal evidence is absent. + +Variable-loop pass counts 7 and 10 are extrapolation probes. The model +was midtrained at 1-5 passes and post-trained at 3; this differential +exposure complicates depth interpretations. + +## Existing source-only implementation + +reader_probe.py evaluates the two-source reader score and recomputes +RMSNorm following a raw coordinate patch. The norm-matched control uses +a deterministic Gaussian direction. It is a synthetic algebra check, +with no activation extraction, GPU allocation, training or external +model access. Run: + + python -m unittest discover -s mechinterp/bpd/experiments/inkling_reader_v0 -p test_reader_probe.py -v + +Development root-level depth audits belong in the EvalMath companion +branch, research/inkling-loop-monitorability-20261121. +A future native adapter and a fresh preregistered sample are prerequisites +for quantitative BPD mechanism claims. + + +## 2026-11-21: constructed learned-gate positive control checked + +[LoopedTransformers Actions #44900273337](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/44900273337) +provides a complete source-only CPU evidence bundle for RMP-INK-PC01, +including saved raw states before/after loop-boundary perturbations. +The model has an explicit supplied permutation graph operator and a +single trained state-update gate. It demonstrates the plumbing of +a real recurrent state intervention; it does **not** instantiate an +Inkling cross-loop Q/K/V/MoE reader. + +The new audit_positive_control.py independently checks SHA-bound source +artifacts, recomputes all graph targets, repeats the recurrent forward +from the trained scalar, checks state displacements and final outcomes, +and fails on incomplete/mutated arm matrices. The GitHub Action pinned +this auditor to commit 5cbd5de63e95b6c70c3e351f68be6676cd830268. +The cross-replay reported 64 development roots, 512 task instances, +3,072 depth records and 1,600 arm records, all consistent with +the saved receipts. The selected active-coordinate direction +corrupted 320/320 cases at L2 dose 0.85; Gaussian random directions +preserved 320/320 and random-coordinate controls preserved 297/320. +Dose selection used an earlier development pilot. + +To replay an extracted artifact directory: + + python mechinterp/bpd/experiments/inkling_reader_v0/audit_positive_control.py \ + --input PATH_TO_EXTRACTED_ARTIFACT \ + --out PATH_TO_NEW_AUDIT.json + +This is a **synthetic positive-control replay**. The original native +Inkling reader-causality hypotheses in this protocol remain untested. +Fresh independent native-model roots, trained competence, reader +instrumentation and EvalMath mechanism-resolution gates remain +prerequisites for causal attribution. NC09/AMM sealed source roots +and their historical verdicts are unaffected. diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/audit_native_trm_exit.py b/mechinterp/bpd/experiments/inkling_reader_v0/audit_native_trm_exit.py new file mode 100644 index 00000000..229d847b --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/audit_native_trm_exit.py @@ -0,0 +1,214 @@ +"""Independent, CPU-free audit of pretrained TRM verifier-gated recurrence receipts. + +Recomputes Sudoku legality and budget consistency from saved text outputs. +This audits the *reported* native trajectories; it does not reexecute weights. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Any + +SCHEMA = "bpd.native_trm_verifier_exit.v1" +PINNED_GAOXIN = "932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3" + + +def _digest(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def _sudoku_valid(question: str, candidate: str) -> bool: + if len(question) != 81 or len(candidate) != 81: + return False + if any(c not in "123456789." for c in question): + return False + if any(c not in "123456789" for c in candidate): + return False + if any(c != "." and c != candidate[i] for i, c in enumerate(question)): + return False + for r in range(9): + if {candidate[r * 9 + c] for c in range(9)} != set("123456789"): + return False + for c in range(9): + if {candidate[r * 9 + c] for r in range(9)} != set("123456789"): + return False + for r in (0, 3, 6): + for c in (0, 3, 6): + if {candidate[(r + dr) * 9 + c + dc] for dr in range(3) for dc in range(3)} != set( + "123456789" + ): + return False + return True + + +def _nonnegative(value: Any) -> float: + if type(value) not in (float, int) or not math.isfinite(value) or value < 0: + raise ValueError("missing or invalid measured nonnegative number") + return float(value) + + +def audit(path: Path) -> dict[str, Any]: + if path.stat().st_size > 16 * 1024 * 1024: + raise ValueError("receipt too large") + obj = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(obj, dict) or obj.get("schema_version") != SCHEMA: + raise ValueError("invalid receipt schema") + if ( + obj.get("evidence_class") != "native_pretrained_development" + or obj.get("model") != "gaoxin492" + or obj.get("model_sha256") != PINNED_GAOXIN + or obj.get("split") != "development" + or obj.get("check_uses_planted_solution") is not False + or obj.get("student_training_eligible") is not False + ): + raise ValueError("wrong model, provenance or task custody") + budget = obj.get("max_outer_steps") + roots = obj.get("roots") + if type(roots) is not int or not 1 <= roots <= 64: + raise ValueError("invalid root count") + if type(budget) is not int or budget < 2 or budget > 8: + raise ValueError("invalid outer depth") + records = obj.get("records") + if not isinstance(records, list) or len(records) != roots: + raise ValueError("incomplete root roster") + identities = set() + totals: dict[str, Any] = {} + for policy in ("fixed_2", "verifier_exit"): + totals[policy] = { + "verified_solved": 0, "cases": roots, + "outer_steps_total": 0, + "elapsed_wall_seconds": 0.0, + "total_native_step_seconds": 0.0, + "total_checker_seconds": 0.0, + "stop_reasons": {}, + } + first_pass = 0 + second_pass = 0 + regrets = 0 + for entry in records: + root, question = entry.get("root_id"), entry.get("question") + if not isinstance(root, str) or root in identities: + raise ValueError("duplicate/invalid source root") + identities.add(root) + if not isinstance(question, str) or len(question) != 81: + raise ValueError("invalid question") + if question.count(".") != obj.get("holes"): + raise ValueError("clue count differs from manifest") + if entry.get("task_digest") != _digest({"question": question}): + raise ValueError("task digest mismatch") + if entry.get("model_sha256") != PINNED_GAOXIN: + raise ValueError("root changed checkpoint") + if set(entry.get("policies", {})) != {"fixed_2", "verifier_exit"}: + raise ValueError("missing policy") + order = entry.get("measured_arm_order") + if not isinstance(order, list) or set(order) != {"fixed_2", "verifier_exit"}: + raise ValueError("missing policy run order") + fixed_trace = entry["policies"]["fixed_2"]["trace"] + conditional_trace = entry["policies"]["verifier_exit"]["trace"] + if len(fixed_trace) != budget or not 1 <= len(conditional_trace) <= budget: + raise ValueError("policy executed wrong depth") + if [r.get("candidate") for r in fixed_trace[:len(conditional_trace)]] != [ + r.get("candidate") for r in conditional_trace + ]: + raise ValueError("mismatched model trajectory between policy arms") + first_pass += int(fixed_trace[0]["sudoku_checker_passed"]) + second_pass += int(fixed_trace[-1]["sudoku_checker_passed"]) + regrets += int(fixed_trace[0]["sudoku_checker_passed"] and not fixed_trace[-1]["sudoku_checker_passed"]) + for policy in ("fixed_2", "verifier_exit"): + row = entry["policies"][policy] + steps = row["trace"] + if row.get("realized_outer_steps") != len(steps): + raise ValueError("reported visits disagree with trace") + if [s.get("outer_step") for s in steps] != list(range(1, len(steps) + 1)): + raise ValueError("non-contiguous recurrent visits") + for step in steps: + if type(step.get("sudoku_checker_passed")) is not bool: + raise ValueError("missing checker boolean") + if _sudoku_valid(question, step["candidate"]) != step["sudoku_checker_passed"]: + raise ValueError("independent exact Sudoku verifier disagrees") + _nonnegative(step.get("native_step_seconds")) + _nonnegative(step.get("exact_check_seconds")) + if policy == "verifier_exit": + if any(step["sudoku_checker_passed"] for step in steps[:-1]): + raise ValueError("adaptive policy kept computing after verified success") + if len(steps) < budget and not steps[-1]["sudoku_checker_passed"]: + raise ValueError("adaptive policy quit without a valid solution") + if row.get("stop_reason") not in {"verified", "depth_budget", "fixed_depth"}: + raise ValueError("invalid stopping status") + if policy == "verifier_exit" and (row["stop_reason"] == "verified") != steps[-1][ + "sudoku_checker_passed" + ]: + raise ValueError("stopping status mismatches verification") + total = totals[policy] + total["verified_solved"] += int(steps[-1]["sudoku_checker_passed"]) + total["outer_steps_total"] += len(steps) + total["elapsed_wall_seconds"] += _nonnegative(row.get("elapsed_seconds")) + total["total_native_step_seconds"] += sum(_nonnegative(s["native_step_seconds"]) for s in steps) + total["total_checker_seconds"] += sum(_nonnegative(s["exact_check_seconds"]) for s in steps) + reason = row["stop_reason"] + total["stop_reasons"][reason] = total["stop_reasons"].get(reason, 0) + 1 + for policy in totals: + rec = obj["summary"][policy] + actual = totals[policy] + for field in ("verified_solved", "cases", "outer_steps_total", "stop_reasons"): + if actual[field] != rec[field]: + raise ValueError(f"summary mismatch: {policy}/{field}") + for field in ("elapsed_wall_seconds", "total_native_step_seconds", "total_checker_seconds"): + if not math.isclose(actual[field], rec[field], abs_tol=0.0001): + raise ValueError(f"timing total mismatch: {policy}/{field}") + fixed, adaptive = totals["fixed_2"], totals["verifier_exit"] + step_savings = 1 - adaptive["outer_steps_total"] / fixed["outer_steps_total"] + native_savings = 1 - adaptive["total_native_step_seconds"] / fixed["total_native_step_seconds"] + if not math.isclose(step_savings, obj["summary"]["step_count_fraction_saved"], abs_tol=1e-9): + raise ValueError("incorrect reported saved steps") + if not math.isclose( + native_savings, obj["summary"]["measured_native_step_fraction_saved"], abs_tol=1e-6 + ): + raise ValueError("incorrect reported native time savings") + return { + "schema_version": "bpd.native_trm_verifier_exit_audit.v1", + "receipt_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "checkpoint_sha256": PINNED_GAOXIN, + "source_roots": roots, + "depth_one_verified": first_pass, + "depth_two_verified": second_pass, + "later_regressions": regrets, + "fixed_solved": fixed["verified_solved"], + "adaptive_solved": adaptive["verified_solved"], + "fixed_steps": fixed["outer_steps_total"], + "adaptive_steps": adaptive["outer_steps_total"], + "step_fraction_saved": step_savings, + "measured_native_fraction_saved": native_savings, + "measured_wall_fraction_saved": ( + 1 - adaptive["elapsed_wall_seconds"] / fixed["elapsed_wall_seconds"] + ), + "root_and_checker_replay_passed": True, + "evidence_class": "independently_rechecked_development_receipts", + "limitations": ( + "Exact solution checked from public puzzle/output and timing totals; native " + "weights were not reexecuted by this auditor. Model and roots are development-exposed." + ), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.out.exists(): + parser.error("audit destination already exists") + report = audit(args.input) + args.out.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({"replayed": True, "roots": report["source_roots"]})) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/audit_positive_control.py b/mechinterp/bpd/experiments/inkling_reader_v0/audit_positive_control.py new file mode 100644 index 00000000..96337ecc --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/audit_positive_control.py @@ -0,0 +1,275 @@ +"""Independently replay RMP-INK-PC01 learned-gate rollout and state-patch receipts. + +Source-only audit of an EXPLICIT permutation operator plus one trained gate. +This does not attest provider identity, native Inkling routing or external sampling. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from collections import Counter, defaultdict +from pathlib import Path +from typing import Any + +SCHEMA = "rmp.inkling_positive_control.v1" +ARCH = "task_supplied_permutation_with_learned_gate_v1" +ARMS = {"clean", "zero", "active_coordinate", "random_direction", "random_coordinate"} +VERIFIER = "rmp.ink_pc01.exact_cycle.v1" + + +def _digest(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def _rows(path: Path) -> list[dict[str, Any]]: + if path.stat().st_size > 16 * 1024 * 1024: + raise ValueError("oversized development stream") + rows = [] + with path.open(encoding="utf-8") as source: + for line in source: + if line.strip(): + item = json.loads(line) + if not isinstance(item, dict): + raise ValueError("nonobject row") + rows.append(item) + if not rows or len(rows) > 20000: + raise ValueError("empty/oversized stream") + return rows + + +def _source_world(row: dict[str, Any]) -> tuple[tuple[int, ...], int, int, int]: + world = row.get("task_world") + if not isinstance(world, dict): + raise ValueError("task world is missing") + permutation = world.get("permutation") + if ( + not isinstance(permutation, list) or len(permutation) != 17 + or any(type(x) is not int for x in permutation) + or sorted(permutation) != list(range(17)) + ): + raise ValueError("invalid permutation") + start, hops = world.get("start"), world.get("hops") + if type(start) is not int or not 0 <= start < 17: + raise ValueError("invalid start node") + if type(hops) is not int or not 1 <= hops < 17 or hops != row.get("hops"): + raise ValueError("invalid hop count") + root_id, case_id = row.get("root_id"), row.get("case_id") + if not isinstance(root_id, str) or not isinstance(case_id, str): + raise ValueError("missing lineage IDs") + if row.get("task_digest") != _digest({"root_id": root_id, "world": world}): + raise ValueError("world binding digest mismatch") + target = start + for _ in range(hops): + target = permutation[target] + if row.get("target") != target: + raise ValueError("target differs from independently replayed graph") + return tuple(permutation), start, hops, target + + +def _next(state: list[float], permutation: tuple[int, ...], alpha: float) -> list[float]: + message = [0.0] * len(state) + for i, dest in enumerate(permutation): + message[dest] = state[i] + return [(1 - alpha) * x + alpha * y for x, y in zip(state, message, strict=True)] + + +def _walk_state( + permutation: tuple[int, ...], start: int, steps: int, alpha: float, + *, state: list[float] | None = None, +) -> list[float]: + value = list(state) if state is not None else [float(i == start) for i in range(17)] + for _ in range(steps): + value = _next(value, permutation, alpha) + return value + + +def _argmax(values: list[float]) -> int: + return max(range(len(values)), key=lambda i: values[i]) + + +def _vector(value: Any) -> list[float]: + if not isinstance(value, list) or len(value) != 17: + raise ValueError("raw state vector missing") + if any(type(x) not in {float, int} or not math.isfinite(x) for x in value): + raise ValueError("nonfinite raw state") + return [float(x) for x in value] + + +def _near(a: float, b: float, *, eps: float = 1e-9) -> bool: + return math.isclose(a, b, abs_tol=eps, rel_tol=eps) + + +def _same_state(a: list[float], b: list[float]) -> bool: + return all(_near(x, y) for x, y in zip(a, b, strict=True)) + + +def _shared(row: dict[str, Any], checkpoint_sha: str) -> None: + if ( + row.get("schema_version") is not None or row.get("model_sha") != checkpoint_sha + or row.get("split") != "development" or row.get("verifier_id") != VERIFIER + or row.get("family") != "explicit_single_cycle_pointer_chase" + or type(row.get("verified")) is not bool + or type(row.get("predicted")) is not int + ): + raise ValueError("wrong model/split/verifier receipt") + + +def audit(directory: Path) -> dict[str, Any]: + summary = json.loads((directory / "summary.json").read_text(encoding="utf-8")) + checkpoint = json.loads((directory / "checkpoint.json").read_text(encoding="utf-8")) + if summary.get("schema_version") != SCHEMA: + raise ValueError("wrong experiment schema") + if summary.get("evidence_class") != "synthetic_trained_gate_development_positive_control": + raise ValueError("unsupported evidence class") + for name in ("checkpoint.json", "depth_matrix.jsonl", "interventions.jsonl"): + actual = hashlib.sha256((directory / name).read_bytes()).hexdigest() + if summary["files_sha256"].get(name) != actual: + raise ValueError(f"source file digest mismatch: {name}") + theta = checkpoint.get("theta") + if type(theta) not in {int, float} or not math.isfinite(theta): + raise ValueError("invalid checkpoint theta") + alpha = 1 / (1 + math.exp(-theta)) + checkpoint_sha = _digest({"theta": theta, "arch": ARCH}) + if ( + checkpoint.get("sha256") != checkpoint_sha + or summary.get("checkpoint_sha256") != checkpoint_sha + or not _near(checkpoint.get("alpha"), alpha) + ): + raise ValueError("checkpoint identity mismatch") + + depths = [int(value) for value in summary["depth_accuracy"]] + if len(set(depths)) != len(depths): + raise ValueError("duplicate depths") + depth_rows = _rows(directory / "depth_matrix.jsonl") + causal_rows = _rows(directory / "interventions.jsonl") + cases: dict[str, dict[str, Any]] = {} + roots: dict[str, set[str]] = defaultdict(set) + matrix: set[tuple[str, int]] = set() + depth_correct: Counter[int] = Counter() + for row in depth_rows: + _shared(row, checkpoint_sha) + perm, start, hops, target = _source_world(row) + case, root, depth = row["case_id"], row["root_id"], row["depth"] + if type(depth) is not int or depth not in depths: + raise ValueError("unexpected depth") + if (case, depth) in matrix: + raise ValueError("duplicate case/depth") + matrix.add((case, depth)) + old = cases.get(case) + if old is not None and old["task_digest"] != row["task_digest"]: + raise ValueError("case world changed across depths") + cases[case] = row + roots[root].add(case) + result = _walk_state(perm, start, min(hops, depth), alpha) + predicted = _argmax(result) + expected = predicted == target + if row["predicted"] != predicted or row["verified"] is not expected: + raise ValueError("depth prediction fails independent recurrence replay") + depth_correct[depth] += int(expected) + if len(matrix) != len(cases) * len(depths): + raise ValueError("incomplete depth matrix") + if len(roots) != summary["source_roots"] or len(cases) != summary["cases"]: + raise ValueError("root/case count mismatch") + for depth in depths: + receipt = summary["depth_accuracy"][str(depth)] + if receipt != {"correct": depth_correct[depth], "total": len(cases)}: + raise ValueError("depth summary disagrees with replayed cases") + + max_depth = max(depths) + causal_seen: set[tuple[str, str]] = set() + arm_correct: Counter[str] = Counter() + eligible_cases = {case for case, row in cases.items() if row["hops"] >= 4} + for row in causal_rows: + _shared(row, checkpoint_sha) + perm, start, hops, target = _source_world(row) + case, arm = row["case_id"], row["arm"] + if case not in eligible_cases or arm not in ARMS or row["depth"] != max_depth: + raise ValueError("invalid intervention case/arm/depth") + if row["task_digest"] != cases[case]["task_digest"]: + raise ValueError("intervention changed task world") + if (case, arm) in causal_seen: + raise ValueError("duplicate case/arm") + causal_seen.add((case, arm)) + if row.get("patch_visit") != 2: + raise ValueError("unsupported patch visit") + if arm == "clean": + if (row.get("pre_patch_raw_state") is not None + or row.get("post_patch_raw_state") is not None): + raise ValueError("clean arm has a patch") + resulting = _walk_state(perm, start, min(hops, max_depth), alpha) + displacement = 0.0 + else: + before = _vector(row.get("pre_patch_raw_state")) + after = _vector(row.get("post_patch_raw_state")) + replay_before = _walk_state(perm, start, 2, alpha) + if not _same_state(replay_before, before): + raise ValueError("raw pre-patch state does not replay") + if row.get("pre_patch_argmax") != _argmax(before): + raise ValueError("raw patch argmax mismatch") + delta = [y - x for x, y in zip(before, after, strict=True)] + displacement = math.sqrt(sum(d * d for d in delta)) + if arm == "zero" and displacement > 1e-10: + raise ValueError("zero patch changed the state") + if arm == "active_coordinate": + selected = _argmax(before) + expected = [0.0] * 17 + expected[selected] -= summary["nominal_dose"] / math.sqrt(2) + expected[(selected + 1) % 17] += summary["nominal_dose"] / math.sqrt(2) + if not _same_state(delta, expected): + raise ValueError("active-coordinate intervention formula changed") + resulting = _walk_state( + perm, start, min(hops, max_depth) - 2, alpha, state=after, + ) + expected_dose = 0.0 if arm in {"zero", "clean"} else summary["nominal_dose"] + if (not _near(displacement, expected_dose) + or not _near(row["realized_raw_l2_displacement"], displacement) + or not _near(row["nominal_l2_dose"], expected_dose)): + raise ValueError("realized/nominal intervention dose mismatch") + predicted = _argmax(resulting) + passed = predicted == target + if row["predicted"] != predicted or row["verified"] is not passed: + raise ValueError("intervened prediction fails independent recurrence replay") + arm_correct[arm] += int(passed) + if len(causal_seen) != len(eligible_cases) * len(ARMS): + raise ValueError("incomplete intervention arm matrix") + for arm in ARMS: + if summary["intervention_accuracy"][arm] != { + "correct": arm_correct[arm], "total": len(eligible_cases) + }: + raise ValueError("intervention summary disagrees with replayed cases") + return { + "schema_version": "bpd.inkling_control_audit.v1", + "evidence_class": "independent_source_only_synthetic_replay", + "checkpoint_sha256": checkpoint_sha, + "roots": len(roots), "cases": len(cases), + "depths": sorted(depths), "per_depth_correct": dict(sorted(depth_correct.items())), + "per_arm_correct": dict(sorted(arm_correct.items())), + "intervention_cases": len(eligible_cases), + "receipt_replay_passed": True, + "claim_boundary": ( + "Explicit graph operator and one trained mixing gate; full state replay " + "only for this synthetic model. No native Inkling activation evidence." + ), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--input", type=Path, required=True) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + if args.out.exists(): + parser.error("output exists") + report = audit(args.input) + args.out.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({"roots": report["roots"], "replay": report["receipt_replay_passed"]})) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/native_receipt_audit.py b/mechinterp/bpd/experiments/inkling_reader_v0/native_receipt_audit.py new file mode 100644 index 00000000..a6c84f83 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/native_receipt_audit.py @@ -0,0 +1,161 @@ +"""Independent stdlib audit for SHA-pinned pretrained TRM root/arm JSON receipts. + +Verifies task outcomes, root pairing, physical dose and zero-patch parity. +It is a receipt audit, NOT a native model re-execution or mechanism confirmation. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from collections import defaultdict +from pathlib import Path +from typing import Any + +ARMS = {"clean", "zero", "head_direction", "random_direction"} +SHA = "932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3" + + +def valid_sudoku(question: str, candidate: str) -> bool: + if len(question) != 81 or len(candidate) != 81: + return False + if any(ch not in "123456789." for ch in question): + return False + if any(ch not in "123456789" for ch in candidate): + return False + if any(q != "." and candidate[i] != q for i, q in enumerate(question)): + return False + groups = [[r * 9 + c for c in range(9)] for r in range(9)] + groups += [[r * 9 + c for r in range(9)] for c in range(9)] + groups += [ + [(r + dr) * 9 + c + dc for dr in range(3) for dc in range(3)] + for r in (0, 3, 6) for c in (0, 3, 6) + ] + return all({candidate[i] for i in group} == set("123456789") for group in groups) + + +def _read(path: Path) -> dict[str, Any]: + if path.stat().st_size > 10_000_000: + raise ValueError("receipt exceeds ten MB") + data = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(data, dict): + raise ValueError("expected JSON object") + return data + + +def audit(paths: list[Path]) -> dict[str, Any]: + if not paths: + raise ValueError("at least one matrix required") + summaries = [] + cohorts: dict[tuple[int | None, int | None, int], dict[str, str]] = {} + for path in paths: + report = _read(path) + if ( + report.get("schema_version") != "bpd.native_trm_boundary_pilot.v1" + or report.get("evidence_class") != "native_pretrained_development" + or report.get("model") != "gaoxin492" + or report.get("model_sha256") != SHA + or report.get("max_clean_parity_difference") != 0 + or set(report.get("arms", [])) != ARMS + ): + raise ValueError("wrong checkpoint, schema or model-parity receipt") + if report.get("outer_steps") not in {1, 2, 3}: + raise ValueError("invalid outer depth") + groups: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict) + for row in report["rows"]: + arm, root = row.get("arm"), row.get("root_id") + if arm not in ARMS or not isinstance(root, str) or arm in groups[root]: + raise ValueError("unknown or repeated arm/root") + if ( + row.get("model_sha256") != SHA or row.get("model_id") != "gaoxin492" + or row.get("experiment_split") != "development" + ): + raise ValueError("model/split mismatch") + q, target, prediction = row["question"], row["clean_exact_solution"], row["predicted"] + if not valid_sudoku(q, target): + raise ValueError("invalid planted puzzle") + if hashlib.sha256(target.encode()).hexdigest() != row.get("target_sha256"): + raise ValueError("target hash incorrect") + if row["selected_cell"] != q.index("."): + raise ValueError("intervention cell differs from first blank") + if ( + row["cell_correct"] != sum(a == b for a, b in zip(prediction, target)) + or row["board_exact"] != (prediction == target) + or row["board_valid"] != valid_sudoku(q, prediction) + or row["selected_cell_correct"] + != (prediction[row["selected_cell"]] == target[row["selected_cell"]]) + ): + raise ValueError("case correctness does not replay") + for field in ("nominal_raw_l2", "actual_raw_l2", "pre_state_norm_l2"): + if not isinstance(row[field], (int, float)) or not math.isfinite(row[field]): + raise ValueError("invalid physical measurement") + expected = 0 if arm in {"clean", "zero"} else ( + row["pre_state_norm_l2"] * report["relative_dose"] + ) + if ( + abs(row["nominal_raw_l2"] - expected) > 0.002 + or abs(row["actual_raw_l2"] - expected) > 0.002 + ): + raise ValueError("physical intervention dose mismatch") + groups[root][arm] = row + if len(groups) != report["roots"] or any(set(g) != ARMS for g in groups.values()): + raise ValueError("incomplete root/arm matrix") + current = {} + for root, rows in groups.items(): + clean, zero = rows["clean"], rows["zero"] + if ( + clean["predicted"] != zero["predicted"] + or clean["final_selected_cell_logits"] != zero["final_selected_cell_logits"] + or zero["mean_abs_logit_change"] != 0 + or len({v["question"] for v in rows.values()}) != 1 + ): + raise ValueError("zero/control parity or root pairing failed") + current[root] = clean["question"] + if report["roots"] > 1: + cohort_key = (report.get("seed"), report.get("holes"), report["roots"]) + if cohort_key in cohorts and cohorts[cohort_key] != current: + raise ValueError("cohort changed across pass/patch conditions") + cohorts[cohort_key] = current + metrics = {} + for arm in sorted(ARMS): + selected = [rows[arm] for rows in groups.values()] + metrics[arm] = { + "board_exact": sum(r["board_exact"] for r in selected), + "mean_cell_correct": sum(r["cell_correct"] for r in selected) / len(selected), + "mean_abs_logit_change": sum(r["mean_abs_logit_change"] for r in selected) / len(selected), + } + summaries.append({ + "file": path.name, "file_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "roots": report["roots"], "holes": report.get("holes"), + "outer_steps": report["outer_steps"], + "patch_h_cycle": report.get("patch_h_cycle", 1), + "relative_dose": report["relative_dose"], "metrics": metrics, + }) + return { + "schema_version": "bpd.native_trm_receipt_audit.v1", + "evidence_class": "descriptive_native_development_receipt_replay", + "checkpoint_sha256": SHA, "matrices": summaries, "verified": True, + "limitations": ( + "Independently checks output correctness, dose and pairing. " + "Does not reexecute pretrained model from weights or establish Inkling routing." + ), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("paths", nargs="+", type=Path) + parser.add_argument("--out", required=True, type=Path) + args = parser.parse_args() + if args.out.exists(): + parser.error("output already exists") + report = audit(args.paths) + args.out.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({"verified": True, "matrices": len(report["matrices"])})) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py b/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py new file mode 100644 index 00000000..ff16c8d2 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_exit.py @@ -0,0 +1,236 @@ +"""Run genuine pretrained TRM with a resumable, exact-verifier recurrent exit. + +Each outer step uses the saved z_H/z_L states of the actual pretrained +attention/MLP recurrent model. A Sudoku checker can stop the model once +it returns a complete legal solution without seeing the planted target. +This is development research, not an Inkling Attention Residual study. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import time +from collections import Counter +from pathlib import Path +from typing import Any + +import torch +from torch import Tensor + +from mechinterp.bpd.adapters.trm import build_mini_trm, load_pretrained_trm +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot import ( + _digest, _permute_sudoku, verify_sudoku, +) +from mechinterp.loopscope02.scripts.trm_sudoku import TRM_CHECKPOINTS, PureSudokuTRM, encode_questions + +SCHEMA = "bpd.native_trm_verifier_exit.v1" + + +@torch.no_grad() +def native_rollout( + model: PureSudokuTRM, + question: str, + *, + max_outer_steps: int, + stop_when_verified: bool, +) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """One uninterrupted recurrence; later steps reuse the preceding state.""" + if type(max_outer_steps) is not int or not 1 <= max_outer_steps <= 8: + raise ValueError("max_outer_steps must be in 1..8") + if len(question) != 81 or "." not in question: + raise ValueError("a bounded incomplete Sudoku question is required") + tokens = encode_questions([question], model.embed_tokens.weight.device) + embedded = model.encode_inputs(tokens) + z_h, z_l = model.init_states(1) + blank = [index for index, value in enumerate(question) if value == "."] + observations: list[dict[str, Any]] = [] + start = time.perf_counter() + for step in range(1, max_outer_steps + 1): + began = time.perf_counter() + z_h, z_l = model.act_step(z_h, z_l, embedded) + step_compute_sec = time.perf_counter() - began + logits = model.digit_logits(z_h)[0].float() + prediction = "".join(str(int(v) + 1) for v in logits.argmax(dim=-1).tolist()) + verify_started = time.perf_counter() + checked = verify_sudoku(question, prediction) + check_sec = time.perf_counter() - verify_started + margin = torch.topk(logits[blank], k=2, dim=-1).values + margins = (margin[:, 0] - margin[:, 1]).tolist() + observations.append({ + "outer_step": step, + "candidate": prediction, + "sudoku_checker_passed": checked, + "mean_blank_logit_margin": sum(margins) / len(margins), + "min_blank_logit_margin": min(margins), + "native_step_seconds": round(step_compute_sec, 6), + "exact_check_seconds": round(check_sec, 6), + }) + if checked and stop_when_verified: + break + return observations, { + "realized_outer_steps": len(observations), + "stop_reason": "verified" if observations[-1]["sudoku_checker_passed"] else "depth_budget", + "elapsed_seconds": round(time.perf_counter() - start, 6), + } + + +def run( + model: PureSudokuTRM, + *, + model_id: str, + model_sha: str, + pretrained: bool, + seed: int = 20261123, + roots: int = 24, + holes: int = 50, + max_outer_steps: int = 2, + max_wall_seconds: float = 600.0, +) -> dict[str, Any]: + if type(roots) is not int or not 1 <= roots <= 32: + raise ValueError("roots must be in 1..32") + if type(seed) is not int or not 0 <= seed < 2**32: + raise ValueError("invalid root seed") + if not math.isfinite(max_wall_seconds) or max_wall_seconds <= 0: + raise ValueError("positive finite wall limit required") + if len(model_sha) != 64: + raise ValueError("checkpoint identity requires SHA-256") + if max_outer_steps != 2: + raise ValueError("v1 comparison uses exactly two permitted outer steps") + model.eval() + started = time.monotonic() + records = [] + for root_index in range(roots): + if time.monotonic() - started > max_wall_seconds: + raise TimeoutError("wall budget exceeded between independent roots") + root_seed = seed + 101 * root_index + question, planted_solution = _permute_sudoku(root_seed, holes=holes) + evaluations = {} + # Alternate run order to avoid assigning warm hardware to one arm. + policies = ("fixed_2", "verifier_exit") if root_index % 2 == 0 else ("verifier_exit", "fixed_2") + for policy in policies: + trace, result = native_rollout( + model, question, max_outer_steps=max_outer_steps, + stop_when_verified=policy == "verifier_exit", + ) + evaluations[policy] = {**result, "trace": trace} + fixed, adaptive = evaluations["fixed_2"], evaluations["verifier_exit"] + if adaptive["trace"][0]["candidate"] != fixed["trace"][0]["candidate"]: + raise RuntimeError("first-visit predictions differed across matched policies") + if not all( + item["sudoku_checker_passed"] == (item["candidate"] == planted_solution) + for policy in evaluations.values() for item in policy["trace"] + ): + raise RuntimeError("checker disagrees with planted uniquely solvable solution") + if adaptive["trace"][-1]["candidate"] != fixed["trace"][ + adaptive["realized_outer_steps"] - 1 + ]["candidate"]: + raise RuntimeError("resumed recurrent state diverged from fixed-depth control") + records.append({ + "root_id": f"sudoku-root-{root_seed}", + "source_split": "development", + "task_digest": _digest({"question": question}), + "question": question, + "planted_solution_sha256": hashlib.sha256(planted_solution.encode()).hexdigest(), + "blank_count": holes, + "model_id": model_id, + "model_sha256": model_sha, + "measured_arm_order": list(policies), + "policies": evaluations, + }) + summary: dict[str, Any] = {} + for name in ("fixed_2", "verifier_exit"): + rows = [row["policies"][name] for row in records] + summary[name] = { + "verified_solved": sum(row["trace"][-1]["sudoku_checker_passed"] for row in rows), + "cases": roots, + "outer_steps_total": sum(row["realized_outer_steps"] for row in rows), + "mean_outer_steps": sum(row["realized_outer_steps"] for row in rows) / roots, + "elapsed_wall_seconds": round(sum(row["elapsed_seconds"] for row in rows), 6), + "total_native_step_seconds": round(sum( + v["native_step_seconds"] for row in rows for v in row["trace"] + ), 6), + "total_checker_seconds": round(sum( + v["exact_check_seconds"] for row in rows for v in row["trace"] + ), 6), + "stop_reasons": dict(sorted(Counter(row["stop_reason"] for row in rows).items())), + } + summary["step_count_fraction_saved"] = ( + 1 - summary["verifier_exit"]["outer_steps_total"] / summary["fixed_2"]["outer_steps_total"] + ) + summary["measured_native_step_fraction_saved"] = ( + 1 - summary["verifier_exit"]["total_native_step_seconds"] + / summary["fixed_2"]["total_native_step_seconds"] + ) + return { + "schema_version": SCHEMA, + "evidence_class": "native_pretrained_development" if pretrained else "untrained_plumbing_smoke", + "model": model_id, + "model_sha256": model_sha, + "seed": seed, + "roots": roots, + "holes": holes, + "max_outer_steps": max_outer_steps, + "checker": "sudoku_9x9_full_grid_clues_and_constraints", + "check_uses_planted_solution": False, + "student_training_eligible": False, + "split": "development", + "configuration": { + "threads": torch.get_num_threads(), + "h_cycles": model.h_cycles, + "l_cycles": model.l_cycles, + "internal_weight_tying": True, + }, + "summary": summary, + "records": records, + "study_limitations": ( + "Task selection is development exposed. Sudoku legal-solution verification " + "provides strong external feedback and does not directly transfer to " + "general language tasks. No Inkling Attention Residual intervention performed." + ), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", required=True, type=Path) + parser.add_argument("--model", choices=("mini", "gaoxin492"), default="mini") + parser.add_argument("--roots", type=int, default=24) + parser.add_argument("--seed", type=int, default=20261123) + parser.add_argument("--holes", type=int, default=50) + parser.add_argument("--wall-limit", type=float, default=600) + args = parser.parse_args() + if args.out.exists(): + parser.error("output exists") + torch.set_num_threads(2) + if args.model == "mini": + model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, + h_cycles=2, l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=43, + ) + pretrained = False + sha = _digest({"mini_seed": 43, "weights": "untrained"}) + else: + model = load_pretrained_trm("gaoxin492", dtype=torch.float32, verify_sha256=True) + pretrained = True + sha = TRM_CHECKPOINTS["gaoxin492"]["sha256"] + result = run( + model, model_id=args.model, model_sha=sha, pretrained=pretrained, + roots=args.roots, seed=args.seed, holes=args.holes, + max_wall_seconds=args.wall_limit, + ) + result["source_sha256"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(result, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8") + print(json.dumps({ + "out": str(args.out), "evidence_class": result["evidence_class"], + "summary": result["summary"], + }, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_pilot.py b/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_pilot.py new file mode 100644 index 00000000..328a1349 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/native_trm_pilot.py @@ -0,0 +1,415 @@ +"""Pretrained 7M Attention-TRM: CPU-bounded native recurrent-state intervention pilot. + +Uses the existing SHA-pinned PureSudokuTRM checkpoint loader. This model +contains learned recurrent attention and MLP blocks; it does not implement +Inkling's Attention Residual cross-loop block readers. + +The selected readout direction is fixed from the digit head and is NOT +chosen using the solution, model's outcome, or held-out contrast. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import random +import time +from pathlib import Path +from typing import Any + +import torch +from torch import Tensor + +from mechinterp.bpd.adapters.trm import build_mini_trm, load_pretrained_trm +from mechinterp.loopscope02.scripts.trm_sudoku import PureSudokuTRM, encode_questions + +SCHEMA = "bpd.native_trm_boundary_pilot.v1" +ARMS = ("clean", "zero", "head_direction", "random_direction") +DEFAULT_SEED = 20261121 + + +def _digest(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def count_solutions(question: str, *, limit: int = 2) -> int: + """Independent Sudoku constraint solver; stop after limit valid completions.""" + if len(question) != 81 or any(ch not in "123456789." for ch in question): + raise ValueError("invalid Sudoku question") + if type(limit) is not int or not 1 <= limit <= 10: + raise ValueError("invalid solution count limit") + board = [0 if ch == "." else int(ch) for ch in question] + row_masks, col_masks, box_masks = [0] * 9, [0] * 9, [0] * 9 + blank = [] + for index, value in enumerate(board): + r, col = divmod(index, 9) + box = (r // 3) * 3 + col // 3 + if not value: + blank.append(index) + continue + bit = 1 << (value - 1) + if row_masks[r] & bit or col_masks[col] & bit or box_masks[box] & bit: + return 0 + row_masks[r] |= bit + col_masks[col] |= bit + box_masks[box] |= bit + + solutions = 0 + + def search() -> None: + nonlocal solutions + if solutions >= limit: + return + target, options, fewest = -1, 0, 10 + for index in blank: + if board[index]: + continue + r, col = divmod(index, 9) + box = (r // 3) * 3 + col // 3 + mask = 0x1FF & ~(row_masks[r] | col_masks[col] | box_masks[box]) + n = mask.bit_count() + if n < fewest: + target, options, fewest = index, mask, n + if n == 0: + return + if n == 1: + break + if target < 0: + solutions += 1 + return + r, col = divmod(target, 9) + box = (r // 3) * 3 + col // 3 + while options and solutions < limit: + bit = options & -options + options -= bit + board[target] = bit.bit_length() + row_masks[r] |= bit + col_masks[col] |= bit + box_masks[box] |= bit + search() + row_masks[r] ^= bit + col_masks[col] ^= bit + box_masks[box] ^= bit + board[target] = 0 + + search() + return solutions + + +def _permute_sudoku(seed: int, holes: int = 22) -> tuple[str, str]: + """Produce reproducible clue/target pairs from a Sudoku-valid solved board.""" + if type(seed) is not int or type(holes) is not int or not 0 <= holes <= 55: + raise ValueError("seed and hole count out of bounds") + rng = random.Random(seed) + bands = list(range(3)) + stacks = list(range(3)) + rng.shuffle(bands) + rng.shuffle(stacks) + rows = [] + cols = [] + for group in bands: + members = list(range(3 * group, 3 * group + 3)) + rng.shuffle(members) + rows.extend(members) + for group in stacks: + members = list(range(3 * group, 3 * group + 3)) + rng.shuffle(members) + cols.extend(members) + digits = list("123456789") + rng.shuffle(digits) + solution = "".join( + digits[((rows[r] * 3 + rows[r] // 3 + cols[c]) % 9)] + for r in range(9) for c in range(9) + ) + question = list(solution) + removed = 0 + # Each removal retains a uniquely solvable puzzle independent of the model. + for position in rng.sample(range(81), 81): + if removed >= holes: + break + question[position] = "." + if count_solutions("".join(question)) == 1: + removed += 1 + else: + question[position] = solution[position] + if removed != holes: + raise ValueError("could not construct uniquely solvable puzzle at requested clue count") + q = "".join(question) + assert verify_sudoku(q, solution) and count_solutions(q) == 1 + return q, solution + + +def verify_sudoku(question: str, candidate: str) -> bool: + if len(question) != 81 or len(candidate) != 81: + return False + if any(ch not in "123456789." for ch in question): + return False + if any(ch not in "123456789" for ch in candidate): + return False + for p, clue in enumerate(question): + if clue != "." and candidate[p] != clue: + return False + groups = [] + for r in range(9): + groups.append([r * 9 + c for c in range(9)]) + for c in range(9): + groups.append([r * 9 + c for r in range(9)]) + for br in range(0, 9, 3): + for bc in range(0, 9, 3): + groups.append([(br + r) * 9 + bc + c for r in range(3) for c in range(3)]) + return all(set(candidate[p] for p in indices) == set("123456789") for indices in groups) + + +def _direction(model: PureSudokuTRM, arm: str, *, root_seed: int) -> Tensor: + width = model.hidden_size + if arm == "head_direction": + direction = ( + model.lm_head.weight[2].detach().float() + - model.lm_head.weight[3].detach().float() + ) + elif arm == "random_direction": + rng = torch.Generator(device="cpu").manual_seed(root_seed) + direction = torch.randn(width, generator=rng) + else: + raise ValueError("unknown direction") + return direction / direction.norm().clamp_min(1e-12) + + +@torch.no_grad() +def run_one( + model: PureSudokuTRM, + question: str, + *, + outer_steps: int = 1, + arm: str = "clean", + root_seed: int = 0, + relative_dose: float = 0.2, + patch_h_cycle: int = 1, +) -> tuple[Tensor, dict[str, Any]]: + """Replay actual pretrained recurrent blocks; patch z_H after H-cycle commit.""" + if arm not in ARMS: + raise ValueError("unknown intervention arm") + if type(outer_steps) is not int or not 1 <= outer_steps <= 3: + raise ValueError("outer_steps must be 1..3") + if type(patch_h_cycle) is not int or not 1 <= patch_h_cycle < model.h_cycles: + raise ValueError("patch must leave at least one subsequent H-cycle") + if not math.isfinite(relative_dose) or not 0 < relative_dose <= 1: + raise ValueError("relative_dose must be finite in (0,1]") + if question.count(".") == 0: + raise ValueError("patch cell must be a blank Sudoku location") + idx = question.index(".") + tokens = encode_questions([question], model.embed_tokens.weight.device) + embeddings = model.encode_inputs(tokens) + z_h, z_l = model.init_states(1) + patch_receipt: dict[str, Any] | None = None + early_logits = None + for outer in range(outer_steps): + for cycle in range(model.h_cycles): + for _ in range(model.l_cycles): + z_l = model.run_l_level(z_l, z_h + embeddings) + z_h = model.run_l_level(z_h, z_l) + if outer == 0 and cycle + 1 == patch_h_cycle: + pre = z_h[:, model.puzzle_emb_len + idx, :].float().clone() + early_logits = model.lm_head(pre.to(model.lm_head.weight.dtype))[0, 2:11].float() + dose = float(pre.norm().item() * relative_dose) + if arm in {"head_direction", "random_direction"}: + direction = _direction(model, arm, root_seed=root_seed).to( + pre.device, dtype=pre.dtype, + ) + delta = direction * dose + patched = z_h.clone() + patched[:, model.puzzle_emb_len + idx, :] += delta.to(z_h.dtype)[None, :] + z_h = patched + actual = float( + (z_h[:, model.puzzle_emb_len + idx, :].float() - pre).norm().item() + ) + else: + actual = 0.0 + patch_receipt = { + "site": "z_H_after_h_cycle", + "outer_step": 1, + "h_cycle": patch_h_cycle, + "selected_cell": idx, + "selected_from": "first_blank_in_question", + "dose_relative_to_raw_state": relative_dose, + "nominal_raw_l2": dose if arm in {"head_direction", "random_direction"} else 0.0, + "actual_raw_l2": actual, + "pre_state_norm_l2": float(pre.norm()), + } + assert early_logits is not None and patch_receipt is not None + logits = model.digit_logits(z_h)[0].float() + prediction = "".join(str(int(v) + 1) for v in logits.argmax(dim=-1).tolist()) + summary = { + **patch_receipt, "arm": arm, + "predicted": prediction, + "initial_selected_cell_logits": early_logits.tolist(), + "final_selected_cell_logits": logits[idx].tolist(), + "recurrent_calls": outer_steps * model.h_cycles * (model.l_cycles + 1), + "model_is_pretrained": None, + } + return logits, summary + + +@torch.no_grad() +def verify_clean_parity(model: PureSudokuTRM, question: str) -> float: + """Independent manual unroll must reproduce the native act_step output.""" + inputs = encode_questions([question], model.embed_tokens.weight.device) + x_emb = model.encode_inputs(inputs) + zh0, zl0 = model.init_states(1) + zh_native, zl_native = model.act_step(zh0.clone(), zl0.clone(), x_emb) + zh, zl = zh0, zl0 + for _ in range(model.h_cycles): + for _ in range(model.l_cycles): + zl = model.run_l_level(zl, zh + x_emb) + zh = model.run_l_level(zh, zl) + max_difference = max( + float((zh - zh_native).float().abs().max().item()), + float((zl - zl_native).float().abs().max().item()), + ) + if max_difference > 1e-5: + raise ValueError(f"manual native recurrence parity failed: {max_difference}") + return max_difference + + +def run_campaign( + model: PureSudokuTRM, + *, + pretrained: bool, + model_id: str, + model_sha: str, + seed: int = DEFAULT_SEED, + roots: int = 2, + outer_steps: int = 1, + relative_dose: float = 0.2, + holes: int = 22, + patch_h_cycle: int = 1, +) -> dict[str, Any]: + if type(roots) is not int or not 1 <= roots <= 32: + raise ValueError("roots must be in 1..32") + if len(model_sha) != 64: + raise ValueError("checkpoint SHA-256 required") + model.eval() + measurements = [] + parity = None + started = time.monotonic() + for i in range(roots): + root_seed = seed + 101 * i + question, target = _permute_sudoku(root_seed, holes=holes) + if parity is None: + parity = verify_clean_parity(model, question) + baseline = None + for arm in ARMS: + begun = time.monotonic() + logits, row = run_one( + model, question, outer_steps=outer_steps, + arm=arm, root_seed=root_seed + 11, + relative_dose=relative_dose, patch_h_cycle=patch_h_cycle, + ) + if arm == "clean": + baseline = logits + assert baseline is not None + row.update( + schema_version=SCHEMA, + experiment_split="development", + case_id=f"sudoku-{seed}-{i}", + root_id=f"source-sudoku-{root_seed}", + question=question, + target_sha256=hashlib.sha256(target.encode()).hexdigest(), + model_id=model_id, + model_sha256=model_sha, + model_pretrained=pretrained, + clean_exact_solution=target, + target_matches_verified_sudoku=verify_sudoku(question, target), + board_exact=row["predicted"] == target, + board_valid=verify_sudoku(question, row["predicted"]), + cell_correct=sum(a == b for a, b in zip(row["predicted"], target)), + selected_cell_correct=row["predicted"][row["selected_cell"]] == target[row["selected_cell"]], + target_digit_at_selected_cell=target[row["selected_cell"]], + mean_abs_logit_change=float((logits - baseline).abs().mean()), + selected_cell_logits_l2_change=float( + (logits[row["selected_cell"]] - baseline[row["selected_cell"]]).norm() + ), + seconds=round(time.monotonic() - begun, 4), + ) + measurements.append(row) + return { + "schema_version": SCHEMA, + "evidence_class": "native_pretrained_development" if pretrained else "untrained_native_plumbing_smoke", + "model": model_id, "model_sha256": model_sha, "pretrained": pretrained, + "roots": roots, "seed": seed, "arms": list(ARMS), "outer_steps": outer_steps, + "actual_model_h_cycles": model.h_cycles, "actual_model_l_cycles": model.l_cycles, + "relative_dose": relative_dose, "holes": holes, "patch_h_cycle": patch_h_cycle, + "max_clean_parity_difference": parity, + "all_sudoku_targets_verified": all(row["target_matches_verified_sudoku"] for row in measurements), + "rows": measurements, "elapsed_seconds": round(time.monotonic() - started, 3), + "claim_boundary": ( + "TRM native recurrent z_H intervention; no cross-loop Attention Residual reader. " + "No native Inkling weights, no independent representation discovery or scientific confirmation. " + "Model outcomes are descriptive on fresh generated development Sudoku worlds." + ), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--model", choices=("mini", "gaoxin492", "yagizdevre"), default="mini") + parser.add_argument("--roots", type=int, default=2) + parser.add_argument("--outer-steps", type=int, default=1) + parser.add_argument("--relative-dose", type=float, default=0.2) + parser.add_argument("--holes", type=int, default=22) + parser.add_argument("--patch-h-cycle", type=int, default=1) + parser.add_argument("--seed", type=int, default=DEFAULT_SEED) + args = parser.parse_args() + if args.out.exists(): + parser.error("output file exists") + torch.set_num_threads(2) + torch.manual_seed(32) + if args.model == "mini": + model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, + h_cycles=2, l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=32, + ) + trained = False + model_sha = _digest({ + "architecture": "build_mini_trm_32x1", + "seed": 32, + "training": False, + }) + else: + model = load_pretrained_trm(args.model, dtype=torch.float32, verify_sha256=True) + from mechinterp.loopscope02.scripts.trm_sudoku import TRM_CHECKPOINTS + model_sha = TRM_CHECKPOINTS[args.model]["sha256"] + trained = True + result = run_campaign( + model, pretrained=trained, model_id=args.model, model_sha=model_sha, + roots=args.roots, seed=args.seed, outer_steps=args.outer_steps, + relative_dose=args.relative_dose, holes=args.holes, patch_h_cycle=args.patch_h_cycle, + ) + result["code_sha256"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(result, sort_keys=True, indent=2, allow_nan=False) + "\n", encoding="utf-8") + print(json.dumps({ + "out": str(args.out), "evidence_class": result["evidence_class"], + "roots": result["roots"], "seconds": result["elapsed_seconds"], + "parity_max": result["max_clean_parity_difference"], + "arms": { + arm: { + "mean_cell_correct": sum( + row["cell_correct"] for row in result["rows"] if row["arm"] == arm + ) / result["roots"], + "mean_logit_abs_delta": sum( + row["mean_abs_logit_change"] for row in result["rows"] if row["arm"] == arm + ) / result["roots"], + } for arm in ARMS + }, + }, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/reader_probe.py b/mechinterp/bpd/experiments/inkling_reader_v0/reader_probe.py new file mode 100644 index 00000000..432ecaf9 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/reader_probe.py @@ -0,0 +1,90 @@ +"""Toy cross-loop reader math for designing native, dose-matched BPD controls. + +All computations use visible synthetic vectors and a frozen linear reader. +No conclusion about Inkling, component transfer, or any trained model. +""" + +from __future__ import annotations + +import math +import random +from collections.abc import Sequence + + +def _finite_vector(values: Sequence[float], *, width: int | None = None) -> tuple[float, ...]: + result = tuple(float(v) for v in values) + if not result or (width is not None and len(result) != width): + raise ValueError("expected nonempty vectors of identical width") + if any(not math.isfinite(x) for x in result): + raise ValueError("all coordinates must be finite") + return result + + +def rmsnorm(values: Sequence[float], *, epsilon: float = 1e-6) -> tuple[float, ...]: + """Normalize vector to RMS one. epsilon acts on mean square.""" + x = _finite_vector(values) + if not math.isfinite(epsilon) or epsilon <= 0: + raise ValueError("epsilon must be positive finite") + scale = math.sqrt(sum(v * v for v in x) / len(x) + epsilon) + if not math.isfinite(scale): + raise ValueError("RMS overflow") + return tuple(v / scale for v in x) + + +def reader_gap( + reader: Sequence[float], block2_raw: Sequence[float], block3_raw: Sequence[float], +) -> dict[str, object]: + """Cross-loop block-3 score gap and score contributions, before intervention.""" + u = _finite_vector(reader) + v2 = rmsnorm(_finite_vector(block2_raw, width=len(u))) + v3 = rmsnorm(_finite_vector(block3_raw, width=len(u))) + droot = math.sqrt(len(u)) + contributions = tuple(u_i * (b - a) / droot for u_i, a, b in zip(u, v2, v3, strict=True)) + gap = sum(contributions) + beta3 = 1.0 / (1.0 + math.exp(-gap)) if gap >= 0 else math.exp(gap) / (1.0 + math.exp(gap)) + return {"score_gap": gap, "block3_weight": beta3, "coordinate_contributions": contributions} + + +def coordinate_patch( + reader: Sequence[float], block2_raw: Sequence[float], block3_raw: Sequence[float], + *, coordinate: int, delta: float, +) -> dict[str, object]: + """Patch RAW block-3 state, then recompute normalization and cross-loop reader.""" + v3 = list(_finite_vector(block3_raw)) + if type(coordinate) is not int or not 0 <= coordinate < len(v3): + raise ValueError("invalid coordinate") + if not math.isfinite(delta): + raise ValueError("finite delta required") + before = reader_gap(reader, block2_raw, v3) + v3[coordinate] += delta + after = reader_gap(reader, block2_raw, v3) + return { + "before": before, + "after": after, + "actual_raw_displacement_l2": abs(delta), + "change_in_block3_weight": after["block3_weight"] - before["block3_weight"], + } + + +def norm_matched_random_patch( + reader: Sequence[float], block2_raw: Sequence[float], block3_raw: Sequence[float], + *, dose: float, seed: int, +) -> dict[str, object]: + """Random-direction sham, L2 matched to coordinate-patch dose.""" + v3 = list(_finite_vector(block3_raw)) + if not math.isfinite(dose) or dose < 0 or type(seed) is not int: + raise ValueError("invalid dose or seed") + rng = random.Random(seed) + direction = [rng.gauss(0.0, 1.0) for _ in v3] + norm = math.sqrt(sum(v * v for v in direction)) + if norm == 0: + raise ValueError("unexpected zero random direction") + before = reader_gap(reader, block2_raw, v3) + v3 = [x + dose * d / norm for x, d in zip(v3, direction, strict=True)] + after = reader_gap(reader, block2_raw, v3) + return { + "before": before, "after": after, + "actual_raw_displacement_l2": dose, + "change_in_block3_weight": after["block3_weight"] - before["block3_weight"], + "seed": seed, + } diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit.py new file mode 100644 index 00000000..dbbb7bb6 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit.py @@ -0,0 +1,73 @@ +"""Test the actual recurrent-state continuation contract without downloading weights.""" + +from __future__ import annotations + +import hashlib +import math +import unittest + +import torch + +from mechinterp.bpd.adapters.trm import build_mini_trm +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_exit import native_rollout, run +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot import _permute_sudoku + + +class ResumableNativeExitTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + torch.set_num_threads(2) + cls.model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, + h_cycles=2, l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=43, + ) + + def test_fixed_and_verifier_arms_replay(self) -> None: + question, _ = _permute_sudoku(20261123, holes=22) + fixed, fixed_result = native_rollout( + self.model, question, max_outer_steps=2, stop_when_verified=False, + ) + conditional, conditional_result = native_rollout( + self.model, question, max_outer_steps=2, stop_when_verified=True, + ) + self.assertEqual(len(fixed), 2) + self.assertTrue(1 <= len(conditional) <= 2) + self.assertEqual(fixed[0]["candidate"], conditional[0]["candidate"]) + self.assertEqual( + fixed[len(conditional) - 1]["candidate"], conditional[-1]["candidate"], + ) + self.assertEqual(fixed_result["realized_outer_steps"], 2) + self.assertEqual(conditional_result["realized_outer_steps"], len(conditional)) + self.assertGreaterEqual(fixed_result["elapsed_seconds"], 0) + self.assertTrue(all(len(row["candidate"]) == 81 for row in fixed)) + + def test_development_run_and_handoff_boundary(self) -> None: + result = run( + self.model, model_id="mini", model_sha=hashlib.sha256(b"fixture").hexdigest(), + pretrained=False, seed=20261123, holes=22, roots=2, + ) + self.assertEqual(result["evidence_class"], "untrained_plumbing_smoke") + self.assertEqual(result["roots"], 2) + self.assertFalse(result["student_training_eligible"]) + self.assertFalse(result["check_uses_planted_solution"]) + self.assertEqual(result["summary"]["fixed_2"]["outer_steps_total"], 4) + self.assertLessEqual(result["summary"]["verifier_exit"]["outer_steps_total"], 4) + self.assertTrue(math.isfinite(result["summary"]["step_count_fraction_saved"])) + self.assertTrue(all( + row["source_split"] == "development" for row in result["records"] + )) + + def test_limits_reject_invalid_settings(self) -> None: + question, _ = _permute_sudoku(1, holes=22) + with self.assertRaisesRegex(ValueError, "max_outer_steps"): + native_rollout(self.model, question, max_outer_steps=9, stop_when_verified=True) + with self.assertRaisesRegex(ValueError, "incomplete"): + native_rollout(self.model, question.replace(".", "1"), + max_outer_steps=2, stop_when_verified=False) + with self.assertRaisesRegex(ValueError, "wall"): + run(self.model, model_id="mini", model_sha="x" * 64, + pretrained=False, max_wall_seconds=-1) + + +if __name__ == "__main__": + unittest.main() diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit_audit.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit_audit.py new file mode 100644 index 00000000..3cb8e55f --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_exit_audit.py @@ -0,0 +1,119 @@ +"""Adversarial tamper fixtures for the development verifier-exit receipt auditor.""" + +from __future__ import annotations + +import hashlib +import json +import tempfile +import unittest +from pathlib import Path + +from mechinterp.bpd.experiments.inkling_reader_v0.audit_native_trm_exit import ( + PINNED_GAOXIN, + _digest, + audit, +) + + +def fixture() -> dict: + solved = "".join(str((r * 3 + r // 3 + c) % 9 + 1) for r in range(9) for c in range(9)) + question = "." + solved[1:] + wrong = "1" * 81 + trace = [ + { + "outer_step": 1, "candidate": wrong, + "sudoku_checker_passed": False, + "native_step_seconds": 0.2, "exact_check_seconds": 0.001, + }, + { + "outer_step": 2, "candidate": solved, + "sudoku_checker_passed": True, + "native_step_seconds": 0.2, "exact_check_seconds": 0.001, + }, + ] + entry = { + "root_id": "dev-1", "question": question, "blank_count": 1, + "model_sha256": PINNED_GAOXIN, + "task_digest": _digest({"question": question}), + "measured_arm_order": ["verifier_exit", "fixed_2"], + "policies": { + "fixed_2": { + "realized_outer_steps": 2, "stop_reason": "verified", + "elapsed_seconds": 0.45, "trace": trace, + }, + "verifier_exit": { + "realized_outer_steps": 2, "stop_reason": "verified", + "elapsed_seconds": 0.44, "trace": [dict(t) for t in trace], + }, + }, + } + summary = {} + for policy in ("fixed_2", "verifier_exit"): + row = entry["policies"][policy] + summary[policy] = { + "verified_solved": 1, "cases": 1, "outer_steps_total": 2, + "elapsed_wall_seconds": row["elapsed_seconds"], + "total_native_step_seconds": 0.4, "total_checker_seconds": 0.002, + "stop_reasons": {"verified": 1}, + } + summary["step_count_fraction_saved"] = 0.0 + summary["measured_native_step_fraction_saved"] = 0.0 + return { + "schema_version": "bpd.native_trm_verifier_exit.v1", + "evidence_class": "native_pretrained_development", + "model": "gaoxin492", "model_sha256": PINNED_GAOXIN, + "split": "development", "student_training_eligible": False, + "check_uses_planted_solution": False, "max_outer_steps": 2, + "roots": 1, "holes": 1, "records": [entry], "summary": summary, + } + + +class ReceiptAuditTest(unittest.TestCase): + def audit_data(self, data: dict) -> dict: + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "receipt.json" + path.write_text(json.dumps(data), encoding="utf-8") + return audit(path) + + def test_independent_valid_solution_and_timing(self) -> None: + report = self.audit_data(fixture()) + self.assertTrue(report["root_and_checker_replay_passed"]) + self.assertEqual(report["source_roots"], 1) + self.assertEqual(report["depth_one_verified"], 0) + self.assertEqual(report["depth_two_verified"], 1) + self.assertEqual(report["adaptive_steps"], 2) + + def test_reject_mutated_solution_grade(self) -> None: + x = fixture() + x["records"][0]["policies"]["fixed_2"]["trace"][1]["sudoku_checker_passed"] = False + with self.assertRaisesRegex(ValueError, "Sudoku verifier"): + self.audit_data(x) + + def test_reject_skipping_valid_stop(self) -> None: + x = fixture() + x["records"][0]["policies"]["verifier_exit"]["trace"][0]["candidate"] = ( + x["records"][0]["policies"]["verifier_exit"]["trace"][1]["candidate"] + ) + x["records"][0]["policies"]["verifier_exit"]["trace"][0]["sudoku_checker_passed"] = True + x["records"][0]["policies"]["fixed_2"]["trace"][0]["candidate"] = ( + x["records"][0]["policies"]["fixed_2"]["trace"][1]["candidate"] + ) + x["records"][0]["policies"]["fixed_2"]["trace"][0]["sudoku_checker_passed"] = True + with self.assertRaisesRegex(ValueError, "kept computing"): + self.audit_data(x) + + def test_reject_tampered_step_totals(self) -> None: + x = fixture() + x["summary"]["verifier_exit"]["outer_steps_total"] = 1 + with self.assertRaisesRegex(ValueError, "summary mismatch"): + self.audit_data(x) + + def test_reject_bad_model(self) -> None: + x = fixture() + x["model_sha256"] = hashlib.sha256(b"wrong").hexdigest() + with self.assertRaisesRegex(ValueError, "wrong model"): + self.audit_data(x) + + +if __name__ == "__main__": + unittest.main() diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_pilot.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_pilot.py new file mode 100644 index 00000000..9b624058 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_native_trm_pilot.py @@ -0,0 +1,88 @@ +"""CPU-only tests of real TRM blocks with randomly initialized mini weights.""" + +from __future__ import annotations + +import hashlib +import json +import math +import unittest + +import torch + +from mechinterp.bpd.adapters.trm import build_mini_trm +from mechinterp.bpd.experiments.inkling_reader_v0.native_trm_pilot import ( + ARMS, _permute_sudoku, run_campaign, run_one, verify_clean_parity, verify_sudoku, +) + + +class NativeTRMTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + torch.set_num_threads(2) + cls.model = build_mini_trm( + hidden_size=32, num_heads=4, l_layers=1, h_cycles=2, + l_cycles=1, puzzle_emb_len=4, seq_len=81, seed=9, + ) + + def test_generator_validity_and_root_change(self) -> None: + q, target = _permute_sudoku(20261121) + self.assertEqual(len(q), 81) + self.assertEqual(q.count("."), 22) + self.assertTrue(verify_sudoku(q, target)) + self.assertFalse(verify_sudoku(q, target[:-1] + "0")) + q2, target2 = _permute_sudoku(20261122) + self.assertNotEqual(target, target2) + self.assertNotEqual(q, q2) + + def test_native_forward_parity(self) -> None: + q, _ = _permute_sudoku(123) + self.assertLessEqual(verify_clean_parity(self.model, q), 1e-5) + + def test_patching_changes_real_hidden_state(self) -> None: + q, _ = _permute_sudoku(543) + with torch.no_grad(): + base, clean = run_one(self.model, q, arm="clean") + zero, zero_row = run_one(self.model, q, arm="zero") + head, readout = run_one(self.model, q, arm="head_direction") + other, sham = run_one(self.model, q, arm="random_direction", root_seed=3) + self.assertTrue(torch.equal(base, zero)) + self.assertEqual(clean["actual_raw_l2"], 0.0) + self.assertEqual(zero_row["actual_raw_l2"], 0.0) + self.assertTrue(math.isclose( + readout["actual_raw_l2"], readout["nominal_raw_l2"], rel_tol=1e-5, + )) + self.assertTrue(math.isclose( + sham["actual_raw_l2"], sham["nominal_raw_l2"], rel_tol=1e-5, + )) + self.assertGreater(float((head - base).abs().sum()), 0) + self.assertGreater(float((other - base).abs().sum()), 0) + self.assertEqual(readout["site"], "z_H_after_h_cycle") + + def test_untrained_campaign_marked_smoke(self) -> None: + checkpoint_sha = hashlib.sha256(b"mini-test").hexdigest() + result = run_campaign( + self.model, model_id="mini-test", model_sha=checkpoint_sha, + pretrained=False, roots=2, seed=20261121, + ) + self.assertEqual(result["evidence_class"], "untrained_native_plumbing_smoke") + self.assertEqual(len(result["rows"]), 2 * len(ARMS)) + self.assertEqual(result["max_clean_parity_difference"], 0.0) + self.assertTrue(result["all_sudoku_targets_verified"]) + self.assertTrue(all(x["experiment_split"] == "development" for x in result["rows"])) + self.assertTrue(all(x["root_id"] and x["model_sha256"] for x in result["rows"])) + self.assertTrue(all(x["target_matches_verified_sudoku"] for x in result["rows"])) + + def test_invalid_patch_limits(self) -> None: + q, _ = _permute_sudoku(1) + with self.assertRaisesRegex(ValueError, "outer_steps"): + run_one(self.model, q, outer_steps=0) + with self.assertRaisesRegex(ValueError, "subsequent H-cycle"): + run_one(self.model, q, patch_h_cycle=self.model.h_cycles) + with self.assertRaisesRegex(ValueError, "relative_dose"): + run_one(self.model, q, relative_dose=float("nan")) + with self.assertRaisesRegex(ValueError, "blank"): + run_one(self.model, q.replace(".", "1")) + + +if __name__ == "__main__": + unittest.main() diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_positive_control_audit.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_positive_control_audit.py new file mode 100644 index 00000000..22dd6472 --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_positive_control_audit.py @@ -0,0 +1,168 @@ +"""Tamper and replay tests for independent synthetic recurrence receipts.""" + +from __future__ import annotations + +import hashlib +import json +import math +import tempfile +import unittest +from pathlib import Path + +try: + from mechinterp.bpd.experiments.inkling_reader_v0.audit_positive_control import ( + ARCH, SCHEMA, VERIFIER, _argmax, _digest, _walk_state, audit, + ) +except ModuleNotFoundError: + from audit_positive_control import ARCH, SCHEMA, VERIFIER, _argmax, _digest, _walk_state, audit + + +def _write_jsonl(path: Path, rows: list[dict]) -> None: + path.write_text( + "".join(json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n" for row in rows), + encoding="utf-8", + ) + + +def build_fixture(folder: Path) -> tuple[list[dict], list[dict]]: + theta = 5.0 + alpha = 1 / (1 + math.exp(-theta)) + sha = _digest({"theta": theta, "arch": ARCH}) + checkpoint = { + "theta": theta, "alpha": alpha, "sha256": sha, + "architecture": "explicit_permutation_one_parameter_recurrent_gate", + } + (folder / "checkpoint.json").write_text(json.dumps(checkpoint), encoding="utf-8") + depth_rows = [] + intervention_rows = [] + for index in range(2): + root_id = f"development-10-{index:04d}" + case_id = f"{root_id}-h4" + perm = tuple((i + 1) % 17 for i in range(17)) + start = index + hops = 4 + target = (start + hops) % 17 + world = {"start": start, "hops": hops, "permutation": list(perm)} + root = { + "root_id": root_id, "case_id": case_id, + "model_sha": sha, "task_world": world, + "task_digest": _digest({"root_id": root_id, "world": world}), + "verifier_id": VERIFIER, "family": "explicit_single_cycle_pointer_chase", + "split": "development", "hops": hops, "target": target, + } + for depth in (1, 2, 5): + state = _walk_state(perm, start, min(hops, depth), alpha) + prediction = _argmax(state) + depth_rows.append({ + **root, "depth": depth, "verified": prediction == target, + "predicted": prediction, + }) + before = _walk_state(perm, start, 2, alpha) + peak = _argmax(before) + dose = 0.85 + for arm in ("clean", "zero", "active_coordinate", "random_direction", "random_coordinate"): + post = before[:] + if arm == "active_coordinate": + post[peak] -= dose / math.sqrt(2) + post[(peak + 1) % 17] += dose / math.sqrt(2) + elif arm == "random_direction": + post[8] += dose + elif arm == "random_coordinate": + post[9] -= dose / math.sqrt(2) + post[10] += dose / math.sqrt(2) + if arm == "clean": + final = _walk_state(perm, start, 4, alpha) + patch = None + displacement = 0.0 + else: + final = _walk_state(perm, start, 2, alpha, state=post) + patch = before + displacement = math.sqrt(sum((a - b) ** 2 for a, b in zip(before, post, strict=True))) + prediction = _argmax(final) + intervention_rows.append({ + **root, "arm": arm, "depth": 5, "patch_visit": 2, + "predicted": prediction, "verified": prediction == target, + "nominal_l2_dose": 0.0 if arm in {"clean", "zero"} else dose, + "realized_raw_l2_displacement": displacement, + "pre_patch_raw_state": patch, + "post_patch_raw_state": None if patch is None else post, + "pre_patch_argmax": None if patch is None else peak, + }) + _write_jsonl(folder / "depth_matrix.jsonl", depth_rows) + _write_jsonl(folder / "interventions.jsonl", intervention_rows) + summary = { + "schema_version": SCHEMA, + "evidence_class": "synthetic_trained_gate_development_positive_control", + "checkpoint_sha256": sha, "source_roots": 2, "cases": 2, + "nominal_dose": 0.85, "depth_accuracy": {}, "intervention_accuracy": {}, + } + for depth in (1, 2, 5): + subset = [row for row in depth_rows if row["depth"] == depth] + summary["depth_accuracy"][str(depth)] = { + "correct": sum(row["verified"] for row in subset), "total": len(subset), + } + for arm in ("clean", "zero", "active_coordinate", "random_direction", "random_coordinate"): + subset = [row for row in intervention_rows if row["arm"] == arm] + summary["intervention_accuracy"][arm] = { + "correct": sum(row["verified"] for row in subset), "total": len(subset), + } + summary["files_sha256"] = { + name: hashlib.sha256((folder / name).read_bytes()).hexdigest() + for name in ("checkpoint.json", "depth_matrix.jsonl", "interventions.jsonl") + } + (folder / "summary.json").write_text(json.dumps(summary), encoding="utf-8") + return depth_rows, intervention_rows + + +def reseal_test_fixture(folder: Path) -> None: + """Test-only reseal ensures auditor catches semantics, not just raw hash tampering.""" + summary = json.loads((folder / "summary.json").read_text()) + for name in ("checkpoint.json", "depth_matrix.jsonl", "interventions.jsonl"): + summary["files_sha256"][name] = hashlib.sha256((folder / name).read_bytes()).hexdigest() + (folder / "summary.json").write_text(json.dumps(summary), encoding="utf-8") + + +class IndependentAuditTests(unittest.TestCase): + def test_fresh_matched_source_fixture(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + build_fixture(folder) + result = audit(folder) + self.assertTrue(result["receipt_replay_passed"]) + self.assertEqual(result["roots"], 2) + self.assertEqual(result["intervention_cases"], 2) + self.assertEqual(result["per_depth_correct"][5], 2) + + def test_independent_oracle_rejects_resealed_target_mutation(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + rows, _ = build_fixture(folder) + rows[0]["target"] = (rows[0]["target"] + 1) % 17 + _write_jsonl(folder / "depth_matrix.jsonl", rows) + reseal_test_fixture(folder) + with self.assertRaisesRegex(ValueError, "target differs"): + audit(folder) + + def test_physical_patch_rejects_resealed_dose_mutation(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + _, rows = build_fixture(folder) + patched = next(row for row in rows if row["arm"] == "active_coordinate") + patched["post_patch_raw_state"][0] += 0.1 + _write_jsonl(folder / "interventions.jsonl", rows) + reseal_test_fixture(folder) + with self.assertRaises(ValueError): + audit(folder) + + def test_incomplete_pair_matrix_is_rejected(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + _, rows = build_fixture(folder) + _write_jsonl(folder / "interventions.jsonl", rows[:-1]) + reseal_test_fixture(folder) + with self.assertRaisesRegex(ValueError, "incomplete intervention"): + audit(folder) + + +if __name__ == "__main__": + unittest.main() diff --git a/mechinterp/bpd/experiments/inkling_reader_v0/test_reader_probe.py b/mechinterp/bpd/experiments/inkling_reader_v0/test_reader_probe.py new file mode 100644 index 00000000..26cbc1aa --- /dev/null +++ b/mechinterp/bpd/experiments/inkling_reader_v0/test_reader_probe.py @@ -0,0 +1,48 @@ +"""Source-only routing decomposition test, not trained-model evidence.""" + +import math +import unittest + +try: + from mechinterp.bpd.experiments.inkling_reader_v0.reader_probe import ( + coordinate_patch, norm_matched_random_patch, reader_gap, rmsnorm, + ) +except ModuleNotFoundError: + from reader_probe import coordinate_patch, norm_matched_random_patch, reader_gap, rmsnorm + + +class ReaderProbeTest(unittest.TestCase): + def test_rms_and_score_decomposition(self): + normalized = rmsnorm([2.0, 0.0, 0.0, 0.0]) + self.assertAlmostEqual(sum(v * v for v in normalized), 4.0, places=5) + scored = reader_gap([1.0, 0.0], [1.0, 0.0], [0.0, 1.0]) + self.assertAlmostEqual(sum(scored["coordinate_contributions"]), scored["score_gap"]) + self.assertLess(scored["block3_weight"], 0.5) + + def test_coordinate_intervention_recomputes_normalizer(self): + original = reader_gap([1.0, 1.0], [1.0, 0.0], [0.0, 1.0]) + patch = coordinate_patch([1.0, 1.0], [1.0, 0.0], [0.0, 1.0], + coordinate=0, delta=5.0) + self.assertEqual(patch["actual_raw_displacement_l2"], 5.0) + self.assertNotEqual(original["score_gap"], patch["after"]["score_gap"]) + self.assertEqual(original, patch["before"]) + + def test_sham_is_dose_matched_and_deterministic(self): + args = ([1.0, 0.5, 0.2], [0.1, 0.4, 0.0], [0.5, 0.0, 0.1]) + a = norm_matched_random_patch(*args, dose=0.3, seed=71) + b = norm_matched_random_patch(*args, dose=0.3, seed=71) + self.assertAlmostEqual(a["actual_raw_displacement_l2"], 0.3) + self.assertEqual(a["change_in_block3_weight"], b["change_in_block3_weight"]) + self.assertTrue(math.isfinite(a["change_in_block3_weight"])) + + def test_bad_inputs_rejected(self): + with self.assertRaises(ValueError): + reader_gap([1.0, 2.0], [1.0], [0.0, 1.0]) + with self.assertRaises(ValueError): + coordinate_patch([1.0], [1.0], [1.0], coordinate=1, delta=1.0) + with self.assertRaises(ValueError): + norm_matched_random_patch([1.0], [1.0], [1.0], dose=-1, seed=2) + + +if __name__ == "__main__": + unittest.main()