From d0b1b699e7a57ca1d66f8688e4717b892d40dad0 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sun, 15 Nov 2026 17:22:47 +0800 Subject: [PATCH 1/5] COE-07 preregister native LoopScope phase-gauge probe and exact split --- mechinterp/phase_gauge07/PROTOCOL.md | 48 +++++++ mechinterp/phase_gauge07/__init__.py | 1 + mechinterp/phase_gauge07/score.py | 181 +++++++++++++++++++++++++ mechinterp/phase_gauge07/test_score.py | 85 ++++++++++++ 4 files changed, 315 insertions(+) create mode 100644 mechinterp/phase_gauge07/PROTOCOL.md create mode 100644 mechinterp/phase_gauge07/__init__.py create mode 100644 mechinterp/phase_gauge07/score.py create mode 100644 mechinterp/phase_gauge07/test_score.py diff --git a/mechinterp/phase_gauge07/PROTOCOL.md b/mechinterp/phase_gauge07/PROTOCOL.md new file mode 100644 index 000000000..ba0290a10 --- /dev/null +++ b/mechinterp/phase_gauge07/PROTOCOL.md @@ -0,0 +1,48 @@ +# COE-07: Native LoopScope pretrained phase-gauge gate + +**Protocol frozen before pretrained checkpoint inference.** November 15, 2026. + +This is the native follow-up to `Compactification-Theory` COE-01..06 and MathCan's phase-blind observer capacity theorem. The existing COE-05/06 runs used small models trained expressly for that experiment. COE-07 uses the exact native checkpoint loader and recurrent state equations from **LoopedTransformers**, on a pretrained 7M Attention TRM. + +## Immutable inputs and resource budget + +- Underlying source branch pinned from `MoralityLabAI/LoopedTransformers@f504111e9985bd76bf321ed3968b46ac03a9811f`; native loader file `mechinterp/loopscope02/scripts/trm_sudoku.py` Git blob `a7396bc74a635b3ccf844e72cf48f73804e6ac5b`. +- Primary checkpoint `gaoxin492/TinyRecursiveModels-Sudoku-Extreme-att`, file `step_21700`, SHA-256 `932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3`. Use the existing `TS.load_trm_checkpoint`, which checks SHA before loading, with CPU float32 inference. Freeze weights. +- Benchmark source `mechinterp/loopscope02/results/benchmark_bundle.json`, internal bundle digest `59459ae0bb60b75db5be017e5f41adead391f2abb0b8fb043cd331c0ee043811`. No external dataset fetch required. Select exactly the **first row of each digit 1–9** in each of four existing strata by committed file order, for 36 distinct boards. The selection depends on metadata alone. +- Fit on `S1_naked1` and `S3_prop3plus`, test on `S2_prop2` and `S4_stalled`. All four groups have one board per digit. Within each held-out group, score the complete 9-vertex evaluator graph, 36 edges each. Exactly 72 held-out pairs per head. Context/stratum shift is an explicit limitation. +- Capture 8 outer ACT visits. Each visit is `3` H cycles with `6` L cycles and two native physical transformer layers, reusing the checkpoint's time-homogeneous weights. Capture target-cell `z_H`, `z_L`, eleven full `lm_head` logits and the `z_H` complement orthogonal to the **entire** `lm_head` row space. Report numerical projector parity and row-space rank. +- CPU-only, at most four threads, one model checkpoint and no fine-tuning. CI download consumes network bandwidth; workflow caps inference job at 30 minutes and uploads receipts and compressed activation arrays. + +## Frozen fit-only probe selection + +For each of four representations `visible`, `dark`, `full`, `scratch`, fit one shared binary linear threshold \(b_t(x)=1\{w\cdot z_t(x)>\theta\}\), the same \(w,\theta\) at all eight steps. Candidate directions are all 36 pairwise differences of fit-only digit centroids, 96 seeded random Gaussian directions, and the first 12 fit-only singular vectors. Norm-normalize each, evaluate the unique fit-only projected quantiles at `[.15,.25,.40,.50,.60,.75,.85]`. Random seed `20261115`. No test activations or held-out labels are available to this fitting routine. + +Select four separately reported heads from this same fixed candidate pool by lexicographic fit-only objectives: + +1. `ordered`: ordered edge retention, then cyclic retention, then count retention. +2. `cyclic`: cyclic-invariant edge retention, then cyclic-above-count gain, then count retention. +3. `cyclic_gain`: cyclic-above-count gain, then cyclic retention, then ordered retention. +4. `count`: count edge retention, then cyclic retention, then ordered retention. + +Tie order is the deterministic enumeration order; no test-based head changes. Each selected head has *one* fitted direction and threshold, with 8 bits of **readout over time**, not 8 learned linear directions. + +## Metric and decision rules + +For each held-out stratum and each of the 36 pairs of distinct target digits, compute the ordered 8-bit words \(w_i\), their canonical cyclic rotations \(N(w_i)\), and popcounts \(C(w_i)\). The exact order of information loss is + +\[D_{\rm ordered}\ge D_{\rm cyclic}\ge D_{\rm count},\qquad +D_{\rm ordered}-D_{\rm cyclic}=\#\{\text{phase-origin-dependent distinctions}\}.\] + +A cyclic-invariant advantage means `D_cyclic − D_count ≥ 8/72` on the **`cyclic_gain` head in the `dark` representation**, with at least one such preserved distinction in each held-out stratum. This is the one pre-fixed binary success gate. Other heads and representations are diagnostics with explicit numerators, denominators and no post-hoc significance claims. A base-model performance gate reports how many of nine target cells are solved by visit at each stratum. If native inference, source hash, or the fit/test firewall fails, label the cell **invalid**, with no substituted synthetic results. + +Controls include the final-step one-bit projection on the same learned direction, the full `lm_head` visible channel versus its exact orthogonal complement, and a frozen selected-head replay from a saved activation file. All source model weights and source codes are preserved; no mutation of the pretrained repository's checkpoint or original LoopScope results. + +## Reproduction + +```sh +python -m unittest discover -s mechinterp/phase_gauge07 -p 'test_*.py' -v +python -m mechinterp.phase_gauge07.run_native --out /tmp/coe07_native --threads 4 +python -m mechinterp.phase_gauge07.replay --input /tmp/coe07_native/native_activations.npz --receipt /tmp/coe07_native/receipt.json +``` + +The first command requires NumPy and no internet. The native command requires CPU PyTorch, Hugging Face Hub connectivity, and the pinned external checkpoint. Final outcomes are conditional on the actual hosted native run. The literature-wide novelty of any resulting mathematical formulation remains unassessed. diff --git a/mechinterp/phase_gauge07/__init__.py b/mechinterp/phase_gauge07/__init__.py new file mode 100644 index 000000000..d7bffb357 --- /dev/null +++ b/mechinterp/phase_gauge07/__init__.py @@ -0,0 +1 @@ +"""COE-07: frozen native LoopScope phase-gauge probe evaluation.""" diff --git a/mechinterp/phase_gauge07/score.py b/mechinterp/phase_gauge07/score.py new file mode 100644 index 000000000..f8edeeb66 --- /dev/null +++ b/mechinterp/phase_gauge07/score.py @@ -0,0 +1,181 @@ +"""COE-07 score library for cyclically invariant native recurrent probes. + +No model weights or held-out labels are used to select candidate thresholds. +The only API crossing the fit/test boundary is ``score_heldout``. +""" +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass +import hashlib +import json +from itertools import combinations +from typing import Any + +import numpy as np + +SOURCE_BUNDLE_SHA256 = "59459ae0bb60b75db5be017e5f41adead391f2abb0b8fb043cd331c0ee043811" +STRATA = ("S1_naked1", "S3_prop3plus", "S2_prop2", "S4_stalled") +FIT_STRATA = STRATA[:2] +HOLDOUT_STRATA = STRATA[2:] +DIGITS = tuple(range(1, 10)) +VISITS = 8 +MODEL_SHA256 = "932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3" + + +def select_manifest(bundle: dict) -> dict: + """Select first available board per target digit and stratum. + + This is label-stratified, deterministic, and evaluated on frozen benchmark + metadata. No model trajectory, probe success, or target predictions enter. + """ + if bundle.get("bundle_sha256") != SOURCE_BUNDLE_SHA256: + raise ValueError("changed LoopScope-02 benchmark bundle") + selection = {} + for stratum in STRATA: + rows = [row for row in bundle["items"] if row["stratum"] == stratum] + by_digit = {} + for row in rows: + digit = int(row["target_digit"]) + if digit in DIGITS and digit not in by_digit: + if len(row["question"]) != 81 or not (0 <= int(row["target_idx"]) < 81): + raise ValueError("invalid Sudoku benchmark row") + if str(row["answer"])[int(row["target_idx"])] != str(digit): + raise ValueError("label mismatch with target cell") + by_digit[digit] = { + "item_id": row["item_id"], + "question": row["question"], + "target_idx": int(row["target_idx"]), + "digit": digit, + } + if sorted(by_digit) != list(DIGITS): + raise ValueError(f"source lacks all nine digits in {stratum}") + selection[stratum] = [by_digit[d] for d in DIGITS] + ids = [r["item_id"] for records in selection.values() for r in records] + if len(set(ids)) != 36: + raise ValueError("duplicate board across strata") + return {"strata": selection, "fit_strata": list(FIT_STRATA), + "heldout_strata": list(HOLDOUT_STRATA), + "manifest_sha256": hashlib.sha256(json.dumps(selection,sort_keys=True,separators=(",", ":")).encode()).hexdigest()} + + +def rotate(word: int, shift: int, width: int = VISITS) -> int: + mask = (1 << width) - 1 + shift %= width + return ((word << shift) | (word >> (width - shift))) & mask + + +def necklace(word: int, width: int = VISITS) -> int: + return min(rotate(word,shift,width) for shift in range(width)) + + +def code_class(word: int, kind: str, width: int = VISITS) -> int: + if kind == "ordered": return word + if kind == "cyclic": return necklace(word, width) + if kind == "count": return word.bit_count() + if kind == "final": return (word >> (width-1)) & 1 + raise ValueError(kind) + + +def score_codes(codes: dict[str, list[int]], width: int = VISITS) -> dict: + """All K9 edges per stratum; exact integer numerator and denominator.""" + breakdown = {} + for group, words in codes.items(): + if len(words) != 9 or any(w < 0 or w >= (1< np.ndarray: + """values: [groups,9,visits] => binary words [groups,9].""" + if values.ndim != 3 or values.shape[1:] != (9,VISITS): + raise ValueError("invalid projection grid") + hits = values > float(threshold) + return np.sum(hits.astype(np.int64) * (1 << np.arange(VISITS,dtype=np.int64)),axis=2) + + +def candidate_heads(fit: np.ndarray, seed: int = 20261115, n_random: int = 96): + """A deterministic pool derived solely from fit states. + + ``fit``: [2,9,T,D]; signed centroid differences and seeded random directions. + Thresholds are fit-only projected quantiles, with no test calibration. + """ + if fit.ndim != 4 or fit.shape[:3] != (2,9,VISITS): + raise ValueError("fit shape must [2,9,8,D]") + width = fit.shape[-1] + rng=np.random.default_rng(seed) + means=fit.mean(axis=2).mean(axis=0) # [9,D], 2 strata and T visits + directions=[] + for a,b in combinations(range(9),2): + directions.append(means[a]-means[b]) + directions.extend(rng.normal(size=(n_random,width))) + arr=fit.reshape(-1,width) + centered=arr-arr.mean(axis=0) + # Principal directions add unsupervised fit-only candidate heads. + _,_,vh=np.linalg.svd(centered,full_matrices=False) + directions.extend(vh[:min(12,len(vh))]) + for i,d in enumerate(directions): + norm=np.linalg.norm(d) + if norm < 1e-10:continue + direction=np.asarray(d,dtype=np.float64)/norm + projected=arr@direction + q=np.unique(np.quantile(projected,[.15,.25,.4,.5,.6,.75,.85])) + for threshold in q: + yield (i, direction, float(threshold)) + + +def select_heads(fit: np.ndarray, seed:int=20261115) -> dict[str,dict]: + """Select three independent objectives by fit-only K9 edge scores.""" + if not np.all(np.isfinite(fit)): + raise ValueError("nonfinite fit states") + best={} + for candidate_id,vec,theta in candidate_heads(fit,seed=seed): + codes=codes_from_projection(np.einsum('gtpd,d->gtp',fit,vec),theta) + score=score_codes({str(g):list(codes[g]) for g in range(2)})["pooled"] + for objective,priority in { + "ordered":(score["ordered"],score["cyclic"],score["count"]), + "cyclic":(score["cyclic"],score["recoverable_order_only"],score["count"]), + "cyclic_gain":(score["recoverable_order_only"],score["cyclic"],score["ordered"]), + "count":(score["count"],score["cyclic"],score["ordered"]), + }.items(): + existing=best.get(objective) + if existing is None or tuple(priority)>tuple(existing["priority"]): + best[objective]={"direction":vec.tolist(),"threshold":theta, + "candidate_id":candidate_id,"priority":list(priority), + "fit_score":score} + if set(best)!={"ordered","cyclic","cyclic_gain","count"}: + raise ValueError("incomplete head search") + return best + + +def evaluate_heads(fit: np.ndarray, test: np.ndarray, seed:int=20261115) -> dict: + """An explicit fit/test firewall: fit-only selection, then test score.""" + chosen=select_heads(fit,seed=seed) + results={} + for name,p in chosen.items(): + vec=np.asarray(p["direction"]) + proj=np.einsum('gtpd,d->gtp',test,vec) + codes=codes_from_projection(proj,p["threshold"]) + results[name]={"fit_priority":p["priority"],"candidate_id":p["candidate_id"], + "threshold":p["threshold"],"direction":p["direction"], + "fit_score":p["fit_score"], + "heldout_scores":score_codes({str(g):list(codes[g]) for g in range(test.shape[0])}), + "heldout_codes":codes.tolist()} + return results + + +def audit_phases_equal(weighted: list[int]) -> bool: + return all(necklace(rotate(word,j))==necklace(word) for word in weighted for j in range(VISITS)) diff --git a/mechinterp/phase_gauge07/test_score.py b/mechinterp/phase_gauge07/test_score.py new file mode 100644 index 000000000..1ff3d0d68 --- /dev/null +++ b/mechinterp/phase_gauge07/test_score.py @@ -0,0 +1,85 @@ +"""COE-07 exact quotient diagnostics and train/test isolation checks.""" +import itertools +import unittest +import numpy as np +try: + from .score import (VISITS, necklace, rotate, score_codes, codes_from_projection, + select_heads, evaluate_heads, audit_phases_equal, select_manifest, + SOURCE_BUNDLE_SHA256, STRATA) +except ImportError: + from score import (VISITS, necklace, rotate, score_codes, codes_from_projection, + select_heads, evaluate_heads, audit_phases_equal, select_manifest, + SOURCE_BUNDLE_SHA256, STRATA) + +class QuotientTests(unittest.TestCase): + def test_cyclic_rotation_invariance_for_every_word(self): + self.assertTrue(audit_phases_equal(list(range(256)))) + + def test_count_cyclic_order_nesting_exhaustively(self): + for a,b in itertools.combinations(range(256),2): + if a.bit_count()!=b.bit_count(): + self.assertNotEqual(necklace(a),necklace(b)) + if necklace(a)!=necklace(b): + self.assertNotEqual(a,b) + + def test_recoverable_order_and_lost_phase(self): + words=list(range(9)) + result=score_codes({'fit':words})['pooled'] + self.assertEqual(result['denominator'],36) + self.assertEqual(result['order_with_unknown_clock_loss'],result['ordered']-result['cyclic']) + self.assertEqual(result['recoverable_order_only'],result['cyclic']-result['count']) + + def test_phase_blind_positive_control(self): + # Distinct constant-weight necklaces have count collision and phase-robust order. + words=[3,5,9,17,33,65,129,6,10] + self.assertTrue(all(x.bit_count()==2 for x in words)) + m=score_codes({'demo':words})['pooled'] + self.assertEqual(m['count'],0) + self.assertGreater(m['cyclic'],0) + + def test_shape_rejects_invalid_projection(self): + with self.assertRaises(ValueError): + codes_from_projection(np.zeros((2,9,7)),.5) + + def test_fit_only_selection_unaffected_by_heldout_state_values(self): + rng=np.random.default_rng(8701) + fit=rng.normal(size=(2,9,VISITS,5)) + test=rng.normal(size=(2,9,VISITS,5)) + chosen1=select_heads(fit,seed=12) + chosen2=select_heads(fit,seed=12) + self.assertEqual(chosen1,chosen2) + a=evaluate_heads(fit,test,seed=12) + b=evaluate_heads(fit,np.zeros_like(test),seed=12) + for key in chosen1: + self.assertEqual(a[key]['direction'],b[key]['direction']) + self.assertEqual(a[key]['threshold'],b[key]['threshold']) + self.assertEqual(a[key]['fit_score'],b[key]['fit_score']) + self.assertNotEqual(a['cyclic']['heldout_codes'],b['cyclic']['heldout_codes']) + + def test_permutation_must_not_turn_cyclic_into_order(self): + rng=np.random.default_rng(271) + for _ in range(100): + words=rng.integers(0,256,size=9).tolist() + shift=int(rng.integers(0,8)) + rotated=[rotate(w,shift) for w in words] + before=score_codes({'a':words})['pooled'] + after=score_codes({'a':rotated})['pooled'] + self.assertEqual(before['cyclic'],after['cyclic']) + self.assertEqual(before['count'],after['count']) + + def test_source_bundle_digest_guard(self): + with self.assertRaises(ValueError): + select_manifest({'bundle_sha256':'wrong','items':[]}) + + def test_deterministic_label_selection(self): + rows=[] + for g in STRATA: + for d in range(1,10): + q='.'*81 + a=str(d)*81 + rows.append(dict(stratum=g,item_id=f'{g}:{d}',target_idx=0,target_digit=d,question=q,answer=a)) + manifest=select_manifest({'bundle_sha256':SOURCE_BUNDLE_SHA256,'items':rows}) + self.assertEqual(list(manifest['strata']),list(STRATA)) + self.assertEqual(len(manifest['strata'][STRATA[0]]),9) + +if __name__=='__main__':unittest.main() From 87ab3060275fdfcac47b856fb02989edf77ac68b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sun, 15 Nov 2026 17:23:46 +0800 Subject: [PATCH 2/5] COE-07 add pinned native TRM activation capture, phase-gauge replay and hosted CPU workflow --- .github/workflows/coe07-native-trm-gauge.yml | 49 +++++++ mechinterp/phase_gauge07/replay.py | 42 ++++++ mechinterp/phase_gauge07/run_native.py | 146 +++++++++++++++++++ 3 files changed, 237 insertions(+) create mode 100644 .github/workflows/coe07-native-trm-gauge.yml create mode 100644 mechinterp/phase_gauge07/replay.py create mode 100644 mechinterp/phase_gauge07/run_native.py diff --git a/.github/workflows/coe07-native-trm-gauge.yml b/.github/workflows/coe07-native-trm-gauge.yml new file mode 100644 index 000000000..12e9245a5 --- /dev/null +++ b/.github/workflows/coe07-native-trm-gauge.yml @@ -0,0 +1,49 @@ +name: COE-07 native LoopScope phase-gauge validation +on: + pull_request: + paths: + - 'mechinterp/phase_gauge07/**' + - '.github/workflows/coe07-native-trm-gauge.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + exact-unit: + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - run: python -m pip install --disable-pip-version-check 'numpy>=1.26,<3' + - run: python -m unittest discover -s mechinterp/phase_gauge07 -p 'test_*.py' -v + native-pretrained: + runs-on: ubuntu-latest + timeout-minutes: 30 + needs: exact-unit + env: + OMP_NUM_THREADS: 4 + MKL_NUM_THREADS: 4 + HF_HUB_DOWNLOAD_TIMEOUT: 150 + HF_HUB_ETAG_TIMEOUT: 45 + PYTHONUNBUFFERED: 1 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install CPU-only native inference dependencies + run: | + python -m pip install --disable-pip-version-check 'numpy>=1.26,<3' 'huggingface_hub>=0.30,<2' + python -m pip install --disable-pip-version-check torch --index-url https://download.pytorch.org/whl/cpu + - name: Run SHA-pinned native TRM and eight-visit observer evaluation + run: python -m mechinterp.phase_gauge07.run_native --threads 4 --out /tmp/coe07_native + - name: Independent frozen-activation score replay + run: python -m mechinterp.phase_gauge07.replay --input /tmp/coe07_native/native_activations.npz --receipt /tmp/coe07_native/receipt.json + - uses: actions/upload-artifact@v4 + if: always() + with: + name: coe07-native-trm-verified-receipts + path: /tmp/coe07_native/ + if-no-files-found: warn diff --git a/mechinterp/phase_gauge07/replay.py b/mechinterp/phase_gauge07/replay.py new file mode 100644 index 000000000..1f2b87c12 --- /dev/null +++ b/mechinterp/phase_gauge07/replay.py @@ -0,0 +1,42 @@ +"""Independent COE-07 replay from the frozen native activation artifact.""" +import argparse +import hashlib +import json +from pathlib import Path +import numpy as np +from .run_native import REPS, evaluate_source +from .score import VISITS,MODEL_SHA256,STRATA + + +def replay(path:Path, receipt:dict): + if receipt['schema']!='COE-07-native-pretrained-TRM-phase-gauge-v1': + raise ValueError('source receipt schema mismatch') + if receipt['source_checkpoint_sha256']!=MODEL_SHA256:raise ValueError('wrong model') + with np.load(path,allow_pickle=False) as z: + arrays={r:z[r] for r in REPS} + for rep in REPS: + if arrays[rep].shape[:3]!=(4,9,VISITS):raise ValueError('source array shape wrong') + sha=hashlib.sha256(np.ascontiguousarray(arrays[rep]).tobytes()).hexdigest() + if sha!=receipt['metadata']['activation_sha256'][rep]: + raise ValueError('native source artifact tampered') + # Replay scoring exactly from frozen selected readouts. Selection itself may + # independently be rerun from the frozen fit states using evaluate_source. + dummy={'manifest_sha256':receipt['source_benchmark_sha256']} + regenerated=evaluate_source(arrays,dummy,receipt['metadata'],MODEL_SHA256) + for rep in REPS: + for head in regenerated['representations'][rep]: + fresh=regenerated['representations'][rep][head] + old=receipt['representations'][rep][head] + if fresh['heldout_codes']!=old['heldout_codes'] or fresh['heldout_scores']!=old['heldout_scores']: + raise ValueError(f'head replay mismatch {rep}/{head}') + if not np.allclose(fresh['direction'],old['direction'],rtol=0,atol=0): + raise ValueError(f'head-selection mismatch {rep}/{head}') + return {'schema':'COE-07-independent-replay-v1','source_checkpoint_sha256':MODEL_SHA256, + 'replayed_representations':list(REPS),'status':'pass'} + + +def main(): + p=argparse.ArgumentParser();p.add_argument('--input',type=Path,required=True) + p.add_argument('--receipt',type=Path,required=True) + a=p.parse_args(); print(json.dumps(replay(a.input,json.loads(a.receipt.read_text())),sort_keys=True)) +if __name__=='__main__':main() diff --git a/mechinterp/phase_gauge07/run_native.py b/mechinterp/phase_gauge07/run_native.py new file mode 100644 index 000000000..6cfebd6e0 --- /dev/null +++ b/mechinterp/phase_gauge07/run_native.py @@ -0,0 +1,146 @@ +"""COE-07: bounded native pretrained Attention-TRM activation extraction. + +Run from LoopedTransformers checkout. Downloads the pinned 7M gaoxin492 TRM +through the repository's existing loader, which verifies the complete SHA256 +before deserialization. Does not update the model or fit it to held-out data. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path +import platform +import sys + +import numpy as np +import torch + +from .score import (FIT_STRATA, HOLDOUT_STRATA, MODEL_SHA256, STRATA, + VISITS, evaluate_heads, select_manifest) +from mechinterp.loopscope02.scripts import trm_sudoku as TS + +ROOT = Path(__file__).resolve().parents[2] +BENCHMARK = ROOT / 'mechinterp/loopscope02/results/benchmark_bundle.json' +REPS = ('visible', 'dark', 'full', 'scratch') + + +def validate_projection(model, zh, exact_lens): + """Apply the same full 11-row-space decomposition as LoopScope-03.""" + w = model.lm_head.weight.float().detach() + q,s,vh = torch.linalg.svd(w, full_matrices=False) + rank = int((s>1e-8*s[0]).sum().item()) + v = vh[:rank].T.contiguous() + dark = zh - ((zh @ v) @ v.T) + parity = (dark @ w.T).abs().max().item() + if parity > 2e-3: + raise AssertionError(f'dark projector failed lens parity: {parity}') + return dark, rank, parity + + +@torch.inference_mode() +def capture(model, manifest: dict) -> tuple[dict[str,np.ndarray],dict]: + """Return model latent values indexed by strata, digit and outer visit.""" + raw={r:[] for r in REPS} + correct={} + projection_rank=None + projection_max_err=0.0 + for group in STRATA: + rows=manifest['strata'][group] + q=TS.encode_questions([r['question'] for r in rows],device='cpu') + emb=model.encode_inputs(q) + zh,zl=model.init_states(len(rows)) + digit_idx=torch.arange(len(rows)) + target=torch.tensor([r['target_idx'] for r in rows],dtype=torch.long)+model.puzzle_emb_len + rep_step={r:[] for r in REPS} + accuracy=[] + for step in range(VISITS): + zh,zl=model.act_step(zh,zl,emb) + part_h=zh[digit_idx,target,:].float() + part_l=zl[digit_idx,target,:].float() + logits=model.lm_head(part_h).float() + dark,rank,parity=validate_projection(model,part_h,logits) + if projection_rank is None: projection_rank=rank + if rank!=projection_rank: raise AssertionError('rank changed') + projection_max_err=max(projection_max_err,parity) + rep_step['visible'].append(logits.cpu().numpy()) + rep_step['dark'].append(dark.cpu().numpy()) + rep_step['full'].append(part_h.cpu().numpy()) + rep_step['scratch'].append(part_l.cpu().numpy()) + predictions=logits[:,2:11].argmax(dim=-1)+1 + truth=torch.tensor([r['digit'] for r in rows],device=predictions.device) + accuracy.append(int((predictions==truth).sum().item())) + for rep in REPS: + raw[rep].append(np.stack(rep_step[rep],axis=1)) # [9,T,D] + correct[group]=accuracy + arrays={rep:np.stack(raw[rep]) for rep in REPS} # [4,9,T,D] + return arrays,{'per_stratum_correct_of_9_by_visit':correct, + 'projector_rank':projection_rank,'max_removed_lens_logit':projection_max_err, + 'dimensions':{k:int(v.shape[-1]) for k,v in arrays.items()}} + + +def evaluate_source(arrays: dict[str,np.ndarray], manifest:dict, checks:dict, model_sha:str): + if model_sha!=MODEL_SHA256: + raise AssertionError('checkpoint hash mismatch') + out={} + for rep in REPS: + fit=arrays[rep][:2].astype(np.float64) + test=arrays[rep][2:].astype(np.float64) + selected=evaluate_heads(fit,test) + # Keep full selected head vectors so independent replays can recompute. + out[rep]=selected + return { + 'schema':'COE-07-native-pretrained-TRM-phase-gauge-v1', + 'source_model':'gaoxin492/TinyRecursiveModels-Sudoku-Extreme-att:step_21700', + 'source_checkpoint_sha256':model_sha, + 'source_benchmark_sha256':manifest['manifest_sha256'], + 'fit_strata':list(FIT_STRATA),'heldout_strata':list(HOLDOUT_STRATA), + 'num_digits':9,'visits':VISITS,'pairs_per_stratum':36, + 'metadata':checks, + 'representations':out, + 'summary':{ + rep:{head:{metric:int(selected[head]['heldout_scores']['pooled'][metric]) + for metric in ('ordered','cyclic','count','final','order_with_unknown_clock_loss','recoverable_order_only','denominator')} + for head in ('ordered','cyclic','cyclic_gain','count')} + for rep,selected in out.items()}, + } + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('--out',type=Path,default=Path('mechinterp/phase_gauge07/output')) + parser.add_argument('--threads',type=int,default=4) + p=parser.parse_args() + if p.threads <1 or p.threads>16:raise ValueError('threads must be 1..16') + torch.set_num_threads(p.threads) + p.out.mkdir(parents=True,exist_ok=True) + bundle=json.loads(BENCHMARK.read_text(encoding='utf8')) + manifest=select_manifest(bundle) + print('COE-07 manifest',manifest['manifest_sha256'],flush=True) + (p.out/'manifest.json').write_text(json.dumps(manifest,indent=2,sort_keys=True)+'\n') + # Runs the existing SHA-pinned checkpoint loader, not a synthetic imitation. + model,checkpoint_sha=TS.load_trm_checkpoint('gaoxin492','cpu',dtype=torch.float32) + if checkpoint_sha!=MODEL_SHA256:raise ValueError('hash mismatch') + print('COE-07 verified native model SHA256',checkpoint_sha,flush=True) + arrays,checks=capture(model,manifest) + checks['source_runner_sha256']=hashlib.sha256(Path(TS.__file__).read_bytes()).hexdigest() + checks['torch_version']=str(torch.__version__) + checks['numpy_version']=str(np.__version__) + checks['platform']=platform.platform() + checks['cpu_threads']=p.threads + checks['activation_sha256']={rep:hashlib.sha256(np.ascontiguousarray(arrays[rep]).tobytes()).hexdigest() + for rep in REPS} + del model + # Export native data with SHA-provenance for future independent replay; CI uploads this artifact. + np.savez_compressed(p.out/'native_activations.npz',**arrays) + result=evaluate_source(arrays,manifest,checks,checkpoint_sha) + (p.out/'receipt.json').write_text(json.dumps(result,indent=2,sort_keys=True)+'\n') + print(json.dumps({'schema':result['schema'], 'model_sha256':checkpoint_sha, + 'manifest_sha256':manifest['manifest_sha256'], + 'native_accuracy':checks['per_stratum_correct_of_9_by_visit'], + 'summary':result['summary']},sort_keys=True),flush=True) + return 0 + +if __name__=='__main__': + raise SystemExit(main()) From 46c08de3527ceef55bd13f915a303448d46cda32 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sun, 15 Nov 2026 17:31:20 +0800 Subject: [PATCH 3/5] COE-07 replay existing native TRM correctness telemetry with pinned Git blob checks --- .github/workflows/coe07-native-trm-gauge.yml | 5 + .../phase_gauge07/NATIVE_OUTPUT_TELEMETRY.md | 36 ++++++ mechinterp/phase_gauge07/telemetry_replay.py | 113 ++++++++++++++++++ mechinterp/phase_gauge07/test_telemetry.py | 24 ++++ 4 files changed, 178 insertions(+) create mode 100644 mechinterp/phase_gauge07/NATIVE_OUTPUT_TELEMETRY.md create mode 100644 mechinterp/phase_gauge07/telemetry_replay.py create mode 100644 mechinterp/phase_gauge07/test_telemetry.py diff --git a/.github/workflows/coe07-native-trm-gauge.yml b/.github/workflows/coe07-native-trm-gauge.yml index 12e9245a5..8758e156a 100644 --- a/.github/workflows/coe07-native-trm-gauge.yml +++ b/.github/workflows/coe07-native-trm-gauge.yml @@ -18,6 +18,11 @@ jobs: python-version: '3.11' - run: python -m pip install --disable-pip-version-check 'numpy>=1.26,<3' - run: python -m unittest discover -s mechinterp/phase_gauge07 -p 'test_*.py' -v + - run: python -m mechinterp.phase_gauge07.telemetry_replay --out /tmp/coe07_native_output_oracle.json + - uses: actions/upload-artifact@v4 + with: + name: coe07-native-output-oracle-replay + path: /tmp/coe07_native_output_oracle.json native-pretrained: runs-on: ubuntu-latest timeout-minutes: 30 diff --git a/mechinterp/phase_gauge07/NATIVE_OUTPUT_TELEMETRY.md b/mechinterp/phase_gauge07/NATIVE_OUTPUT_TELEMETRY.md new file mode 100644 index 000000000..a0ed4ddf3 --- /dev/null +++ b/mechinterp/phase_gauge07/NATIVE_OUTPUT_TELEMETRY.md @@ -0,0 +1,36 @@ +# COE-07 A: Native pretrained output-oracle replay + +**Evidence type:** reanalysis of existing **pretrained** LoopScope-02 output traces. The source is the earlier `gaoxin492/step_21700` (SHA-256 `932b5e0d...`) native TRM run, with all 256 puzzle target-cell correctness histories saved across 16 ACT steps. This is a **truth-conditioned correctness indicator** and has access to ground truth. It is not a model-observable latent probe, a learned readout, or a new inference run. + +Source files and locked Git blob IDs: + +- `mechinterp/loopscope02/results/benchmark_bundle.json` `01ec63b4b2a4ae5399f783c6036a7fc018825a87` +- `mechinterp/loopscope02/results/trm_results.json` `3c35daeb71da32f5c9ebbf03da539b8ee718b0ee` +- Both report the same internal benchmark digest `59459ae0bb60b75db5be017e5f41adead391f2abb0b8fb043cd331c0ee043811`. + +Read the first T binary correctness observations for each board; assign bit t to outer visit t+1. Within each of the original 64-item Sudoku strata, compare every unordered pair with distinct target digits. Report retained distinctions under ordered words, canonical cyclic-orbit words and popcount-only words; `final` reports only the correctness of the final visit. + +## Eight-visit results on full original 64-item strata + +| Stratum | Eligible cross-label pairs | Ordered | Cyclic-invariant | Popcount | Final step | +|---|---:|---:|---:|---:|---:| +| S1_naked1 | 1,811 | 0 | 0 | 0 | 0 | +| S2_prop2 | 1,788 | 0 | 0 | 0 | 0 | +| S3_prop3plus | 1,789 | 446 | 446 | 446 | 0 | +| S4_stalled | 1,795 | **1,414** | **1,389** | **1,369** | **738** | + +For S4, cyclic structure contains 20 extra distinctions beyond count, while a known starting phase contains 25 more. Every S1/S2 item is correct at all eight steps, collapsing the truth-conditioned histories to the same all-ones code. These results are expected from an oracle that conditions on correctness; they cannot establish that a real quantized latent probe can recover the extra distinctions. + +The **preregistered one-board-per-digit** heldout selection gives S2 `0/36` and S4 `28/36` distinctions for all three (ordered, cyclic, count) at T=8. The full S4 stratum exposes the rare phase-invariant distinctions that the small first-nine selection misses. The full-stratum result is **post-hoc diagnostic** and does not satisfy COE-07's preregistered native activation-probe success gate. + +At `T=4` on all 64 S4 boards, (ordered,cyclic,count,final) = (1278,1244,1244,802)/1795. At `T=16` the values are (1447,1428,1422,685)/1795, giving 6 cyclic-above-count distinctions and 19 phase-sensitive distinctions. A longer observation horizon can reduce differences in the final correctness state as more puzzles converge, while history retains earlier distinctions. + +An illustrative `T=8` pair is S4 item 05 versus item 25, binary histories `11111000` and `01001111`. Both contain five correct steps, and their necklaces differ, so the cyclic-invariant observation distinguishes them even with an unknown starting visit. + +## Reproduce + +``` +python -m mechinterp.phase_gauge07.telemetry_replay --out /tmp/coe07_output_oracle.json +``` + +`telemetry_replay.py` verifies both source Git blob hashes, the original benchmark digest, the model SHA-256, and the complete 16×256 binary array before computing the result. Because it reads data already committed to this repository, the replay requires neither the checkpoint download nor a GPU. It can run with the Python standard library except that the shared `score.py` import currently needs NumPy. The full native activation extraction in `run_native.py` remains independently gated behind checkpoint download and hosted runner availability. diff --git a/mechinterp/phase_gauge07/telemetry_replay.py b/mechinterp/phase_gauge07/telemetry_replay.py new file mode 100644 index 000000000..2483ffe37 --- /dev/null +++ b/mechinterp/phase_gauge07/telemetry_replay.py @@ -0,0 +1,113 @@ +"""Exact native LoopScope-02 output telemetry replay for COE-07. + +Reads the *previously committed* 16-step correctness traces of the original +SHA-pinned pretrained model. This is a truth-conditioned output-oracle +observation. It is never represented as a fitted latent activation probe. +""" +from __future__ import annotations +import argparse +import hashlib +import json +from collections import Counter +from itertools import combinations +from pathlib import Path + +try: + from .score import (VISITS, SOURCE_BUNDLE_SHA256, MODEL_SHA256, STRATA, + select_manifest, rotate, necklace) +except ImportError: + from score import (VISITS, SOURCE_BUNDLE_SHA256, MODEL_SHA256, STRATA, + select_manifest, rotate, necklace) + +ROOT=Path(__file__).resolve().parents[2] +BUNDLE=ROOT/'mechinterp/loopscope02/results/benchmark_bundle.json' +TRACE=ROOT/'mechinterp/loopscope02/results/trm_results.json' +BUNDLE_BLOB_SHA='01ec63b4b2a4ae5399f783c6036a7fc018825a87' +TRACE_BLOB_SHA='3c35daeb71da32f5c9ebbf03da539b8ee718b0ee' + + +def git_blob_digest(path:Path) -> str: + data=path.read_bytes() + return hashlib.sha1(b'blob '+str(len(data)).encode()+b'\x00'+data).hexdigest() + + +def verify_source(bundle:dict,trace:dict): + if bundle.get('bundle_sha256')!=SOURCE_BUNDLE_SHA256 or trace.get('bundle_sha256')!=SOURCE_BUNDLE_SHA256: + raise ValueError('source benchmark SHA mismatch') + if trace.get('checkpoint_sha256')!=MODEL_SHA256 or trace.get('steps')!=16: + raise ValueError('source checkpoint/visit mismatch') + outcomes=trace.get('items_target_correct_by_step') + if (len(outcomes)!=16 or any(len(row)!=len(bundle['items']) for row in outcomes) + or any(a not in (0,1) for row in outcomes for a in row)): + raise ValueError('corrupt output truth-conditioned traces') + return True + + +def trace_word(data:dict,idx:int,width:int) -> int: + if not 1<=width<=16:raise ValueError('wrong width') + return sum(int(data['items_target_correct_by_step'][t][idx])<dict: + if len(words)!=len(labels):raise ValueError('shapes differ') + totals=dict(eligible=0,ordered=0,cyclic=0,count=0,final=0) + for i,j in combinations(range(len(labels)),2): + if labels[i]==labels[j]:continue + a,b=words[i],words[j] + totals['eligible']+=1 + totals['ordered']+=a!=b + totals['cyclic']+=necklace(a,width)!=necklace(b,width) + totals['count']+=a.bit_count()!=b.bit_count() + totals['final']+=((a>>(width-1))&1)!=((b>>(width-1))&1) + totals['order_with_unknown_clock_loss']=totals['ordered']-totals['cyclic'] + totals['cyclic_beyond_count']=totals['cyclic']-totals['count'] + if not (totals['ordered']>=totals['cyclic']>=totals['count']): + raise AssertionError('quotient nesting violated') + return totals + + +def analyze(bundle:dict,trace:dict) -> dict: + verify_source(bundle,trace) + manifest=select_manifest(bundle) + per_stratum={}; first_nine={} + for T in (4,8,16): + per_stratum[str(T)]={};first_nine[str(T)]={} + for stratum in STRATA: + idx=[i for i,r in enumerate(bundle['items']) if r['stratum']==stratum] + labels=[int(bundle['items'][i]['target_digit']) for i in idx] + words=[trace_word(trace,i,T) for i in idx] + score=pair_stats(words,labels,T) + score['code_hist']={str(w):n for w,n in sorted(Counter(words).items())} + per_stratum[str(T)][stratum]=score + chosen=set(r['item_id'] for r in manifest['strata'][stratum]) + chosen_idx=[i for i in idx if bundle['items'][i]['item_id'] in chosen] + first_nine[str(T)][stratum]={ + **pair_stats([trace_word(trace,i,T) for i in chosen_idx], + [int(bundle['items'][i]['target_digit']) for i in chosen_idx],T), + 'items':[bundle['items'][i]['item_id'] for i in chosen_idx], + 'words':[trace_word(trace,i,T) for i in chosen_idx]} + return dict(schema='COE-07-native-output-oracle-replay-v1', + classification='pretrained checkpoint *truth-conditioned output telemetry*, not activation probe', + checkpoint_sha256=trace['checkpoint_sha256'], + source_bundle_sha256=bundle['bundle_sha256'], + source_github_blobs={'benchmark':BUNDLE_BLOB_SHA,'trm_results':TRACE_BLOB_SHA}, + group_manifest_sha256=manifest['manifest_sha256'], + windows=per_stratum,first_nine=first_nine) + + +def load_and_verify() -> dict: + for path,digest in ((BUNDLE,BUNDLE_BLOB_SHA),(TRACE,TRACE_BLOB_SHA)): + if git_blob_digest(path)!=digest: + raise RuntimeError(f'Git blob SHA mismatch in {path.name}') + return analyze(json.loads(BUNDLE.read_text()),json.loads(TRACE.read_text())) + + +def main(): + p=argparse.ArgumentParser();p.add_argument('--out',type=Path);a=p.parse_args() + result=load_and_verify() + text=json.dumps(result,indent=2,sort_keys=True)+'\n' + if a.out:a.out.write_text(text,encoding='utf8') + summary={T:{s:{k:result['windows'][T][s][k] for k in ('eligible','ordered','cyclic','count','final','cyclic_beyond_count','order_with_unknown_clock_loss')} + for s in STRATA} for T in ('4','8','16')} + print(json.dumps({'model_sha256':MODEL_SHA256,'summary':summary},sort_keys=True)) +if __name__=='__main__':main() diff --git a/mechinterp/phase_gauge07/test_telemetry.py b/mechinterp/phase_gauge07/test_telemetry.py new file mode 100644 index 000000000..4354c8518 --- /dev/null +++ b/mechinterp/phase_gauge07/test_telemetry.py @@ -0,0 +1,24 @@ +"""Exact sealed finite cells from earlier published LoopScope-02 native receipts.""" +import unittest +try: + from .telemetry_replay import pair_stats, trace_word, analyze, SOURCE_BUNDLE_SHA256, MODEL_SHA256 +except ImportError: + from telemetry_replay import pair_stats, trace_word, analyze, SOURCE_BUNDLE_SHA256, MODEL_SHA256 + +class TestTelemetry(unittest.TestCase): + def test_s4_eight_step_phase_advantage_witnesses(self): + words=[0b11111000,0b01001111,0b01011011,0b01110011] + x=pair_stats(words,[1,2,3,4],8) + self.assertEqual(x['count'],0) + self.assertEqual(x['cyclic'],6) + self.assertEqual(x['ordered'],6) + def test_native_source_requires_exact_shape_and_pin(self): + with self.assertRaises(ValueError): + analyze({'items':[],'bundle_sha256':SOURCE_BUNDLE_SHA256}, + {'checkpoint_sha256':MODEL_SHA256,'bundle_sha256':SOURCE_BUNDLE_SHA256, + 'steps':16,'items_target_correct_by_step':[[1]]}) + def test_quotient_nesting_on_numeric_fixture(self): + x=pair_stats([255,0,248,254,192,239,129,16,36],list(range(1,10)),8) + self.assertTrue(x['ordered']>=x['cyclic']>=x['count']) + self.assertEqual(x['denominator'] if 'denominator' in x else x['eligible'],36) +if __name__=='__main__': unittest.main() From 228678f8a40a2338cabaa31bb2511bd4de9566ee Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sun, 15 Nov 2026 17:56:17 +0800 Subject: [PATCH 4/5] COE-07R: exact dihedral-gauge replay and decoder collision audit --- .../phase_gauge07/DIHEDRAL_GAUGE_REPORT.md | 59 +++++++ mechinterp/phase_gauge07/dihedral_replay.py | 149 ++++++++++++++++++ .../phase_gauge07/test_dihedral_replay.py | 76 +++++++++ 3 files changed, 284 insertions(+) create mode 100644 mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md create mode 100644 mechinterp/phase_gauge07/dihedral_replay.py create mode 100644 mechinterp/phase_gauge07/test_dihedral_replay.py diff --git a/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md b/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md new file mode 100644 index 000000000..3eda7ffca --- /dev/null +++ b/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md @@ -0,0 +1,59 @@ +# COE-07R: Native-output reversal-gauge audit + +**2026-11-15.** Post-hoc computation on the exact, previously committed LoopScope-02 output-correctness traces. This is an additional diagnostic under COE-07's sealed benchmark and checkpoint pins. It is **not** the preregistered learned-activation-probe outcome. + +## Source and scope + +- Repository: `MoralityLabAI/LoopedTransformers`. +- Checkpoint: `gaoxin492/TinyRecursiveModels-Sudoku-Extreme-att`, `step_21700`, SHA-256 `932b5e0df4e90021c21a064d4e716154086c46fda7afa676ea294484a30e38c3`. +- Original native data: `mechinterp/loopscope02/results/trm_results.json`, Git blob SHA `3c35daeb71da32f5c9ebbf03da539b8ee718b0ee`; original 256-board benchmark Git blob SHA `01ec63b4b2a4ae5399f783c6036a7fc018825a87`, benchmark SHA `59459ae0bb60b75db5be017e5f41adead391f2abb0b8fb043cd331c0ee043811`. +- For each target cell and each ACT step, the observed bit is `1` precisely if the model's predicted digit equals the **known correct answer**. These bits are an oracle that depends on target truth. The readout is unsuitable for deployment without access to those answers. +- Every group has 64 Sudoku boards. Pair counts include pairs with **different** correct digits and exclude same-digit pairs, leading to unequal denominators across strata. The benchmark was fixed before these post-hoc analyses. + +## Exact group-action decomposition + +For an ordered T-bit history `W`, let `N(W)` be its cyclic necklace, `B(W)` its dihedral bracelet (allowing rotation and reversal), and `C(W)` its popcount. On any fixed evaluator edge set, the retained-pair count obeys + +``` +D(W) >= D(N) >= D(B) >= D(C). +D(W)-D(C) = [D(W)-D(N)] + [D(N)-D(B)] + [D(B)-D(C)]. +``` + +Thus the information lost when the start clock is hidden, the additional loss when forward/backward time is ambiguous, and the order-shape information retained despite those symmetries can be priced separately. The companion MathCan note proves the formula for arbitrary repeated task labels. + +## Replayed pretrained observations: stalled stratum S4 + +There are **1,795** distinct-digit evaluator pairs in the 64-board S4 group. The original checkpoint and dataset digest were independently checked using the linked GitHub connector before reporting the following values. + +| ACT visits | Ordered | Necklace | Bracelet | Count | Unknown clock loss | Unknown orientation loss | Dihedral order gain | +|---:|---:|---:|---:|---:|---:|---:|---:| +| 4 | 1,278 | 1,244 | 1,244 | 1,244 | 34 | 0 | 0 | +| 8 | 1,414 | 1,389 | 1,389 | 1,369 | 25 | 0 | **20** | +| 16 | 1,447 | 1,428 | 1,428 | 1,422 | 19 | 0 | **6** | + +For the **same** 64 labeled boards, assigning each observed descriptor to its most frequent target digit gives the following in-sample, truth-dependent *decoder oracle upper-bound scores*; these are intentionally not held-out learning metrics: + +| ACT visits | Ordered | Necklace | Bracelet | Count | +|---:|---:|---:|---:|---:| +| 4 | 23/64 | 18/64 | 18/64 | 18/64 | +| 8 | 30/64 | 24/64 | 24/64 | 19/64 | +| 16 | 31/64 | 26/64 | 26/64 | 24/64 | + +The other three groups of 64 each have zero bracelet-beyond-count gain for these windows; S1 and S2 are uniform correctness traces in the replay. S3 has 446 retained different-digit pairs under each of the four descriptors, independent of which window was chosen. + +**Empirical boundary:** the eight-step, 20-pair gain survives unknown start time **and** unknown time direction in this particular oracle descriptor. The underlying probe is defined by the answer, so its performance cannot establish an unsupervised, externally observable or causally active dark-fiber mechanism. The native latent run of `mechinterp/phase_gauge07/run_native.py` is required for that question. + +## Independent finite positive control + +At 8 visits and Hamming weight 4 there are exactly 10 binary necklaces and 8 binary bracelets. Under time reversal, 6 of the 10 necklaces are fixed, hence Burnside's formula gives `(10+6)/2=8`. The words `0b00001011` and its reversal have equal bracelets and counts but distinct cyclic necklaces. The reference verifies reversals, rotations, nested pair losses and the weighted-label decoder on exhaustive small inputs. + +## Reproduction and CI + +``` +python -m unittest discover -s mechinterp/phase_gauge07 -p 'test_*.py' -v +python -m mechinterp.phase_gauge07.dihedral_replay --out /tmp/coe07r_gauge.json +``` + +The first command works with NumPy and no model checkpoint. Its source-file-dependent test runs inside a full repository checkout. The second command also checks the **Git blob SHA** of the two original native receipts. Both are pure CPU and use only standard-library arithmetic for the new code. + +**Hosted inference status:** On the COE-07 PR branch, GitHub Actions run `43699655642` failed in its preliminary `exact-unit` job before exposed step logs and skipped `native-pretrained`. Its second attempt failed identically. A successful native activation-probe result is therefore pending; no synthetic or truth-conditioned substitute is promoted into that role. diff --git a/mechinterp/phase_gauge07/dihedral_replay.py b/mechinterp/phase_gauge07/dihedral_replay.py new file mode 100644 index 000000000..6503d65c5 --- /dev/null +++ b/mechinterp/phase_gauge07/dihedral_replay.py @@ -0,0 +1,149 @@ +"""COE-07R: exact rotation/reversal-invariant telemetry audit. + +Reuses the original pinned LoopScope-02 *truth-conditioned correctness* series. +The descriptor requires target labels to form the bit at each visit. These +numbers are diagnostic oracles, not a readout implementable from activations. +""" +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from itertools import combinations +import json +from pathlib import Path + +try: + from .score import STRATA, rotate, necklace, select_manifest + from .telemetry_replay import (BUNDLE, TRACE, load_and_verify, + trace_word, verify_source) +except ImportError: + from score import STRATA, rotate, necklace, select_manifest + from telemetry_replay import BUNDLE, TRACE, load_and_verify, trace_word, verify_source + + +def reverse_bits(word: int, width: int) -> int: + if width < 1 or not 0 <= word < (1 << width): + raise ValueError("invalid binary history") + return sum(((word >> bit) & 1) << (width - bit - 1) for bit in range(width)) + + +def bracelet(word: int, width: int) -> int: + """Canonical orbit representative under cyclic shifts and time reversal.""" + if width < 1 or not 0 <= word < (1 << width): + raise ValueError("invalid binary history") + return min(necklace(word, width), necklace(reverse_bits(word, width), width)) + + +def descriptor(word: int, width: int, mode: str) -> int: + if width < 1 or not 0 <= word < (1 << width): + raise ValueError("history out of bounds") + if mode == "ordered": + return word + if mode == "cyclic": + return necklace(word, width) + if mode == "dihedral": + return bracelet(word, width) + if mode == "count": + return word.bit_count() + raise ValueError("unknown descriptor") + + +def necklace_counts(width: int, weight: int) -> dict[str, int]: + """Enumerate finite fixed-weight cyclic and dihedral orbit counts.""" + if not 1 <= width <= 16 or not 0 <= weight <= width: + raise ValueError("outside exact finite enumeration budget") + members = [w for w in range(1 << width) if w.bit_count() == weight] + necklaces = {necklace(w, width) for w in members} + bracelets = {bracelet(w, width) for w in members} + fixed = {n for n in necklaces if necklace(reverse_bits(n, width), width) == n} + assert len(necklaces) + len(fixed) == 2 * len(bracelets) + return {"width": width, "weight": weight, "necklaces": len(necklaces), + "reversal_fixed_necklaces": len(fixed), "bracelets": len(bracelets)} + + +def pair_and_decoder_ledger(words: list[int], labels: list[int], width: int) -> dict: + """Exact complete evaluator restricted to unequal labels. + + Decoder values are *in-sample oracle upper bounds*: choose the majority + label within each descriptor class, after seeing all these same labels. + They are not held-out probe accuracy measurements. + """ + if len(words) != len(labels) or not words or width < 1: + raise ValueError("invalid group") + modes = ("ordered", "cyclic", "dihedral", "count") + maps = {mode: [descriptor(w, width, mode) for w in words] for mode in modes} + result = {"eligible": 0} + for mode in modes: + class_counts = defaultdict(Counter) + for index, label in enumerate(labels): + class_counts[maps[mode][index]][label] += 1 + result[mode] = { + "distinguished": 0, + "classes": len(class_counts), + "in_sample_oracle_correct": sum(max(counts.values()) for counts in class_counts.values()), + "denominator": len(words), + } + for i, j in combinations(range(len(words)), 2): + if labels[i] == labels[j]: + continue + result["eligible"] += 1 + for mode in modes: + result[mode]["distinguished"] += maps[mode][i] != maps[mode][j] + o, c, d, h = (result[k]["distinguished"] for k in modes) + assert result["eligible"] >= o >= c >= d >= h + assert all(result[a]["in_sample_oracle_correct"] >= result[b]["in_sample_oracle_correct"] + for a, b in zip(modes, modes[1:])) + result["phase_sensitive"] = o - c + result["time_orientation_sensitive"] = c - d + result["dihedral_beyond_count"] = d - h + assert (o - h == result["phase_sensitive"] + result["time_orientation_sensitive"] + + result["dihedral_beyond_count"]) + return result + + +def analyze(bundle: dict, trace: dict) -> dict: + verify_source(bundle, trace) + manifest = select_manifest(bundle) + by_window = {} + for width in (4, 8, 16): + by_window[str(width)] = {} + for group in STRATA: + indices = [index for index, row in enumerate(bundle["items"]) + if row["stratum"] == group] + words = [trace_word(trace, index, width) for index in indices] + labels = [int(bundle["items"][index]["target_digit"]) for index in indices] + full = pair_and_decoder_ledger(words, labels, width) + chosen_ids = {row["item_id"] for row in manifest["strata"][group]} + selected = [index for index in indices if bundle["items"][index]["item_id"] in chosen_ids] + small = pair_and_decoder_ledger( + [trace_word(trace, index, width) for index in selected], + [int(bundle["items"][index]["target_digit"]) for index in selected], width) + by_window[str(width)][group] = {"all_64": full, "preregistered_nine": small} + return {"schema": "COE-07R-pretrained-output-dihedral-gauge-v1", + "status": "truth-conditioned native output oracle, post-hoc structural diagnostic", + "model_checkpoint_sha256": trace["checkpoint_sha256"], + "benchmark_sha256": bundle["bundle_sha256"], + "manifest_sha256": manifest["manifest_sha256"], + "orbit_capacity": {str(w): necklace_counts(8,w) + for w in (3,4,5)}, + "windows": by_window} + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--out", type=Path) + args = ap.parse_args() + # Validates the exact Git blob IDs of both committed source artifacts. + load_and_verify() + result = analyze(json.loads(BUNDLE.read_text()), json.loads(TRACE.read_text())) + if args.out: + args.out.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8") + print(json.dumps({ + "schema": result["schema"], + "stalled": {T: result["windows"][T]["S4_stalled"]["all_64"] + for T in ("4", "8", "16")}, + }, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/mechinterp/phase_gauge07/test_dihedral_replay.py b/mechinterp/phase_gauge07/test_dihedral_replay.py new file mode 100644 index 000000000..588932a02 --- /dev/null +++ b/mechinterp/phase_gauge07/test_dihedral_replay.py @@ -0,0 +1,76 @@ +"""COE-07R exact finite tests, with optional pinned native-source replay.""" +from __future__ import annotations +from pathlib import Path +import unittest +try: + from .dihedral_replay import (analyze, bracelet, descriptor, necklace_counts, + pair_and_decoder_ledger, reverse_bits) + from .score import rotate + from .telemetry_replay import BUNDLE, TRACE, load_and_verify +except ImportError: + from dihedral_replay import (analyze, bracelet, descriptor, necklace_counts, + pair_and_decoder_ledger, reverse_bits) + from score import rotate + from telemetry_replay import BUNDLE, TRACE, load_and_verify + + +class TestDihedralGauge(unittest.TestCase): + def test_reversal_is_involutive(self): + for T in (4, 8, 12): + for word in range(1 << T): + self.assertEqual(reverse_bits(reverse_bits(word, T), T), word) + + def test_orbit_invariance(self): + for T in (4,8,12): + for word in range(1 << T): + b = bracelet(word, T) + for shift in range(T): + self.assertEqual(bracelet(rotate(word, shift, T), T), b) + self.assertEqual(bracelet(rotate(reverse_bits(word,T),shift,T),T),b) + + def test_orientation_strict_pair(self): + word = 0b1011 + other = reverse_bits(word,8) + self.assertNotEqual(descriptor(word,8,'cyclic'),descriptor(other,8,'cyclic')) + self.assertEqual(descriptor(word,8,'dihedral'),descriptor(other,8,'dihedral')) + self.assertEqual(descriptor(word,8,'count'),descriptor(other,8,'count')) + s=pair_and_decoder_ledger([word,other],[1,2],8) + self.assertEqual((s['phase_sensitive'],s['time_orientation_sensitive'],s['dihedral_beyond_count']), (0,1,0)) + + def test_weight_four_burnside(self): + self.assertEqual(necklace_counts(8,4),{ + 'width':8,'weight':4,'necklaces':10,'reversal_fixed_necklaces':6,'bracelets':8}) + self.assertEqual(necklace_counts(8,3)['necklaces'],7) + self.assertEqual(necklace_counts(8,3)['bracelets'],5) + + def test_unequal_digit_exclusion_and_bayes_upper_bound(self): + words=[0,0,0b11,0b11,0b100] + labels=[1,1,1,2,2] + result=pair_and_decoder_ledger(words,labels,4) + self.assertEqual(result['eligible'],6) + self.assertEqual(result['ordered']['distinguished'],5) + self.assertEqual(result['ordered']['in_sample_oracle_correct'],4) + for a,b in [('ordered','cyclic'),('cyclic','dihedral'),('dihedral','count')]: + self.assertGreaterEqual(result[a]['distinguished'],result[b]['distinguished']) + + def test_invalid_inputs(self): + with self.assertRaises(ValueError): bracelet(256,8) + with self.assertRaises(ValueError): necklace_counts(17,4) + with self.assertRaises(ValueError): pair_and_decoder_ledger([1],[1,2],4) + + @unittest.skipUnless(BUNDLE.is_file() and TRACE.is_file(), + 'native pinned LoopScope-02 JSON is not mounted locally') + def test_pinned_native_exact_dihedral_ledger(self): + old=load_and_verify() + import json + data=analyze(json.loads(BUNDLE.read_text()),json.loads(TRACE.read_text())) + self.assertEqual(data['model_checkpoint_sha256'],old['checkpoint_sha256']) + for T,expect in [('4',(1278,1244,1244,1244,23,18,18,18)), + ('8',(1414,1389,1389,1369,30,24,24,19)), + ('16',(1447,1428,1428,1422,31,26,26,24))]: + r=data['windows'][T]['S4_stalled']['all_64'] + self.assertEqual(tuple(r[k]['distinguished'] for k in ('ordered','cyclic','dihedral','count')) + + tuple(r[k]['in_sample_oracle_correct'] for k in ('ordered','cyclic','dihedral','count')),expect) + self.assertEqual(r['eligible'],1795) + +if __name__ == '__main__': unittest.main() From 71b815c68a6f5d6a48541797e60e9ed1e79ae8fe Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Sun, 15 Nov 2026 18:00:47 +0800 Subject: [PATCH 5/5] COE-07: optional device-aware native checkpoint replay with CPU protocol preserved --- .../phase_gauge07/DIHEDRAL_GAUGE_REPORT.md | 11 +++++++++++ mechinterp/phase_gauge07/run_native.py | 17 +++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md b/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md index 3eda7ffca..414b67949 100644 --- a/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md +++ b/mechinterp/phase_gauge07/DIHEDRAL_GAUGE_REPORT.md @@ -57,3 +57,14 @@ python -m mechinterp.phase_gauge07.dihedral_replay --out /tmp/coe07r_gauge.json The first command works with NumPy and no model checkpoint. Its source-file-dependent test runs inside a full repository checkout. The second command also checks the **Git blob SHA** of the two original native receipts. Both are pure CPU and use only standard-library arithmetic for the new code. **Hosted inference status:** On the COE-07 PR branch, GitHub Actions run `43699655642` failed in its preliminary `exact-unit` job before exposed step logs and skipped `native-pretrained`. Its second attempt failed identically. A successful native activation-probe result is therefore pending; no synthetic or truth-conditioned substitute is promoted into that role. + +## Optional local GPU extraction + +The default native runner retains the **pre-registered CPU float32** path. A device-aware patch also permits a secondary local GPU float32 run, preserving the same checkpoint SHA, source manifest, heads, and output receipts while tagging GPU evidence as exploratory: + +```sh +python -m mechinterp.phase_gauge07.run_native --device cuda --threads 4 --out ./coe07_native_gpu +python -m mechinterp.phase_gauge07.replay --input ./coe07_native_gpu/native_activations.npz --receipt ./coe07_native_gpu/receipt.json +``` + +The GPU replicate is an additional numerical sensitivity check and is reported separately from the CPU protocol. The GPU option has been syntax-tested locally, but a CUDA checkpoint replay requires a machine with the pinned model download and GPU runtime. diff --git a/mechinterp/phase_gauge07/run_native.py b/mechinterp/phase_gauge07/run_native.py index 6cfebd6e0..f090f5960 100644 --- a/mechinterp/phase_gauge07/run_native.py +++ b/mechinterp/phase_gauge07/run_native.py @@ -48,11 +48,12 @@ def capture(model, manifest: dict) -> tuple[dict[str,np.ndarray],dict]: projection_max_err=0.0 for group in STRATA: rows=manifest['strata'][group] - q=TS.encode_questions([r['question'] for r in rows],device='cpu') + device = next(model.parameters()).device + q=TS.encode_questions([r['question'] for r in rows],device=device) emb=model.encode_inputs(q) zh,zl=model.init_states(len(rows)) - digit_idx=torch.arange(len(rows)) - target=torch.tensor([r['target_idx'] for r in rows],dtype=torch.long)+model.puzzle_emb_len + digit_idx=torch.arange(len(rows),device=device) + target=torch.tensor([r['target_idx'] for r in rows],dtype=torch.long,device=device)+model.puzzle_emb_len rep_step={r:[] for r in REPS} accuracy=[] for step in range(VISITS): @@ -111,8 +112,12 @@ def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--out',type=Path,default=Path('mechinterp/phase_gauge07/output')) parser.add_argument('--threads',type=int,default=4) + parser.add_argument('--device',choices=('cpu','cuda'),default='cpu', + help='CPU float32 is the preregistered primary; CUDA float32 is an exploratory replication') p=parser.parse_args() if p.threads <1 or p.threads>16:raise ValueError('threads must be 1..16') + if p.device == 'cuda' and not torch.cuda.is_available(): + raise RuntimeError('CUDA requested but unavailable') torch.set_num_threads(p.threads) p.out.mkdir(parents=True,exist_ok=True) bundle=json.loads(BENCHMARK.read_text(encoding='utf8')) @@ -120,7 +125,7 @@ def main(): print('COE-07 manifest',manifest['manifest_sha256'],flush=True) (p.out/'manifest.json').write_text(json.dumps(manifest,indent=2,sort_keys=True)+'\n') # Runs the existing SHA-pinned checkpoint loader, not a synthetic imitation. - model,checkpoint_sha=TS.load_trm_checkpoint('gaoxin492','cpu',dtype=torch.float32) + model,checkpoint_sha=TS.load_trm_checkpoint('gaoxin492',p.device,dtype=torch.float32) if checkpoint_sha!=MODEL_SHA256:raise ValueError('hash mismatch') print('COE-07 verified native model SHA256',checkpoint_sha,flush=True) arrays,checks=capture(model,manifest) @@ -129,6 +134,10 @@ def main(): checks['numpy_version']=str(np.__version__) checks['platform']=platform.platform() checks['cpu_threads']=p.threads + checks['inference_device']=p.device + checks['inference_dtype']='float32' + checks['protocol_role']='preregistered_primary' if p.device == 'cpu' else 'exploratory_device_replication' + if p.device=='cuda': checks['cuda_name']=torch.cuda.get_device_name(torch.cuda.current_device()) checks['activation_sha256']={rep:hashlib.sha256(np.ascontiguousarray(arrays[rep]).tobytes()).hexdigest() for rep in REPS} del model