diff --git a/.github/workflows/inkling-trained-gate-control.yml b/.github/workflows/inkling-trained-gate-control.yml new file mode 100644 index 000000000..bbd0ae101 --- /dev/null +++ b/.github/workflows/inkling-trained-gate-control.yml @@ -0,0 +1,71 @@ +name: RMP Inkling trained-gate development positive control + +on: + push: + branches: + - research/inkling-middle-loop-20261121 + paths: + - "research_gym/inkling_positive_control/**" + - ".github/workflows/inkling-trained-gate-control.yml" + pull_request: + paths: + - "research_gym/inkling_positive_control/**" + - ".github/workflows/inkling-trained-gate-control.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + trained-gate: + runs-on: ubuntu-latest + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.12"] + env: + OPENBLAS_NUM_THREADS: "1" + OMP_NUM_THREADS: "1" + MKL_NUM_THREADS: "1" + PYTHONDONTWRITEBYTECODE: "1" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install numerical dependency + run: python -m pip install "numpy>=1.24" + - name: Run small train and intervention tests + run: >- + python -m unittest discover -s research_gym/inkling_positive_control + -p 'test_experiment.py' -v + - name: Run fresh-root development sweep + if: matrix.python-version == '3.12' + run: >- + python -m research_gym.inkling_positive_control.experiment + --out runs/inkling_positive_control_20261121 + - name: Cross-check with pinned BPD and EvalMath source auditors + if: matrix.python-version == '3.12' + run: | + curl --fail --silent --show-error --location --retry 3 \ + https://raw.githubusercontent.com/MoralityLabAI/BPD/5cbd5de63e95b6c70c3e351f68be6676cd830268/mechinterp/bpd/experiments/inkling_reader_v0/audit_positive_control.py \ + -o /tmp/bpd_inkling_audit.py + python /tmp/bpd_inkling_audit.py \ + --input runs/inkling_positive_control_20261121 \ + --out runs/inkling_positive_control_20261121/bpd_independent_audit.json + curl --fail --silent --show-error --location --retry 3 \ + https://raw.githubusercontent.com/MoralityLabAI/EvalMath/ff32b93a311842967da1e4e33ac08e4ac576c46e/research/inkling_loop_monitorability/depth_matrix.py \ + -o /tmp/evalmath_inkling_audit.py + python /tmp/evalmath_inkling_audit.py \ + --input runs/inkling_positive_control_20261121/depth_matrix.jsonl \ + --baseline-depth 1 --candidate-depth 3 \ + --out runs/inkling_positive_control_20261121/evalmath_development + - name: Retain development provenance + if: matrix.python-version == '3.12' + uses: actions/upload-artifact@v4 + with: + name: inkling-trained-gate-sourceonly-dev + path: runs/inkling_positive_control_20261121/ + if-no-files-found: error + retention-days: 7 diff --git a/configs/inkling_rmp_extension_20261121.json b/configs/inkling_rmp_extension_20261121.json new file mode 100644 index 000000000..5720bae62 --- /dev/null +++ b/configs/inkling_rmp_extension_20261121.json @@ -0,0 +1,109 @@ +{ + "schema_version": "inkling_rmp_extension.v0", + "status": "design_only_unfrozen", + "source_notes": "docs/inkling_literature_bridge_20261121.md", + "provider_model": "thinkingmachines/TML-d24-varloop-research", + "pass_counts": [ + 1, + 2, + 3, + 5, + 7, + 10 + ], + "trained_midtraining_distribution": { + "1": 1, + "2": 2, + "3": 6, + "4": 2, + "5": 1 + }, + "rl_depth": 3, + "tasks": { + "serial_hops": [ + 1, + 2, + 4, + 8, + 16 + ], + "convergent": [ + "linear_least_squares", + "iterative_repair" + ], + "knowledge_control": [ + "closed_book_fact_recall" + ], + "independent_unit": "source_task_root" + }, + "causal_experiments": { + "sites": [ + "cross_loop_block2_end", + "cross_loop_block3_end", + "core_first_layer_readers", + "coda_output" + ], + "controls": [ + "untreated", + "zero_delta", + "matched_norm_random_direction", + "matched_norm_random_coordinate", + "swapped_donor", + "corrupted_target" + ], + "readouts": [ + "verified_success", + "first_verified_visit", + "corruptions", + "repairs", + "reader_score_gap", + "actual_displacement", + "future_logit_kl" + ] + }, + "controls": [ + "constant_cost", + "no_loop", + "fully_untied", + "no_input_reinjection", + "fixed_gate", + "matched_damping" + ], + "monitors": [ + "tool_only", + "tool_and_verbalized_reasoning", + "tool_plus_sparse_probes", + "tool_plus_full_boundary_access" + ], + "receipts": [ + "source_sha256", + "checkpoint_sha256", + "model_variant", + "pass_count", + "cache_mode", + "task_root", + "task_split", + "token_usage", + "wall_ms", + "memory_peak_mb", + "verifier_id", + "intervention_dose" + ], + "holdout": { + "development_only": true, + "sealed_confirmation_access_allowed": false + }, + "evidence_class": "source_only_protocol", + "promotion": { + "requires_trained_positive_control": true, + "requires_evalmath_preflight": true, + "requires_new_independent_roots": true, + "requires_holdout_release": true + }, + "limitations": [ + "fixed_pass_coordinate_2027_not_transferred", + "depths_7_10_off_training", + "architecture_and_training_exposure_confounded", + "no_measured_outcomes" + ] +} diff --git a/docs/inkling_literature_bridge_20261121.md b/docs/inkling_literature_bridge_20261121.md new file mode 100644 index 000000000..0aa3d2052 --- /dev/null +++ b/docs/inkling_literature_bridge_20261121.md @@ -0,0 +1,141 @@ +# Inkling 2 Mini literature bridge to recurrence monitorability and architecture search + +2026-11-21. Status: **development design; source-only literature review**. +Companion to [Recurrence Monitorability Program v0](recurrence_monitorability_program_v0.md) +and [Loop Schedule Architecture Discovery](loop_schedule_architecture_discovery_v1.md). +This file does not revise any completed or sealed LSAD/RMP/LS-SAE/LOOPSCOPE verdict. + +## Citations followed + +1. Thinking Machines, [Introducing Inkling 2 Mini](https://thinkingmachines.ai/news/inkling-2-mini/), + November 20, 2026. 24 stored layers, middle 12 looped three times, 48 effective applications; + 27/28 evaluations favor middle over last-layer recurrence. +2. Dehghani et al., [Universal Transformers](https://arxiv.org/abs/1807.03819): + position-wise adaptive halting and iterative refinement, subject to its stated assumptions. +3. Chen et al. (Kimi Team), [Attention Residuals](https://arxiv.org/abs/2603.15031): + content-dependent depth-wise selection and block-level aggregation; state access is richer + than a simple running residual sum. +4. Yang et al., [Looped Transformers Are Better at Learning Learning Algorithms](https://arxiv.org/abs/2311.12424): + repeated decoder can imitate an iterative regression algorithm with prompt reinjection; + extrapolation beyond trained loops is task- and regime-dependent. +5. Zhu et al., [Scaling Latent Reasoning via Looped Language Models (Ouro)](https://arxiv.org/abs/2510.25741): + entropy-regularized exit distribution and additional exit-controller training. +6. Bae et al., [Mixture-of-Recursions](https://arxiv.org/abs/2507.10524): + token-specific recurrence budgets, selective KV caching, causal routing trade-offs. +7. Goodfire, [Interpreting Inkling 2 Mini](https://www.goodfire.com/research/interpreting-inkling-2-mini/): + block-boundary writing, cross-loop reader decomposition, outlier coordinate 2027 on + the FIXED 3-pass release, and tuned/coda lens results. +8. Chen Yueh-Han et al., [Reasoning Models Struggle to Control their Chains of Thought](https://arxiv.org/abs/2603.05706): + monitorability depends on what the monitor can actually infer, not just trace readability. +9. Korbak et al., [Chain of Thought Monitorability](https://arxiv.org/abs/2507.11473): + monitorability can change under architecture/training decisions. +10. Thinking Machines, [variable-loop research model card](https://thinkingmachines.ai/model-card/tml-d24-varloop-research/): + pass counts 1–5 midtrained in ratio 1:2:6:2:1, followed by post-training at 3. + Passes 7 and 10 extrapolate outside the trained range. + +## Structural lesson for the existing gym + +Inkling routes information over **block sums**. Its core block receives a +state-dependent cross-loop message from the previous pass; near the end +of a pass, high-magnitude coordinates can influence the *next pass's* +reader scores. In Goodfire's 400-document FineWeb sample, fixed-pass +coordinate 2027 accounts for approximately 46% of the squared norm +of a normalized activation vector. The same coordinate contributes +6–19% of selected cross-loop reader score gaps. These observations +are correlations in a specific released checkpoint, not a certified +circuit or a stable coordinate index across models. + +For two source blocks, a useful pre-intervention readout is + + beta_3 = sigmoid((u · (RMSNorm(v_3)-RMSNorm(v_2))) / sqrt(d)). + +Record the score gap, every coordinate contribution, the normalized +vectors, and the reader weights BEFORE the perturbation; compare with +full recomputation after intervention. Intervening on a single coordinate +changes the normalizer, so its causal effect is generally different +from deleting its additive contribution from a fixed normalized vector. + +### Experiment A: a trained positive control first + +The existing RMP document records LSAD v1's chance-level results. +Do not use those models to infer a negative depth effect. Begin with +a checkpoint that demonstrates an independently verified algorithm: +native Inkling research weights if a 32GB+ host is available, or a +compact trained pointer-chase checkpoint with frozen evidence of +multi-hop success. Report exact checkpoint identity and training depth +distribution. The 5080 does not have sufficient memory for the native +20GB variable-loop checkpoint without a supported external offload path. + +Cross pass counts [1,2,3,5,7,10] on the SAME task roots, with separate: +- direct final-answer/no-CoT evaluation on single-hop versus 2/4/8/16-hop chains; +- visible reasoning quality at matched generated-token budgets; +- output-correctness and regression after an earlier correct answer; +- observed prefill+decode time, memory and energy where available; +- fixed 3-pass and constant-cost controls, including a task-agnostic exit; +- inference-only perturbations of positional depth tags and input reinjection. + +Report prefix task-state correctness alongside final success; an optimizer +converging in state norm is not equivalent to serial symbolic progress. +Treat architectural passes, RLT student visits, autoregressive tokens and +environment verifier calls as distinct quantities. + +### Experiment B: middle versus terminal recurrence + +Train the same-size core blocks on identical source task families with +identical training-token exposure. Compare (i) middle-12 looping, +(ii) last-12 looping, (iii) untied fixed-depth, and (iv) tied original +architecture as controls. Match *applied* layer count at each test depth +and separately report unique-parameter counts, state-storage costs and +time-to-quality. This is a training intervention. Comparing the +pretrained native Inkling middle-loop to an untrained final-loop splice +would confound architecture with weight specialization. + +### Experiment C: block routing and coda lens + +Collect the four cross-loop readers at block starts (query/key/value/MoE), +block outputs after layers 12 and 18, and coda states. Train a shared +tuned lens, a coda lens, and fixed decoder as competing methods on +monitor-TRAIN; calibrate lens choices and thresholds on a separate +monitor-CAL. Evaluate first-hop through last-hop decoding accuracy and +causal repair on untouched roots. Lens CE and token readability alone +do not establish mechanism. + +Search for outlier routing features independently in the variable-loop +checkpoint; keep fixed-three-pass coordinate 2027 as a hypothesis only. +Use dose-matched random-coordinate and subspace controls. Record clean +task accuracy, corruption, repair, state displacement and monitor +false-positive rates. + +### Experiment D: exit controllers + +Compare fixed depth with (a) task-level learned gate (Ouro), +(b) per-position ACT from Universal Transformers, and +(c) causal token-level routing (Mixture-of-Recursions). +Use a frozen cost budget and separate prompt-reinjection control as +suggested by Yang et al. Selection and learning take place entirely +on development roots. Confirm once on untouched task families. +The exit gate's ground-truth label is **first verifier-valid depth**, +not the number of tokens in the generated explanation; an oracle +look-ahead exit is an analysis bound. + +## Data contract, interpretation and controls + +- Independent unit: source task root / checkpoint population as registered. + Tokens, loop passes, directions and lens features are within-root repeats. +- Primary positive-control metric: final independently verified task success + at fixed measured effective inference cost. Set a meaningful effect above + development sham variation with EvalMath preflight before running a GPU sweep. +- Preserve train/calibration/heldout/OOD custody, registration SHA and all + failed model candidates. Holm-correct prespecified comparison family. +- Monitor access arms: tool outputs only; tool + written explanation; + tool + sparse activations; tool + full monitored boundary data. + Calibrate each monitor at equal false-positive rate on development. +- Compare a visible CoT compression metric on *all* attempted tasks as + well as the intersection correct at every depth. Report that + intersection's selection bias explicitly. +- The linked Inkling model card notes RL at depth 3 only. Differences at + other depths are joint effects of architecture and training exposure. + +Next required work: source-only adapter interface and a positive-control +checkpoint audit before selecting candidate interventions. This registration +is proposed, not frozen and not evidence of a mechanism. diff --git a/research_gym/inkling_positive_control/README.md b/research_gym/inkling_positive_control/README.md new file mode 100644 index 000000000..5efcdfd36 --- /dev/null +++ b/research_gym/inkling_positive_control/README.md @@ -0,0 +1,113 @@ +# RMP-INK-PC01: trained recurrent gate, serial-step and state-patch positive control + +Status: development-only, 2026-11-21. A *real trained scalar* in an otherwise +**explicitly supplied graph-transition operator**. This is a CPU functional +positive control for the loop instrumentation, not evidence that an LLM +learned to perform graph reasoning. It also does not establish any feature +of Inkling or the Goodfire coordinate-2027 routing hypothesis. + +## Why this arm exists + +The existing RMP experiments report chance-level results in several +independently trained tiny LoopedDecoderLM cells. Huginn-0125 has a +pretrained positive result on one-hop variable-copy chains but reaches +only 26% on three-hop examples at 16 recurrent passes. The native Inkling +variable-loop research checkpoint requires a supported memory-suitable +runtime and is not used in this CPU instrument. + +A small known-working recurrent computation gives us a **required** check: +if a program claims to patch the active state coordinate and still cannot +affect the correct output, its instrumentation is broken. + +## Model and data + +There are 17 possible graph nodes. Each source root defines a random +single-cycle permutation P and starting node i. A task requests a number +h of graph hops and its exact target is computed by h successive +applications of P, independently of model output. + +The operator P is **given explicitly** to the recurrent system. The only +learned parameter is theta, with alpha = sigmoid(theta). Each pass +proposes m = z P and mixes + + z_(t+1) = (1-alpha) z_t + alpha (z_t P). + +The model is informed of h and freezes its state after h passes. The +training objective is cross-entropy on the exact target at h, with +analytic gradients through the unrolled recurrence. Training uses +48 independent roots with hop lengths 1–4, 70 epochs, learning rate .75. +The development suite uses 64 new roots, hop lengths 1–8, and inference +budgets 1/2/3/5/7/10. Multiple tasks from one graph share a root and +are correlated; inference depth observations are repeats, not fresh roots. + +Training and evaluation are deterministic, with independent source seed +pairs (23 and 20261121). The source generator never opens an external +test split. GitHub Actions runs it on CPU, retaining a checkpoint and +source fingerprints in an artifact rather than committing generated data +to the repository. + +## Loop-boundary causal control + +At visit 2, for tasks of length 4–8, patch the raw 17D activation at a +fixed L2 dose .85. The *selected* direction subtracts from the current +argmax coordinate and adds to the next coordinate. The selected index is +computed from the running model state, not a named pretrained neuron. +The perturbation tests are clean, zero, selected, seeded Gaussian random +direction, and seeded random coordinate. Each physical displacement is +recomputed and checked against the nominal dose. The same tasks and +model are used for every arm. + +The dose was selected in a separate synthetic development pilot, so the +following results and any CI replication are **development descriptive +engineering checks**. A comparison of this selected active coordinate +with random-coordinate shams is intentionally asymmetric: the selected +coordinate is guaranteed to be active. It cannot establish a discovered +causal feature in a native neural network. + +## Run and independently review receipts + + python -m pip install numpy + python -m unittest discover -s research_gym/inkling_positive_control \ + -p 'test_experiment.py' -v + OPENBLAS_NUM_THREADS=1 python -m research_gym.inkling_positive_control.experiment \ + --out runs/rmp-ink-pc01 + +The command writes: + +- checkpoint.json: theta, alpha, training recipe and learning-curve snapshots. +- depth_matrix.jsonl: source-root paired verified correctness, with fields + compatible with EvalMath's development-only variable-loop depth auditor. +- interventions.jsonl: every arm, source root, case ID, nominal and realized + L2 dose, intervention visit and final externally recomputed target. +- summary.json: SHA-256 source and output hashes, root-cluster effect + summaries, per-depth accuracy, positive-control gates and limitations. + +The exact per-case correctness verifier walks the supplied source +permutation; it is separate from the differentiable model forward pass. + +The local engineering result from an initial fresh-root run was 64/512 +at one pass, 128/512 at two, 192/512 at three, 320/512 at five, +448/512 at seven and 512/512 at ten. The learned alpha was 0.9924545. +On 320 cases whose requested hop length exceeded the patch visit, +clean and zero arms scored 320/320, selected 0/320, seeded Gaussian +sham 319/320 and random-coordinate sham 309/320. Those numbers are +development observations, not a prospectively confirmed result. + +## Native successor gate + +Before claiming a general recurrent mechanism, move to a model with +learned graph interpretation and fixed checkpoint identity. Score +exactly the same independent task roots for all pass counts. Measure +both model correctness and first-valid passes. Then extend the adapter +to give a named block-boundary state, a real cross-loop reader, and a +tied control with no intervention. Random-direction shams need matched +actual state displacement; judge only independently verified final +answers after the recomputed native forward pass. + +The 2027 coordinate observed by Goodfire belongs to the fixed-pass +Inkling checkpoint and cannot be assumed in a different model. The +BPD source-only reader protocol is in its independent +research/inkling-cross-loop-causal-20261121 branch; its existing +NC09 and AMM sealed cohorts remain untouched. EvalMath FSI-01 +root-level power, multiple-comparison and prospective-source gates +apply before any scientific confirmation. diff --git a/research_gym/inkling_positive_control/RESULTS_DEV_20261121.md b/research_gym/inkling_positive_control/RESULTS_DEV_20261121.md new file mode 100644 index 000000000..84a3504ac --- /dev/null +++ b/research_gym/inkling_positive_control/RESULTS_DEV_20261121.md @@ -0,0 +1,106 @@ +# RMP-INK-PC01: first cross-audited CPU development run + +Date: 2026-11-21. Status: **synthetic trained-gate positive control, development-only**. + +Evidence: [GitHub Actions #44900273337](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/44900273337), +artifact [inkling-trained-gate-sourceonly-dev #14706051354](https://github.com/MoralityLabAI/LoopedTransformers/actions/runs/44900273337/artifacts/14706051354). + +Both Python 3.10 and 3.12 unittest suites passed. The Python 3.12 job +retrained the one-parameter gate on 48 independent TRAIN roots, +then scored **64 separately generated development source roots** and +all matched intervention arms. The public graph transition P and +requested hop budget h are given explicitly to the model. A single +scalar mixing gate alpha is learned by analytic cross-entropy gradients, +rather than learning graph structure from language tokens. + +## Original experimental records and independent checks + +| Measurement | Observed | +| --- | ---: | +| Learned alpha = sigmoid(theta) | 0.9924544921475802 | +| TRAIN roots / lengths / epochs | 48 / 1–4 hops / 70 | +| DEV roots / tasks | 64 / 512 (8 hop lengths per root) | +| Paired depth records | 3,072 | +| Matched intervention records | 1,600 | +| Targeted state-patch visit and L2 dose | 2 / 0.85 | +| Checkpoint digest | 75935f9314f4ca1a49da121a353c5f87b5497ae4697de2c9787aefaf14feb802 | +| BPD independent full recurrence/raw-state replay | PASS | +| EvalMath root-paired development audit | PASS | + +### Inference visits versus exact answer + +| Maximum permitted passes | Correct / 512 | Verified accuracy | +| ---: | ---: | ---: | +| 1 | 64 | 12.5% | +| 2 | 128 | 25.0% | +| 3 | 192 | 37.5% | +| 5 | 320 | 62.5% | +| 7 | 448 | 87.5% | +| 10 | 512 | 100% | + +Given the correct explicit graph operator and hop budget, this +constructed recurrence advances along the permutation one step per +pass. The result validates the visit counter and exact task verifier. +It cannot establish that a transformer learned an algorithm, nor +that its latent state contains interpretable cross-loop routing tags. +Longer permitted passes after the requested hop count are explicitly +frozen by the model's input-specified stop rule. + +### Matched loop-boundary interventions + +Each of 320 tasks with hop length 4–8 was evaluated with 5 arms at +the same checkpoint. The target direction was deliberately chosen +from the current argmax state coordinate. Dose 0.85 was selected on +an earlier synthetic development pilot; the following comparison +is exposed to that development choice. + +| Intervention | Correct / 320 | Notes | +| --- | ---: | --- | +| Clean | 320 | Reference | +| Zero perturbation | 320 | Negative control | +| Active-coordinate targeted direction | 0 | Mechanically shifts the known active state | +| Gaussian random direction, same L2 | 320 | Seeded within root and task | +| Random-coordinate shift, same L2 | 297 | Seeded within root and task | + +The root-macro paired active-minus-random-direction effect is -1.0 +on these DEV roots, and active-minus-random-coordinate is +-0.928125. The large selected effect is a **constructed active-state +causal positive control**. It depends on the prescribed active-index +selection rule and hand-supplied transition matrix. The random control +selection distribution is a different policy, so this result is not +evidence of a discovered pretrained mechanism. + +## Independent audit + +The BPD auditor source was fetched from pinned commit +5cbd5de63e95b6c70c3e351f68be6676cd830268. It reconstructed +the target graph walks, repeated the full learned recurrence from +the saved scalar theta, checked each pre/post patch raw state, verified +L2 dose, and replayed every patched final answer. Its result is stored +in the Actions artifact as bpd_independent_audit.json with +receipt_replay_passed=true, 64 roots and 320 intervention cases. + +EvalMath's development-only depth auditor was fetched from pinned +commit ff32b93a311842967da1e4e33ac08e4ac576c46e. It checked +all 3,072 paired depth rows against root, model and cache mode +identities and exported fsi_dev_manifest.json. The 1-vs-3 paired +case/root macro effect is +0.25. Its FSI manifest retains +sealed_readout=false, hypothesis_preregistered=false and +clusters_independent=false, preventing mistaken confirmation claims. +No measured token generation, inference joules or device-memory use +exists for this synthetic one-parameter model. + +## Why the next stage remains open + +This study provides a reliable positive control for the collection +and BPD intervention machinery. Scientific follow-up requires a +trained neural model with input-to-transition interpretation that +achieves a preregistered independent task threshold, a named real +loop-boundary activation interface, and interventions against +representational hypotheses selected before fresh confirmation. +Huginn's archived experiments show modest multi-hop competence; +the Inkling variable-loop checkpoint remains a better large-model +target once available on a suitable host. + +Nothing here changes the existing LSAD, RMP, LOOPSCOPE or sealed +BPD/EvalMath scientific verdicts. diff --git a/research_gym/inkling_positive_control/__init__.py b/research_gym/inkling_positive_control/__init__.py new file mode 100644 index 000000000..f38ee5fcd --- /dev/null +++ b/research_gym/inkling_positive_control/__init__.py @@ -0,0 +1 @@ +"""Learned recurrence positive control and fresh-root patching receipts.""" diff --git a/research_gym/inkling_positive_control/experiment.py b/research_gym/inkling_positive_control/experiment.py new file mode 100644 index 000000000..d69469cfe --- /dev/null +++ b/research_gym/inkling_positive_control/experiment.py @@ -0,0 +1,413 @@ +"""CPU empirical positive control for recurrent state patching. + +One learned scalar gate mixes a fixed, task-provided permutation operator with +the previous state. The permutation and hop budget are available explicitly. +This instrument verifies tracing/dose plumbing, not neural graph discovery. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np + +NODES = 17 +TRAIN_SEED = 23 +DEVELOPMENT_SEED = 20261121 +TRAIN_ROOTS = 48 +DEVELOPMENT_ROOTS = 64 +TRAIN_HOPS = 4 +DEVELOPMENT_HOPS = 8 +EPOCHS = 70 +LEARNING_RATE = 0.75 +INTERVENTION_DOSE = 0.85 +INTERVENTION_VISIT = 2 +DEPTHS = (1, 2, 3, 5, 7, 10) +ARMS = ("clean", "zero", "active_coordinate", "random_direction", "random_coordinate") +SCHEMA = "rmp.inkling_positive_control.v1" + + +@dataclass(frozen=True) +class Task: + root_id: str + case_id: str + permutation: tuple[int, ...] + start: int + hops: int + target: int + + +def _hash(value: Any) -> str: + return hashlib.sha256( + json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + ).hexdigest() + + +def _jsonl(path: Path, rows: list[dict[str, Any]]) -> None: + with path.open("x", encoding="utf-8", newline="\n") as stream: + for row in rows: + stream.write(json.dumps(row, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n") + + +def generate_roots(seed: int, split: str, roots: int, max_hops: int) -> list[list[Task]]: + """A source-root is one independently drawn directed single-cycle graph.""" + if type(seed) is not int or not 0 <= seed < 2**32: + raise ValueError("seed must be uint32") + if split not in {"train", "development"}: + raise ValueError("protected splits cannot be generated here") + if type(roots) is not int or not 1 <= roots <= 256: + raise ValueError("root count must be in [1,256]") + if type(max_hops) is not int or not 1 <= max_hops < NODES: + raise ValueError("hop count is out of bounds") + groups = [] + for root in range(roots): + identity = f"{split}:{seed}:{root}" + digest = hashlib.sha256(identity.encode()).digest() + rng = np.random.default_rng(int.from_bytes(digest[:8], "big")) + order = rng.permutation(NODES) + permutation = [0] * NODES + for a, b in zip(order, np.roll(order, -1), strict=True): + permutation[int(a)] = int(b) + start = int(rng.integers(NODES)) + current = start + group = [] + root_id = f"{split}-{seed}-{root:04d}" + for hops in range(1, max_hops + 1): + current = permutation[current] + group.append( + Task(root_id, f"{root_id}-h{hops}", tuple(permutation), start, hops, current) + ) + groups.append(group) + return groups + + +def exact_verifier(task: Task, candidate: int) -> bool: + """Recompute the graph walk independently of the model prediction.""" + if len(task.permutation) != NODES or sorted(task.permutation) != list(range(NODES)): + raise ValueError("task permutation must be a bijection") + current = task.start + for _ in range(task.hops): + current = task.permutation[current] + if current != task.target: + raise ValueError("corrupted oracle target") + return type(candidate) is int and candidate == current + + +def sigmoid(value: float) -> float: + return 1.0 / (1.0 + math.exp(-value)) + + +def _advance(state: np.ndarray, permutation: tuple[int, ...]) -> np.ndarray: + moved = np.zeros_like(state) + moved[list(permutation)] = state + return moved + + +def _intervention( + state: np.ndarray, arm: str, *, dose: float, seed: int, +) -> tuple[np.ndarray, dict[str, Any]]: + """Apply a physical raw-state perturbation at a named loop boundary.""" + n = state.size + direction = np.zeros(n, dtype=np.float64) + selected = int(state.argmax()) + if arm == "active_coordinate": + direction[selected] = -1.0 / math.sqrt(2) + direction[(selected + 1) % n] = 1.0 / math.sqrt(2) + elif arm == "random_direction": + direction = np.random.default_rng(seed).normal(size=n) + direction /= np.linalg.norm(direction) + elif arm == "random_coordinate": + random_index = int(np.random.default_rng(seed).integers(n)) + direction[random_index] = -1.0 / math.sqrt(2) + direction[(random_index + 1) % n] = 1.0 / math.sqrt(2) + elif arm == "zero": + dose = 0.0 + else: + raise ValueError("unrecognized intervention arm") + after = state + dose * direction + displacement = float(np.linalg.norm(after - state)) + if arm != "zero" and not math.isclose(displacement, dose, abs_tol=1e-10): + raise ValueError("physical patch dose mismatch") + return after, { + "selected_pre_patch_coordinate": selected, + "realized_raw_l2_displacement": displacement, + "pre_patch_argmax": selected, + "post_patch_argmax": int(after.argmax()), + "pre_patch_raw_state": state.tolist(), + "post_patch_raw_state": after.tolist(), + } + + +def forward( + task: Task, + theta: float, + visits: int, + *, + intervention: str = "clean", + patch_visit: int = INTERVENTION_VISIT, + dose: float = INTERVENTION_DOSE, + seed: int = 0, + derivative: bool = False, +) -> tuple[np.ndarray, np.ndarray, dict[str, Any] | None]: + if type(visits) is not int or not 1 <= visits <= 64: + raise ValueError("visits must be in [1,64]") + if not math.isfinite(theta) or not math.isfinite(dose) or dose < 0: + raise ValueError("invalid gate or dose") + state = np.zeros(NODES, dtype=np.float64) + state[task.start] = 1.0 + derivative_state = np.zeros(NODES, dtype=np.float64) + gate = sigmoid(theta) + gate_gradient = gate * (1.0 - gate) + receipt = None + for visit in range(1, visits + 1): + if visit <= task.hops: + message = _advance(state, task.permutation) + dmessage = _advance(derivative_state, task.permutation) + updated = (1 - gate) * state + gate * message + new_derivative = ( + (1 - gate) * derivative_state + + gate * dmessage + gate_gradient * (message - state) + ) + state, derivative_state = updated, new_derivative + # The hop count is supplied by the task. After that count, state is held. + if intervention != "clean" and visit == patch_visit: + if derivative: + raise ValueError("derivative through an intervention is not supported") + state, receipt = _intervention(state, intervention, dose=dose, seed=seed) + return state, derivative_state, receipt + + +def train_gate( + *, + seed: int = TRAIN_SEED, + roots: int = TRAIN_ROOTS, + epochs: int = EPOCHS, + learning_rate: float = LEARNING_RATE, +) -> tuple[float, list[dict[str, Any]]]: + """Train a real scalar gate via analytic gradients of cross-entropy.""" + if type(epochs) is not int or not 1 <= epochs <= 500: + raise ValueError("epochs out of bounds") + if not 0 < learning_rate <= 2 or not math.isfinite(learning_rate): + raise ValueError("learning rate out of bounds") + examples = [t for group in generate_roots(seed, "train", roots, TRAIN_HOPS) for t in group] + theta = 0.0 + trace = [] + for epoch in range(epochs): + gradients = [] + losses = [] + for task in examples: + state, derivative_state, _ = forward(task, theta, task.hops, derivative=True) + probability = max(float(state[task.target]), 1e-20) + losses.append(-math.log(probability)) + gradients.append(-float(derivative_state[task.target]) / probability) + mean_gradient = float(np.mean(gradients)) + mean_loss = float(np.mean(losses)) + theta -= learning_rate * mean_gradient + if epoch in {0, 1, 4, 9, 19, 39, epochs - 1}: + trace.append({ + "epoch": epoch, "cross_entropy": mean_loss, + "gate": sigmoid(theta), "gradient": mean_gradient, + }) + return theta, trace + + +def _seed(task: Task, arm: str) -> int: + return int.from_bytes(hashlib.sha256(f"{task.case_id}:{arm}".encode()).digest()[:8], "big") + + +def evaluate( + theta: float, + *, + seed: int = DEVELOPMENT_SEED, + roots: int = DEVELOPMENT_ROOTS, + dose: float = INTERVENTION_DOSE, + depths: tuple[int, ...] = DEPTHS, +) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]: + if len(set(depths)) != len(depths) or not depths: + raise ValueError("depths must be distinct and nonempty") + groups = generate_roots(seed, "development", roots, DEVELOPMENT_HOPS) + checkpoint_hash = _hash({"theta": theta, "arch": "task_supplied_permutation_with_learned_gate_v1"}) + depth_rows = [] + causal_rows = [] + for group in groups: + for task in group: + task_world = { + "start": task.start, "permutation": list(task.permutation), + "hops": task.hops, + } + task_digest = _hash({"root_id": task.root_id, "world": task_world}) + for depth in depths: + state, _, _ = forward(task, theta, depth) + predicted = int(state.argmax()) + depth_rows.append({ + "case_id": task.case_id, "root_id": task.root_id, + "task_world": task_world, "task_digest": task_digest, + "verifier_id": "rmp.ink_pc01.exact_cycle.v1", + "family": "explicit_single_cycle_pointer_chase", + "model_sha": checkpoint_hash, "cache_mode": "none", + "split": "development", "depth": depth, "hops": task.hops, + "verified": exact_verifier(task, predicted), + "predicted": predicted, "target": task.target, + "output_state_rms": float(np.sqrt(np.mean(state * state))), + "reasoning_tokens": None, "total_tokens": None, + "wall_ms": None, "joules": None, + "architectural_passes": depth, + }) + if task.hops >= 4: + for arm in ARMS: + output, _, patch = forward( + task, theta, max(depths), intervention=arm, + patch_visit=INTERVENTION_VISIT, + dose=dose, seed=_seed(task, arm), + ) + causal_rows.append({ + "case_id": task.case_id, "root_id": task.root_id, + "task_world": task_world, "task_digest": task_digest, + "verifier_id": "rmp.ink_pc01.exact_cycle.v1", + "family": "explicit_single_cycle_pointer_chase", + "model_sha": checkpoint_hash, + "split": "development", "hops": task.hops, + "depth": max(depths), "arm": arm, + "patch_visit": INTERVENTION_VISIT, + "nominal_l2_dose": 0.0 if arm in {"clean", "zero"} else dose, + "realized_raw_l2_displacement": 0.0 if patch is None else patch[ + "realized_raw_l2_displacement" + ], + "selected_pre_patch_coordinate": None if patch is None else patch[ + "selected_pre_patch_coordinate" + ], + "pre_patch_argmax": None if patch is None else patch["pre_patch_argmax"], + "post_patch_argmax": None if patch is None else patch["post_patch_argmax"], + "pre_patch_raw_state": None if patch is None else patch["pre_patch_raw_state"], + "post_patch_raw_state": None if patch is None else patch["post_patch_raw_state"], + "intervention_seed": None if patch is None else _seed(task, arm), + "verified": exact_verifier(task, int(output.argmax())), + "predicted": int(output.argmax()), "target": task.target, + }) + accuracy = { + str(depth): { + "correct": sum(row["verified"] for row in depth_rows if row["depth"] == depth), + "total": sum(row["depth"] == depth for row in depth_rows), + } + for depth in depths + } + intervention_accuracy = { + arm: { + "correct": sum(row["verified"] for row in causal_rows if row["arm"] == arm), + "total": sum(row["arm"] == arm for row in causal_rows), + } + for arm in ARMS + } + per_root = {} + for group in groups: + root_id = group[0].root_id + arm_correct = { + arm: sum( + row["verified"] for row in causal_rows + if row["root_id"] == root_id and row["arm"] == arm + ) for arm in ARMS + } + per_root[root_id] = { + "active_minus_random_direction": ( + arm_correct["active_coordinate"] - arm_correct["random_direction"] + ) / (DEVELOPMENT_HOPS - 3), + "active_minus_random_coordinate": ( + arm_correct["active_coordinate"] - arm_correct["random_coordinate"] + ) / (DEVELOPMENT_HOPS - 3), + } + result = { + "schema_version": SCHEMA, "evidence_class": "synthetic_trained_gate_development_positive_control", + "checkpoint_sha256": checkpoint_hash, "gate": sigmoid(theta), + "source_roots": roots, "cases": roots * DEVELOPMENT_HOPS, + "train_hop_exposure": [1, 2, 3, 4], + "evaluation_hops": list(range(1, DEVELOPMENT_HOPS + 1)), + "depth_accuracy": accuracy, "intervention_accuracy": intervention_accuracy, + "patch_visit": INTERVENTION_VISIT, "nominal_dose": dose, + "root_macro_active_minus_random_direction": float(np.mean([ + item["active_minus_random_direction"] for item in per_root.values() + ])), + "root_macro_active_minus_random_coordinate": float(np.mean([ + item["active_minus_random_coordinate"] for item in per_root.values() + ])), + "positive_control": { + "learned_gate_above_point_9": sigmoid(theta) >= 0.9, + "full_depth_exact": accuracy[str(max(depths))]["correct"] == roots * DEVELOPMENT_HOPS, + "dose_matched_shams_present": ( + all(intervention_accuracy[arm]["total"] == roots * (DEVELOPMENT_HOPS - 3) + for arm in ARMS) + ), + }, + "limitations": [ + "permutation_transition_is_explicitly_supplied", + "hop_budget_is_explicitly_supplied", + "one_scalar_gate_learned_not_an_end_to_end_transformer", + "selected_active_coordinate_is_a_contrived_positive_control", + "dose_was_selected_on_prior_development_pilot", + "no_future_or_sealed_roots_used", + "random_directions_are_not_a_neural_routing_mechanism", + ], + } + return result, depth_rows, causal_rows + + +def run(out: Path) -> dict[str, Any]: + if out.exists(): + raise FileExistsError(f"output already exists: {out}") + started = time.perf_counter() + theta, history = train_gate() + training_seconds = time.perf_counter() - started + result, depth_rows, causal_rows = evaluate(theta) + eval_seconds = time.perf_counter() - started - training_seconds + out.mkdir(parents=True) + checkpoint = { + "architecture": "explicit_permutation_one_parameter_recurrent_gate", + "theta": theta, "alpha": sigmoid(theta), + "training_seed": TRAIN_SEED, "training_roots": TRAIN_ROOTS, + "training_hops": TRAIN_HOPS, "epochs": EPOCHS, "learning_rate": LEARNING_RATE, + "trace": history, "sha256": result["checkpoint_sha256"], + } + (out / "checkpoint.json").write_text( + json.dumps(checkpoint, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + _jsonl(out / "depth_matrix.jsonl", depth_rows) + _jsonl(out / "interventions.jsonl", causal_rows) + result["training_seconds_measured"] = training_seconds + result["evaluation_seconds_measured"] = eval_seconds + result["files_sha256"] = { + name: hashlib.sha256((out / name).read_bytes()).hexdigest() + for name in ("checkpoint.json", "depth_matrix.jsonl", "interventions.jsonl") + } + result["module_sha256"] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + (out / "summary.json").write_text( + json.dumps(result, indent=2, sort_keys=True, allow_nan=False) + "\n", + encoding="utf-8", + ) + return result + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + result = run(args.out) + print(json.dumps({ + "out": str(args.out), + "gate": result["gate"], + "source_roots": result["source_roots"], + "depth_accuracy": result["depth_accuracy"], + "intervention_accuracy": result["intervention_accuracy"], + "evidence_class": result["evidence_class"], + }, sort_keys=True, allow_nan=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/research_gym/inkling_positive_control/test_experiment.py b/research_gym/inkling_positive_control/test_experiment.py new file mode 100644 index 000000000..96d55eb4d --- /dev/null +++ b/research_gym/inkling_positive_control/test_experiment.py @@ -0,0 +1,79 @@ +"""Unit tests for learned gate, exact verifier and physical positive controls.""" + +from __future__ import annotations + +import math +import unittest + +try: + from research_gym.inkling_positive_control.experiment import ( + ARMS, DEPTHS, INTERVENTION_DOSE, evaluate, exact_verifier, + forward, generate_roots, sigmoid, train_gate, + ) +except ModuleNotFoundError: + from experiment import ( + ARMS, DEPTHS, INTERVENTION_DOSE, evaluate, exact_verifier, + forward, generate_roots, sigmoid, train_gate, + ) + + +class LearnedGatePositiveControl(unittest.TestCase): + def test_roots_are_frozen_and_independent_of_split(self): + first = generate_roots(23, "train", 3, 5) + repeated = generate_roots(23, "train", 3, 5) + other = generate_roots(23, "development", 3, 5) + self.assertEqual(first, repeated) + self.assertNotEqual(first, other) + self.assertEqual(len({group[0].root_id for group in first}), 3) + for group in first: + self.assertEqual(sorted(group[0].permutation), list(range(17))) + for task in group: + self.assertTrue(exact_verifier(task, task.target)) + self.assertFalse(exact_verifier(task, (task.target + 1) % 17)) + + def test_analytic_gate_gradient_matches_finite_difference(self): + task = generate_roots(73, "train", 1, 3)[0][2] + theta = 0.45 + state, derivative, _ = forward(task, theta, task.hops, derivative=True) + epsilon = 0.00001 + up, _, _ = forward(task, theta + epsilon, task.hops) + down, _, _ = forward(task, theta - epsilon, task.hops) + numerical = (up[task.target] - down[task.target]) / (2 * epsilon) + self.assertAlmostEqual(derivative[task.target], numerical, places=6) + self.assertGreater(state[task.target], 0) + + def test_train_then_intervene_at_equal_l2_dose(self): + theta, history = train_gate(seed=23, roots=8, epochs=24, learning_rate=0.75) + self.assertGreater(sigmoid(theta), 0.9) + self.assertLess(history[-1]["cross_entropy"], history[0]["cross_entropy"]) + result, depth_rows, causal_rows = evaluate(theta, seed=4242, roots=8, dose=INTERVENTION_DOSE) + self.assertEqual(result["source_roots"], 8) + self.assertEqual(len(depth_rows), 8 * 8 * len(DEPTHS)) + self.assertEqual(len(causal_rows), 8 * 5 * len(ARMS)) + self.assertEqual(result["depth_accuracy"]["1"]["correct"], 8) + self.assertEqual(result["depth_accuracy"]["10"]["correct"], 64) + self.assertEqual(result["intervention_accuracy"]["clean"]["correct"], 40) + self.assertEqual(result["intervention_accuracy"]["zero"]["correct"], 40) + self.assertEqual(result["intervention_accuracy"]["active_coordinate"]["correct"], 0) + self.assertTrue(all( + math.isclose(row["realized_raw_l2_displacement"], INTERVENTION_DOSE, abs_tol=1e-10) + for row in causal_rows if row["arm"] not in {"clean", "zero"} + )) + self.assertTrue(all(row["split"] == "development" for row in causal_rows)) + self.assertTrue(all(len(row["task_world"]["permutation"]) == 17 for row in causal_rows)) + self.assertTrue(all(row["task_digest"] and row["verifier_id"] for row in depth_rows)) + self.assertIn("dose_was_selected_on_prior_development_pilot", result["limitations"]) + + def test_invalid_inputs_fail_closed(self): + with self.assertRaises(ValueError): + generate_roots(1, "sealed", 4, 5) + with self.assertRaises(ValueError): + generate_roots(1, "train", 0, 5) + with self.assertRaises(ValueError): + forward(generate_roots(1, "train", 1, 1)[0][0], 0, 0) + with self.assertRaises(ValueError): + evaluate(0, roots=2, depths=(1, 1)) + + +if __name__ == "__main__": + unittest.main()