From 453c15dd882938351ecfc1c8028fdfddc0fa18bc Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Tue, 10 Nov 2026 23:00:49 +0800 Subject: [PATCH 1/8] ARG-02: recurrent-depth Qwen3.5 evaluation harness for the Algernon gym Adds research/algernon/algebraic_reasoning_gym/arg02: an explicit, untrained block-loop recurrence over Qwen3.5-0.8B-Base decoder layers; open-loop (residual-feedback) and donor-shuffle ablations; repeated-forward and Qwen3.5-2B equal-compute controls; an external verifier-feedback controller; state perturbation and answer-site patching; linear probes on per-step states; EvalMath grading of every proposal; clustered paired statistics; GPU-time, MAC, token and verifier accounting; a replayable answer tape; a checkpoint lock; and a protocol registered before any Qwen output on the development or test rows. Verified locally: 26 torch-free and 10 torch tests pass (tiny random Qwen3.5 on CPU, including depth-1 parity with the HF forward, ablation identities, a runner that cannot reach the roster, and the full export-select-test-report-replay chain). On CPU the real 0.8B weights give a depth-1 readout identical to the HF forward (max |log-prob diff| 0.0). ARG-01's 14 tests and receipt replay pass unchanged. The GPU stages have not run. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/algernon-arg02.yml | 60 ++ research/algernon/README.md | 2 + .../algebraic_reasoning_gym/README.md | 4 + .../algebraic_reasoning_gym/arg02/PROTOCOL.md | 86 ++ .../algebraic_reasoning_gym/arg02/README.md | 51 ++ .../algebraic_reasoning_gym/arg02/STATUS.md | 21 + .../algebraic_reasoning_gym/arg02/__init__.py | 6 + .../algebraic_reasoning_gym/arg02/analyze.py | 739 ++++++++++++++++++ .../arg02/checkpoint_check.py | 100 +++ .../arg02/config/arg02_config.json | 107 +++ .../arg02/config/checkpoint_lock.json | 183 +++++ .../algebraic_reasoning_gym/arg02/flops.py | 79 ++ .../algebraic_reasoning_gym/arg02/probe.py | 92 +++ .../algebraic_reasoning_gym/arg02/prompts.py | 87 +++ .../arg02/recurrence.py | 216 +++++ .../arg02/results/arg02_checkpoint_check.json | 124 +++ .../arg02/results/arg02_export_manifest.json | 9 + .../arg02/results/arg02_splits_audit.json | 54 ++ .../arg02/run_arg02.ps1 | 47 ++ .../algebraic_reasoning_gym/arg02/runner.py | 631 +++++++++++++++ .../algebraic_reasoning_gym/arg02/scoring.py | 128 +++ .../algebraic_reasoning_gym/arg02/settings.py | 22 + .../algebraic_reasoning_gym/arg02/smoke.py | 42 + .../algebraic_reasoning_gym/arg02/splits.py | 157 ++++ .../algebraic_reasoning_gym/arg02/stats.py | 81 ++ .../algebraic_reasoning_gym/arg02/symbolic.py | 33 + .../arg02/test_arg02.py | 257 ++++++ .../arg02/test_arg02_torch.py | 160 ++++ 28 files changed, 3578 insertions(+) create mode 100644 .github/workflows/algernon-arg02.yml create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/PROTOCOL.md create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/README.md create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/STATUS.md create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/__init__.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/analyze.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/checkpoint_check.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/config/arg02_config.json create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/config/checkpoint_lock.json create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/flops.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/probe.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/prompts.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/recurrence.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/results/arg02_checkpoint_check.json create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/results/arg02_export_manifest.json create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/results/arg02_splits_audit.json create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/run_arg02.ps1 create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/runner.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/scoring.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/settings.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/smoke.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/splits.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/stats.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/symbolic.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/test_arg02.py create mode 100644 research/algernon/algebraic_reasoning_gym/arg02/test_arg02_torch.py diff --git a/.github/workflows/algernon-arg02.yml b/.github/workflows/algernon-arg02.yml new file mode 100644 index 000000000..05a8ca4ef --- /dev/null +++ b/.github/workflows/algernon-arg02.yml @@ -0,0 +1,60 @@ +name: Algernon ARG-02 recurrent Qwen evaluation +on: + push: + paths: + - 'research/algernon/algebraic_reasoning_gym/**' + - '.github/workflows/algernon-arg02.yml' + pull_request: + paths: + - 'research/algernon/algebraic_reasoning_gym/**' + - '.github/workflows/algernon-arg02.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + protocol-and-grading: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: MoralityLabAI/EvalMath + ref: 88bb6cf8d2fe172e37d25964dfb2c285d9033841 + path: .arg02_evalmath + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: pip install numpy==2.5.3 + - name: ARG-01 receipt still verifies + run: PYTHONPATH=.:.arg02_evalmath/src python -m research.algernon.algebraic_reasoning_gym.gym --check + - name: Splits, public-only prompts, grading, statistics, probes + run: PYTHONPATH=.:.arg02_evalmath/src python -m unittest research.algernon.algebraic_reasoning_gym.arg02.test_arg02 -v + - name: Committed answer tape regrades to the committed receipt + run: | + R=research/algernon/algebraic_reasoning_gym/arg02/results + if [ -f $R/arg02_receipt.json ]; then + PYTHONPATH=.:.arg02_evalmath/src python -m research.algernon.algebraic_reasoning_gym.arg02.analyze replay \ + --tape $R/arg02_answer_tape.jsonl.gz --check $R/arg02_receipt.json + else + echo "no ARG-02 receipt committed yet" + fi + cpu-recurrence-smoke: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/checkout@v4 + with: + repository: MoralityLabAI/EvalMath + ref: 88bb6cf8d2fe172e37d25964dfb2c285d9033841 + path: .arg02_evalmath + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: pip install torch==2.11.0 --index-url https://download.pytorch.org/whl/cpu + - run: pip install transformers==5.17.0 numpy==2.5.3 + - name: Block-loop identities, HF parity, leakage guard, end-to-end smoke (tiny random Qwen3.5) + run: PYTHONPATH=.:.arg02_evalmath/src python -m unittest research.algernon.algebraic_reasoning_gym.arg02.test_arg02_torch -v diff --git a/research/algernon/README.md b/research/algernon/README.md index d391098f3..e449b9949 100644 --- a/research/algernon/README.md +++ b/research/algernon/README.md @@ -2,6 +2,8 @@ **ARG-01 CPU algebraic reasoning gym:** [Frozen RRC-19 recurrent proposer with independent, pinned EvalMath verification](algebraic_reasoning_gym/README.md), [results](algebraic_reasoning_gym/REPORT.md), and [Qwen/looped-model workorder](algebraic_reasoning_gym/QWEN_WORKORDER.md). The CPU baseline is executed; a Qwen latent graft remains unrun. +**ARG-02 recurrent Qwen evaluation:** [Qwen3.5-0.8B with an explicit block-loop recurrence, open-loop, donor-shuffle, repeated-forward, 2B feedforward and external-controller controls](algebraic_reasoning_gym/arg02/README.md), [registered protocol](algebraic_reasoning_gym/arg02/PROTOCOL.md), [status](algebraic_reasoning_gym/arg02/STATUS.md). Implemented and CPU-verified; the GPU stages have not run. + **Algernon-02 executable experiment:** [Circuit Mirror](circuit_mirror/README.md) combines a typed pointer-machine transition, an exact BN254 R1CS-style checker, generated Circom source, a tiny trained recurrent readout, and retained CPU-only experiment receipts. [Experimental falsification criteria](circuit_mirror/EXPERIMENT.md). diff --git a/research/algernon/algebraic_reasoning_gym/README.md b/research/algernon/algebraic_reasoning_gym/README.md index 7d4c9413a..3024e0297 100644 --- a/research/algernon/algebraic_reasoning_gym/README.md +++ b/research/algernon/algebraic_reasoning_gym/README.md @@ -45,6 +45,10 @@ PYTHONPATH=.:../EvalMath/src python -m research.algernon.algebraic_reasoning_gym --score-proposals /tmp/qwen_arg01.jsonl --out /tmp/qwen_arg01_scored.json ``` +## ARG-02 + +[`arg02/`](arg02/README.md) evaluates Qwen3.5-0.8B-Base on this roster with explicit recurrent depth and matched-compute controls, through the same public-only export and EvalMath grading. Protocol: [`arg02/PROTOCOL.md`](arg02/PROTOCOL.md). + ## Research interpretation The primary signal is executable-program *future* accuracy per full measured computation, including class compilation, predictor inference and exact candidate verification. Aggregate correctness should be split by known/novel source family; source-family holdouts in RRC-19 itself are public, so ARG-01 is another deterministic research evaluation rather than an independently blind study. An RRC-19 GRU forward pass processes the thirteen coefficient steps of its input **once**; additional candidate-verifier calls are external computation, not new GRU refinement steps. A true recurrence-depth comparison requires the external checkpoint and actual latent forward traces. diff --git a/research/algernon/algebraic_reasoning_gym/arg02/PROTOCOL.md b/research/algernon/algebraic_reasoning_gym/arg02/PROTOCOL.md new file mode 100644 index 000000000..9fe444f60 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/PROTOCOL.md @@ -0,0 +1,86 @@ +# ARG-02 protocol: recurrent depth in a pretrained Qwen on the Algernon algebraic gym + +**Registered 2026-11-10, before any Qwen output on the development or test rows existed.** The only model outputs produced before registration are the CPU parity check in `results/arg02_checkpoint_check.json` (two development prompts, depth 1 and one extra block pass, no grading) and the tiny random-model smoke runs used by the tests. + +## Question + +Does additional internal recurrent computation make a pretrained model recover algebraic programs that its first forward pass misses, with an advantage over exact symbolic search and over neural controls that spend the same compute without recurrence? This is a falsification test: every arm and every negative outcome is reported. + +## Model and recurrence + +- Inventory (`config/checkpoint_lock.json`): no looped-layer Qwen checkpoint survives on this machine. LoopedTransformers `experiments/recurrent_recovery_laco_v1` (Qwen3-0.6B with a LaCo recurrent block) kept manifests only; its `trainable.pt` and tuned teacher are gone. HybridTRMLDT has no recurrent language model. `tomg-group-umd/huginn-0125` is natively recurrent but is not a Qwen model and is not used. +- Model: `Qwen/Qwen3.5-0.8B-Base` at `dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68`, bf16, SDPA, transformers 5.17.0, torch 2.11.0+cu128, loaded as `Qwen3_5ForCausalLM` (752,393,024 text parameters). File SHA-256 values are in the lock; the runner refuses a snapshot that differs. +- Qwen3.5-0.8B has no native recurrence. ARG-02 adds an explicit, **untrained** block loop (`recurrence.py`): decoder layers `[a, b)` form a block B applied `d` times to the residual stream with the pretrained weights unchanged. `x = layers[0:a](embed)`, `h_1 = B(x)`, `h_t = B(h_{t-1})`, readout `lm_head(norm(layers[b:](h_t)))`. Depth 1 is the unmodified model; the CPU check measured a maximum absolute log-probability difference of 0.0 against the HF forward on the real weights. +- The 24 layers repeat a 3 linear-attention (Gated DeltaNet) + 1 full-attention pattern. Candidate blocks are four-layer groups: `[12,16)`, `[8,12)`, `[16,20)`, `[4,8)`. +- The external iterative controller (below) is a separate, explicitly external arm. Repeated prompting is never described as latent recurrence. + +## Splits (fixed, `splits.py`, audit in `results/arg02_splits_audit.json`) + +| Split | Rows | Source | Use | +|---|---:|---|---| +| test | 192 | ARG-01 EvalMath roster (168 positives over 7 generators, 12 inconsistent negatives, 6 future-collision pairs) | final run, once | +| calibration | 36 | ARG-01 calibration roster (seen generators) | development selection, probe hyperparameters | +| dev | 96 | ARG-02 roster, seed 2026111102, seen generators only | development selection, probe training | +| shots | 4 | ARG-02 roster, seed 2026111103, one per topology | in-context examples when shots = 4 | + +Development = calibration + dev (132 rows). All non-test rosters are signature-disjoint from every EvalMath roster case. The test rows are byte-identical to `external.public_records()`. The four novel generators (rational, squared, twisted product, lacunary) appear only in test. + +## Model input and answers + +- The runner reads only exported public JSONL (`topology`, two demonstrations through degree 12, query, digest). It never builds the roster; a test patches `oracle.roster` to raise during every runner stage. Source graphs and future coefficients are used only by the grader. The query series is public but not rendered: it carries no information about the program. Case identifiers are not rendered. +- The prompt states the four operators and four topologies (the public DSL), the two demonstrations, and ends with `\nProgram:`. Operators ` I`, ` N`, ` S`, ` R` are single tokens. +- Each prompt is scored as 16 rows (prompt + every operator pair), giving the full-vocabulary log-probabilities of all 64 programs and the unconstrained greedy decode. **Constrained proposal**: the 64 programs ranked by joint log-probability. **Greedy proposal**: argmax tokens; invalid when any is not an operator token (the invalid-program rate). +- Every proposal is checked by `oracle.search` on the two public demonstrations; future correctness is read only inside `oracle.grade`. Budgets: 1 check (top-1) and 12 checks (the ARG-01 budget). + +## Arms + +| Arm | Definition | Compute charged | +|---|---|---| +| base = loop(1) | unmodified forward | 1 forward | +| loop(d), d = 2,4,8,16 | `h_t = B(h_{t-1})`; every step 1..16 is also read out for the depth curve | prelude + d blocks + readout, per CUDA-event timing | +| open(d) | residual-feedback ablation: `h_t = h_{t-1} + (h_1 - x)`. The block sees only x; its single update is re-applied d times, never recomputed from the current state | prelude + 1 block + readout | +| shuffle(d) | shuffled intermediate state: `h_t = h_1 + D_t`, D_t = `h_t - h_1` of a donor case's own loop (the previous test row, cyclic), right-aligned by position and matched by candidate row | recipient + donor loop to d | +| ensemble(m(d)) | repeated-forward control: mean joint log-probability over the first m(d) prompt variants (canonical, demos swapped, space separators, both), depth 1; m(d) = round((24 + (d-1)(b-a)) / 24) capped at 4, i.e. matched layer evaluations | m forwards | +| ff2b | matched-compute feedforward: `Qwen/Qwen3.5-2B-Base` at `b1485b2fa6dfa1287294f269f5fb618e03d52d7c`, single pass, same prompt and tokenizer; 2.68x the 0.8B forward MACs, between loop(8) (2.16x) and loop(16) (3.49x) | 1 forward | +| controller | external iterative controller: depth-1 model, after each rejected candidate the prompt gains "Rejected: a b c (example k differs at x^n ...)" from a public-demo check; next proposal is the best untried program; up to 12 rounds | one forward per round + public checks | +| perturbation | loop to 16 with a Gaussian kick of 0.25 x RMS(h_1) added after step 1 (seeded per row); readouts at 1,2,4,8,16; distance to the clean trajectory per step | as loop(16) | +| patching | at depth p = max(2, d*), the answer-site states (last 5 positions: `\n`, `Program`, `:`, two candidate tokens) are replaced by the donor's at step 1, ceil(p/2) or p, then the loop continues | 3 loops to p + donor | +| symbolic | ARG-01 arms re-scored per case through the unmodified `gym.score_case`: class-size order (12 checks), complete certified class search, exhaustive 64-program search, frozen RRC-19 GRU and FF | CPU time + verifier work | + +The base model is the parameter-matched feedforward control for every loop depth (identical weights). ensemble and ff2b are the equal-compute controls. + +## Development selection (run before the test stage) + +1. Shots: k in {0, 4} at depth 1 on the 132 development rows; choose the larger development future-correct count at 12 checks; tie -> 0. +2. Block and depth: with the chosen k, each candidate block's loop trajectory on the development rows; choose (block, d*) with d* in {2,4,8,16} maximising development future-correct at 12 checks; tie -> smaller d, then the block order above. The selection is the one most favourable to recurrence that development data supports. It is written to `selection.json`, whose SHA-256 enters every test part key. +3. No other setting is tuned. Sigma, ensemble variants, patch steps, controller rounds and budgets are fixed here. + +## Measurements + +- Per arm on the 168 positives: future-correct and accepted at 12 and at 1 check, greedy validity, greedy acceptance, rank of the source program, by generator family and known/novel split; negatives accepted (must be 0); collision pairs with identical traces (identical public input must give identical proposals). +- Depth: per-step curves 1..16, first step at which top-1 is future-correct, programs found only after step 1 and whether they survive to step 16, answers lost or gained between step 1 and each depth, relative residual norm `|h_t - h_{t-1}| / |h_{t-1}|` per step and its per-step reduction ratio. +- Perturbation recovery: future-correct and top-1 agreement with the clean run per readout, and distance to the clean state over the kick norm per step. +- Patching: top-1 kept, moved to the donor's answer, changed; KL of the 64-program distribution to the clean run. +- Probes (`probe.py`): linear probes on the block output at the last prompt token, step 0 (block input) to 16. Labels from the canonical certified class representative (RRC-18 class map) of the source program: its outer operator (4 classes) and whether it uses R. Trained on the 96 dev rows, PCA size and L2 chosen on the 36 calibration rows, tested on seen-generator and novel-generator test positives, with the majority baseline and a 200-permutation label null. +- Compute: CUDA-event GPU time per segment (a depth-d latency is prelude + d block steps + its readout inside the combined trajectory), analytic MACs (`flops.py`), tokens, layer evaluations, forward passes, verifier checks, ARG-01 integer-loop proxy, verifier CPU time, p50/p95 end-to-end latency, peak allocated VRAM per stage. Integer-loop work and neural MACs are never summed. + +## Statistics and decision rules + +Primary metric: future-correct at 12 checks on the 168 test positives. Paired differences use exact McNemar tests and a 95% cluster bootstrap (clusters: source family x topology, 28 cells, 10,000 resamples, seed 2026111104). + +- **H1 depth**: loop(d*) - loop(1) > 0, cluster-bootstrap lower bound > 0 and McNemar p < 0.05. +- **H2a feedback**: loop(d*) - open(d*) > 0, lower bound > 0. +- **H2b state**: loop(d*) - shuffle(d*) > 0, lower bound > 0. A depth gain that survives replacing the case's own recurrent displacement with another case's is not evidence of case-specific recurrent reasoning. +- **H3a repeat**: loop(d*) - ensemble(m(d*)) > 0, lower bound > 0. +- **H3b feedforward**: loop(d*) - ff2b > 0, lower bound > 0. +- **H3c efficiency**: future-correct per end-to-end second of loop(d*) above loop(1) and ensemble(m(d*)). +- **H4 symbolic**: loop(d*) future-correct >= complete certified class search and more future-correct per end-to-end second. +- A useful recurrent mechanism is claimed only if H1, H2a, H2b, H3a and H3b all hold. Every other outcome is reported as the negative result it is, with the failing rule named. + +## Stop conditions + +The runner stops on a checkpoint hash mismatch, a public row with any non-public field, a prompt whose tail tokenises differently, operator tokens that are not single tokens, or parts written under different keys. It exits 75 at a part boundary when the GPU is power-capped (`vramorama run --pause-exit 75` restarts it; finished parts are reused only under an identical key). The analysis stops if ARG-01's `external.py` scorer disagrees with ARG-02's top-1 grading. + +## Reproduction + +`results/arg02_answer_tape.jsonl.gz` holds every model answer record (log-probabilities rounded to 1e-6 before grading). `analyze replay` regrades it on CPU against `results/arg02_receipt.json` with no model or GPU. diff --git a/research/algernon/algebraic_reasoning_gym/arg02/README.md b/research/algernon/algebraic_reasoning_gym/arg02/README.md new file mode 100644 index 000000000..2669d8ec8 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/README.md @@ -0,0 +1,51 @@ +# ARG-02: recurrent-depth evaluation of Qwen3.5 on the Algernon algebraic gym + +ARG-02 runs a pretrained Qwen checkpoint on the ARG-01 held-out roster with explicit recurrent depth, exact EvalMath verification of every proposal, and the controls needed to tell recurrence apart from extra compute. The registered design, arms and decision rules are in [PROTOCOL.md](PROTOCOL.md); the current execution state is in [STATUS.md](STATUS.md). + +## Layout + +| File | Role | +|---|---| +| `config/arg02_config.json` | depths, candidate blocks, shot options, budgets, perturbation, controller, decision rules | +| `config/checkpoint_lock.json` | model revisions, file SHA-256, text configs, checkpoint inventory, software | +| `splits.py` | fixed test/calibration rosters from EvalMath, seeded dev and shot rosters, contamination audit | +| `prompts.py` | prompt text from public records only | +| `recurrence.py` | block-loop runner over Qwen3.5 decoder layers: loop, open loop, donor shuffle, site patching, perturbation, per-step capture | +| `runner.py` | GPU stages (dev shots, dev blocks, test, test ff), resumable parts, power watch | +| `scoring.py` | 64-program ranking, greedy decode, EvalMath search/grade, controller regrade | +| `analyze.py` | export, development selection, grading, statistics, probes, receipts, tape replay | +| `stats.py`, `flops.py`, `probe.py`, `symbolic.py` | paired statistics, analytic MACs, numpy probes, ARG-01 baselines | +| `checkpoint_check.py` | CPU pre-run check on the real weights | +| `smoke.py` | the whole pipeline on a tiny random Qwen3.5 on CPU | +| `run_arg02.ps1` | the GPU chain under vramorama | + +## Run + +From the Compactification-Theory root, with EvalMath checked out at the commit in `../evalmath_pin.json`: + +```sh +export PYTHONPATH=.:../EvalMath/src +python -m unittest research.algernon.algebraic_reasoning_gym.arg02.test_arg02 # numpy only +python -m unittest research.algernon.algebraic_reasoning_gym.arg02.test_arg02_torch # torch + transformers>=5.17 +python -m research.algernon.algebraic_reasoning_gym.arg02.smoke --run-dir /tmp/arg02-smoke +``` + +GPU run (Windows, RTX 5080, vramorama 0.15): + +```powershell +powershell -ExecutionPolicy Bypass -File research\algernon\algebraic_reasoning_gym\arg02\run_arg02.ps1 -RunDir C:\Users\patri\Documents\Codex\algernon\runs\arg02 +``` + +The chain is export -> `runner dev --stage shots` -> `analyze select --stage shots` -> `runner dev --stage blocks` -> `analyze select --stage blocks` (writes `selection.json`) -> `runner test` -> `runner test --model ff` -> `analyze report --out arg02/results` -> `analyze replay`. Analytic compute from `flops.py` at the measured prompt lengths: about 3 PFLOP for the shots stage, 14 PFLOP (0 shots) or 47 PFLOP (4 shots) for the block stage, 40 or 133 PFLOP for the 0.8B test arms and 3 or 9 PFLOP for the 2B control. + +Replay the committed results on CPU, with no model: + +```sh +python -m research.algernon.algebraic_reasoning_gym.arg02.analyze replay \ + --tape research/algernon/algebraic_reasoning_gym/arg02/results/arg02_answer_tape.jsonl.gz \ + --check research/algernon/algebraic_reasoning_gym/arg02/results/arg02_receipt.json +``` + +## Boundaries + +The EvalMath oracle and its tests are imported from the pinned checkout and not modified. ARG-01's `gym.py`, `external.py`, `test_gym.py` and receipts are unchanged; `symbolic.py` calls `gym.score_case` as is, and the report re-scores ARG-02's top-1 answers through ARG-01's `external.py` as a cross-check. diff --git a/research/algernon/algebraic_reasoning_gym/arg02/STATUS.md b/research/algernon/algebraic_reasoning_gym/arg02/STATUS.md new file mode 100644 index 000000000..73cba6d7b --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/STATUS.md @@ -0,0 +1,21 @@ +# ARG-02 status + +**2026-11-10: implemented, registered and checked on CPU. The GPU stages have not run**: the owner put the GPU on hold for this work on 2026-11-10, and other jobs held 7.5-14 GB of the shared card that day. There are no Qwen scores on the development or test rows yet, so no hypothesis in [PROTOCOL.md](PROTOCOL.md) has an outcome. + +## Done and verified + +- Splits: 192 test rows identical to ARG-01's `external.public_records()`, 36 calibration, 96 dev, 4 shots; zero signature overlap between any non-test roster and test (`results/arg02_splits_audit.json`). +- Checkpoints: Qwen3.5-0.8B-Base and Qwen3.5-2B-Base snapshot files match `config/checkpoint_lock.json`. +- Real-weight CPU check (`results/arg02_checkpoint_check.json`): the 0.8B loads as `Qwen3_5ForCausalLM` with 752,393,024 text parameters; the block-loop runner's depth-1 readout equals the HF forward exactly (max |log-prob difference| 0.0) on two development prompts; one extra pass of block `[12,16)` moves the block output by 58% of its norm. Prompt lengths: 321-399 tokens with 0 shots, 1084-1194 with 4 shots. +- Tests: 26 torch-free tests (`test_arg02.py`) and 10 torch tests on a tiny random Qwen3.5 (`test_arg02_torch.py`) pass locally: HF parity at depth 1 for three block placements, a readout inside a trajectory equals a standalone run at that depth, open(1) equals loop(1), a self-donor shuffle equals the loop, a self-patch and a zero kick change nothing, every runner stage runs with `oracle.roster` patched to raise, a restart reuses every part, and the full export -> select -> test -> report -> replay chain completes. +- ARG-01: `gym --check` still verifies its receipt in this branch; `gym.py`, `external.py`, `test_gym.py` and the ARG-01 receipts are unchanged. + +## Next command + +From the repository root on the RTX 5080 machine, once the GPU is released: + +```powershell +powershell -ExecutionPolicy Bypass -File research\algernon\algebraic_reasoning_gym\arg02\run_arg02.ps1 -RunDir C:\Users\patri\Documents\Codex\algernon\runs\arg02 +``` + +The run directory already holds the exported public rows (`export_manifest.json` digests match `results/arg02_export_manifest.json`). The chain writes `selection.json` from development data before the test stage, runs the test stage once, and writes `results/arg02_receipt.json`, `arg02_profile.json`, `arg02_traces.jsonl.gz` and `arg02_answer_tape.jsonl.gz`. Peak VRAM has not been measured on the GPU; the runner caps itself at 45% of the card (`cuda_memory_fraction`) inside an 8 GB lease. diff --git a/research/algernon/algebraic_reasoning_gym/arg02/__init__.py b/research/algernon/algebraic_reasoning_gym/arg02/__init__.py new file mode 100644 index 000000000..f038aac5d --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/__init__.py @@ -0,0 +1,6 @@ +"""ARG-02: recurrent-depth evaluation of a pretrained Qwen checkpoint on the ARG-01 gym. + +Torch-free modules: splits, prompts, scoring, stats, flops, probe, analyze, +symbolic. Torch modules: recurrence, runner. The EvalMath oracle is imported, +never copied. +""" diff --git a/research/algernon/algebraic_reasoning_gym/arg02/analyze.py b/research/algernon/algebraic_reasoning_gym/arg02/analyze.py new file mode 100644 index 000000000..4873b25fe --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/analyze.py @@ -0,0 +1,739 @@ +"""ARG-02 oracle side: export public rows, select dev settings, grade, report. + + export --run-dir D [--sample N] public JSONL for the runner + split audit + select --run-dir D --stage shots|blocks + report --run-dir D --out DIR grade every part, statistics, probes, tape + replay --tape T --check R regrade a committed answer tape (CPU, no model) + +Grading uses `oracle.search` / `oracle.grade` only; futures never leave them. +""" +from __future__ import annotations + +import argparse +import gzip +from hashlib import sha256 +import json +import math +from pathlib import Path + +from spiral_ln import algebraic_reasoning_oracle as oracle + +from research.algernon.algebraic_reasoning_gym import external +from . import flops, scoring, splits, stats +from .settings import load_config + +HERE = Path(__file__).resolve().parent +CONFIG = HERE / "config" / "arg02_config.json" +LOCK = HERE / "config" / "checkpoint_lock.json" +RESULT_SCHEMA = "algernon.arg02.receipt.v1" + + +def load_json(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def dump(obj): + return json.dumps(obj, sort_keys=True, indent=2) + "\n" + + +def file_sha256(path): + return sha256(Path(path).read_bytes()).hexdigest() + + +def write(path, text): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8", newline="\n") + + +# ---------------------------------------------------------------- export + +def _sample(cases, n, key): + out, count = [], {} + for c in cases: + k = key(c) + if count.get(k, 0) < n: + out.append(c) + count[k] = count.get(k, 0) + 1 + return out + + +def cmd_export(args): + run = Path(args.run_dir) + test = splits.test_cases() + ext_rows = list(external.public_records()) + if ext_rows != [splits.public_record(c) for c in test]: + raise AssertionError("ARG-02 test rows differ from the ARG-01 public export") + dev = splits.development_cases() + if args.sample: + test = _sample(test, args.sample, lambda c: c.split) + dev = _sample(dev, args.sample, lambda c: (c.split, c.family)) + splits.write_public(run / "public" / "test.jsonl", test) + splits.write_public(run / "public" / "development.jsonl", dev) + write(run / "public" / "shots.json", json.dumps([splits.shot_record(c) for c in splits.shot_cases()], indent=1) + "\n") + audit = splits.audit() + write(run / "splits_audit.json", dump(audit)) + manifest = {"sample": args.sample, "files": {p.name: file_sha256(p) for p in sorted((run / "public").iterdir())}, + "audit_sha256": sha256(json.dumps(audit, sort_keys=True).encode()).hexdigest()} + write(run / "export_manifest.json", dump(manifest)) + print("exported", len(test), "test and", len(dev), "development rows to", run / "public") + + +# ---------------------------------------------------------------- loading + +def all_cases(): + cases = {c.identifier: c for c in splits.test_cases()} + cases.update({c.identifier: c for c in splits.development_cases()}) + return cases + + +def public_ids(run, split): + return [json.loads(l)["case_id"] for l in (Path(run) / "public" / f"{split}.jsonl").read_text().splitlines() if l.strip()] + + +def load_label(run, label, ids, *, allow_partial=False): + root = Path(run) / "parts" / label + out, keys = {}, set() + for cid in ids: + import re + p = root / (re.sub(r"[^A-Za-z0-9_.-]", "_", cid) + ".json") + if not p.exists(): + if allow_partial: + continue + raise FileNotFoundError(f"missing part {label}/{cid}") + rec = load_json(p) + if rec["id"] != cid: + raise AssertionError("part id mismatch") + keys.add(json.dumps(rec["key"], sort_keys=True)) + out[cid] = rec["value"] + if len(keys) > 1: + raise AssertionError(f"{label}: parts written under {len(keys)} different keys") + key = json.loads(next(iter(keys))) if keys else None + return out, key + + +def load_states(run, label, cid): + import re + import numpy as np + p = Path(run) / "parts" / label / (re.sub(r"[^A-Za-z0-9_.-]", "_", cid) + ".npz") + with np.load(p) as z: + return z["states"] + + +def op_ids(run, model_key="model"): + return load_json(Path(run) / f"op_ids_{model_key}.json") + + +# ---------------------------------------------------------------- selection + +def _future12(case, rec, ops): + return scoring.score_record(case, rec, ops)["at12"]["future_correct"] + + +def is_smoke(run): + return load_json(Path(run) / "export_manifest.json").get("sample") is not None + + +def cmd_select(args): + run = Path(args.run_dir) + cfg = load_config(is_smoke(run)) + cases = all_cases() + ids = public_ids(run, "development") + ops = op_ids(run) + if args.stage == "shots": + table = {} + for k in cfg["shot_options"]: + parts, _ = load_label(run, f"dev_shots_k{k}", ids, allow_partial=args.allow_partial) + table[str(k)] = {"cases": len(parts), + "future12": sum(_future12(cases[c], v["records"]["1"], ops) for c, v in parts.items())} + best = max(cfg["shot_options"], key=lambda k: (table[str(k)]["future12"], -k)) + sel = {"stage": "shots", "shots": best, "table": table, + "rule": "max development future-correct at 12 checks, depth 1; tie -> fewer shots"} + write(run / "selection_shots.json", dump(sel)) + print(dump(sel), end="") + return + shots_sel = load_json(run / "selection_shots.json") + table = {} + for block in cfg["block_candidates"]: + label = f"dev_block_{block[0]}_{block[1]}" + parts, _ = load_label(run, label, ids, allow_partial=args.allow_partial) + row = {} + for d in cfg["depths"]: + row[str(d)] = sum(_future12(cases[c], v["records"][str(d)], ops) for c, v in parts.items()) + table[label] = {"cases": len(parts), "future12_by_depth": row} + candidates = [] + for order, block in enumerate(cfg["block_candidates"]): + label = f"dev_block_{block[0]}_{block[1]}" + for d in cfg["depths"]: + if d > 1: + candidates.append((table[label]["future12_by_depth"][str(d)], -d, -order, block, d)) + best = max(candidates) + block, depth = best[3], best[4] + base = table[f"dev_block_{block[0]}_{block[1]}"]["future12_by_depth"]["1"] + sel = {"stage": "blocks", "shots": shots_sel["shots"], "block": block, "depth": depth, + "dev_future12_selected": best[0], "dev_future12_depth1": base, "dev_gain": best[0] - base, + "table": table, "selection_shots_sha256": file_sha256(run / "selection_shots.json"), + "rule": "max development future-correct at 12 checks over blocks x depths>1; tie -> smaller depth, earlier block"} + write(run / "selection.json", dump(sel)) + print(dump(sel), end="") + + +# ---------------------------------------------------------------- grading + +def _row(case): + return {"family": case.family, "split": case.split, "topology": case.topology, + "positive": case.split in splits.POSITIVE_SPLITS, "novel": case.family in splits.NOVEL_FAMILIES} + + +def _compact(g): + return {"top1": g["top1"], "rank_of_source": g["rank_of_source"], "greedy_valid": g["greedy_valid"], + "greedy_program": g["greedy"]["program"], "greedy_accepted": g["greedy"]["accepted"], + "greedy_future": g["greedy"]["future_correct"], + "at1": {k: g["at1"][k] for k in ("accepted", "future_correct", "false_future", "program")}, + "at12": {k: g["at12"][k] for k in ("accepted", "future_correct", "false_future", "queries", + "integer_loop_proxy", "program", "trace")}, + "verify_ns": g["at12"]["verify_ns"]} + + +TAPE_DECIMALS = 6 + + +def _rounded(rec): + """Tape form of a runner record: log-probs rounded to 1e-6 before grading, + so the committed tape regrades to exactly the committed receipt.""" + r = lambda x: round(float(x), TAPE_DECIMALS) + return {"lp1": [r(x) for x in rec["lp1"]], "lp2": [[r(x) for x in row] for row in rec["lp2"]], + "lp3": [[[r(x) for x in col] for col in row] for row in rec["lp3"]], + "g1": int(rec["g1"]), "g2": [int(x) for x in rec["g2"]], "g3": [[int(x) for x in row] for row in rec["g3"]], + "row_spread": r(rec.get("row_spread", 0.0))} + + +def answer_tape(run, ids, sel, cfg): + """Every model answer record of the test run, keyed (case, arm, step).""" + tape = _tape(run, ids) + for item in tape: + if "record" in item: + item["record"] = _rounded(item["record"]) + return tape + + +def _tape(run, ids): + tape = [] + loop, _ = load_label(run, "test_loop", ids) + for cid in ids: + for t, r in loop[cid]["records"].items(): + tape.append({"case": cid, "arm": "loop", "step": int(t), "record": r}) + for label, arm in (("test_open", "open"), ("test_shuffle", "shuffle"), ("test_perturb", "perturb")): + parts, _ = load_label(run, label, ids) + for cid in ids: + for t, r in parts[cid]["records"].items(): + tape.append({"case": cid, "arm": arm, "step": int(t), "record": r}) + ens, _ = load_label(run, "test_ensemble", ids) + for cid in ids: + for v, r in ens[cid]["records"].items(): + tape.append({"case": cid, "arm": "ensemble:" + v, "step": 1, "record": r}) + patch, _ = load_label(run, "test_patch", ids) + for cid in ids: + for t, r in patch[cid]["patches"].items(): + tape.append({"case": cid, "arm": "patch", "step": int(t), "record": r["record"], + "donor": patch[cid]["donor"]}) + ff, _ = load_label(run, "test_ff", ids) + for cid in ids: + tape.append({"case": cid, "arm": "ff2b", "step": 1, "record": ff[cid]["records"]["1"]}) + ctl, _ = load_label(run, "test_controller", ids) + for cid in ids: + tape.append({"case": cid, "arm": "controller", "step": len(ctl[cid]["tested"]), + "tested": ctl[cid]["tested"]}) + return tape + + +def grade_tape(tape, cases, ops, cfg, sel): + """Deterministic grades of a tape. Returns {arm_key: {case: compact grade}}.""" + by = {} + ens = {} + for item in tape: + case = cases[item["case"]] + arm = item["arm"] + if arm == "controller": + g = scoring.score_controller(case, [tuple(p) for p in item["tested"]]) + by.setdefault("controller", {})[item["case"]] = { + "accepted": g["accepted"], "future_correct": g["future_correct"], "false_future": g["false_future"], + "queries": g["queries"], "integer_loop_proxy": g["integer_loop_proxy"], "program": g["program"], + "trace": g["trace"], "verify_ns": g["verify_ns"]} + continue + if arm.startswith("ensemble:"): + ens.setdefault(item["case"], {})[arm.split(":", 1)[1]] = item["record"] + continue + key = f"{arm}@{item['step']}" + by.setdefault(key, {})[item["case"]] = _compact(scoring.score_record(case, item["record"], ops)) + block = sel["block"] + n = cfg_layers(sel) + sizes = flops.ensemble_sizes(n, block, cfg["depths"], len(cfg["ensemble_variants"])) + for cid, recs in ens.items(): + for d, m in sizes.items(): + chosen = [recs[v] for v in cfg["ensemble_variants"][:m]] + g = scoring.score_scores(cases[cid], scoring.ensemble_scores(chosen), None) + by.setdefault(f"ensemble@{d}", {})[cid] = _compact(g) + return by, sizes + + +def cfg_layers(sel): + return load_json(LOCK)["model"]["text_config"]["num_hidden_layers"] if not sel.get("smoke") else \ + load_json(LOCK)["smoke"]["text_config"]["num_hidden_layers"] + + +def write_tape(path, tape): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + with gzip.GzipFile(path, "wb", mtime=0) as fh: + for item in tape: + fh.write((json.dumps(item, sort_keys=True, separators=(",", ":")) + "\n").encode()) + + +def read_tape(path): + with gzip.open(path, "rt", encoding="utf-8") as fh: + return [json.loads(l) for l in fh if l.strip()] + + +# ---------------------------------------------------------------- summaries + +def summarise(grades, ids, cases): + pos = [c for c in ids if cases[c].split in splits.POSITIVE_SPLITS] + out = {} + for arm, g in sorted(grades.items()): + def tot(cids, path): + s = 0 + for c in cids: + v = g[c] + for k in path: + v = v[k] + s += v + return s + nested = "at12" in next(iter(g.values())) + f12 = ("at12", "future_correct") if nested else ("future_correct",) + a12 = ("at12", "accepted") if nested else ("accepted",) + rec = {"positives": len(pos), "future12": tot(pos, f12), "accepted12": tot(pos, a12)} + if nested: + rec.update({"future1": tot(pos, ("at1", "future_correct")), "accepted1": tot(pos, ("at1", "accepted")), + "greedy_valid": tot(pos, ("greedy_valid",)), "greedy_accepted": tot(pos, ("greedy_accepted",)), + "greedy_future": tot(pos, ("greedy_future",)), "queries12": tot(pos, ("at12", "queries")), + "mean_rank_of_source": sum(g[c]["rank_of_source"] for c in pos) / len(pos)}) + rec["invalid_program_rate"] = 1 - rec["greedy_valid"] / len(pos) + rec["by_family"] = {f: sum(1 for c in pos if cases[c].family == f and _get(g[c], f12)) + for f in splits.POSITIVE_SPLITS} + rec["novel_future12"] = sum(1 for c in pos if cases[c].family in splits.NOVEL_FAMILIES and _get(g[c], f12)) + neg = [c for c in ids if cases[c].split == "negative"] + rec["negative_accepted"] = sum(_get(g[c], a12) for c in neg) + col = [c for c in ids if cases[c].split == "collision"] + rec["collision_false_future"] = sum(_get(g[c], ("at12", "false_future") if nested else ("false_future",)) for c in col) + pairs = {} + for c in col: + pairs.setdefault(cases[c].pair_id, []).append(c) + tr = ("at12", "trace") if nested else ("trace",) + rec["collision_pairs_identical_trace"] = sum(1 for p in pairs.values() if len(p) == 2 and + _get(g[p[0]], tr) == _get(g[p[1]], tr)) + out[arm] = rec + return out + + +def _get(v, path): + for k in path: + v = v[k] + return v + + +def outcome(g, path=("at12", "future_correct")): + return {c: (_get(v, path) if "at12" in v else v["future_correct"]) for c, v in g.items()} + + +def compare(grades, a, b, pos, cases, path=("at12", "future_correct")): + va, vb = outcome(grades[a], path), outcome(grades[b], path) + cl = [f"{cases[c].family}|{cases[c].topology}" for c in pos] + return stats.paired([va[c] for c in pos], [vb[c] for c in pos], cl) + + +def symbolic_grades(sym): + return {f"symbolic:{arm}": rows for arm, rows in sym.items()} + + +# ---------------------------------------------------------------- compute + +def _macs(tc, length, layers, rows=16): + return flops.forward_macs(tc, length, rows, layers) + + +def compute_table(run, ids, sel, cfg, grades, sizes, sym, sym_meta): + lock = load_json(LOCK) + entry = lock["smoke"] if sel.get("smoke") else lock["model"] + ff_entry = lock["smoke"] if sel.get("smoke") else lock["ff_control"] + tc, tcff = entry["text_config"], ff_entry["text_config"] + block = tuple(sel["block"]) + loop, _ = load_label(run, "test_loop", ids) + opn, _ = load_label(run, "test_open", ids) + shf, _ = load_label(run, "test_shuffle", ids) + ens, _ = load_label(run, "test_ensemble", ids) + ff, _ = load_label(run, "test_ff", ids) + ctl, _ = load_label(run, "test_controller", ids) + per = {} + + def add(arm, cid, macs, gpu_ms, tokens, layer_evals, passes, extra_cpu_ns=0): + g = grades[arm][cid] + vns = g["verify_ns"] + extra_cpu_ns + per.setdefault(arm, []).append({"case": cid, "macs": macs, "gpu_ms": gpu_ms, "tokens": tokens, + "layer_evals": layer_evals, "forward_passes": passes, + "verifier_queries": g["at12"]["queries"] if "at12" in g else g["queries"], + "integer_loop_proxy": g["at12"]["integer_loop_proxy"] if "at12" in g else g["integer_loop_proxy"], + "verify_ms": vns / 1e6, "end_to_end_ms": gpu_ms + vns / 1e6}) + + a, b = block + for cid in ids: + lv = loop[cid] + L = lv["usage"]["length"] + tm = lv["usage"]["timing"] + for d in range(1, max(cfg["depths"]) + 1): + layers = flops.path(tc, block, d) + ms = tm["prelude_ms"] + sum(tm["block_ms"][:d]) + tm["readout_ms"][str(d)] + add(f"loop@{d}", cid, _macs(tc, L, layers), ms, 16 * L, 16 * L * len(layers), 1) + ov = opn[cid] + otm = ov["usage"]["timing"] + for d in [x for x in cfg["depths"] if x > 1]: + layers = flops.path(tc, block, 1) + ms = otm["prelude_ms"] + sum(otm["block_ms"][:d]) + otm["readout_ms"][str(d)] + add(f"open@{d}", cid, _macs(tc, L, layers), ms, 16 * L, 16 * L * len(layers), 1) + sv = shf[cid] + stm = sv["usage"]["timing"] + Ld = sv["usage"]["donor_tokens"] // 16 + for d in [x for x in cfg["depths"] if x > 1]: + own = flops.path(tc, block, 1) + donor_layers = list(range(a)) + list(range(a, b)) * d + macs = _macs(tc, L, own) + 16 * sum(flops.layer_macs(tc, i, Ld) for i in donor_layers) + dt = sv["usage"]["donor_timing"] + ms = stm["prelude_ms"] + stm["block_ms"][0] + stm["readout_ms"][str(d)] + dt["prelude_ms"] + sum(dt["block_ms"][:d]) + add(f"shuffle@{d}", cid, macs, ms, 16 * (L + Ld), 16 * (L * len(own) + Ld * len(donor_layers)), 2) + ev = ens[cid] + for d, m in sizes.items(): + vs = cfg["ensemble_variants"][:m] + macs = sum(_macs(tc, ev["usage_by_variant"][v]["length"], flops.path(tc)) for v in vs) + ms = sum(ev["usage_by_variant"][v]["gpu_ms"] for v in vs) + tok = sum(16 * ev["usage_by_variant"][v]["length"] for v in vs) + add(f"ensemble@{d}", cid, macs, ms, tok, sum(ev["usage_by_variant"][v]["layer_evals"] for v in vs), m) + fv = ff[cid] + add("ff2b@1", cid, _macs(tcff, fv["usage"]["length"], flops.path(tcff)), fv["usage"]["gpu_ms"], + 16 * fv["usage"]["length"], fv["usage"]["layer_evals"], 1) + cv = ctl[cid] + macs = sum(_macs(tc, r["prompt_tokens"] + 2, flops.path(tc)) for r in cv["rounds"]) + tok = sum(16 * (r["prompt_tokens"] + 2) for r in cv["rounds"]) + add("controller", cid, macs, cv["usage"]["gpu_ms"], tok, cv["usage"]["layer_evals"], len(cv["rounds"]), + extra_cpu_ns=sum(r["check_ns"] for r in cv["rounds"])) + for arm, rows in sym.items(): + for cid in ids: + r = rows[cid] + per.setdefault(f"symbolic:{arm}", []).append({ + "case": cid, "macs": r["model_macs"], "gpu_ms": 0.0, "tokens": 0, "layer_evals": 0, + "forward_passes": 1 if r["model_macs"] else 0, "verifier_queries": r["queries"], + "integer_loop_proxy": r["integer_loop_proxy"], "verify_ms": r["verify_ns"] / 1e6, + "cpu_order_ms": r["order_ns"] / 1e6, "end_to_end_ms": (r["order_ns"] + r["verify_ns"]) / 1e6}) + summary = {} + for arm, rows in per.items(): + e2e = [r["end_to_end_ms"] for r in rows] + summary[arm] = {"cases": len(rows), "total_macs": sum(r["macs"] for r in rows), + "total_pflop": 2 * sum(r["macs"] for r in rows) / 1e15, + "gpu_seconds": sum(r["gpu_ms"] for r in rows) / 1e3, + "verifier_cpu_seconds": sum(r["verify_ms"] + r.get("cpu_order_ms", 0.0) for r in rows) / 1e3, + "end_to_end_seconds": sum(e2e) / 1e3, + "tokens": sum(r["tokens"] for r in rows), "layer_evals": sum(r["layer_evals"] for r in rows), + "forward_passes": sum(r["forward_passes"] for r in rows), + "verifier_queries": sum(r["verifier_queries"] for r in rows), + "integer_loop_proxy": sum(r["integer_loop_proxy"] for r in rows), + "latency_ms_p50": stats.quantile(e2e, 0.5), "latency_ms_p95": stats.quantile(e2e, 0.95)} + summary["_shared"] = {"symbolic_checkpoint_load_ms": sym_meta["checkpoint_load_ns"] / 1e6, + "symbolic_class_compile_ms": sym_meta["class_compile_ns"] / 1e6} + return summary, per + + +def peaks(run, ids): + out = {} + for label in ("test_loop", "test_perturb", "test_open", "test_shuffle", "test_patch", "test_ensemble", + "test_controller", "test_ff"): + parts, _ = load_label(run, label, ids) + vals = [v.get("peak_bytes") for v in parts.values() if v.get("peak_bytes") is not None] + out[label] = max(vals) if vals else None + return out + + +# ---------------------------------------------------------------- intermediate states + +def depth_analysis(grades, ids, cases, cfg, run): + pos = [c for c in ids if cases[c].split in splits.POSITIVE_SPLITS] + T = max(cfg["depths"]) + curve = {} + for t in range(1, T + 1): + g = grades[f"loop@{t}"] + curve[str(t)] = {"future12": sum(g[c]["at12"]["future_correct"] for c in pos), + "future1": sum(g[c]["at1"]["future_correct"] for c in pos), + "accepted1": sum(g[c]["at1"]["accepted"] for c in pos), + "greedy_valid": sum(g[c]["greedy_valid"] for c in pos), + "greedy_accepted": sum(g[c]["greedy_accepted"] for c in pos)} + first = {} + for c in pos: + hit = next((t for t in range(1, T + 1) if grades[f"loop@{t}"][c]["at1"]["future_correct"]), None) + first[c] = hit + hist = {} + for v in first.values(): + hist[str(v)] = hist.get(str(v), 0) + 1 + later = [c for c, v in first.items() if v is not None and v > 1] + damage = {} + for d in [x for x in cfg["depths"] if x > 1]: + for k, path in (("at1", ("at1", "future_correct")), ("at12", ("at12", "future_correct"))): + g1, gd = grades["loop@1"], grades[f"loop@{d}"] + damage[f"{k}@{d}"] = {"lost": sum(1 for c in pos if _get(g1[c], path) and not _get(gd[c], path)), + "gained": sum(1 for c in pos if _get(gd[c], path) and not _get(g1[c], path))} + loop, _ = load_label(run, "test_loop", ids) + res = [[loop[c]["residual"][t] for c in ids] for t in range(T)] + residual = {str(t + 1): {"median": stats.quantile(res[t], 0.5), "p95": stats.quantile(res[t], 0.95)} for t in range(T)} + reduction = {str(t + 1): stats.quantile([loop[c]["residual"][t] / max(loop[c]["residual"][t - 1], 1e-12) for c in ids], 0.5) + for t in range(1, T)} + return {"curve": curve, "first_success_step_hist": hist, "first_success_after_step1": len(later), + "first_success_after_step1_kept_at_T": sum(1 for c in later if grades[f"loop@{T}"][c]["at1"]["future_correct"]), + "damage": damage, "residual_relative_norm": residual, "residual_reduction_median": reduction} + + +def perturb_analysis(grades, ids, cases, cfg, run): + pos = [c for c in ids if cases[c].split in splits.POSITIVE_SPLITS] + pert, _ = load_label(run, "test_perturb", ids) + out = {"sigma": cfg["perturb"]["sigma"], "step": cfg["perturb"]["step"], "readouts": {}} + for t in cfg["perturb"]["readout_steps"]: + gp, gc = grades[f"perturb@{t}"], grades[f"loop@{t}"] + out["readouts"][str(t)] = {"future12": sum(gp[c]["at12"]["future_correct"] for c in pos), + "clean_future12": sum(gc[c]["at12"]["future_correct"] for c in pos), + "top1_agrees_with_clean": sum(gp[c]["top1"] == gc[c]["top1"] for c in pos)} + T = cfg["perturb"]["depth"] + rel = [[pert[c]["distance"][t] / max(pert[c]["kick_norm"], 1e-12) for c in ids] for t in range(T)] + out["distance_over_kick_median"] = {str(t + 1): stats.quantile(rel[t], 0.5) for t in range(T)} + return out + + +def _grammar_dist(rec): + s = scoring.joint_scores(rec) + m = max(s) + z = sum(math.exp(x - m) for x in s) + return [math.exp(x - m) / z for x in s] + + +def patch_analysis(run, ids, cases, grades, sel, tape_index): + pos = [c for c in ids if cases[c].split in splits.POSITIVE_SPLITS] + patch, _ = load_label(run, "test_patch", ids) + depth = patch[ids[0]]["depth"] + out = {"depth": depth, "steps": {}} + for t in patch[ids[0]]["patches"]: + n_own = n_donor = n_changed = 0 + kls = [] + for c in pos: + donor = patch[c]["donor"] + g = grades[f"patch@{t}"][c] + own = grades[f"loop@{depth}"][c]["top1"] + don = grades[f"loop@{depth}"][donor]["top1"] + n_own += g["top1"] == own + n_donor += g["top1"] == don and don != own + n_changed += g["top1"] != own + p = _grammar_dist(tape_index[("patch", t, c)]) + q = _grammar_dist(tape_index[("loop", str(depth), c)]) + kls.append(sum(x * (math.log(x) - math.log(y)) for x, y in zip(p, q) if x > 0)) + out["steps"][t] = {"cases": len(pos), "top1_kept": n_own, "top1_to_donor": n_donor, "top1_changed": n_changed, + "kl_median": stats.quantile(kls, 0.5), "kl_p95": stats.quantile(kls, 0.95), + "future12": sum(grades[f"patch@{t}"][c]["at12"]["future_correct"] for c in pos)} + return out + + +def probe_analysis(run, ids, cases, sel, cfg): + import numpy as np + from research.rrc_compactification import learn18 + from . import probe + classes_map = learn18.class_map() + + def labels(case): + rep = classes_map[case.topology]["mapping"][tuple(case.source_graph)] + return {"outer_op": rep[2], "uses_R": "R" in rep} + + dev_ids = public_ids(run, "development") + block = sel["block"] + dlabel = f"dev_block_{block[0]}_{block[1]}" + train = [c for c in dev_ids if not c.startswith("calibration:")] + select_ids = [c for c in dev_ids if c.startswith("calibration:")] + pos = [c for c in ids if cases[c].split in splits.POSITIVE_SPLITS] + seen = [c for c in pos if cases[c].family in splits.SEEN_FAMILIES] + novel = [c for c in pos if cases[c].family in splits.NOVEL_FAMILIES] + S = {c: load_states(run, dlabel, c)[:, 0, :] for c in train + select_ids} + S.update({c: load_states(run, "test_loop", c)[:, 0, :] for c in pos}) + steps = sorted(set(range(0, max(cfg["depths"]) + 1)) & set(range(S[train[0]].shape[0])) & + set(range(S[pos[0]].shape[0]))) + out = {"train": len(train), "select": len(select_ids), "test_seen": len(seen), "test_novel": len(novel), + "site": "block output at the last prompt token, step 0 = block input", "labels": {}} + for name, classes in (("outer_op", list(oracle.OPS)), ("uses_R", [False, True])): + per = {} + for t in steps: + X = lambda cs: np.stack([S[c][t] for c in cs]) + Y = lambda cs: [labels(cases[c])[name] for c in cs] + per[str(t)] = probe.evaluate(X(train), Y(train), X(select_ids), Y(select_ids), + {"seen": (X(seen), Y(seen)), "novel": (X(novel), Y(novel))}, classes) + out["labels"][name] = per + return out + + +def external_crosscheck(grades, ids, cases, revision, tmp): + """Top-1 loop answers through ARG-01's external.py scorer (depths 1, 2, 4, 8).""" + rows = [] + depths = [d for d in external.DEPTHS if f"loop@{d}" in grades] + for d in depths: + for c in ids: + rows.append({"case_id": c, "public_sha256": cases[c].signature, "depth": d, + "program": grades[f"loop@{d}"][c]["top1"], "model_revision": revision}) + tmp.parent.mkdir(parents=True, exist_ok=True) + tmp.write_text("".join(json.dumps(r, sort_keys=True) + "\n" for r in rows)) + ext = external.score(tmp) + agree = {} + for d in depths: + mine = sum(grades[f"loop@{d}"][c]["at1"]["accepted"] for c in ids) + agree[str(d)] = {"arg01_exact_accepted": ext["scores"][str(d)]["exact_accepted"], "arg02_at1_accepted": mine, + "arg01_future_correct": ext["scores"][str(d)]["future_correct"], + "arg02_at1_future": sum(grades[f"loop@{d}"][c]["at1"]["future_correct"] for c in ids)} + if agree[str(d)]["arg01_exact_accepted"] != mine: + raise AssertionError("ARG-01 external scorer disagrees with ARG-02 grading") + return {"proposal_sha256": ext["proposal_sha256"], "by_depth": agree} + + +# ---------------------------------------------------------------- decisions + +def decisions(cmp, compute, summary, sel, sizes): + d = sel["depth"] + ok = lambda r: r["difference"] > 0 and r["cluster_ci95"][0] > 0 + eff = lambda arm: summary[arm]["future12"] / max(compute[arm]["end_to_end_seconds"], 1e-12) + res = { + "H1_depth": ok(cmp[f"loop@{d}_vs_loop@1"]) and cmp[f"loop@{d}_vs_loop@1"]["mcnemar_p"] < 0.05, + "H2a_feedback": ok(cmp[f"loop@{d}_vs_open@{d}"]), + "H2b_state": ok(cmp[f"loop@{d}_vs_shuffle@{d}"]), + "H3a_repeat": ok(cmp[f"loop@{d}_vs_ensemble@{d}"]), + "H3b_ff": ok(cmp[f"loop@{d}_vs_ff2b@1"]), + "H3c_efficiency": eff(f"loop@{d}") > eff("loop@1") and eff(f"loop@{d}") > eff(f"ensemble@{d}"), + "H4_symbolic": summary[f"loop@{d}"]["future12"] >= summary["symbolic:certified_mass_full"]["future12"] and + eff(f"loop@{d}") > eff("symbolic:certified_mass_full"), + } + res["mechanism_claim"] = all(res[k] for k in ("H1_depth", "H2a_feedback", "H2b_state", "H3a_repeat", "H3b_ff")) + res["efficiency_future12_per_e2e_second"] = {arm: eff(arm) for arm in + (f"loop@{d}", "loop@1", f"ensemble@{d}", "ff2b@1", "controller", + "symbolic:certified_mass_full", "symbolic:certified_mass12", + "symbolic:exhaustive_64", "symbolic:frozen_gru")} + res["selected"] = {"block": sel["block"], "depth": d, "shots": sel["shots"], "ensemble_size": sizes[d]} + return res + + +def cmd_report(args): + run = Path(args.run_dir) + smoke = is_smoke(run) + cfg = load_config(smoke) + sel = load_json(run / "selection.json") + sel["smoke"] = smoke + cases = all_cases() + ids = public_ids(run, "test") + ops = op_ids(run) + tape = answer_tape(run, ids, sel, cfg) + grades, sizes = grade_tape(tape, cases, ops, cfg, sel) + sym, sym_meta = __import__("research.algernon.algebraic_reasoning_gym.arg02.symbolic", fromlist=["run"]).run( + [cases[c] for c in ids]) + grades.update(symbolic_grades(sym)) + summary = summarise(grades, ids, cases) + pos = [c for c in ids if cases[c].split in splits.POSITIVE_SPLITS] + d = sel["depth"] + pairs = [(f"loop@{x}", "loop@1") for x in cfg["depths"] if x > 1] + pairs += [(f"loop@{d}", f"open@{d}"), (f"loop@{d}", f"shuffle@{d}"), (f"loop@{d}", f"ensemble@{d}"), + (f"loop@{d}", "ff2b@1"), ("controller", "loop@1"), (f"loop@{d}", "symbolic:certified_mass12"), + (f"loop@{d}", "symbolic:certified_mass_full"), (f"loop@{d}", "symbolic:exhaustive_64"), + ("loop@1", "symbolic:frozen_gru"), ("loop@1", "symbolic:frozen_ff"), + ("loop@1", "symbolic:certified_mass12"), ("ff2b@1", "loop@1")] + pairs += [(f"open@{x}", "loop@1") for x in cfg["depths"] if x > 1] + pairs += [(f"shuffle@{x}", "loop@1") for x in cfg["depths"] if x > 1] + cmp = {f"{a}_vs_{b}": compare(grades, a, b, pos, cases) for a, b in pairs} + cmp1 = {f"{a}_vs_{b}": compare(grades, a, b, pos, cases, ("at1", "future_correct")) + for a, b in pairs if not (a.startswith("symbolic") or b.startswith("symbolic") or a == "controller")} + compute, per_case_compute = compute_table(run, ids, sel, cfg, grades, sizes, sym, sym_meta) + tape_index = {} + for item in tape: + if "record" in item: + tape_index[(item["arm"], str(item["step"]), item["case"])] = item["record"] + lock = load_json(LOCK) + entry = lock["smoke"] if smoke else lock["model"] + receipt = { + "schema": RESULT_SCHEMA, "smoke": smoke, "op_ids": ops, + "model": {k: entry[k] for k in ("repo", "revision", "dtype") if k in entry}, + "ff_control": {k: (lock["smoke"] if smoke else lock["ff_control"])[k] for k in ("repo", "revision")}, + "selection": {k: sel[k] for k in ("shots", "block", "depth", "dev_gain", "dev_future12_selected", + "dev_future12_depth1") if k in sel}, + "ensemble_sizes": {str(k): v for k, v in sizes.items()}, + "splits": splits.audit(), + "evalmath_pin": load_json(HERE.parent / "evalmath_pin.json"), + "arg01_receipt_sha256": file_sha256(HERE.parent / "results" / "arg01_reference.json"), + "summary": summary, "paired_future12": cmp, "paired_future1": cmp1, + "depth": depth_analysis(grades, ids, cases, cfg, run), + "perturbation": perturb_analysis(grades, ids, cases, cfg, run), + "patching": patch_analysis(run, ids, cases, grades, sel, tape_index), + "probes": probe_analysis(run, ids, cases, sel, cfg), + "external_crosscheck": external_crosscheck(grades, ids, cases, entry["revision"], run / "arg01_external.jsonl"), + } + profile = {"schema": "algernon.arg02.profile.v1", "compute": compute, "peak_allocated_bytes": peaks(run, ids), + "manifests": {p.name: load_json(p) for p in sorted(run.glob("manifest_*.json"))}, + "timing_scope": "CUDA-event timings per segment; a depth-d latency is prelude + d block steps + its readout, " + "measured inside the combined trajectory; verifier time is this machine's CPU wall time at grading"} + receipt["decisions"] = decisions(cmp, compute, summary, sel, sizes) + out = Path(args.out) + write_tape(out / "arg02_answer_tape.jsonl.gz", tape) + receipt["answer_tape_sha256"] = file_sha256(out / "arg02_answer_tape.jsonl.gz") + write(out / "arg02_receipt.json", dump(receipt)) + write(out / "arg02_profile.json", dump(profile)) + with gzip.GzipFile(out / "arg02_traces.jsonl.gz", "wb", mtime=0) as fh: + for arm in sorted(grades): + for cid in ids: + row = {"arm": arm, "case_id": cid, **_row(cases[cid]), "grade": grades[arm][cid]} + fh.write((json.dumps(row, sort_keys=True, separators=(",", ":")) + "\n").encode()) + write(out / "arg02_selection.json", dump({k: v for k, v in sel.items() if k != "smoke"})) + print("wrote", out) + + +def cmd_replay(args): + """Regrade the committed tape on CPU and compare the grade-derived receipt fields.""" + receipt = load_json(args.check) + tape = read_tape(args.tape) + if file_sha256(args.tape) != receipt["answer_tape_sha256"]: + raise SystemExit("answer tape differs from receipt") + cfg = load_config(receipt["smoke"]) + sel = dict(receipt["selection"]) + sel["smoke"] = receipt["smoke"] + cases = all_cases() + ids = sorted({t["case"] for t in tape}, key=[c.identifier for c in splits.test_cases()].index) + ops = load_json(Path(args.op_ids)) if args.op_ids else receipt.get("op_ids") + grades, _ = grade_tape(tape, cases, ops, cfg, sel) + from . import symbolic + sym, _ = symbolic.run([cases[c] for c in ids]) + grades.update(symbolic_grades(sym)) + summary = summarise(grades, ids, cases) + if summary != receipt["summary"]: + raise SystemExit("regraded summary differs from receipt") + print("ARG-02 answer tape regraded: summary matches receipt for", len(summary), "arms") + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("command", choices=["export", "select", "report", "replay"]) + p.add_argument("--run-dir") + p.add_argument("--stage", choices=["shots", "blocks"]) + p.add_argument("--sample", type=int) + p.add_argument("--out") + p.add_argument("--allow-partial", action="store_true") + p.add_argument("--tape") + p.add_argument("--check") + p.add_argument("--op-ids") + args = p.parse_args(argv) + {"export": cmd_export, "select": cmd_select, "report": cmd_report, "replay": cmd_replay}[args.command](args) + + +if __name__ == "__main__": + main() diff --git a/research/algernon/algebraic_reasoning_gym/arg02/checkpoint_check.py b/research/algernon/algebraic_reasoning_gym/arg02/checkpoint_check.py new file mode 100644 index 000000000..3445c205c --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/checkpoint_check.py @@ -0,0 +1,100 @@ +"""Pre-run checkpoint check on CPU: file hashes, tokenizer contract, prompt +lengths, and depth-1 parity of the block-loop runner against the HF forward +on the real weights. Uses no GPU and grades nothing. + + python -m research.algernon.algebraic_reasoning_gym.arg02.checkpoint_check \\ + --run-dir D --out results/arg02_checkpoint_check.json [--parity 2] + +`--run-dir` must hold the `analyze export` output. +""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import time + +from . import runner +from .prompts import VARIANTS +from .settings import load_config, load_lock + + +def lengths(tok, rows, shots, variants=VARIANTS): + eng = type("E", (), {})() + eng.tok, eng.shots = tok, shots + out = {} + for v in variants: + ls = [len(runner.Engine.prompt_ids(eng, r, v)) for r in rows] + out[v] = {"min": min(ls), "max": max(ls), "mean": sum(ls) / len(ls)} + return out + + +def parity(model, tok, rows, block, op_ids, n): + import torch + from .recurrence import BlockLoop, candidate_rows + bl = BlockLoop(model, block) + eng = type("E", (), {})() + eng.tok, eng.shots = tok, [] + out = [] + for row in rows[:n]: + ids = candidate_rows(runner.Engine.prompt_ids(eng, row), op_ids)[:2] + t0 = time.perf_counter() + with torch.inference_mode(): + ref = torch.log_softmax(model(input_ids=ids).logits[:, -3:].float(), -1) + emb, ctx = bl.prepare(ids) + h = bl.run(emb, 0, bl.n, ctx) + mine = torch.log_softmax(model.lm_head(bl.base.norm(h[:, -3:])).float(), -1) + x = bl.run(emb, 0, block[0], ctx) + h1 = bl.run(x, block[0], block[1], ctx) + h2 = bl.run(h1, block[0], block[1], ctx) + rel = float((h2 - h1).float().norm() / h1.float().norm()) + out.append({"case_id": row["case_id"], "tokens": ids.shape[1], + "max_abs_logprob_diff": float((ref - mine).abs().max()), + "top_token_equal": bool((ref.argmax(-1) == mine.argmax(-1)).all()), + "depth2_relative_residual": rel, "seconds": time.perf_counter() - t0}) + return out + + +def main(): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--run-dir", required=True) + p.add_argument("--out", required=True) + p.add_argument("--parity", type=int, default=0, help="rows to run through the real model on CPU") + args = p.parse_args() + lock, cfg = load_lock(), load_config() + from transformers import AutoTokenizer + report = {"schema": "algernon.arg02.checkpoint_check.v1", "device": "cpu"} + for key in ("model", "ff_control"): + t0 = time.perf_counter() + root = runner.verify_snapshot(lock[key]) + report[key] = {"repo": lock[key]["repo"], "revision": lock[key]["revision"], "files_verified": sorted(lock[key]["files_sha256"]), + "hash_seconds": time.perf_counter() - t0} + tok = AutoTokenizer.from_pretrained(runner.snapshot_dir(lock["model"]), local_files_only=True) + op_ids = runner.op_token_ids(tok) + run = Path(args.run_dir) + test = runner.read_public(run / "public" / "test.jsonl") + dev = runner.read_public(run / "public" / "development.jsonl") + shots = runner.read_shots(run / "public" / "shots.json", max(cfg["shot_options"])) + report["tokenizer"] = {"class": type(tok).__name__, "op_token_ids": op_ids, + "tail_ids": tok.encode("\nProgram:", add_special_tokens=False)} + report["prompt_tokens"] = {f"test_shots{k}": lengths(tok, test, shots[:k]) for k in cfg["shot_options"]} + report["prompt_tokens"].update({f"development_shots{k}": lengths(tok, dev, shots[:k], ("canonical",)) + for k in cfg["shot_options"]}) + if args.parity: + import torch + from transformers import AutoModelForCausalLM + root = runner.snapshot_dir(lock["model"]) + t0 = time.perf_counter() + model = AutoModelForCausalLM.from_pretrained(root, dtype=torch.bfloat16, local_files_only=True, + attn_implementation="sdpa").eval() + report["load_seconds"] = time.perf_counter() - t0 + report["model_class"] = type(model).__name__ + report["text_parameters"] = sum(p.numel() for p in model.model.parameters()) + report["parity"] = parity(model, tok, dev, tuple(cfg["block_candidates"][0]), op_ids, args.parity) + Path(args.out).parent.mkdir(parents=True, exist_ok=True) + Path(args.out).write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") + print(json.dumps(report, indent=2, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/research/algernon/algebraic_reasoning_gym/arg02/config/arg02_config.json b/research/algernon/algebraic_reasoning_gym/arg02/config/arg02_config.json new file mode 100644 index 000000000..c1421ac7a --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/config/arg02_config.json @@ -0,0 +1,107 @@ +{ + "schema": "algernon.arg02.config.v1", + "depths": [ + 1, + 2, + 4, + 8, + 16 + ], + "block_candidates": [ + [ + 12, + 16 + ], + [ + 8, + 12 + ], + [ + 16, + 20 + ], + [ + 4, + 8 + ] + ], + "shot_options": [ + 0, + 4 + ], + "budget": 12, + "ensemble_variants": [ + "canonical", + "swap", + "space", + "swap_space" + ], + "perturb": { + "step": 1, + "sigma": 0.25, + "depth": 16, + "readout_steps": [ + 1, + 2, + 4, + 8, + 16 + ], + "seed_base": 2026111105 + }, + "controller": { + "rounds": 12 + }, + "cuda_memory_fraction": 0.45, + "min_power_w": 100, + "clusters": "source family x topology", + "decision": { + "metric": "future_correct at 12 exact checks on the 168 test positives", + "ci": "cluster bootstrap 95%, 10000 resamples, seed 2026111104", + "alpha": 0.05, + "H1_depth": "loop(d*) - loop(1) > 0 with CI lower bound > 0 and exact McNemar p < alpha", + "H2a_feedback": "loop(d*) - open(d*) > 0, CI lower bound > 0", + "H2b_state": "loop(d*) - shuffle(d*) > 0, CI lower bound > 0", + "H3a_repeat": "loop(d*) - ensemble(m(d*)) > 0, CI lower bound > 0", + "H3b_ff": "loop(d*) - Qwen3.5-2B single pass > 0, CI lower bound > 0", + "H3c_efficiency": "future-correct per end-to-end second of loop(d*) above loop(1) and ensemble(m(d*))", + "H4_symbolic": "loop(d*) future-correct >= complete certified class search and higher future-correct per end-to-end second", + "mechanism_claim": "H1 and H2a and H2b and H3a and H3b" + }, + "smoke_overrides": { + "block_candidates": [ + [ + 2, + 4 + ], + [ + 4, + 6 + ] + ], + "depths": [ + 1, + 2, + 4 + ], + "shot_options": [ + 0, + 1 + ], + "perturb": { + "step": 1, + "sigma": 0.25, + "depth": 4, + "readout_steps": [ + 1, + 2, + 4 + ], + "seed_base": 2026111105 + }, + "controller": { + "rounds": 3 + }, + "note": "tiny random 8-layer Qwen3.5 on CPU; exercises every code path, scores are meaningless" + } +} diff --git a/research/algernon/algebraic_reasoning_gym/arg02/config/checkpoint_lock.json b/research/algernon/algebraic_reasoning_gym/arg02/config/checkpoint_lock.json new file mode 100644 index 000000000..e8490244f --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/config/checkpoint_lock.json @@ -0,0 +1,183 @@ +{ + "schema": "algernon.arg02.checkpoint_lock.v1", + "locked_on": "2026-11-10", + "model": { + "repo": "Qwen/Qwen3.5-0.8B-Base", + "revision": "dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68", + "dtype": "bfloat16", + "attn_implementation": "sdpa", + "snapshot_env": "ARG02_SNAPSHOT_MAIN", + "files_sha256": { + "config.json": "b90b86f35c8e6925ef74ee04d0e758f0a845c83a42089ad82bbaa948de9b4204", + "tokenizer.json": "fe000e3ed39ed12b8d2481d527d44f93c65d37e87645d2dcc80d1bf9d50d2927", + "tokenizer_config.json": "e611fbccc7c29ef3b1cafb1cb7ea548d189968632901d678fd62be68c47885de", + "model.safetensors-00001-of-00001.safetensors": "c2b1e5a17d9c1e27685d92ed9b382911ebb99955ecd89052d1721241adfbab6c", + "model.safetensors.index.json": "ce9a885efdf27d3664fdef5d512ad365216f1074051ef840c7cd8e5431495d0a" + }, + "text_config": { + "num_hidden_layers": 24, + "hidden_size": 1024, + "intermediate_size": 3584, + "num_attention_heads": 8, + "num_key_value_heads": 2, + "head_dim": 256, + "attn_output_gate": true, + "linear_num_key_heads": 16, + "linear_num_value_heads": 16, + "linear_key_head_dim": 128, + "linear_value_head_dim": 128, + "linear_conv_kernel_dim": 4, + "vocab_size": 248320, + "tie_word_embeddings": true, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "model_type": "qwen3_5_text" + } + }, + "ff_control": { + "repo": "Qwen/Qwen3.5-2B-Base", + "revision": "b1485b2fa6dfa1287294f269f5fb618e03d52d7c", + "dtype": "bfloat16", + "attn_implementation": "sdpa", + "snapshot_env": "ARG02_SNAPSHOT_FF", + "files_sha256": { + "config.json": "ed1c1723241f23f7f4e23430759cbd7dcfb4103cbdfe052bfe7626b57c2615b4", + "tokenizer.json": "fe000e3ed39ed12b8d2481d527d44f93c65d37e87645d2dcc80d1bf9d50d2927", + "tokenizer_config.json": "e611fbccc7c29ef3b1cafb1cb7ea548d189968632901d678fd62be68c47885de", + "model.safetensors-00001-of-00001.safetensors": "928acbf11878c32185bbd863514d191769285065ab9ea14fbfe431303f5fdf2d", + "model.safetensors.index.json": "74d2ddfe79f10f35b27b498632f02b97b60dd9ec39b35d7c5a890c399284e319" + }, + "text_config": { + "num_hidden_layers": 24, + "hidden_size": 2048, + "intermediate_size": 6144, + "num_attention_heads": 8, + "num_key_value_heads": 2, + "head_dim": 256, + "attn_output_gate": true, + "linear_num_key_heads": 16, + "linear_num_value_heads": 16, + "linear_key_head_dim": 128, + "linear_value_head_dim": 128, + "linear_conv_kernel_dim": 4, + "vocab_size": 248320, + "tie_word_embeddings": true, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "model_type": "qwen3_5_text" + } + }, + "smoke": { + "repo": "smoke/tiny-random-qwen3_5", + "revision": "0000000000000000000000000000000000000000", + "dtype": "float32", + "text_config": { + "num_hidden_layers": 8, + "hidden_size": 64, + "intermediate_size": 96, + "num_attention_heads": 4, + "num_key_value_heads": 2, + "head_dim": 16, + "attn_output_gate": true, + "linear_num_key_heads": 2, + "linear_num_value_heads": 2, + "linear_key_head_dim": 16, + "linear_value_head_dim": 16, + "linear_conv_kernel_dim": 4, + "vocab_size": 128, + "tie_word_embeddings": true, + "layer_types": [ + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention", + "linear_attention", + "linear_attention", + "linear_attention", + "full_attention" + ], + "model_type": "qwen3_5_text" + }, + "files_sha256": {} + }, + "recurrence": { + "mechanism": "untrained block loop over pretrained decoder layers [a,b); see recurrence.py", + "native_recurrence": false, + "trained_for_recurrence": false + }, + "inventory": { + "looped_qwen_checkpoints": "none on disk: LoopedTransformers experiments/recurrent_recovery_laco_v1 (Qwen3-0.6B LaCo recurrent block, conditions D/E) keeps manifests only; trainable.pt and checkpoints/teacher_tuned are absent", + "hybridtrmldt": "no recurrent language-model checkpoint (TRM checkpoints are task-specific, outside Git); Huginn work there used tomg-group-umd/huginn-0125", + "native_recurrent_non_qwen": "tomg-group-umd/huginn-0125 in the local HF cache (natively recurrent-depth, not Qwen); not used in ARG-02", + "qwen_cache": [ + "Qwen/Qwen3.5-0.8B-Base", + "Qwen/Qwen3.5-2B-Base", + "Qwen/Qwen3.5-4B-Base", + "Qwen/Qwen3-1.7B", + "Qwen/Qwen3-4B-Instruct-2507", + "Qwen/Qwen3-8B", + "Qwen/Qwen2.5-0.5B-Instruct" + ] + }, + "hardware": { + "gpu": "NVIDIA GeForce RTX 5080 Laptop GPU", + "vram_mib": 16303, + "shared": true, + "note": "other jobs held 13977 MiB at lock time" + }, + "software": { + "venv": "C:/Users/patri/.venvs/bluebeam (read-only use)", + "torch": "2.11.0+cu128", + "transformers": "5.17.0", + "numpy": "2.5.3", + "fla_kernels": false + } +} diff --git a/research/algernon/algebraic_reasoning_gym/arg02/flops.py b/research/algernon/algebraic_reasoning_gym/arg02/flops.py new file mode 100644 index 000000000..1e2b853fc --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/flops.py @@ -0,0 +1,79 @@ +"""Analytic multiply-accumulate counts for Qwen3.5 text decoders. + +An estimate from the config: dense projections, the gated delta-rule state +update (about 4 dk*dv MACs per value head per token), causal softmax attention +(QK and AV) and the LM head on the scored positions only. Norms, activations +and elementwise residual arithmetic are omitted. FLOPs = 2 * MACs. Measured +GPU seconds are recorded separately and are the primary cost; this count makes +arms comparable across machines. +""" +from __future__ import annotations + + +def text_config(cfg): + return cfg.get("text_config", cfg) + + +def _dense_linear_attention(t): + h = t["hidden_size"] + nk, nv = t["linear_num_key_heads"], t["linear_num_value_heads"] + dk, dv = t["linear_key_head_dim"], t["linear_value_head_dim"] + key_dim, value_dim = nk * dk, nv * dv + conv_dim = 2 * key_dim + value_dim + proj = h * conv_dim + h * value_dim + 2 * h * nv + value_dim * h + conv = conv_dim * t["linear_conv_kernel_dim"] + state = 4 * nv * dk * dv + return proj + conv + state + + +def _dense_full_attention(t): + h, nh, nkv, hd = t["hidden_size"], t["num_attention_heads"], t["num_key_value_heads"], t["head_dim"] + q = h * nh * hd * (2 if t.get("attn_output_gate") else 1) + return q + 2 * h * nkv * hd + nh * hd * h + + +def _mlp(t): + return 3 * t["hidden_size"] * t["intermediate_size"] + + +def layer_macs(cfg, layer, length): + """MACs for one row of `length` tokens through decoder layer `layer`.""" + t = text_config(cfg) + kind = t["layer_types"][layer] + if kind == "linear_attention": + return length * (_dense_linear_attention(t) + _mlp(t)) + if kind == "full_attention": + attn = t["num_attention_heads"] * t["head_dim"] * length * (length + 1) + return length * (_dense_full_attention(t) + _mlp(t)) + attn + raise ValueError(f"unknown layer type {kind}") + + +def head_macs(cfg, positions): + t = text_config(cfg) + return positions * t["hidden_size"] * t["vocab_size"] + + +def path(cfg, block=None, depth=1): + """Layer indices evaluated by a block-looped forward.""" + n = text_config(cfg)["num_hidden_layers"] + if block is None or depth == 1: + return list(range(n)) + a, b = block + if not (0 <= a < b <= n) or depth < 1: + raise ValueError("bad block or depth") + return list(range(a)) + list(range(a, b)) * depth + list(range(b, n)) + + +def forward_macs(cfg, length, rows, layers, scored_positions=3): + per_row = sum(layer_macs(cfg, i, length) for i in layers) + return rows * (per_row + head_macs(cfg, scored_positions)) + + +def layer_evaluations(rows, length, layers): + return rows * length * len(layers) + + +def ensemble_sizes(n_layers, block, depths, max_variants): + """Repeated-forward count matched to a depth-d block loop's layer evaluations.""" + a, b = block + return {d: max(1, min(max_variants, round((n_layers + (d - 1) * (b - a)) / n_layers))) for d in depths} diff --git a/research/algernon/algebraic_reasoning_gym/arg02/probe.py b/research/algernon/algebraic_reasoning_gym/arg02/probe.py new file mode 100644 index 000000000..673edee28 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/probe.py @@ -0,0 +1,92 @@ +"""Linear probes on recurrent states, numpy only. + +Standardise, project to k principal components (fitted on the training +states), multinomial logistic regression with L2 penalty lam, fitted by +deterministic full-batch gradient descent. (k, lam) is chosen on a separate +selection split; the test split is scored once per step. +""" +from __future__ import annotations + +import numpy as np + +GRID_K = (8, 16, 32) +GRID_LAM = (1e-3, 1e-2, 1e-1, 1.0) +ITERS = 400 +LR = 0.5 +PERMUTATIONS = 200 +PERM_SEED = 2026111106 + + +class Probe: + def __init__(self, k, lam, classes): + self.k, self.lam, self.classes = k, lam, list(classes) + + def fit(self, x, y): + x = np.asarray(x, dtype=np.float64) + self.mu = x.mean(0) + self.sd = x.std(0) + 1e-6 + z = (x - self.mu) / self.sd + _, _, vt = np.linalg.svd(z, full_matrices=False) + k = min(self.k, vt.shape[0]) + self.proj = vt[:k].T + f = z @ self.proj + self.fs = f.std(0) + 1e-6 + f = f / self.fs + n, c = len(y), len(self.classes) + yi = np.array([self.classes.index(v) for v in y]) + onehot = np.zeros((n, c)) + onehot[np.arange(n), yi] = 1 + self.w = np.zeros((f.shape[1], c)) + self.b = np.zeros(c) + for _ in range(ITERS): + logits = f @ self.w + self.b + logits -= logits.max(1, keepdims=True) + p = np.exp(logits) + p /= p.sum(1, keepdims=True) + g = p - onehot + self.w -= LR * (f.T @ g / n + self.lam * self.w) + self.b -= LR * g.mean(0) + return self + + def predict(self, x): + f = ((np.asarray(x, dtype=np.float64) - self.mu) / self.sd) @ self.proj / self.fs + return [self.classes[i] for i in (f @ self.w + self.b).argmax(1)] + + +def accuracy(pred, y): + return float(np.mean([a == b for a, b in zip(pred, y)])) if len(y) else 0.0 + + +def select(train_x, train_y, sel_x, sel_y, classes): + best = None + for k in GRID_K: + for lam in GRID_LAM: + acc = accuracy(Probe(k, lam, classes).fit(train_x, train_y).predict(sel_x), sel_y) + if best is None or acc > best[0] + 1e-12: + best = (acc, k, lam) + return {"selection_accuracy": best[0], "k": best[1], "lam": best[2]} + + +def evaluate(train_x, train_y, sel_x, sel_y, tests, classes, *, permutations=PERMUTATIONS, seed=PERM_SEED): + """tests: {name: (x, y)}. Returns selected settings, test accuracies, + majority baseline and a label-permutation null for each test split.""" + choice = select(train_x, train_y, sel_x, sel_y, classes) + probe = Probe(choice["k"], choice["lam"], classes).fit(train_x, train_y) + values, counts = np.unique(np.asarray(train_y), return_counts=True) + majority = values[counts.argmax()] + rng = np.random.default_rng(seed) + null = {name: [] for name in tests} + for _ in range(permutations): + perm = list(rng.permutation(np.asarray(train_y))) + pp = Probe(choice["k"], choice["lam"], classes).fit(train_x, perm) + for name, (x, y) in tests.items(): + null[name].append(accuracy(pp.predict(x), y)) + out = {"settings": choice, "majority_label": str(majority), "tests": {}} + for name, (x, y) in tests.items(): + acc = accuracy(probe.predict(x), y) + nd = np.array(null[name]) + out["tests"][name] = {"n": len(y), "accuracy": acc, + "majority_accuracy": accuracy([majority] * len(y), y), + "permutation_mean": float(nd.mean()) if len(nd) else None, + "permutation_p": float((1 + (nd >= acc).sum()) / (1 + len(nd))) if len(nd) else None} + return out diff --git a/research/algernon/algebraic_reasoning_gym/arg02/prompts.py b/research/algernon/algebraic_reasoning_gym/arg02/prompts.py new file mode 100644 index 000000000..e0ac379e0 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/prompts.py @@ -0,0 +1,87 @@ +"""Prompt rendering from ARG-01 public records only. + +Input rows have exactly the fields `external.public_records` exports. The +query series is public but plays no part in identifying the program, so it is +not rendered. Case identifiers are never rendered. Every prompt ends with the +fixed tail "\\nProgram:"; the three answer positions follow it. +""" +from __future__ import annotations + +PUBLIC_FIELDS = {"case_id", "topology", "observed_degree", "demos", "query", "public_sha256"} +SHOT_FIELDS = PUBLIC_FIELDS | {"program"} +OPS = ("I", "N", "S", "R") +TAIL = "\nProgram:" +OP_TEXT = {op: " " + op for op in OPS} + +HEADER = ( + "Each line lists the coefficients of x^0..x^12 of an integer power series f.\n" + "Operators: I(f)=f, N(f)=f(-x), S(f)=f(x^2), R(f)=1/f.\n" + "A program 'a b c' maps an input f to an output y by its topology:\n" + "fork: y=c(a(f)*b(f)); cascade: y=c(a(f)*b(a(f))); additive: y=c(a(f)+b(f)-1); " + "hadamard: y=c(1+sum_{n>=1} a(f)_n*b(f)_n*x^n).\n" + "Find the program that maps both inputs to their outputs.\n" +) + +VARIANTS = ("canonical", "swap", "space", "swap_space") + + +def _check_public(row, allowed): + if not isinstance(row, dict): + raise TypeError("public record must be a dict") + extra = set(row) - allowed + if extra: + raise ValueError(f"non-public fields in model input: {sorted(extra)}") + if row.get("observed_degree") != 12 or len(row.get("demos", ())) != 2: + raise ValueError("unexpected public record shape") + + +def _series(values, sep): + if not values or values[0] != 1 or any(type(v) is not int for v in values): + raise ValueError("bad public series") + return sep.join(str(v) for v in values) + + +def case_block(row, *, variant="canonical", program=None, feedback=()): + if variant not in VARIANTS: + raise ValueError("unknown prompt variant") + sep = " " if variant in ("space", "swap_space") else ", " + demos = list(row["demos"]) + if variant in ("swap", "swap_space"): + demos = demos[::-1] + lines = [f"\nTopology: {row['topology']}"] + for i, demo in enumerate(demos, 1): + lines.append(f"Input {i}: {_series(demo['input'], sep)}") + lines.append(f"Output {i}: {_series(demo['output'], sep)}") + for item in feedback: + lines.append(feedback_line(item, swapped=variant in ("swap", "swap_space"))) + text = "\n".join(lines) + TAIL + if program is not None: + text += "".join(OP_TEXT[op] for op in program) + "\n" + return text + + +def feedback_line(item, *, swapped=False): + """One rejected candidate and its first mismatching degree in each demo.""" + program, faults = item + if tuple(program) not in {(a, b, c) for a in OPS for b in OPS for c in OPS}: + raise ValueError("feedback program outside grammar") + faults = list(faults)[::-1] if swapped else list(faults) + parts = [] + for i, fault in enumerate(faults, 1): + parts.append(f"example {i} ok" if fault is None else f"example {i} differs at x^{int(fault)}") + return f"Rejected: {' '.join(program)} ({', '.join(parts)})" + + +def render(row, *, shots=(), variant="canonical", feedback=()): + """Full prompt text for one public record. `shots` are solved shot records.""" + _check_public(row, PUBLIC_FIELDS) + text = HEADER + for shot in shots: + _check_public(shot, SHOT_FIELDS) + if "program" not in shot: + raise ValueError("shot without program") + text += case_block(shot, variant="canonical", program=shot["program"]) + text += case_block(row, variant=variant, feedback=feedback) + if not text.endswith(TAIL): + raise AssertionError("prompt tail drift") + return text diff --git a/research/algernon/algebraic_reasoning_gym/arg02/recurrence.py b/research/algernon/algebraic_reasoning_gym/arg02/recurrence.py new file mode 100644 index 000000000..a8951a244 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/recurrence.py @@ -0,0 +1,216 @@ +"""Explicit block-loop recurrence for a pretrained Qwen3.5 text decoder. + +Qwen3.5-0.8B has no native recurrence. ARG-02 adds one, untrained: decoder +layers [a, b) form a block B that is applied `depth` times to the residual +stream, with the pretrained weights unchanged: + + x = layers[0:a](embed(tokens)) block input + h_1 = B(x) = the ordinary forward + h_t = B(h_{t-1}) (loop) residual feedback + h_t = h_{t-1} + (h_1 - x) (open) no feedback: the block only + ever sees x; its single update + is re-applied + h_t = h_1 + D_t (shuffle) D_t = h_t - h_1 of a donor + case's loop, right-aligned + logits = lm_head(norm(layers[b:](h_t))) readout after any step t + +depth 1 is the unmodified model (checked against the HF forward in tests). +Every layer is called directly with the module's own masks and rotary +embeddings, so hidden states after every step are exact, inspectable tensors. +""" +from __future__ import annotations + +import time + +import torch + +from .prompts import OPS + +SITE = 5 # right-aligned answer site: "\n", "Program", ":" and the two candidate tokens + + +class Timer: + def __init__(self, device): + self.cuda = torch.device(device).type == "cuda" + + def start(self): + if self.cuda: + ev = torch.cuda.Event(enable_timing=True) + ev.record() + return ev + return time.perf_counter() + + def stop(self, mark): + if self.cuda: + ev = torch.cuda.Event(enable_timing=True) + ev.record() + ev.synchronize() + return mark.elapsed_time(ev) + return (time.perf_counter() - mark) * 1000.0 + + +def candidate_rows(prompt_ids, op_ids): + """16 rows: prompt + (op1, op2) for every pair; row index 4*i + j.""" + rows = [] + for a in OPS: + for b in OPS: + rows.append(list(prompt_ids) + [op_ids[a], op_ids[b]]) + return torch.tensor(rows, dtype=torch.long) + + +def extract(logprobs, op_ids): + """Answer record from (16, 3, V) log-softmax over the last three positions.""" + tok = [op_ids[o] for o in OPS] + lp = logprobs.float() + lp1 = [float(lp[0, 0, t]) for t in tok] + g1 = int(lp[0, 0].argmax()) + lp2, g2, lp3, g3 = [], [], [], [] + for i in range(4): + lp2.append([float(lp[4 * i, 1, t]) for t in tok]) + g2.append(int(lp[4 * i, 1].argmax())) + row3, rowg = [], [] + for j in range(4): + r = 4 * i + j + row3.append([float(lp[r, 2, t]) for t in tok]) + rowg.append(int(lp[r, 2].argmax())) + lp3.append(row3) + g3.append(rowg) + # Rows share a prefix, so these positions must agree across rows. + spread1 = float((lp[:, 0] - lp[0:1, 0]).abs().max()) + spread2 = max(float((lp[4 * i:4 * i + 4, 1] - lp[4 * i:4 * i + 1, 1]).abs().max()) for i in range(4)) + return {"lp1": lp1, "lp2": lp2, "lp3": lp3, "g1": g1, "g2": g2, "g3": g3, + "row_spread": max(spread1, spread2)} + + +def align_index(recipient_len, donor_len, device): + """Recipient position p takes donor position donor_len-1-((recipient_len-1-p) mod donor_len).""" + k = torch.arange(recipient_len - 1, -1, -1, device=device) % donor_len + return donor_len - 1 - k + + +class BlockLoop: + def __init__(self, model, block=None): + self.model = model + self.base = model.model + self.layers = self.base.layers + self.cfg = self.base.config + if getattr(self.cfg, "model_type", None) != "qwen3_5_text": + raise ValueError("BlockLoop supports Qwen3.5 text decoders only") + self.n = len(self.layers) + self.types = list(self.cfg.layer_types) + if block is not None: + a, b = block + if not (0 <= a < b <= self.n): + raise ValueError("block outside the decoder") + self.block = tuple(block) if block is not None else (0, self.n) + + @property + def device(self): + return self.base.embed_tokens.weight.device + + @torch.no_grad() + def prepare(self, ids): + from transformers.masking_utils import create_causal_mask, create_recurrent_attention_mask + ids = ids.to(self.device) + emb = self.base.embed_tokens(ids) + rows, length = ids.shape + pos = torch.arange(length, device=self.device).view(1, 1, -1).expand(4, rows, -1) + text_pos, rope_pos = pos[0], pos[1:] + kw = {"config": self.cfg, "inputs_embeds": emb, "attention_mask": None, + "past_key_values": None, "position_ids": text_pos} + masks = {"full_attention": create_causal_mask(**kw), + "linear_attention": create_recurrent_attention_mask(**kw)} + pe = self.base.rotary_emb(emb, rope_pos) + return emb, {"pe": pe, "masks": masks, "pos": text_pos} + + @torch.no_grad() + def run(self, h, lo, hi, ctx): + for i in range(lo, hi): + h = self.layers[i](h, position_embeddings=ctx["pe"], attention_mask=ctx["masks"][self.types[i]], + position_ids=ctx["pos"], past_key_values=None, use_cache=False) + return h + + @torch.no_grad() + def readout(self, h, ctx): + h = self.run(h, self.block[1], self.n, ctx) + h = self.base.norm(h[:, -3:, :]) + return torch.log_softmax(self.model.lm_head(h).float(), dim=-1) + + @torch.no_grad() + def trajectory(self, ids, op_ids, depth, *, mode="loop", readout_steps=(), capture=(-3,), + donor_delta=None, patch=None, perturb=None, keep_delta=(), keep_site=(), + clean_states=None, keep_states=False): + """Run one block-looped forward over the 16 candidate rows of one prompt. + + donor_delta: {t: (rows, Ld, H)} donor h_t - h_1, for mode "shuffle". + patch: {"step": t, "site": (rows, SITE, H)} donor site states written at step t. + perturb: {"step": t, "sigma": s, "seed": n} Gaussian kick of s * RMS(h_t). + clean_states: [row-0 states x, h_1..h_T] of an unperturbed run, for distances. + """ + if mode not in ("loop", "open", "shuffle"): + raise ValueError("unknown recurrence mode") + if mode == "shuffle" and donor_delta is None: + raise ValueError("shuffle needs donor deltas") + a, b = self.block + timer = Timer(self.device) + timing = {"prelude_ms": 0.0, "block_ms": [], "readout_ms": {}} + mark = timer.start() + emb, ctx = self.prepare(ids) + x = self.run(emb, 0, a, ctx) + timing["prelude_ms"] = timer.stop(mark) + rows, length, _ = x.shape + out = {"records": {}, "states": [x[0, list(capture)].float().cpu()], "residual": [], + "residual_site": [], "deltas": {}, "sites": {}, "distance": [], "timing": timing, + "rows": rows, "length": length, "full_states": [x[0].float()] if keep_states else None} + index = None + if mode == "shuffle": + any_delta = next(iter(donor_delta.values())) + index = align_index(length, any_delta.shape[1], x.device) + h_prev, h1, upd = x, None, None + for t in range(1, depth + 1): + mark = timer.start() + if t == 1 or mode == "loop": + h = self.run(h_prev, a, b, ctx) + elif mode == "open": + h = h_prev + upd + elif t in donor_delta: + # The recipient never runs its own block after step 1, so only + # steps that are read out need a donor displacement. + h = h1 + donor_delta[t].to(h1.dtype)[:, index, :] + else: + h = h_prev + if t == 1: + h1, upd = h, h - x + if perturb is not None and t == perturb["step"]: + gen = torch.Generator(device="cpu").manual_seed(int(perturb["seed"])) + noise = torch.randn((1, length, h.shape[-1]), generator=gen).to(h.device, torch.float32) + rms = h[0].float().pow(2).mean().sqrt() + h = (h.float() + perturb["sigma"] * rms * noise).to(h.dtype) + out["kick_norm"] = float((perturb["sigma"] * rms * noise[0]).norm()) + if patch is not None and t == patch["step"]: + h = h.clone() + h[:, -SITE:, :] = patch["site"].to(h.dtype) + timing["block_ms"].append(timer.stop(mark)) + diff = (h[0].float() - h_prev[0].float()) + out["residual"].append(float(diff.norm() / h_prev[0].float().norm().clamp_min(1e-12))) + out["residual_site"].append(float(diff[-SITE:].norm() / h_prev[0, -SITE:].float().norm().clamp_min(1e-12))) + out["states"].append(h[0, list(capture)].float().cpu()) + if keep_states: + out["full_states"].append(h[0].float()) + if clean_states is not None and t < len(clean_states): + out["distance"].append(float((h[0].float() - clean_states[t]).norm())) + if t in keep_delta: + out["deltas"][t] = (h - h1).detach() + if t in keep_site: + out["sites"][t] = h[:, -SITE:, :].detach().clone() + if t in readout_steps: + mark = timer.start() + rec = extract(self.readout(h, ctx), op_ids) + timing["readout_ms"][t] = timer.stop(mark) + out["records"][t] = rec + h_prev = h + return out + + def latency_ms(self, timing, depth): + """Standalone latency of a depth-`depth` forward from step timings.""" + return timing["prelude_ms"] + sum(timing["block_ms"][:depth]) + timing["readout_ms"][depth] diff --git a/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_checkpoint_check.json b/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_checkpoint_check.json new file mode 100644 index 000000000..7d622c430 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_checkpoint_check.json @@ -0,0 +1,124 @@ +{ + "device": "cpu", + "ff_control": { + "files_verified": [ + "config.json", + "model.safetensors-00001-of-00001.safetensors", + "model.safetensors.index.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "hash_seconds": 6.3, + "repo": "Qwen/Qwen3.5-2B-Base", + "revision": "b1485b2fa6dfa1287294f269f5fb618e03d52d7c" + }, + "load_seconds": 3.81, + "model": { + "files_verified": [ + "config.json", + "model.safetensors-00001-of-00001.safetensors", + "model.safetensors.index.json", + "tokenizer.json", + "tokenizer_config.json" + ], + "hash_seconds": 2.56, + "repo": "Qwen/Qwen3.5-0.8B-Base", + "revision": "dc7cdfe2ee4154fa7e30f5b51ca41bfa40174e68" + }, + "model_class": "Qwen3_5ForCausalLM", + "note": "CPU, bf16, 2 development prompts, first 2 candidate rows; no grading. Run 2026-11-10 under vramorama run --vram 256M --max-commit 85.", + "parity": [ + { + "case_id": "calibration:signed:00001", + "depth2_relative_residual": 0.580950915813446, + "max_abs_logprob_diff": 0.0, + "seconds": 13.82, + "tokens": 433, + "top_token_equal": true + }, + { + "case_id": "calibration:signed:00002", + "depth2_relative_residual": 0.5842715501785278, + "max_abs_logprob_diff": 0.0, + "seconds": 9.97, + "tokens": 376, + "top_token_equal": true + } + ], + "prompt_tokens": { + "development_shots0": { + "canonical": { + "max": 431, + "mean": 328.8484848484849, + "min": 321 + } + }, + "development_shots4": { + "canonical": { + "max": 1194, + "mean": 1091.8484848484848, + "min": 1084 + } + }, + "test_shots0": { + "canonical": { + "max": 399, + "mean": 327.2760416666667, + "min": 321 + }, + "space": { + "max": 351, + "mean": 279.2760416666667, + "min": 273 + }, + "swap": { + "max": 399, + "mean": 327.2760416666667, + "min": 321 + }, + "swap_space": { + "max": 351, + "mean": 279.2760416666667, + "min": 273 + } + }, + "test_shots4": { + "canonical": { + "max": 1162, + "mean": 1090.2760416666667, + "min": 1084 + }, + "space": { + "max": 1114, + "mean": 1042.2760416666667, + "min": 1036 + }, + "swap": { + "max": 1162, + "mean": 1090.2760416666667, + "min": 1084 + }, + "swap_space": { + "max": 1114, + "mean": 1042.2760416666667, + "min": 1036 + } + } + }, + "schema": "algernon.arg02.checkpoint_check.v1", + "text_parameters": 752393024, + "tokenizer": { + "class": "Qwen2Tokenizer", + "op_token_ids": { + "I": 353, + "N": 443, + "R": 423, + "S": 326 + }, + "tail_ids": [ + 198, + 10374, + 25 + ] + } +} diff --git a/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_export_manifest.json b/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_export_manifest.json new file mode 100644 index 000000000..5e0b0ce1f --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_export_manifest.json @@ -0,0 +1,9 @@ +{ + "audit_sha256": "aad4d16fe1aa0effca1ade97fdebc737d84dc30f170d2ef4fbf38dee647f6cc8", + "files": { + "development.jsonl": "0b68940d4aa214bef5d18fc2f17dee2badeaf13f2f72d18133f71c2a20bf6234", + "shots.json": "c8b209b709c71ce9247ca5b3a207bdcd8d99831852b56f874328075f25476058", + "test.jsonl": "3bc149de73ae0f5107cb4d452c9946ddcde3abbea2df38a3069ac85b133454c3" + }, + "sample": null +} diff --git a/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_splits_audit.json b/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_splits_audit.json new file mode 100644 index 000000000..c3417b239 --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/results/arg02_splits_audit.json @@ -0,0 +1,54 @@ +{ + "counts": { + "calibration": 36, + "dev": 96, + "shots": 4, + "test": 192, + "test_positive": 168 + }, + "dev_families": [ + "product", + "signed", + "sparse" + ], + "dev_seed": 2026111102, + "evalmath_seed": 2026111027, + "roster_sha256": { + "calibration": "088c8dc031f9aa14c94339bd08983f55e730be9415952aed20c66921aa6abf19", + "dev": "113081f8fe58a3a42bb198130436ecf8dc7d9247416694c5ac0ce57b5264041e", + "shots": "201a4dbce72f1a2f9703579c4ab901503da2fa31efd520c56ea1a40fb3a15994", + "test": "0e8caf0649d30f834d0bcfd1469b705d6d73371812cb87575fd3e12243ebcbba" + }, + "schema": "algernon.arg02.splits.v1", + "shot_programs": { + "additive": [ + "I", + "R", + "I" + ], + "cascade": [ + "N", + "N", + "S" + ], + "fork": [ + "S", + "I", + "S" + ], + "hadamard": [ + "R", + "R", + "N" + ] + }, + "shot_seed": 2026111103, + "signature_overlaps": { + "calibration_vs_test": 0, + "dev_vs_calibration": 0, + "dev_vs_test": 0, + "shots_vs_dev": 0, + "shots_vs_test": 0 + }, + "test_duplicate_public_signatures": 6 +} diff --git a/research/algernon/algebraic_reasoning_gym/arg02/run_arg02.ps1 b/research/algernon/algebraic_reasoning_gym/arg02/run_arg02.ps1 new file mode 100644 index 000000000..12e55146f --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/run_arg02.ps1 @@ -0,0 +1,47 @@ +# ARG-02 GPU chain: development selection, then the single test run, then the report. +# One vramorama lease at a time; every GPU stage is resumable and exits 75 on a power cap. +# +# powershell -ExecutionPolicy Bypass -File research\algernon\algebraic_reasoning_gym\arg02\run_arg02.ps1 ` +# -RunDir C:\Users\patri\Documents\Codex\algernon\runs\arg02 +# +# Run from the Compactification-Theory root. A stage that already finished is skipped by the +# runner (parts are reused under an identical key), so the script can be started again after a stop. +param( + [Parameter(Mandatory = $true)][string]$RunDir, + [string]$Python = "C:\Users\patri\.venvs\bluebeam\Scripts\python.exe", + [string]$EvalMathSrc = "C:\Users\patri\OneDrive\Documents\GitHub\EvalMath\src", + [string]$Vram = "8G", + [string]$Vramorama = "$env:LOCALAPPDATA\Programs\vramorama\vramorama.exe", + [string]$ResultsDir = "research\algernon\algebraic_reasoning_gym\arg02\results" +) +$ErrorActionPreference = "Stop" +$env:PYTHONPATH = ".;$EvalMathSrc" +$env:PYTHONUTF8 = "1" +$env:HF_HUB_OFFLINE = "1" +$pkg = "research.algernon.algebraic_reasoning_gym.arg02" + +function Cpu([string[]]$a) { + & $Python -m "$pkg.analyze" @a + if ($LASTEXITCODE -ne 0) { throw "analyze $($a -join ' ') failed ($LASTEXITCODE)" } +} + +function Gpu([string]$name, [string[]]$a) { + $done = Join-Path $RunDir "$name.done" + if (Test-Path $done) { Write-Host "skip $name (done)"; return } + & $Vramorama run --vram $Vram --owner "arg02-$name" --pause-exit 75 --guard-power 90 --restart 20 ` + -- $Python -m "$pkg.runner" @a --run-dir $RunDir + if ($LASTEXITCODE -ne 0) { throw "runner $name failed ($LASTEXITCODE)" } + New-Item -ItemType File -Path $done -Force | Out-Null +} + +if (-not (Test-Path (Join-Path $RunDir "export_manifest.json"))) { Cpu @("export", "--run-dir", $RunDir) } +Gpu "dev_shots" @("dev", "--stage", "shots") +Cpu @("select", "--run-dir", $RunDir, "--stage", "shots") +Gpu "dev_blocks" @("dev", "--stage", "blocks") +if (-not (Test-Path (Join-Path $RunDir "selection.json"))) { Cpu @("select", "--run-dir", $RunDir, "--stage", "blocks") } +Gpu "test_main" @("test") +Gpu "test_ff" @("test", "--model", "ff") +Cpu @("report", "--run-dir", $RunDir, "--out", $ResultsDir) +Cpu @("replay", "--tape", "$ResultsDir\arg02_answer_tape.jsonl.gz", "--check", "$ResultsDir\arg02_receipt.json") +New-Item -ItemType File -Path (Join-Path $RunDir "chain.done") -Force | Out-Null +Write-Host "ARG-02 chain finished; receipts in $ResultsDir" diff --git a/research/algernon/algebraic_reasoning_gym/arg02/runner.py b/research/algernon/algebraic_reasoning_gym/arg02/runner.py new file mode 100644 index 000000000..257b7c8ff --- /dev/null +++ b/research/algernon/algebraic_reasoning_gym/arg02/runner.py @@ -0,0 +1,631 @@ +"""ARG-02 model runner: Qwen3.5 block-loop recurrence on public ARG-01 records. + +The runner reads public JSONL rows exported by `analyze export` and never +builds the EvalMath roster, so hidden graphs and future coefficients cannot +reach a prompt. It writes per-case answer distributions, hidden-state +captures and timings under /parts/; `analyze` grades them with the +oracle afterwards. The external controller is the one arm that calls a +verifier during the run: it checks candidates against the public demos only. + +Stages (see PROTOCOL.md): + dev --stage shots depth-1 answers with 0 and 4 shots on development rows + dev --stage blocks loop trajectories for each candidate block + test every Qwen3.5-0.8B arm on the 192 test rows, once + test --model ff the Qwen3.5-2B feedforward control + smoke the whole pipeline on a tiny random Qwen3.5, CPU + +Exit 75 when the GPU is power-capped; `vramorama run --pause-exit 75` +restarts it and finished parts are reused. +""" +from __future__ import annotations + +import argparse +from hashlib import sha256 +import json +import math +import os +from pathlib import Path +import platform +import re +import subprocess +import sys +import time + +HERE = Path(__file__).resolve().parent +CONFIG = HERE / "config" / "arg02_config.json" +LOCK = HERE / "config" / "checkpoint_lock.json" +PAUSE_EXIT = 75 +CODE_FILES = ("prompts.py", "recurrence.py", "runner.py", "scoring.py") + + +class Paused(Exception): + pass + + +def file_sha256(path): + h = sha256() + with open(path, "rb") as fh: + for chunk in iter(lambda: fh.read(1 << 22), b""): + h.update(chunk) + return h.hexdigest() + + +def load_json(path): + return json.loads(Path(path).read_text(encoding="utf-8")) + + +def write_atomic(path, text): + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(text, encoding="utf-8") + os.replace(tmp, path) + + +def code_hashes(): + return {name: file_sha256(HERE / name) for name in CODE_FILES} + + +def read_public(path): + from .prompts import PUBLIC_FIELDS + rows = [] + for n, line in enumerate(Path(path).read_text(encoding="utf-8").splitlines(), 1): + if not line.strip(): + continue + row = json.loads(line) + if set(row) != PUBLIC_FIELDS: + raise ValueError(f"{path}:{n}: public row has fields {sorted(row)}") + rows.append(row) + return rows + + +def read_shots(path, k): + from .prompts import SHOT_FIELDS + shots = load_json(path) + if k == 0: + return [] + if any(set(s) != SHOT_FIELDS for s in shots): + raise ValueError("shot rows must be public fields plus program") + if k > len(shots): + raise ValueError("not enough shots") + return shots[:k] + + +def nvidia_smi(): + q = "name,driver_version,memory.total,memory.used,enforced.power.limit,pstate" + try: + out = subprocess.run(["nvidia-smi", f"--query-gpu={q}", "--format=csv,noheader"], + capture_output=True, text=True, timeout=30).stdout.strip() + except (OSError, subprocess.SubprocessError) as e: + return {"error": str(e)} + return dict(zip(q.split(","), [x.strip() for x in out.split(",")])) + + +def enforced_power_limit(): + try: + out = subprocess.run(["nvidia-smi", "--query-gpu=enforced.power.limit", "--format=csv,noheader,nounits"], + capture_output=True, text=True, timeout=10).stdout.split() + return float(out[0]) + except (OSError, subprocess.SubprocessError, ValueError, IndexError): + return None + + +class PowerWatch: + def __init__(self, min_w, *, active, every=10.0, read=enforced_power_limit): + self.min_w, self.active, self.every, self.read, self.last = min_w, active, every, read, None + + def check(self, where): + if not self.active: + return + now = time.monotonic() + if self.last is not None and now - self.last < self.every: + return + self.last = now + watts = self.read() + if watts is not None and watts < self.min_w: + raise Paused(f"{where}: GPU power-capped at {watts:.0f} W") + + +class Parts: + """Per-case results under /parts/