diff --git a/.github/workflows/coe01-chromatic-observers.yml b/.github/workflows/coe01-chromatic-observers.yml new file mode 100644 index 000000000..e33463faa --- /dev/null +++ b/.github/workflows/coe01-chromatic-observers.yml @@ -0,0 +1,29 @@ +name: COE-01 chromatic observer exact checks + +on: + pull_request: + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe01-chromatic-observers.yml' + push: + branches: [main] + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe01-chromatic-observers.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + exact-finite: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Check all finite certificates and extension tests + run: python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v + - name: Print pinned reference witnesses + run: python research/chromatic_observer_gym_v1/observer_codes.py diff --git a/.github/workflows/coe02-cut-observers.yml b/.github/workflows/coe02-cut-observers.yml new file mode 100644 index 000000000..7c48a48fa --- /dev/null +++ b/.github/workflows/coe02-cut-observers.yml @@ -0,0 +1,31 @@ +name: COE-02 exact cut observer tests + +on: + pull_request: + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe02-cut-observers.yml' + push: + branches: [main] + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe02-cut-observers.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + finite-cut-oracles: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Run cut BFS and independent word exhaustive tests + run: python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v + - name: Print frozen exact rational witness + run: python research/chromatic_observer_gym_v1/activation_case.py research/chromatic_observer_gym_v1/frozen_k5_onehot.json + - name: Print sharp code phase points + run: python research/chromatic_observer_gym_v1/l1_cut_codes.py diff --git a/.github/workflows/coe03-soft-observers.yml b/.github/workflows/coe03-soft-observers.yml new file mode 100644 index 000000000..9def009c1 --- /dev/null +++ b/.github/workflows/coe03-soft-observers.yml @@ -0,0 +1,31 @@ +name: COE-03 soft observer precision and depth checks + +on: + pull_request: + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe03-soft-observers.yml' + push: + branches: [main] + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe03-soft-observers.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + exact-finite-and-training: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: All COE-01/02/03 exact and CPU pilot tests + run: python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v + - name: Reproduce 1024-state rational witness + run: python research/chromatic_observer_gym_v1/soft_precision_codes.py + - name: Reproduce ten-seed synthetic linear probe pilot + run: python research/chromatic_observer_gym_v1/train_soft_probe.py diff --git a/.github/workflows/coe04-frozen-loop.yml b/.github/workflows/coe04-frozen-loop.yml new file mode 100644 index 000000000..fb88c1176 --- /dev/null +++ b/.github/workflows/coe04-frozen-loop.yml @@ -0,0 +1,38 @@ +name: COE-04 frozen tied-loop temporal observer checks + +on: + pull_request: + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe04-frozen-loop.yml' + push: + branches: [main] + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe04-frozen-loop.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + frozen-evaluator-replay: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Verify all chromatic observer and frozen temporal tests + run: python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v + - name: Print checkpoint provenance and all three SHA256 checks + run: | + python - <<'PY' + import sys + sys.path.insert(0, 'research/chromatic_observer_gym_v1') + from frozen_loader import verify_frozen + data, hashes = verify_frozen() + assert len(data['items']) == 3 + for entry in hashes: + print(entry) + PY diff --git a/.github/workflows/coe05-phase-order.yml b/.github/workflows/coe05-phase-order.yml new file mode 100644 index 000000000..b516f60b6 --- /dev/null +++ b/.github/workflows/coe05-phase-order.yml @@ -0,0 +1,54 @@ +name: COE-05 phase-order and clock-gauge certificates + +on: + pull_request: + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe05-phase-order.yml' + push: + branches: [main] + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe05-phase-order.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + finite-and-frozen: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Exact finite math and frozen-head evidence (no model downloads) + run: python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_phase_order.py' -v + - name: Replay new model cohort without torch + run: | + python research/chromatic_observer_gym_v1/phase_order_replay.py \ + --activation research/chromatic_observer_gym_v1/replication_activations.json.gz \ + --receipt research/chromatic_observer_gym_v1/new_fit_phase_receipt.json + - name: Recompute exhaustive fit-only search with NumPy + run: | + python -m pip install 'numpy==2.3.5' + python research/chromatic_observer_gym_v1/phase_order_search.py \ + --input research/chromatic_observer_gym_v1/replication_activations.json.gz \ + --out /tmp/coe05_recomputed.json + python - <<'PY' + import json + root='research/chromatic_observer_gym_v1/' + a=json.load(open(root+'new_fit_phase_receipt.json')) + b=json.load(open('/tmp/coe05_recomputed.json')) + for x,y in zip(a['records'],b['records']): + assert x['model_seed']==y['model_seed'] + assert x['candidate_count']==y['candidate_count'] + for key in ('primary_stable_order_head','comparative_best_total_head'): + for field in ('candidate_index','fit_stable_novel_edges', + 'fit_order_only_hits','fit_total_edge_hits', + 'heldout_order_only_hits','heldout_total_edge_hits', + 'heldout_count_only_hits','heldout_order_only_by_context'): + assert x[key][field]==y[key][field], (x['model_seed'],key,field) + print('Fit-only selection exactly recovered across independent CI runtime') + PY diff --git a/.github/workflows/coe06-phase-blind.yml b/.github/workflows/coe06-phase-blind.yml new file mode 100644 index 000000000..6a981819c --- /dev/null +++ b/.github/workflows/coe06-phase-blind.yml @@ -0,0 +1,42 @@ +name: COE-06 phase-invariant quantized observer and frozen replay + +on: + pull_request: + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe06-phase-blind.yml' + push: + branches: [main] + paths: + - 'research/chromatic_observer_gym_v1/**' + - '.github/workflows/coe06-phase-blind.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + orbit-and-frozen: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Replay exact cyclic code, resource bounds, and frozen heads + run: python -m unittest discover -s research/chromatic_observer_gym_v1 -p test_phase_blind.py -v + - name: Print exact finite phase-blind witness + run: python research/chromatic_observer_gym_v1/gauge_orbit_codes.py + - name: Confirm golden committed ledger from exhaustive integer enumeration + run: | + python research/chromatic_observer_gym_v1/resource_bound.py > /tmp/coe06-resource-preview.txt + python research/chromatic_observer_gym_v1/phase_gauge_replay.py \ + --activation research/chromatic_observer_gym_v1/replication_activations.json.gz \ + --receipt research/chromatic_observer_gym_v1/new_fit_phase_receipt.json \ + --out /tmp/coe06-gauge-replay.json + python - <<'PY' + import json + src='research/chromatic_observer_gym_v1/' + assert json.load(open('/tmp/coe06-gauge-replay.json')) == json.load(open(src+'COE06_GAUGE_REPLAY.json')) + print('Post-hoc frozen replay matches checked-in receipt') + PY diff --git a/research/chromatic_observer_gym_v1/COE02.md b/research/chromatic_observer_gym_v1/COE02.md new file mode 100644 index 000000000..54e6886fe --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE02.md @@ -0,0 +1,56 @@ +## COE-02: exact ℓ1 cut-capacity and quantization gap + +**November 15, 2026.** This extends COE-01 on the existing draft research branch. + +Each binary probe is an oriented cut of a finite sample of latent states. Its +pairwise Hamming contribution is a cut semimetric. The exact minimum binary +width under an `ell_1` Lipschitz constraint is therefore a nonnegative integer +cut-multiplicity covering problem with per-pair capacity constraints. The +companion [MathCan theorem and proof](https://github.com/patrickdugan/MathCan/blob/feat/coe01-chromatic-observer-20261115/research/compactification/CHROMATIC_CUT_CAPACITY.md) +explains the exactness, rational dual lower certificates and the sharp +unbounded gap between fractional cut-mass and physical binary coordinates. + +### Reproduce + +Run from this repository's root with Python 3.10+ and its standard library: + +```bash +python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v +python research/chromatic_observer_gym_v1/l1_cut_codes.py +python research/chromatic_observer_gym_v1/activation_case.py research/chromatic_observer_gym_v1/frozen_k5_onehot.json +``` + +The frozen fixture is a **synthetic**, rational five-state, five-feature +one-hot activation prototype with equilateral `ell_1` metric. It requires all +pairs distinguished. These are mathematical test states, not model activations. +The exact solver and a separate word-level exhaustive oracle agree across all +8 three-state evaluator graphs at `L=0,1,2` with Hamming margins 1 and 2. + +| Equilateral K5 evaluator | Minimum bits | Method | +| --- | ---: | --- | +| `ell_infinity`, Lipschitz `L=1` | 3 | COE-01 graph coloring | +| `ell_1`, `L=1` | infeasible | odd-cycle/cube-diameter obstruction | +| `ell_1`, `L=2` | 4 | exact cut BFS, sharp anticode theorem | +| `ell_1`, `L=3` | 3 | exact cut BFS and witness | +| fractional cut LP, `L=2` | 5/3 | balanced rational cut witness and dual | + +The integer/fractional ratio is `12/5` for K5 and grows on the order of `n/2` +for equilateral complete evaluators K_n. Fractional cut mass is only a +mathematical relaxation: its value does not measure the number of discrete +feature coordinates a network has learned. + +### Real activation adapter + +`activation_case.py` accepts a frozen JSON document with `format` set to +`coe02-activation-v1`, a list of states with unique `id` and equal-length +`activation` feature vectors (rational or decimal strings), `evaluator_edges` +of state-ID pairs, `lipschitz` (rational string), and `hamming_margin`. +The adapter computes the *exact rational feature-ell_1 metric* and compares the +COE-01 `ell_infinity` observer with the COE-02 `ell_1` optimum, preserving an +explicit provenance string. For larger datasets, prototype selection and the +evaluator split must be frozen before choosing probes. The exact method is +small-n exponential and raises when a resource guard is hit. + +Current evidence is synthetic and combinatorial. Model checkpoint extraction, +trained/held-out SAE probes, intervention response, and empirical mechanism +claims remain future verification gates. diff --git a/research/chromatic_observer_gym_v1/COE03.md b/research/chromatic_observer_gym_v1/COE03.md new file mode 100644 index 000000000..4658e4347 --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE03.md @@ -0,0 +1,31 @@ +# COE-03: precision/time observer capacity and controlled quantization pilot + +**Date:** 2026-11-15. Follows COE-01 and COE-02 on the existing draft PR. + +A finite equilateral `K_n` evaluator with ℓ1 output margin 1 and total output Lipschitz budget 2 requires `n-1` one-bit features. Its continuous scalar observer needs `Theta(log n)` feature dimensions, with an explicit small-amplitude construction. If those outputs must occupy a uniform `b`-bit grid while retaining `O(log n)` coordinates, the necessary and sufficient order of precision is `Theta(log log n)`. Reusing `w` binary output channels over T observable steps requires `w*T >= n-1` when the **whole transcript's total ℓ1 budget is 2**. Each theorem's hypotheses and proofs appear in [MathCan COE-03](https://github.com/patrickdugan/MathCan/blob/feat/coe01-chromatic-observer-20261115/research/compactification/SOFT_PRECISION_DEPTH.md). + +The construction has no dependence on the unverified deep proofs in its source-motivating OpenAI Math families 098 and 332. The finite metric is synthetic. The 10-bit outputs are numeric values, not 10 separate unit-amplitude Boolean probes. + +## Repeat all checks + +Python 3.10+ standard library suffices, from repository root: + +```sh +python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v +python research/chromatic_observer_gym_v1/soft_precision_codes.py +python research/chromatic_observer_gym_v1/train_soft_probe.py +``` + +The cumulative suite has 30 tests, including 9 new COE-03 cases. A `Random(2305)` 1,024-state, 256-head, ten-bit-grid code yields Hamming extrema `91,168` over all 523,776 pairs. The rational amplitude is `12/1023`, so minimum and maximum ℓ1 distances are exactly `364/341` and `672/341`. The deterministic code hash is pinned in the test. The binary equivalent requires 1,023 output channels under the **same** ℓ1 budget/margin conditions. These counts describe observer output dimension, not stored parameter or data bits. + +The K5 exact continuous three-feature certificate and all 64 coordinatewise threshold patterns are independently checked, along with a binary four-feature witness. The temporal reference packs an n-state one-hot transcript into `ceil((n-1)/w)` steps of width w, and checks the full transcript budget. + +An exploratory standard-library training pilot fits a three-output linear probe on five frozen one-hot states. It uses projected pairwise squared-hinge subgradients, seeds 0 to 9, a fixed learning rate and 4,000-step limit. Across ten runs with all ten edges used in training, 10/10 reach tolerance `1e-3`. Threshold at `0.5` yields zero valid binary K5 codes. An exploratory seven-edge train/three-edge withheld evaluation gives 10/10 train and 2/10 withheld passes. The held-out split was explored before commitment; these proportions are diagnostic, not model generalization statistics. Test replay checks them under Python 3.12 CI. + +### Work that remains + +- Compare a named frozen looped-transformer or SAE checkpoint after extracting latent activation vectors and independently measured evaluator edges. +- Establish a blinded train/test task split before modeling, with quantized and unquantized head budgets fixed. +- Separate observer width, bit precision, wall time and full-transcript memory during recurrent inference. + +Only synthetic finite codes and the specified CPU training pilot have been executed. diff --git a/research/chromatic_observer_gym_v1/COE03_RECEIPT.json b/research/chromatic_observer_gym_v1/COE03_RECEIPT.json new file mode 100644 index 000000000..6cb241f0d --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE03_RECEIPT.json @@ -0,0 +1,96 @@ +{ + "exploratory_seven_train_three_withheld": { + "seeds": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "steps": [ + 35, + 13, + 68, + 56, + 44, + 27, + 10, + 38, + 39, + 23 + ], + "train_fit_count": 10, + "withheld_edges": [ + [ + 0, + 4 + ], + [ + 1, + 3 + ], + [ + 2, + 4 + ] + ], + "withheld_fit_count": 2 + }, + "format": "coe03-frozen-receipt-v1", + "rational_reference": { + "binary_one_shot_min_channels": 1023, + "demo_amplitude": "4/341", + "demo_digest": "2a99809deb1babd57d9d10e959775429470fafa90d390331b6d82f6f581dd5eb", + "demo_grid_bits": 10, + "demo_hamming_max": 168, + "demo_hamming_min": 91, + "demo_l1_max": "672/341", + "demo_l1_min": "364/341", + "demo_seed": 2305, + "demo_soft_channels": 256, + "demo_states": 1024, + "format": "coe03-reference-v1", + "mux_n17_k4_rounds": 4, + "provenance": "deterministic synthetic, not checkpoint activations", + "soft_k5_pairwise_distances": [ + "1", + "2", + "4/3" + ], + "soft_k5_width": 3 + }, + "synthetic_only": true, + "training_all_ten_pairs": { + "seeds": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + "soft_fit_count": 10, + "steps": [ + 51, + 47, + 41, + 77, + 42, + 51, + 46, + 56, + 158, + 235 + ], + "threshold_half_fit_count": 0 + } +} diff --git a/research/chromatic_observer_gym_v1/COE04.md b/research/chromatic_observer_gym_v1/COE04.md new file mode 100644 index 000000000..098e5d517 --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE04.md @@ -0,0 +1,74 @@ +# COE-04: measured recurrent quantizer capacity on frozen tied attention + +**Executed:** 2026-11-15. **Status:** CPU-trained small causal-attention checkpoint, frozen before probe fitting, with exact offline replay. Companion mathematical theorem in `patrickdugan/MathCan/research/compactification/TEMPORAL_OBSERVER_CAPACITY.md`. + +## Why this experiment + +COE-01 to COE-03 show that symbolic observer width depends on evaluator edges, metric constraints, precision and the distinction between soft and binary cuts. COE-04 asks whether successive residual states of one *frozen shared-weight attention model* can supply useful binary features from **one tied readout**, and whether that benefit survives a matched total-bit comparison. + +The source design follows the pre-norm, tied-block causal visit-state equations in `MoralityLabAI/LoopedTransformers/research_gym/neural/looped_decoder.py`: a 24-dimensional two-token embedding, three attention heads, one physical shared block, pre-norm attention plus GELU MLP, four unrolled visits, `alpha=1`, `beta=0.7`. `run_frozen_loop.py` is an independently executable small implementation. This is a **locally trained synthetic checkpoint**, rather than the external TRM, Huginn or Nanbeige weights discussed in LoopedTransformers. We examined their public experiment receipts; the current environment had no directly loadable pretrained model-weight artifact. + +## Frozen task and split + +The training task is to copy the first symbol `a` from input `(a,b)` with `a,b in {0,...,7}` into the model's final-token logits. Every one of the 64 symbolic pairs is trained for 160 full-batch AdamW steps at fixed learning rate `0.01`, with independently fixed random seeds `2406,2407,2408`. This is a small supervised associative task; it is **not a held-out language task**. All 64 predictions were correct for each seed before probes were selected. The model weights were frozen and replayed to produce hidden states of shape `[64,4,24]` per seed. + +For the *separate probe fit*, distractor contexts `b in {0,1,2,3}` form the training set; contexts `{4,5,6,7}` are held out. The evaluator graph `K8` is fixed by the source-token identity `a`, independently from readout codes. At each held-out context, the 28 unordered pairs of different source labels are the required distinctions. Each seed therefore has exactly 112 held-out evaluator pairs. + +A shared readout is one fixed linear threshold `(w,theta)` applied at the query-token residual on visits 1,2,3,4, giving a four-bit transcript. `temporal_observers.py` generates a deterministic pool of hyperplanes from *probe fitting data alone*, maximizes the number of correctly distinguished training pairs, then evaluates the unchanged head on heldout contexts. The last-visit 1-bit baseline uses the same candidate family and selection objective. The final 4-bit control greedily chooses four readouts only from the fitting data; an untied per-visit control chooses four separate heads. Each result is evaluated on identical held-out contexts. Selected heads and raw integer counts are stored in JSON receipts. + +### Source provenance and exact replay + +- Synthetic model source: `MoralityLabAI/LoopedTransformers` `research_gym/neural/looped_decoder.py` at source commit `bb51f116acf7ebd4a8f337ec9ab54475f3e0cb1d` (November 15, 2026). This self-contained reproduction follows its tied pre-norm block equations and causal attention. It is not an invocation of the upstream class. +- Training runtime: Python 3.13, `torch 2.10.0+cpu`, deterministic CPU operations, one thread. +- `frozen_loop_weights.json.gz` and `frozen_loop_activations.json.gz` store all three original unrounded float32 weight arrays and all 768 residual vectors. +- Source checkpoint SHA256 values (canonical JSON of each state_dict): `2406`: `13b9c3c63f7d7d27ef9aac2144fd2dd5469e144d940bee97e0a975a38e1d1841`; `2407`: `46a99c7a348d2d0250ff9f7289ed2c3078cd847f506a65941d24dd5213e217ee`; `2408`: `5bb8809a753e08f5ade9f3ff40b3ec50cecdb2aa8085c3a2624506d201196a88`. +- Optional torch audit reloads the frozen weights and obtains every stored residual to *exactly zero absolute difference* under the original CPU environment; no probe training is involved in this audit. +- CI runs the Python standard-library verifier against compressed artifacts, signed fit-only readout vectors, full held-out evaluator enumeration, train/test split integrity, tied transducer constructions and integer code optimality cells. The costly upstream checkpoint regeneration is optional (`python run_frozen_loop.py`, then `python audit_model_alignment.py`). + +## Primary measurements + +| Seed | Last visit, 1 bit | Tied head, 1 bit × 4 visits | Tied head, 2-bit uniform quantization × 4 | Final, 4 independently fitted bits | Untied heads, 1 bit × 4 visits | +| --- | ---: | ---: | ---: | ---: | ---: | +| 2406 | 64/112 | **90/112** | 102/112 | 112/112 | 105/112 | +| 2407 | 62/112 | **72/112** | 86/112 | 106/112 | 111/112 | +| 2408 | 61/112 | **79/112** | 97/112 | 111/112 | 111/112 | +| Pooled | **187/336 = 55.65%** | **241/336 = 71.73%** | **285/336 = 84.82%** | **329/336 = 97.92%** | **327/336 = 97.32%** | + +The repeated-last snapshot control gives exactly the same edge retention as last visit 1-bit; repeating a frozen bit cannot increase its distinctions. The tied temporal observer beats that per-tick baseline for all three model seeds. Under the **matched total output-bit bandwidth** of four, a final-layer readout with four independent heads performs much better. A temporal tied head has one fitted direction whereas the four-head final baseline has four, and four temporal observations require storing a four-bit history. These are different engineering budgets and are reported separately. + +### Post-hoc diagnostics, executed without refitting on held-out data + +1. **Count-only collapse.** For every selected tied one-bit head on each seed, reducing its four ordered observations to the count of positive readings preserves *exactly the same* held-out edge set: `90,72,79` hits. The order provides **zero additional pairwise distinctions** in these cells. This narrows the interpretation of the temporal benefit to a coarse crossing-count signal. In the general theorem, a count-only `T=4` bit observer has at most five possible output categories, compared with 16 distinct ordered histories. For an eight-state complete evaluator it can preserve at most `25/28` edges per context. These finite observations fall below that bound. +2. **Hard Hamming diameter-two constraint.** The main temporal heads reach a maximum pairwise Hamming distance of **four**, and therefore do not satisfy the COE-02 global diameter-two condition. A separate fit-only re-selection imposed `d_H <= 2` for all training evaluator pairs. Three resulting probe heads retained `79,59,74` held-out edges respectively, and also respected maximum diameter two on all held-out contexts. `cap2_receipt.json` stores the independently scored witnesses. This is explicitly post-hoc. +3. **Layer separation.** Across held-out evaluator pairs, mean Euclidean separation increases with visit depth in all three local checkpoints (seed 2406: `11.47,26.89,43.74,60.96`; seed 2407: `11.85,26.70,42.28,58.04`; seed 2408: `14.52,32.72,51.88,71.28`). These data do not establish an alpha-contractive recurrence, so the common-fixed-point late-observation theorem does not apply to this run. +4. **One-bit final versus temporal precision.** A two-bit quantizer fitted with the same temporal direction achieves `102,86,97` hits; the final-step two-bit baseline achieves `82,83,83`. Its quantization bins were calibrated on training data alone. Comparisons of bits and readout parameters remain separate. + +## Model and proof separation + +The task-domain labels are known during fitting, and all contexts appeared during base-model training. This checks **probe generalization across contexts on a fixed small synthetic model**, rather than generalization of a pretrained model to unfamiliar tasks or causal control of a trained language model. There are three model seeds and the evaluated pair indicators are correlated; pooled fractions are descriptive, with no independence-based p-values. A learned threshold readout is an observational probe and does not establish causal necessity. The metric-budget theorem is a conditional property of the codes; its hypotheses are not silently asserted of the unconstrained trained heads. + +## Reproduce + +From the Compactification-Theory root, standard library Python 3.10+: + +```bash +python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v +``` + +Regenerate the probe receipts from the frozen states (CPU, standard library only): + +```bash +cd research/chromatic_observer_gym_v1 +python temporal_observers.py --input frozen_loop_activations.json.gz --out /tmp/coe04_temporal.json +python run_temporal_baselines.py --input frozen_loop_activations.json.gz --out /tmp/coe04_equal.json +python run_cap2_control.py --input frozen_loop_activations.json.gz --out /tmp/coe04_cap2.json +``` + +Optional CPU torch replay (`torch 2.10.0+cpu` is the reference version): + +```bash +python run_frozen_loop.py --out frozen_loop_activations.json +python audit_model_alignment.py +``` + +The regeneration script overwrites uncompressed local outputs only; review hashes before updating frozen Git artifacts. The references to native LoopedTransformers are architecture/provenance links; this study does not claim checkpoints were downloaded from or trained by that repository. diff --git a/research/chromatic_observer_gym_v1/COE05.md b/research/chromatic_observer_gym_v1/COE05.md new file mode 100644 index 000000000..fe552cd21 --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE05.md @@ -0,0 +1,93 @@ +# COE-05: does a recurrent one-bit head encode the order of its visits? + +**Executed:** 2026-11-15. **Scope:** six small CPU-trained frozen synthetic causal-attention models, exact phase-code control, deterministic reproducibility. **Primary status:** exploratory observational probe experiment and constructive mathematical positive control. No pretrained TRM, Huginn, Nanbeige, or Qwen weights were loaded. + +Companion formal note: [MathCan PHASE_GAUGE_CAPACITY.md](https://github.com/patrickdugan/MathCan/blob/feat/coe01-chromatic-observer-20261115/research/compactification/PHASE_GAUGE_CAPACITY.md). + +## Scientific question + +COE-04 showed that the four-tick transcript of a shared, frozen one-bit threshold head improved evaluator separation over a one-bit final-only head. Yet the selected transcripts were no more informative than their **positive-bit count**. COE-05 asks whether selecting for an order-specific gain helps on unseen probe contexts. An independent exact cyclic-register model is used as a test of whether the proposed phase mechanism is mathematically possible at all. + +For a chosen head `h=(w,theta)`, let `c(a,b)` denote its four-bit transcript across tied visits for source label `a` and distractor context `b`. Define + +`order_only(u,v,b) := [c(u,b) != c(v,b)] AND [popcount(c(u,b)) = popcount(c(v,b))]`. + +This predicate measures exactly those evaluator pairs distinguished by the **sequence** but merged by a count-only observer. Ordinary temporal separation is the disjoint union of count-separated pairs and order-only pairs. + +## Provenance and experimental design + +The base model implementation is `run_frozen_loop.py` from COE-04: a shared pre-norm causal multihead-attention block, four visits, two tokens, residual dimension 24 and three heads. It was adapted from the tied-visit equations in `MoralityLabAI/LoopedTransformers/research_gym/neural/looped_decoder.py` and is **not** a load of the external LoopedTransformers model weights. + +- COE-04 model seeds `2406,2407,2408`: frozen and evaluated in the previous study. **Retrospective diagnostic cohort**, because their prior heldout contexts had already been inspected. +- New independent initialization seeds `2411,2412,2413`: each trained for the same `160` deterministic, full-batch AdamW steps on `64` synthetic `(source,distractor)` inputs, then frozen. All `64/64` first-token copy predictions succeeded before probe fitting. The model and probe tasks still share those 64 base inputs; the context holdout is for the *probe*, not the base model. +- Probe fitting receives contexts `b=0..3`, evaluation receives contexts `b=4..7`; the complete `K8` evaluator has `4*28=112` edge-tests per heldout model. This split, along with the fitter's deterministic candidates, is inherited from COE-04. The earlier negative result helped motivate the new head-selection objective, so this is **exploratory**, not a preregistered confirmatory result. +- Candidate generation is exactly the earlier `candidate_projections` list: fit-only between-class mean directions, fixed-seed random directions, thresholds from fit-only projection quantiles and per-label means. The selected head maximizes the lexicographically ordered tuple `(number of order-only edges present in at least two fit contexts, total order-only fit hits, all fit hits, -candidate index)`. Ties are resolved solely by the fit data and original candidate position. +- The `comparative_best_total_head` in each record is the same-pool head maximizing `(fit_all_hits, fit_order_only_hits, -candidate_index)`. + +`phase_order_search.py` reruns exhaustive fit-only selection with NumPy for speed. `phase_order_replay.py` uses **only the Python standard library** to recompute every reported fit and heldout metric from the immutable selected head and frozen activation values. The input weights and activations are separately committed as gzip files for the new cohort; weight SHA-256s are verified against the stored model state dictionaries, without requiring Torch for replay. All original float32 weight arrays and all 64×4×24 activations per new model are retained. + +## Heldout outcomes + +| Cohort | Seed | Ordered edge hits /112 | Count-only hits /112 | Order-only gain /112 | +| --- | ---: | ---: | ---: | ---: | +| Previous (retrospective) | 2406 | 37 | 37 | 0 | +| Previous (retrospective) | 2407 | 69 | 69 | 0 | +| Previous (retrospective) | 2408 | 84 | 83 | 1 | +| **New model initialization** | **2411** | **82** | **78** | **4** | +| **New model initialization** | **2412** | **70** | **69** | **1** | +| **New model initialization** | **2413** | **91** | **86** | **5** | +| New cohort pooled | | **243/336** | **233/336** | **10/336** | + +A phase-sensitive signal appears in the new cohort, but the gain from ordered history is **2.98 percentage points** of the total evaluated pairs. The selected head commonly loses evaluator distinctions compared with the head selected to maximize *total* fit coverage. No model-level statistical significance is assigned from three seeds or from correlated evaluator edges. + +**Falsification boundary.** The new synthetic result does not demonstrate that larger *pretrained* recurrent transformers exploit noncommutative visit order. The external pretrained model weights were absent from this sandbox. Earlier LoopedTransformers summaries contain measurements and model tags but do not supply the exact raw residual sequences needed for a new probe fit. A native-pretrained execution will require pinned checkpoint and dataset hashes, pre-registered evaluator edges, per-visit latent traces, and exact group-disjoint probe splits; see the final section. + +## Exact constructive positive control: an eight-visit affine-plane clock + +The companion `phase_register.py` implements the time-independent map `R(word)=rotate_right_8(word)` and the tied readout `p(word)=word&1`. Each of the fourteen initial eight-bit registers is the indicator of one affine hyperplane in `F2^3`. This is a classical `S(3,4,8)` code. Each register contains exactly four one-bits, and every two distinct registers differ in at least four positions. + +The exact oracle verifies: + +- **91/91** K14 evaluator edges separated by the eight-bit *ordered* history, and **0/91** separated by the count-only observation (every count is four). +- **112/112** independently injected single-bit flips recovered uniquely by nearest-codeword decoding. These are all 14 labels × all eight flip positions. +- All **56** possible three-element subsets of the eight positions occur exactly once among the four-element supports. This meets the `14`-code upper bound from triple counting, while a seven-visit constant-count one-flip code can carry at most **seven** labels. The eight-visit construction is therefore sharp for 14 labels. +- Under an unknown uniformly random cyclic phase *per example*, the codebook falls into only **four** rotation orbits of sizes `[2,4,4,4]`. Its optimal noiseless uniform-prior label decoder falls from `14/14` to **`4/14`** accuracy. For count-only decoding the accuracy is `1/14`. + +This phase-orbit result is a **clock-calibration obstruction**: a capable ordered observer can depend on knowing which repeated application was the first. The cyclic-register system is deliberately constructed; its results are *capacity witnesses*, not measurements on the trained tied-attention models. + +## Reproduce + +From the Compactification-Theory repository root: + +```bash +python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v +python research/chromatic_observer_gym_v1/phase_order_replay.py \ + --activation research/chromatic_observer_gym_v1/replication_activations.json.gz \ + --receipt research/chromatic_observer_gym_v1/new_fit_phase_receipt.json +python research/chromatic_observer_gym_v1/phase_register.py +``` + +Re-run the exhaustive fit-only head selection (requires NumPy 2.x; CI pins it): + +```bash +python research/chromatic_observer_gym_v1/phase_order_search.py \ + --input research/chromatic_observer_gym_v1/replication_activations.json.gz \ + --out /tmp/coe05_selection.json +``` + +Regenerate the independent model seeds and their frozen weights (optional; requires CPU PyTorch as in COE-04): + +```bash +python research/chromatic_observer_gym_v1/freeze_replication.py +``` + +The provided artifact hashes lock the exact data used for the reported result: + +- `replication_activations.json.gz`: SHA256 `4a5c72532881c7b0f6d9d20bd006b5c50bed5ee65e815d3650746c2fed97cdc0`. +- `replication_weights.json.gz`: SHA256 `5c68678b33e9fb5a57890d4d43e56273573416470f085a6d7fa4095440a10097`. + +## Next native-pretrained gate + +Use the existing `MoralityLabAI/LoopedTransformers` LoopScope checkpoint capture machinery. Freeze one checkpoint and a group-disjoint board/task split before probing. Extract the **same residual site** for eight or more visit indices, with input identity, evaluator-pair label, final behavioral correctness, model checkpoint SHA and provenance recorded. Compare ordered-bit separation, count-only separation, unknown-phase control, and matched eight-bit final readouts on heldout groups. The evaluator should use independent causal or task-output evidence rather than the labels of a newly fitted probe. Keep unsolved or base-model-failed items in a separately reported stratum; a probe reading without task behavior has a different interpretation. + +The proof manuscript and Lean exact-code certificates live in [MathCan PR #47](https://github.com/patrickdugan/MathCan/pull/47). The synthetic experiment and immutable witnesses live in [Compactification-Theory PR #143](https://github.com/MoralityLabAI/Compactification-Theory/pull/143). diff --git a/research/chromatic_observer_gym_v1/COE06.md b/research/chromatic_observer_gym_v1/COE06.md new file mode 100644 index 000000000..728e180b8 --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE06.md @@ -0,0 +1,34 @@ +# COE-06: phase-blind observers, clock gauge, and a sharp 21-label certificate + +**Research date:** 2026-11-15. The frozen-model study and the mathematical positive control are independent components. The first is a post-hoc read-only diagnostic on six context groups from COE-05; the second gives a fully explicit finite coding theorem under an unknown cyclic starting phase. + +## Applied measurement + +On held-out contexts 4–7 for the frozen synthetic tied-attention models 2411, 2412 and 2413, the selected fixed heads distinguish 243/336 ordered evaluator pairs. Canonicalizing each four-bit history under cyclic rotation reduces this to 233/336, identical to positive-count-only distinction. All ten additional order-sensitive hits were phase-origin-sensitive. The source activation and fit-only head receipts remain immutable and are validated by `phase_gauge_replay.py`. + +The new mathematical positive control uses a **14-bit cyclic register**, one fixed low-bit readout and fourteen iterations. Its codebook has **21 labels**, constant Hamming weight six, and minimum inter-orbit Hamming distance four. Every cyclicly shifted input with zero or one corrupted bit is uniquely decoded: 3,885 of 3,885 exact cases. The count-only observer separates none of 210 label pairs. + +## Sharp width certificate + +The [pure math proof in MathCan](https://github.com/patrickdugan/MathCan/blob/feat/coe01-chromatic-observer-20261115/research/compactification/PHASE_BLIND_OBSERVER_CAPACITY.md) uses disjoint necklace classes of deleted `(w−1)`-subsets to bound the maximum phase-invariant code size. Exact exhaustive counting across `T=1..13` gives an upper bound of **17** labels for any length at most thirteen. Consequently fourteen visits are necessary and sufficient for 21 constant-weight labels robust to one flip with unknown phase. This is a theorem in the specified abstract coding model, not an empirical measure of transformer capacity. + +The all-width finite counting proof uses only integer masks and combinatorics; the 14-visit witness is checked by independent brute-force distance, rotation and corruption loops. Lean checks the specific codewords and arithmetic budget consequences, while the written proof covers the general deletion-resource theorem. Source papers OpenAI Math #098 and #332 motivate task-relative compactification and stable observation; neither is assumed as an axiom. + +## Reproduction + +From the repo root: + +```bash +python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_phase_blind.py' -v +python research/chromatic_observer_gym_v1/gauge_orbit_codes.py +python research/chromatic_observer_gym_v1/resource_bound.py +python research/chromatic_observer_gym_v1/phase_gauge_replay.py \ + --activation research/chromatic_observer_gym_v1/replication_activations.json.gz \ + --receipt research/chromatic_observer_gym_v1/new_fit_phase_receipt.json +``` + +CI uses Python 3.12 with standard-library-only tests. Frozen weights and activation files were already committed in COE-05 and are reused without modification. No pretrained transformer weights were loaded or downloaded in COE-06. + +## Scope + +The cycle-register witness is a deterministic mechanism whose information survives unknown phase. The trained four-step attention models do not demonstrate that mechanism, and the phase-invariant quotient removes their observed order-only gains. The correct next experimental test uses native pinned LoopedTransformers or LoopScope checkpoints with eight or more stored visits, preregistered evaluator labels, and frozen group-disjoint probe splits. diff --git a/research/chromatic_observer_gym_v1/COE06_BOUND_LEDGER.json b/research/chromatic_observer_gym_v1/COE06_BOUND_LEDGER.json new file mode 100644 index 000000000..cd490ada6 --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE06_BOUND_LEDGER.json @@ -0,0 +1,614 @@ +[ + { + "T": 1, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 2, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 2, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 3, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 3, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 4, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 4, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 4, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 2 + }, + "w": 2 + }, + { + "T": 5, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 5, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 5, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 2 + }, + "w": 2 + }, + { + "T": 6, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 6, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 6, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 3 + }, + "w": 2 + }, + { + "T": 6, + "bound": 2, + "combined_bound": 2, + "complement_bound": 2, + "total_resources": 3, + "usage_counts": { + "1": 1, + "2": 1, + "3": 2 + }, + "w": 3 + }, + { + "T": 7, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 7, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 7, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 3 + }, + "w": 2 + }, + { + "T": 7, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 3, + "usage_counts": { + "2": 3, + "3": 2 + }, + "w": 3 + }, + { + "T": 8, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 8, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 8, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 4 + }, + "w": 2 + }, + { + "T": 8, + "bound": 2, + "combined_bound": 2, + "complement_bound": 2, + "total_resources": 4, + "usage_counts": { + "2": 3, + "3": 4 + }, + "w": 3 + }, + { + "T": 8, + "bound": 3, + "combined_bound": 3, + "complement_bound": 3, + "total_resources": 7, + "usage_counts": { + "1": 1, + "2": 1, + "3": 2, + "4": 6 + }, + "w": 4 + }, + { + "T": 9, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 9, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 9, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 4 + }, + "w": 2 + }, + { + "T": 9, + "bound": 2, + "combined_bound": 2, + "complement_bound": 3, + "total_resources": 4, + "usage_counts": { + "1": 1, + "2": 3, + "3": 6 + }, + "w": 3 + }, + { + "T": 9, + "bound": 3, + "combined_bound": 3, + "complement_bound": 3, + "total_resources": 10, + "usage_counts": { + "3": 3, + "4": 11 + }, + "w": 4 + }, + { + "T": 10, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 10, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 10, + "bound": 1, + "combined_bound": 1, + "complement_bound": 2, + "total_resources": 1, + "usage_counts": { + "1": 5 + }, + "w": 2 + }, + { + "T": 10, + "bound": 2, + "combined_bound": 2, + "complement_bound": 3, + "total_resources": 5, + "usage_counts": { + "2": 4, + "3": 8 + }, + "w": 3 + }, + { + "T": 10, + "bound": 5, + "combined_bound": 5, + "complement_bound": 5, + "total_resources": 12, + "usage_counts": { + "2": 3, + "3": 2, + "4": 17 + }, + "w": 4 + }, + { + "T": 10, + "bound": 5, + "combined_bound": 5, + "complement_bound": 5, + "total_resources": 22, + "usage_counts": { + "1": 1, + "4": 2, + "5": 23 + }, + "w": 5 + }, + { + "T": 11, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 11, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 11, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 5 + }, + "w": 2 + }, + { + "T": 11, + "bound": 2, + "combined_bound": 2, + "complement_bound": 4, + "total_resources": 5, + "usage_counts": { + "2": 5, + "3": 10 + }, + "w": 3 + }, + { + "T": 11, + "bound": 5, + "combined_bound": 5, + "complement_bound": 6, + "total_resources": 15, + "usage_counts": { + "3": 5, + "4": 25 + }, + "w": 4 + }, + { + "T": 11, + "bound": 7, + "combined_bound": 7, + "complement_bound": 7, + "total_resources": 30, + "usage_counts": { + "4": 5, + "5": 37 + }, + "w": 5 + }, + { + "T": 12, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 12, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 12, + "bound": 1, + "combined_bound": 1, + "complement_bound": 2, + "total_resources": 1, + "usage_counts": { + "1": 6 + }, + "w": 2 + }, + { + "T": 12, + "bound": 3, + "combined_bound": 3, + "complement_bound": 5, + "total_resources": 6, + "usage_counts": { + "1": 1, + "2": 4, + "3": 14 + }, + "w": 3 + }, + { + "T": 12, + "bound": 7, + "combined_bound": 7, + "complement_bound": 10, + "total_resources": 19, + "usage_counts": { + "1": 1, + "2": 2, + "3": 3, + "4": 37 + }, + "w": 4 + }, + { + "T": 12, + "bound": 9, + "combined_bound": 9, + "complement_bound": 12, + "total_resources": 43, + "usage_counts": { + "3": 1, + "4": 4, + "5": 61 + }, + "w": 5 + }, + { + "T": 12, + "bound": 14, + "combined_bound": 14, + "complement_bound": 14, + "total_resources": 66, + "usage_counts": { + "1": 1, + "2": 1, + "3": 3, + "5": 4, + "6": 71 + }, + "w": 6 + }, + { + "T": 13, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 0, + "usage_counts": {}, + "w": 0 + }, + { + "T": 13, + "bound": 1, + "combined_bound": 1, + "complement_bound": 1, + "total_resources": 1, + "usage_counts": { + "1": 1 + }, + "w": 1 + }, + { + "T": 13, + "bound": 1, + "combined_bound": 1, + "complement_bound": 2, + "total_resources": 1, + "usage_counts": { + "1": 6 + }, + "w": 2 + }, + { + "T": 13, + "bound": 3, + "combined_bound": 3, + "complement_bound": 6, + "total_resources": 6, + "usage_counts": { + "2": 6, + "3": 16 + }, + "w": 3 + }, + { + "T": 13, + "bound": 7, + "combined_bound": 7, + "complement_bound": 11, + "total_resources": 22, + "usage_counts": { + "3": 6, + "4": 49 + }, + "w": 4 + }, + { + "T": 13, + "bound": 12, + "combined_bound": 12, + "complement_bound": 17, + "total_resources": 55, + "usage_counts": { + "4": 6, + "5": 93 + }, + "w": 5 + }, + { + "T": 13, + "bound": 17, + "combined_bound": 17, + "complement_bound": 19, + "total_resources": 99, + "usage_counts": { + "5": 6, + "6": 126 + }, + "w": 6 + } +] diff --git a/research/chromatic_observer_gym_v1/COE06_GAUGE_REPLAY.json b/research/chromatic_observer_gym_v1/COE06_GAUGE_REPLAY.json new file mode 100644 index 000000000..6854b0399 --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE06_GAUGE_REPLAY.json @@ -0,0 +1,127 @@ +{ + "cohort_results": [ + { + "context_details": [ + { + "context": 4, + "distinct_codes": 3, + "distinct_counts": 3, + "distinct_necklaces": 3 + }, + { + "context": 5, + "distinct_codes": 4, + "distinct_counts": 4, + "distinct_necklaces": 4 + }, + { + "context": 6, + "distinct_codes": 4, + "distinct_counts": 3, + "distinct_necklaces": 3 + }, + { + "context": 7, + "distinct_codes": 4, + "distinct_counts": 3, + "distinct_necklaces": 3 + } + ], + "count": 78, + "cyclic": 78, + "cyclic_beyond_count": 0, + "denominator": 112, + "model_checkpoint_sha256": "bfebe1d7c15fc61b0516a93fd82ffa9a34ade170c62dca48734a27a9934c8c3e", + "model_seed": 2411, + "order_only": 4, + "ordered": 82, + "phase_sensitive_only": 4 + }, + { + "context_details": [ + { + "context": 4, + "distinct_codes": 3, + "distinct_counts": 3, + "distinct_necklaces": 3 + }, + { + "context": 5, + "distinct_codes": 4, + "distinct_counts": 3, + "distinct_necklaces": 3 + }, + { + "context": 6, + "distinct_codes": 3, + "distinct_counts": 3, + "distinct_necklaces": 3 + }, + { + "context": 7, + "distinct_codes": 2, + "distinct_counts": 2, + "distinct_necklaces": 2 + } + ], + "count": 69, + "cyclic": 69, + "cyclic_beyond_count": 0, + "denominator": 112, + "model_checkpoint_sha256": "2af2207f5e56a09154122026c7e27ff1c74b7d682b98457a202ba2aba87a878f", + "model_seed": 2412, + "order_only": 1, + "ordered": 70, + "phase_sensitive_only": 1 + }, + { + "context_details": [ + { + "context": 4, + "distinct_codes": 5, + "distinct_counts": 4, + "distinct_necklaces": 4 + }, + { + "context": 5, + "distinct_codes": 5, + "distinct_counts": 4, + "distinct_necklaces": 4 + }, + { + "context": 6, + "distinct_codes": 4, + "distinct_counts": 3, + "distinct_necklaces": 3 + }, + { + "context": 7, + "distinct_codes": 4, + "distinct_counts": 4, + "distinct_necklaces": 4 + } + ], + "count": 86, + "cyclic": 86, + "cyclic_beyond_count": 0, + "denominator": 112, + "model_checkpoint_sha256": "cf3a08068a13f52ab87f0123cc03b4fb352e409642bc229e81e49919fcc91e83", + "model_seed": 2413, + "order_only": 5, + "ordered": 91, + "phase_sensitive_only": 5 + } + ], + "interpretation": "post-hoc on fit-only selected COE-05 heads; no new fitting", + "pooled": { + "count": 233, + "cyclic": 233, + "cyclic_beyond_count": 0, + "denominator": 336, + "order_only": 10, + "ordered": 243, + "phase_sensitive_only": 10 + }, + "schema": "COE-06-posthoc-frozen-phase-gauge-v1", + "source_schema": "COE-05-fit-only-phase-probe-exploratory-v1" +} diff --git a/research/chromatic_observer_gym_v1/COE06_RECEIPT.json b/research/chromatic_observer_gym_v1/COE06_RECEIPT.json new file mode 100644 index 000000000..cea0f717b --- /dev/null +++ b/research/chromatic_observer_gym_v1/COE06_RECEIPT.json @@ -0,0 +1,46 @@ +{ + "codebook": [ + 207, + 243, + 311, + 473, + 543, + 629, + 697, + 811, + 851, + 903, + 1133, + 1175, + 1337, + 1351, + 1419, + 1445, + 1587, + 1677, + 1865, + 2451, + 2709 + ], + "count_only_pairwise_distinctions": 0, + "cross_orbit_distance_min": 4, + "distinct_necklaces": 21, + "labels": 21, + "noiseless_and_single_flip_decoded": 3885, + "noiseless_and_single_flip_total": 3885, + "orbit_sizes": [ + [ + 7, + 5 + ], + [ + 14, + 16 + ] + ], + "ordered_orbit_pairwise_distinctions": 210, + "pairwise_orbit_comparisons": 210, + "schema": "COE-06-clock-invariant-single-flip-v1", + "weight": 6, + "width": 14 +} diff --git a/research/chromatic_observer_gym_v1/README.md b/research/chromatic_observer_gym_v1/README.md new file mode 100644 index 000000000..ee7307245 --- /dev/null +++ b/research/chromatic_observer_gym_v1/README.md @@ -0,0 +1,72 @@ +# COE-01: evaluator-graph chromatic compactification gym + +**2026-11-15. Research stage:** exact synthetic finite benchmark, without a trained transformer or SAE result. + +Inspired by two distinct mathematical mechanisms from the October OpenAI collection: + +- [Family 098](https://github.com/openai/math/blob/4eaee87548250b2682affda7d05d947c05554bae/lean/docs/098.md): globally bi-Lipschitz faithful embedding of certain compact doubling Hilbert sets into finite-dimensional spaces fails. +- [Family 332](https://github.com/openai/math/blob/4eaee87548250b2682affda7d05d947c05554bae/preprints/Metric-Markov-Cotype-Two-of-l1-October-5-2026/README.md): claims arbitrary Hilbert-subset ℓ1-valued Lipschitz functions admit extensions with universal multiplicative Lipschitz loss. + +For compact models, the practical question is often which **specific evaluator-relevant distinctions** the latents must preserve. Define a graph with one vertex per synthetic activation state, and an edge for each required distinction. Assign bits to each vertex and require different codes across tested edges. + +The direct result proved in [the MathCan theorem note](https://github.com/patrickdugan/MathCan/blob/feat/coe01-chromatic-observer-20261115/research/compactification/CHROMATIC_OBSERVER_THEOREM.md) is + +``` +min_ordinary_probe_bits(G) = ceil(log2(chromatic_number(G))). +``` + +A separation margin `r` in Hamming distance survives any `r-1` erased readout features, or `t` adversarial bit flips when `r>=2*t+1`. Any graph can use a repeated-color code of width `r*ceil(log2 χ)`, while an exhaustive solver can find smaller codes for finite cases. The stronger **metric-quotient theorem** first identifies all points connected by short metric edges `d(x,y)<1/L`. Tested edges internal to such a component make a binary L-Lipschitz observer impossible. Otherwise the same chromatic formula applies to the quotient evaluator graph. A **critical regularity threshold** follows from the quotient: `rho(u,v)` is the minimum, over all paths from u to v, of the largest metric jump on that path. The smallest feasible positive Lipschitz constant is exactly `L_* = max_(uv in E) 1/rho(u,v)`, including equality. Above this value, the minimum bit width is a nonincreasing staircase; it changes only at reciprocals of sampled pair distances. `critical_lipschitz` computes the threshold in exact rational arithmetic using a min/max Floyd-Warshall recurrence. + +The abstract feature map embeds tested states in a Hilbert star `0,e_1,...,e_n`, and each bit can extend to the entire Hilbert space by a 1-Lipschitz clipped McShane formula. This is a forward-observable result. It does not certify latent-state reconstruction or inverse bi-Lipschitz geometry. + +## Reproduction + +At repository root (Python 3.10+, standard library only): + +```bash +python -m unittest discover -s research/chromatic_observer_gym_v1 -p 'test_*.py' -v +python research/chromatic_observer_gym_v1/observer_codes.py +``` + +The test suite has eleven regression methods, including complete enumeration of all 64 undirected simple graphs on four vertices, exact chromatic palette bounds, independent Hamming-erasure/flip checks, exact rational metric-quotient and bottleneck-threshold checks (including 64 evaluator graphs) and 300 deterministic input-pair Lipschitz extension checks. + +| Evaluator interface | States | χ | Bare bit width | Margin 3 width | +| --- | ---: | ---: | ---: | ---: | +| Full-distinction clique K6 | 6 | 6 | 3 | 6 | +| Adjacent-step path P8 | 8 | 2 | 1 | 3 | +| Odd cycle C5 | 5 | 3 | 2 | 4 | + +Margin-3 values are **exact** for these finite inputs because the solver scans all smaller widths with graph-symmetry-preserving search; check `minimum_observer`, which is exponential and intended only for small graphs. For K6, the width-5 lower bound has a separate six-radius-one-spheres packing proof, and the six-bit witness is also enumerated in Lean. + +## How to connect to live compactification experiments + +1. Extract a frozen set of latent states or SAE reconstructions from a specific checkpoint. Define evaluator edges from independently tested behavior, splitting train/test states before adjusting the graph. +2. Compare edge accuracy of learned 1-, 2-, ...-bit probes with the exact graph χ bound on a deliberately tiny controlled subset, while varying per-edge Hamming margin. Treat edge sets from held-out tasks separately. +3. Report full pairwise embedding distortion, evaluator-edge retention, erasure tolerance and bit width separately. The graph theorem predicts the best **unconstrained symbolic observer**, not trainability or robustness under nonlinear learned probes. + +The present run contains no model training, causal interventions, source-paper proof reproduction, or out-of-sample biological/mechanistic claims. Its purpose is an independently checkable benchmark and a concrete mathematical distinction between global geometry and task-local observation. + +## Source and verification ledger + +- OpenAI source repository pin: `openai/math@4eaee87548250b2682affda7d05d947c05554bae`. +- Application starting commit: `MoralityLabAI/Compactification-Theory@28d8186d2393f0f80d0d4302e86b0bb82ef61190`. +- Pure math starting commit: `patrickdugan/MathCan@fca46bfb3430ac85ffca16f6a6a83bb0b0231e41`. +- Local test environment: Python 3.13 standard library; `python -m unittest discover` eleven tests passed on 2026-11-15. +- Lean kernel target: v4.35.0 (repository pinned), the COE-01 Lean workflow passed on GitHub Actions at MathCan commit `c55e66d3325796c53db1dcdbe9e5c284e8f569d2`; only the finite lemmas in that module are Lean certified. General graph and Lipschitz theorems have the written proofs in MathCan. + +## COE-02 continuation + +See [COE02.md](COE02.md) for the exact `ell_1` integer-cut geometry, +sharp `K_5` code width and fractional integrality-gap theorem, and a +provenance-preserving frozen-activation adapter. + +## COE-05: clock-gauge phase bits and exact 14-state witness + +[Experiment and replay](COE05.md) | [Affine-phase oracle](phase_register.py) | [Frozen-probe scorer](phase_order_replay.py) + +A fixed tied one-bit readout can distinguish 14 affine-hyperplane states across eight cyclic visits even when every state activates exactly four times. Its constant-weight code corrects one bit flip; an unknown cyclic phase collapses the 14 messages to four rotation orbits. A new 3-seed synthetic tied-attention replication shows only 10 order-only heldout evaluator hits among 336 tested pairs. The pretrained TRM/Huginn/Nanbeige measurements remain outside this experiment. + + +## COE-06: phase-blind clock-gauge observer capacity + +The [COE-06 continuation](COE06.md) replays frozen COE-05 heads under unknown cyclic phase (243/336 ordered versus 233/336 phase-invariant). A 14-visit, 21-label constant-weight code corrects one flipped bit with arbitrary cyclic phase. The [resource oracle](resource_bound.py) bounds every shorter such code by 17 labels. See [test_phase_blind.py](test_phase_blind.py) and [MathCan theorem](https://github.com/patrickdugan/MathCan/blob/feat/coe01-chromatic-observer-20261115/research/compactification/PHASE_BLIND_OBSERVER_CAPACITY.md). diff --git a/research/chromatic_observer_gym_v1/activation_case.py b/research/chromatic_observer_gym_v1/activation_case.py new file mode 100644 index 000000000..1403fb1e7 --- /dev/null +++ b/research/chromatic_observer_gym_v1/activation_case.py @@ -0,0 +1,82 @@ +"""COE-02 frozen evaluator-interface adapter for exact rational latent vectors. + +This is an audit harness. It accepts fixed activation prototypes and evaluator +edges; it neither extracts checkpoints nor treats a synthetic prototype as +observed model behavior. Uses ell_1 distance of the supplied feature vectors. +""" + +import argparse +import json +from fractions import Fraction +from pathlib import Path + +try: + from .l1_cut_codes import minimum_l1_observer + from .observer_codes import metric_quotient_observer +except ImportError: + from l1_cut_codes import minimum_l1_observer + from observer_codes import metric_quotient_observer + + +def analyse(case: dict) -> dict: + if case.get('format') != 'coe02-activation-v1': + raise ValueError('unsupported frozen activation case format') + states = case['states'] + if not states or len(states) > 8: + raise ValueError('small-n reference requires between one and eight states') + names = [s['id'] for s in states] + if any(not isinstance(x, str) or not x for x in names) or len(set(names)) != len(names): + raise ValueError('state IDs must be unique nonempty strings') + vectors = [tuple(Fraction(a) for a in s['activation']) for s in states] + nfeatures = len(vectors[0]) + if nfeatures < 1 or any(len(x) != nfeatures for x in vectors): + raise ValueError('all activation vectors must have a shared positive dimension') + if len(set(vectors)) != len(vectors): + raise ValueError('repeated activations make a genuine metric impossible') + index = {name: i for i, name in enumerate(names)} + try: + edges = tuple((index[u], index[v]) for u, v in case['evaluator_edges']) + except KeyError as e: + raise ValueError('unknown state ID in evaluator edge') from e + d = tuple(tuple(sum(abs(a-b) for a, b in zip(x,y)) for y in vectors) + for x in vectors) + L = Fraction(case['lipschitz']) + if L <= 0: + raise ValueError('activation comparison requires a strictly positive Lipschitz budget') + r = case.get('hamming_margin',1) + if not isinstance(r, int) or isinstance(r,bool) or r < 1: + raise ValueError('positive integer Hamming margin required') + l1 = minimum_l1_observer(d, edges, L, r) + try: + linf_width, linf_words, _ = metric_quotient_observer(d, edges, L, r) + linf = {'width': linf_width, 'words': list(linf_words)} + except ValueError as e: + if 'forced-equivalent' not in str(e): + raise + linf = None + return { + 'format':'coe02-activation-report-v1', + 'provenance': case.get('provenance','UNSPECIFIED: synthetic or user-supplied'), + 'state_count':len(states),'activation_width':nfeatures, + 'lipschitz':str(L),'margin':r, + 'metric':'input_feature_l1_exact_rational', + 'distance':[[str(v) for v in row] for row in d], + 'linf':linf, + 'l1':None if l1 is None else {'width':l1.width, + 'words':list(l1.words), + 'cut_masks':list(l1.cuts), + 'pair_capacities':list(l1.capacities), + 'pair_loads':list(l1.loads)} + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('case', type=Path) + args=parser.parse_args() + print(json.dumps(analyse(json.loads(args.case.read_text(encoding='utf-8'))), + indent=2,sort_keys=True)) + + +if __name__ == '__main__': + main() diff --git a/research/chromatic_observer_gym_v1/audit_model_alignment.py b/research/chromatic_observer_gym_v1/audit_model_alignment.py new file mode 100644 index 000000000..457182c1d --- /dev/null +++ b/research/chromatic_observer_gym_v1/audit_model_alignment.py @@ -0,0 +1,42 @@ +"""Optional PyTorch replay proves frozen weights yield stored activations.""" +from __future__ import annotations +import json, hashlib +from pathlib import Path +import torch +from run_frozen_loop import FrozenTiedLooper,canonical,VOCAB + +def audit(weights_path,trace_path): + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + weights=json.loads(Path(weights_path).read_text()) + traces=json.loads(Path(trace_path).read_text()) + max_abs=0.0 + reports=[] + for item in traces['items']: + seed=item['model_seed'] + w=weights[str(seed)] + sha=hashlib.sha256(canonical(w).encode()).hexdigest() + assert sha==item['model_checkpoint_sha256'] + m=FrozenTiedLooper() + s=m.state_dict() + s={name:torch.tensor(array, dtype=s[name].dtype) for name,array in w.items()} + m.load_state_dict(s) + m.eval() + xs=torch.tensor([(a,b) for a in range(8) for b in range(8)]) + with torch.no_grad(): + logits,z=m(xs,trace=True) + assert logits.argmax(-1).tolist()==item['model_predictions'] + raw=z.tolist() + for a in range(8): + for b in range(8): + stored=item['activations'][f'{a}:{b}'] + for t in range(4): + for j in range(24): + max_abs=max(max_abs,abs(raw[8*a+b][t][j]-stored[t][j])) + reports.append({'seed':seed,'sha256':sha,'accuracy64':int((logits.argmax(-1)==xs[:,0]).sum().item())}) + assert max_abs==0.0,max_abs + return {'weights_to_trace_max_abs_diff':max_abs,'reports':reports} + +if __name__=='__main__': + root=Path(__file__).parent + print(json.dumps(audit(root/'frozen_loop_weights.json',root/'frozen_loop_activations.json'),indent=2)) diff --git a/research/chromatic_observer_gym_v1/cap2_receipt.json b/research/chromatic_observer_gym_v1/cap2_receipt.json new file mode 100644 index 000000000..ec2629de2 --- /dev/null +++ b/research/chromatic_observer_gym_v1/cap2_receipt.json @@ -0,0 +1,114 @@ +{ + "posthoc": true, + "rows": [ + { + "candidates_checked": 9208, + "fit_diameter": 2, + "fit_edge_hits": 78, + "fit_feasible_candidates": 1059, + "heldout_diameter": 2, + "heldout_edge_hits": 79, + "seed": 2406, + "threshold": 5.592513955605966, + "weight": [ + -0.21990507916521462, + -0.18848972262727928, + -0.40837170623836333, + -0.2892899717056641, + 0.1255747311996351, + -0.044826652447206475, + 0.06288767352903506, + 0.01979062037324886, + -0.37183695487941726, + -0.04975692076346606, + -0.006518583412759782, + 0.11972279968211127, + -0.05515338112670352, + 0.012548982929136778, + -0.2808175527926485, + -0.4773307903420829, + -0.19604735117591252, + -0.04651600004073404, + 0.1799132189848688, + 0.21498169891434205, + -0.0167081628708322, + 0.011264981844918844, + -0.19267078708695323, + -0.14765809032806082 + ] + }, + { + "candidates_checked": 9228, + "fit_diameter": 2, + "fit_edge_hits": 78, + "fit_feasible_candidates": 1303, + "heldout_diameter": 2, + "heldout_edge_hits": 59, + "seed": 2407, + "threshold": -4.873730259406543, + "weight": [ + 0.13295766076554796, + 0.004797149459404625, + 0.18739159880265924, + 0.007511866322791264, + -0.14530879073054567, + -0.0362979508633362, + 0.24857675354962105, + -0.11929205417210266, + -0.06410308666214375, + 0.014408547086274006, + -0.29639407493057346, + -0.340930039564661, + 0.3093195645650991, + -0.2632293179655998, + 0.18411516231244035, + -0.0341484238914105, + 0.030425496701506835, + -0.029945233617642647, + -0.583020958921786, + -0.1637917043686261, + 0.22002899631061387, + 0.008079176821341353, + -0.07829984392414074, + 0.13064919815929624 + ] + }, + { + "candidates_checked": 8751, + "fit_diameter": 2, + "fit_edge_hits": 78, + "fit_feasible_candidates": 1088, + "heldout_diameter": 2, + "heldout_edge_hits": 74, + "seed": 2408, + "threshold": -3.9327435220930242, + "weight": [ + 0.08503856130689444, + -0.15744242456879076, + 0.09624556489151412, + 0.213021095579875, + -0.28747810728022377, + 0.14125559532754195, + 0.0856274948179675, + 0.2608583876754631, + 0.17358295535279905, + -0.22357348405026345, + 0.4121956089441867, + -0.11617554905291104, + 0.029590060584876315, + 0.2173347154275651, + 0.1141854609461657, + 0.039206383515147915, + -0.06517445271489591, + -0.3595530910943892, + 0.45344772663591504, + 0.19377112671036828, + 0.08927834164187337, + 0.13331045044643905, + 0.05744090052343291, + 0.058563165594031574 + ] + } + ], + "schema": "COE-04-cap2-diagnostic-v1" +} diff --git a/research/chromatic_observer_gym_v1/equal_budget_baselines.json b/research/chromatic_observer_gym_v1/equal_budget_baselines.json new file mode 100644 index 000000000..8a9e9f4bc --- /dev/null +++ b/research/chromatic_observer_gym_v1/equal_budget_baselines.json @@ -0,0 +1,866 @@ +{ + "rows": [ + { + "final_four_bits": { + "candidate_count": 9208, + "fit_edge_hits": 112, + "fit_edge_total": 112, + "fit_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "heldout_edge_hits": 112, + "heldout_edge_total": 112, + "heldout_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "train_coverage": 112 + }, + "final_heads": [ + { + "threshold": 1.5600467381744834, + "visit": 3, + "w": [ + -0.00561919464417287, + 0.16151309717199716, + 0.4230175274763852, + -0.2736985648078286, + -0.024591792667305865, + -0.3564757180542284, + -0.09040279265427845, + 0.07430303792337395, + -0.10514408789298296, + 0.02215850647697226, + -0.021974803863923625, + -0.08041341584226873, + -0.02356679236737102, + -0.197198441097606, + -0.21225247231713065, + 0.024380325409565647, + -0.28592168998839246, + 0.17768987072143205, + -0.2123433575207236, + 0.524439555078322, + -0.12129646411799842, + -0.07877486504801279, + 0.11271887939869925, + 0.08941466895099542 + ] + }, + { + "threshold": 1.5767707396358648, + "visit": 3, + "w": [ + 0.38829587180179465, + 0.1896760029489978, + 0.19433274265293965, + -0.0071789379111806524, + 0.022380735790369435, + -0.23042431646800987, + 0.2118447158340196, + -0.20544620704411465, + -0.07274992095301795, + -0.08935973119396573, + -0.1710321845481774, + -0.20521373466380421, + 0.09156583657253305, + -0.3947248520607921, + -0.1617372228423354, + 0.11029249871478981, + -0.03086402590999882, + -0.15701066708507147, + -0.14191370322416214, + 0.17769305513321518, + 0.22665901262961155, + -0.12400820757712575, + 0.31748092197486494, + 0.32050971252009663 + ] + }, + { + "threshold": -6.444821786921796, + "visit": 3, + "w": [ + 0.2764337303445526, + 0.28892090397067766, + -0.02971041362479641, + -0.06681201471137052, + -0.33156049666448195, + 0.18559645419350854, + -0.188441102482932, + -0.10675591551215734, + 0.08651355730426398, + -0.33338054676695544, + -0.009743276564794916, + -0.20774315362855003, + 0.05738858350497876, + 0.30227601325842673, + -0.06538671127640645, + 0.21679041809705757, + -0.30789655335435995, + 0.4119952403923768, + 0.06357946791440332, + -0.06980615250412299, + -0.09521101435291741, + 0.15518556113893, + 0.15207588267265923, + 0.07700523736375414 + ] + }, + { + "threshold": -15.40278863453129, + "visit": 3, + "w": [ + -0.5622066547608611, + -0.23813144735593264, + 0.07548209868651623, + 0.019393207770757405, + 0.1825634935673781, + -0.01894875779408888, + -0.05206381711396955, + 0.2682717268909834, + -0.10926264318473555, + 0.31320566935529875, + 0.05538409823078414, + 0.25806861642068873, + -0.16472854433046433, + 0.005220034805300181, + 0.1413494798736366, + -0.21282820939076602, + 0.07612125848337228, + -0.05318168374757848, + -0.014965777615144386, + 0.11843158079325271, + -0.1823004265892801, + -0.018106141450220402, + -0.3602912062802941, + -0.23321584396934486 + ] + } + ], + "seed": 2406, + "untied_four_visits": { + "candidate_count": 9208, + "fit_edge_hits": 112, + "fit_edge_total": 112, + "fit_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "heldout_edge_hits": 105, + "heldout_edge_total": 112, + "heldout_unique_per_context": [ + 5, + 7, + 5, + 8 + ], + "train_coverage": 112 + }, + "untied_heads": [ + { + "threshold": -0.145032306150088, + "visit": 0, + "w": [ + -0.2704438261309579, + -0.16354876994102668, + -0.32173497273771307, + -0.2498932304872753, + -0.07640454735171487, + 0.16057126440535488, + -0.13970474268426017, + 0.26468757479474203, + 0.1017349679944248, + 0.09055430805183531, + -0.2362412079689401, + -0.15186632344278447, + -0.09940252354738893, + 0.19987113255481273, + -0.4349912910010225, + 0.0840036598933777, + -0.024293729465731526, + 0.10111713078318298, + 0.11257443799823308, + 0.4258036079159688, + 0.12104563628843008, + -0.13556787395533426, + -0.17774819167045464, + 0.002402011320586335 + ] + }, + { + "threshold": -2.804493852110423, + "visit": 1, + "w": [ + 0.2764337303445526, + 0.28892090397067766, + -0.02971041362479641, + -0.06681201471137052, + -0.33156049666448195, + 0.18559645419350854, + -0.188441102482932, + -0.10675591551215734, + 0.08651355730426398, + -0.33338054676695544, + -0.009743276564794916, + -0.20774315362855003, + 0.05738858350497876, + 0.30227601325842673, + -0.06538671127640645, + 0.21679041809705757, + -0.30789655335435995, + 0.4119952403923768, + 0.06357946791440332, + -0.06980615250412299, + -0.09521101435291741, + 0.15518556113893, + 0.15207588267265923, + 0.07700523736375414 + ] + }, + { + "threshold": -8.176928185315344, + "visit": 2, + "w": [ + 0.4832531019641022, + 0.3186683821526256, + 0.10555418186312963, + -0.0276282282554945, + -0.18305840755425898, + -0.11285934030027625, + 0.02071254755769569, + -0.21798242446999835, + 0.06727720759427495, + -0.3194209581005144, + 0.0048773610553801, + -0.32411992477048274, + 0.20759750703642407, + -0.23788565495359967, + -0.20369401706482493, + 0.08113543441952727, + -0.15195473623465414, + 0.14788969527295973, + 0.11318443034795622, + -0.028796217081981455, + 0.10411699519223203, + -0.06418127722534414, + 0.23199158728970182, + 0.26840959327521263 + ] + }, + { + "threshold": -16.816972497932454, + "visit": 3, + "w": [ + -0.4850379838055407, + -0.06566833983440737, + 0.4099782929977248, + -0.12800109012611444, + 0.15341055097719528, + -0.23517829376111843, + -0.06265547450725453, + 0.21313593258744398, + -0.10513407739186215, + 0.295541840706629, + -0.007156414195178829, + 0.2420711242270677, + -0.10491355836775822, + -0.11874922667076153, + -0.021653572536043896, + -0.10288738132526021, + -0.08182717210985654, + -0.05557457166260605, + -0.20330266554597265, + 0.3252960908020582, + -0.11443839629014602, + -0.03688143825620583, + -0.27746106700104, + -0.07859765078308154 + ] + } + ] + }, + { + "final_four_bits": { + "candidate_count": 9228, + "fit_edge_hits": 112, + "fit_edge_total": 112, + "fit_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "heldout_edge_hits": 106, + "heldout_edge_total": 112, + "heldout_unique_per_context": [ + 7, + 6, + 7, + 7 + ], + "train_coverage": 112 + }, + "final_heads": [ + { + "threshold": -4.728956983803451, + "visit": 3, + "w": [ + 0.06895654759449149, + 0.4306406810450028, + 0.05033380403370782, + 0.08315255595872263, + -0.054758909600874955, + -0.05975888282097973, + 0.18548048245186302, + 0.2541892292301981, + 0.11407427172866239, + 0.0033159356884175546, + 0.292047969775134, + 0.04577406741279415, + 0.10612996799046875, + 0.014983399849386536, + 0.19808385131509978, + -0.05464808676774127, + -0.2104065840831397, + -0.13814499707497255, + -0.2242767363280734, + -0.5614925227145561, + 0.11075818118527858, + -0.04565759164294441, + -0.16729169582920989, + -0.2633830445429923 + ] + }, + { + "threshold": 9.730819528108668, + "visit": 3, + "w": [ + -0.3043077769074912, + -0.24235854961051076, + -0.3019567165815671, + -0.047717843667300766, + -0.18799801658434068, + 0.4270446316800974, + -0.16798674907621694, + 0.07190866511500577, + -0.02020640595542644, + -0.3093496832692118, + -0.2881936639446837, + -0.011046175761055219, + -0.19349586287478346, + 0.1544617377453084, + 0.21423861619874948, + 0.11065849056687527, + 0.1379246484461325, + 0.0975289430876264, + 0.05562208823151237, + 0.10795220532927896, + 0.1899629639895169, + -0.07153892312723227, + -0.3205184873399587, + 0.134756609565449 + ] + }, + { + "threshold": 4.54333142420759, + "visit": 3, + "w": [ + -0.1920014684505043, + -0.1480440170378084, + -0.33068068328303524, + 0.2478761723484091, + 0.03549377072336489, + 0.08363183901332662, + 0.0723790449238257, + 0.17355799157955465, + -0.19569214305789345, + 0.04131503305504115, + -0.3160026556982485, + -0.2872386377539794, + -0.257040327637759, + -0.09112105802193565, + 0.015356042845131623, + 0.05809325024855127, + 0.07023117625733884, + -0.39522087541271156, + 0.21318737731600185, + 0.1891963733760399, + 0.3936890662806955, + -0.04976543501134484, + -0.06665523504152554, + 0.14891186688312882 + ] + }, + { + "threshold": -15.364551384679391, + "visit": 3, + "w": [ + 0.06895654759449149, + 0.4306406810450028, + 0.05033380403370782, + 0.08315255595872263, + -0.054758909600874955, + -0.05975888282097973, + 0.18548048245186302, + 0.2541892292301981, + 0.11407427172866239, + 0.0033159356884175546, + 0.292047969775134, + 0.04577406741279415, + 0.10612996799046875, + 0.014983399849386536, + 0.19808385131509978, + -0.05464808676774127, + -0.2104065840831397, + -0.13814499707497255, + -0.2242767363280734, + -0.5614925227145561, + 0.11075818118527858, + -0.04565759164294441, + -0.16729169582920989, + -0.2633830445429923 + ] + } + ], + "seed": 2407, + "untied_four_visits": { + "candidate_count": 9228, + "fit_edge_hits": 112, + "fit_edge_total": 112, + "fit_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "heldout_edge_hits": 111, + "heldout_edge_total": 112, + "heldout_unique_per_context": [ + 7, + 8, + 8, + 8 + ], + "train_coverage": 112 + }, + "untied_heads": [ + { + "threshold": 0.5758022820613108, + "visit": 0, + "w": [ + -0.08446654634874068, + -0.2564078656455928, + -0.042502210819780915, + 0.0010674004469248253, + 0.13563371761067106, + -0.035403873564153525, + -0.08301981197897042, + 0.033020684857079784, + -0.18220585511094012, + 0.1576354877571079, + -0.4083711486756565, + -0.23694559725754166, + -0.07975117183004649, + -0.023742884426688475, + -0.1346995758804806, + 0.09132018843018679, + 0.057766007798819366, + -0.4231562503296115, + 0.1778835027460259, + 0.35090715804004496, + 0.18702104476556722, + 0.06844084441207726, + 0.311805172830834, + 0.33053713083241953 + ] + }, + { + "threshold": 1.2819646722212252, + "visit": 1, + "w": [ + -0.20536381841077422, + -0.18692490093741063, + -0.11890220877420744, + 0.20814472132741674, + -0.006857911043549087, + -0.10106434587764228, + 0.044786048555030634, + -0.1338513497885032, + -0.13685251964266645, + 0.056853028950146836, + 0.14401744030677127, + -0.018495756706978905, + -0.25095365891938515, + -0.21124644850133711, + -0.5330927903629507, + -0.22413960621421916, + 0.22798494894960294, + 0.22807956611344016, + 0.1037680674391608, + 0.4027406246356784, + -0.18485347336847582, + -0.13932204243991, + 0.11927409272845999, + 0.07344071547807715 + ] + }, + { + "threshold": 1.256205819635523, + "visit": 2, + "w": [ + -0.19561222708726095, + 0.019416107907819263, + -0.4285484102792001, + 0.34864297963254615, + -0.07065920971988428, + 0.14946092799604369, + 0.1759700874083456, + 0.2153887261151634, + -0.11382654369773558, + -0.08203139060481855, + -0.08221316639361569, + -0.19421948289642563, + -0.2915368229069203, + -0.10738103162869557, + 0.14154400268128858, + 0.0006543775162393083, + 0.04763734302054169, + -0.18077967803345663, + 0.14234802626448645, + -0.04548387271631483, + 0.38878651396286673, + -0.13110119941987103, + -0.3715231445058557, + -0.08416934354152325 + ] + }, + { + "threshold": -15.364551384679391, + "visit": 3, + "w": [ + 0.06895654759449149, + 0.4306406810450028, + 0.05033380403370782, + 0.08315255595872263, + -0.054758909600874955, + -0.05975888282097973, + 0.18548048245186302, + 0.2541892292301981, + 0.11407427172866239, + 0.0033159356884175546, + 0.292047969775134, + 0.04577406741279415, + 0.10612996799046875, + 0.014983399849386536, + 0.19808385131509978, + -0.05464808676774127, + -0.2104065840831397, + -0.13814499707497255, + -0.2242767363280734, + -0.5614925227145561, + 0.11075818118527858, + -0.04565759164294441, + -0.16729169582920989, + -0.2633830445429923 + ] + } + ] + }, + { + "final_four_bits": { + "candidate_count": 8751, + "fit_edge_hits": 112, + "fit_edge_total": 112, + "fit_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "heldout_edge_hits": 111, + "heldout_edge_total": 112, + "heldout_unique_per_context": [ + 8, + 7, + 8, + 8 + ], + "train_coverage": 112 + }, + "final_heads": [ + { + "threshold": 0.6081804607283319, + "visit": 3, + "w": [ + 0.18612832220805714, + 0.22807975815410264, + 0.09543100496799023, + 0.11300049847427085, + 0.3864768011341915, + -0.13707635305093274, + -0.026680300956215944, + -0.19412451722071739, + -0.18338401865051387, + -0.21462874960512116, + 0.4094011224145829, + 0.09696422860304942, + -0.14498891723909674, + 0.08186707360606454, + -0.17063628715019924, + -0.11245912701253408, + -0.05054888360295475, + 0.24905539532164003, + 0.32847411546034216, + 0.012845992049991555, + 0.10446368793210531, + 0.011250768555772171, + -0.19999310442032622, + -0.36747027521274195 + ] + }, + { + "threshold": 1.5519795649799915, + "visit": 3, + "w": [ + 0.009237370866563493, + 0.11170602239167914, + -0.021604588422452383, + -0.3663501929170135, + -0.26372541737809985, + -0.19969882766533364, + 0.10053789150511225, + 0.28405832019105476, + -0.31044775369681793, + 0.02752590258241147, + -0.10803960599719688, + -0.05868504677021264, + 0.06214568846172297, + 0.257333902537878, + 0.3874080384126118, + -0.14745249775974292, + -0.2938823358763728, + 0.26564041130290006, + 0.07182063750599203, + 0.27402084738037763, + -0.06566140712243956, + 0.01687741498549507, + 0.2300484397136634, + 0.06059403490305257 + ] + }, + { + "threshold": -2.8209934219757873, + "visit": 3, + "w": [ + 0.38770514628010927, + 0.1745817253265101, + -0.1074798271709703, + -0.0006033427292911786, + -0.21970939015597815, + -0.06892235301990028, + -0.07856211027968624, + -0.1549027446117497, + 0.14673348213050125, + 0.12657056968640468, + 0.04176413844297742, + -0.05519404753594565, + 0.03581557233086588, + 0.22903845584137394, + 0.019883971036168686, + -0.15376676855927202, + -0.1589449172743081, + -0.11857666585019716, + 0.22039517667309425, + -0.4043705665607975, + -0.508302292534979, + 0.3070568639173988, + -0.005529112688591295, + -0.015577850627226067 + ] + }, + { + "threshold": -16.53357541751647, + "visit": 3, + "w": [ + 0.18612832220805714, + 0.22807975815410264, + 0.09543100496799023, + 0.11300049847427085, + 0.3864768011341915, + -0.13707635305093274, + -0.026680300956215944, + -0.19412451722071739, + -0.18338401865051387, + -0.21462874960512116, + 0.4094011224145829, + 0.09696422860304942, + -0.14498891723909674, + 0.08186707360606454, + -0.17063628715019924, + -0.11245912701253408, + -0.05054888360295475, + 0.24905539532164003, + 0.32847411546034216, + 0.012845992049991555, + 0.10446368793210531, + 0.011250768555772171, + -0.19999310442032622, + -0.36747027521274195 + ] + } + ], + "seed": 2408, + "untied_four_visits": { + "candidate_count": 8751, + "fit_edge_hits": 112, + "fit_edge_total": 112, + "fit_unique_per_context": [ + 8, + 8, + 8, + 8 + ], + "heldout_edge_hits": 111, + "heldout_edge_total": 112, + "heldout_unique_per_context": [ + 8, + 7, + 8, + 8 + ], + "train_coverage": 112 + }, + "untied_heads": [ + { + "threshold": -0.3021124243791762, + "visit": 0, + "w": [ + 0.1330480092729424, + 0.22997189006335403, + 0.09723902183110332, + -0.17872331829282503, + 0.16689387902735336, + -0.1804151696507312, + 0.13491456969372798, + -0.009797123108753563, + -0.40075125029763875, + -0.2044681334431389, + 0.3060743831618523, + 0.09397345577886121, + -0.038636839163803685, + 0.24506563321012126, + 0.042535824754187476, + -0.1612891225217088, + -0.2675686348273345, + 0.34033571064838825, + 0.3238754296056952, + 0.08866288077082396, + 0.06032116012961068, + 0.132124963786351, + -0.052442379881067855, + -0.3016524322619271 + ] + }, + { + "threshold": 2.7380566221827696, + "visit": 1, + "w": [ + -0.0020372477752755697, + 0.1059311469160533, + 0.37265549895181205, + -0.06796172295376876, + -0.3610348764748536, + 0.1456645876634481, + -0.0919231383005006, + -0.07642083933627734, + -0.11636482014180438, + 0.020643341735724716, + -0.15168472749809497, + 0.056025014519944336, + -0.1931683724953957, + 0.2585698667016305, + 0.46277098052177035, + 0.2259144245423714, + -0.20876476244986703, + 0.01360560768447625, + -0.276451431764846, + 0.2749649410651994, + -0.24978128816469658, + 0.029357208040353112, + 0.046236854319589495, + -0.09359030718025003 + ] + }, + { + "threshold": -5.5981500993528215, + "visit": 2, + "w": [ + -0.16090192719308202, + -0.22961884369298327, + -0.3179744824322739, + -0.32344388208428737, + -0.21009815948343477, + -0.05036798821883618, + 0.21631972752993825, + 0.346713830015366, + 0.0014898790696779751, + 0.15629478515939849, + -0.308686089627823, + -0.16359043379031973, + 0.33031000981792674, + -0.08984620184590122, + -0.011761638872624002, + -0.11882300785713981, + -0.021676136978646073, + -0.0736328357445981, + -0.010129699151108163, + -0.10278956603499331, + 0.08042444031304792, + 0.06082115432812335, + 0.2516143068359408, + 0.3660992343719654 + ] + }, + { + "threshold": -16.53357541751647, + "visit": 3, + "w": [ + 0.18612832220805714, + 0.22807975815410264, + 0.09543100496799023, + 0.11300049847427085, + 0.3864768011341915, + -0.13707635305093274, + -0.026680300956215944, + -0.19412451722071739, + -0.18338401865051387, + -0.21462874960512116, + 0.4094011224145829, + 0.09696422860304942, + -0.14498891723909674, + 0.08186707360606454, + -0.17063628715019924, + -0.11245912701253408, + -0.05054888360295475, + 0.24905539532164003, + 0.32847411546034216, + 0.012845992049991555, + 0.10446368793210531, + 0.011250768555772171, + -0.19999310442032622, + -0.36747027521274195 + ] + } + ] + } + ], + "schema": "COE-04-equal-bits-baselines-v1" +} diff --git a/research/chromatic_observer_gym_v1/freeze_replication.py b/research/chromatic_observer_gym_v1/freeze_replication.py new file mode 100644 index 000000000..851a3a915 --- /dev/null +++ b/research/chromatic_observer_gym_v1/freeze_replication.py @@ -0,0 +1,51 @@ +"""Regenerate COE-05 independent synthetic model seeds from COE-04 architecture. + +Requires torch 2.10 CPU; reuses the exact native equations of run_frozen_loop. +This intentionally runs no model downloads, uses no cloud compute, and never +fits readouts. The frozen activation and weight artifacts are committed too. +""" +from __future__ import annotations +import argparse +import gzip +from pathlib import Path +import torch +try: + from .run_frozen_loop import freeze, canonical +except ImportError: + from run_frozen_loop import freeze, canonical + +MODEL_SEEDS = (2411, 2412, 2413) + + +def regenerate(out: Path): + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + rows=[] + weights={} + for seed in MODEL_SEEDS: + row, w=freeze(seed) + rows.append(row) + weights[str(seed)]=w + print('frozen',seed,row['model_checkpoint_sha256'],row['train_loss']) + bundle={ + 'schema':'COE-04-native-tied-loop-frozen-v1', + 'task':'copy first token, with second token as a distracting query position', + 'model_fit_pairs':'all 8 x 8 symbolic cases before probe fit', + 'probe_fit_contexts':[0,1,2,3], + 'probe_heldout_contexts':[4,5,6,7], + 'evaluator_graph':'K8 on source-token labels 0..7', + 'model_training_framework':{'torch':str(torch.__version__)}, + 'items':rows, + } + out.parent.mkdir(parents=True,exist_ok=True) + with gzip.open(out,'wt') as f:f.write(canonical(bundle)) + with gzip.open(out.with_name('replication_weights.json.gz'),'wt') as f: + f.write(canonical(weights)) + return out + + +if __name__=='__main__': + parser=argparse.ArgumentParser() + parser.add_argument('--out',type=Path,default=Path(__file__).with_name('replication_activations.json.gz')) + args=parser.parse_args() + regenerate(args.out) diff --git a/research/chromatic_observer_gym_v1/frozen_k5_onehot.json b/research/chromatic_observer_gym_v1/frozen_k5_onehot.json new file mode 100644 index 000000000..bc1ea4d9d --- /dev/null +++ b/research/chromatic_observer_gym_v1/frozen_k5_onehot.json @@ -0,0 +1,18 @@ +{ + "format": "coe02-activation-v1", + "provenance": "Synthetic one-hot rational latent prototypes; no checkpoint or trained-model measurements", + "lipschitz": "2", + "hamming_margin": 1, + "states": [ + {"id": "s0", "activation": ["1/2", "0", "0", "0", "0"]}, + {"id": "s1", "activation": ["0", "1/2", "0", "0", "0"]}, + {"id": "s2", "activation": ["0", "0", "1/2", "0", "0"]}, + {"id": "s3", "activation": ["0", "0", "0", "1/2", "0"]}, + {"id": "s4", "activation": ["0", "0", "0", "0", "1/2"]} + ], + "evaluator_edges": [ + ["s0", "s1"], ["s0", "s2"], ["s0", "s3"], ["s0", "s4"], + ["s1", "s2"], ["s1", "s3"], ["s1", "s4"], + ["s2", "s3"], ["s2", "s4"], ["s3", "s4"] + ] +} diff --git a/research/chromatic_observer_gym_v1/frozen_loader.py b/research/chromatic_observer_gym_v1/frozen_loader.py new file mode 100644 index 000000000..3ffd691c9 --- /dev/null +++ b/research/chromatic_observer_gym_v1/frozen_loader.py @@ -0,0 +1,32 @@ +"""COE-04 pure-stdlib verifier for stored pretrained-in-sandbox checkpoints. + +The gzip artifacts are real frozen weights and hidden states produced by the +optional torch runner; verification of exact model inference needs torch. +""" +import gzip, hashlib, json +from pathlib import Path +from temporal_observers import canonical,validate_bundle + +ROOT=Path(__file__).resolve().parent + + +def read_payload(name,root=ROOT): + p=Path(root)/name + if p.suffix=='.gz': + with gzip.open(p,'rt',encoding='utf8') as f:return json.load(f) + return json.loads(p.read_text(encoding='utf8')) + + +def verify_frozen(root=ROOT): + x=read_payload('frozen_loop_activations.json.gz',root) + w=read_payload('frozen_loop_weights.json.gz',root) + validate_bundle(x) + verified=[] + for item in x['items']: + seed=item['model_seed'] + assert str(seed) in w + digest=hashlib.sha256(canonical(w[str(seed)]).encode('utf8')).hexdigest() + if digest != item['model_checkpoint_sha256']: + raise ValueError('weight hash mismatch for seed '+str(seed)) + verified.append({'seed':seed,'checkpoint_sha256':digest}) + return x,verified diff --git a/research/chromatic_observer_gym_v1/frozen_loop_activations.json.gz b/research/chromatic_observer_gym_v1/frozen_loop_activations.json.gz new file mode 100644 index 000000000..0ca4c4732 Binary files /dev/null and b/research/chromatic_observer_gym_v1/frozen_loop_activations.json.gz differ diff --git a/research/chromatic_observer_gym_v1/frozen_loop_weights.json.gz b/research/chromatic_observer_gym_v1/frozen_loop_weights.json.gz new file mode 100644 index 000000000..8f4e68915 Binary files /dev/null and b/research/chromatic_observer_gym_v1/frozen_loop_weights.json.gz differ diff --git a/research/chromatic_observer_gym_v1/gauge_orbit_codes.py b/research/chromatic_observer_gym_v1/gauge_orbit_codes.py new file mode 100644 index 000000000..11857857d --- /dev/null +++ b/research/chromatic_observer_gym_v1/gauge_orbit_codes.py @@ -0,0 +1,107 @@ +"""COE-06: finite cyclic-gauge observer codes and independent replay. + +All metric checks are exact Hamming computations. Construction uses a pinned +14-bit, constant-weight-six codebook found by integer programming; the witness +is validated independently, without requiring an optimizer. +""" +from __future__ import annotations + +from collections import Counter +from itertools import combinations +from math import comb +from typing import Sequence + +WIDTH = 14 +WEIGHT = 6 +# Feasible orbit-representative words from a T=14, weight=6 integer program. +# Each pair of *orbits* is separated by at least four Hamming positions. +ORBIT_WORDS = (207, 243, 311, 473, 543, 629, 697, 811, 851, 903, 1133, + 1175, 1337, 1351, 1419, 1445, 1587, 1677, 1865, 2451, 2709) + + +def rotate(word: int, width: int = WIDTH) -> int: + if width < 1 or not 0 <= word < (1 << width): + raise ValueError("word must fit in a positive-width register") + return (word >> 1) | ((word & 1) << (width - 1)) + + +def orbit(word: int, width: int = WIDTH) -> tuple[int, ...]: + result = set() + current = word + for _ in range(width): + result.add(current) + current = rotate(current, width) + return tuple(sorted(result)) + + +def necklace(word: int, width: int = WIDTH) -> int: + return min(orbit(word, width)) + + +def orbit_distance(left: int, right: int, width: int = WIDTH) -> int: + """Min Hamming distance between two rotation orbits.""" + return min((left ^ shift).bit_count() for shift in orbit(right, width)) + + +def trace(word: int, visits: int = WIDTH, width: int = WIDTH) -> int: + """One tied transition and a fixed one-bit head over visits.""" + state = word + history = 0 + for t in range(visits): + history |= (state & 1) << t + state = rotate(state, width) + return history + + +def decode_under_unknown_phase(observed: int, words: Sequence[int] = ORBIT_WORDS, + width: int = WIDTH, allowed_flips: int = 1) -> int | None: + """Nearest *orbit* decoding; resolves arbitrary cyclic phase plus flips. + + A candidate gets its closest cyclic rotation. If there is no unique label + within the allowed radius, reject rather than assign. + """ + if not 0 <= observed < (1 << width): + raise ValueError("out-of-range readout") + if allowed_flips < 0: + raise ValueError("negative radius") + distances = [orbit_distance(observed, word, width) for word in words] + dmin = min(distances) + if dmin > allowed_flips or distances.count(dmin) != 1: + return None + return distances.index(dmin) + + +def certificate(words: Sequence[int] = ORBIT_WORDS, width: int = WIDTH, + weight: int = WEIGHT) -> dict: + """Auditable finite witness, all distinct-label orbit pairs and corruptions.""" + words = tuple(words) + if not words or len(set(words)) != len(words): + raise ValueError("unique codebook required") + if not all(0 <= w < (1 << width) and w.bit_count() == weight for w in words): + raise ValueError("constant-weight words outside range") + orbits = tuple(orbit(w, width) for w in words) + if len(set(necklace(w, width) for w in words)) != len(words): + raise ValueError("clock-invariant label collision") + pair_d = tuple(orbit_distance(a, b, width) for a, b in combinations(words, 2)) + if pair_d and min(pair_d) < 4: + raise ValueError("single-bit correction requires cross-orbit distance >= 3") + checked = sum(1 for i, w in enumerate(words) for shifted in orbits[i] + for sample in (shifted,) + tuple(shifted ^ (1 << j) for j in range(width)) + if decode_under_unknown_phase(sample, words, width) == i) + total = sum(len(o) * (width + 1) for o in orbits) + assert checked == total + return {"schema": "COE-06-clock-invariant-single-flip-v1", + "width": width, "weight": weight, "labels": len(words), + "codebook": list(words), "distinct_necklaces": len(orbits), + "orbit_sizes": sorted(Counter(map(len, orbits)).items()), + "cross_orbit_distance_min": min(pair_d) if pair_d else None, + "pairwise_orbit_comparisons": len(pair_d), + "noiseless_and_single_flip_decoded": checked, + "noiseless_and_single_flip_total": total, + "count_only_pairwise_distinctions": 0, + "ordered_orbit_pairwise_distinctions": len(pair_d)} + + +if __name__ == "__main__": + import json + print(json.dumps(certificate(), indent=2, sort_keys=True)) diff --git a/research/chromatic_observer_gym_v1/l1_cut_codes.py b/research/chromatic_observer_gym_v1/l1_cut_codes.py new file mode 100644 index 000000000..f17b20e12 --- /dev/null +++ b/research/chromatic_observer_gym_v1/l1_cut_codes.py @@ -0,0 +1,223 @@ +"""COE-02: exact finite binary observer design with an ell_1 Lipschitz budget. + +Each binary coordinate induces a cut of the latent sample. Its Hamming distance +is the sum of the cut semimetrics. A breadth-first search over all feasible +integer pair-distance vectors finds a minimum-width cut multiset, or proves +infeasibility for a finite metric. This is deliberately an exact small-n oracle. +""" + +from collections import deque +from dataclasses import dataclass +from fractions import Fraction +from itertools import combinations +from math import ceil +from typing import Iterable, Sequence + + +Pair = tuple[int, int] + + +def metric_matrix(distance: Sequence[Sequence[object]]) -> tuple[tuple[Fraction, ...], ...]: + """Check and return an exact rational finite metric.""" + n = len(distance) + if n < 1: + raise ValueError("at least one state is required") + d = tuple(tuple(Fraction(v) for v in row) for row in distance) + if any(len(row) != n for row in d): + raise ValueError("metric must be square") + for i in range(n): + for j in range(n): + if d[i][j] < 0 or d[i][j] != d[j][i]: + raise ValueError("metric must be symmetric and nonnegative") + if (i == j) != (d[i][j] == 0): + raise ValueError("metric must separate distinct states") + if any(d[i][j] > d[i][k] + d[k][j] for k in range(n)): + raise ValueError("triangle inequality violated") + return d + + +def graph_edges(n: int, edges: Iterable[Pair]) -> tuple[Pair, ...]: + result = set() + for u, v in edges: + if not (0 <= u < n and 0 <= v < n) or u == v: + raise ValueError("evaluator edges must join distinct valid vertices") + result.add((min(u, v), max(u, v))) + return tuple(sorted(result)) + + +def crossing(mask: int, u: int, v: int) -> int: + return ((mask >> u) ^ (mask >> v)) & 1 + + +def canonical_cuts(n: int) -> tuple[int, ...]: + """One orientation of each nontrivial cut, anchored at vertex zero.""" + if n < 1: + raise ValueError("n must be positive") + return tuple(mask for mask in range(2, 1 << n, 2)) + + +@dataclass(frozen=True) +class CutObserver: + words: tuple[int, ...] + cuts: tuple[int, ...] + loads: tuple[int, ...] + capacities: tuple[int, ...] + + @property + def width(self) -> int: + return len(self.cuts) + + +def words_from_cuts(n: int, cuts: Sequence[int]) -> tuple[int, ...]: + return tuple(sum(crossing(cut, 0, u) << j for j, cut in enumerate(cuts)) + for u in range(n)) + + +def verify_observer(distance: Sequence[Sequence[object]], edges: Iterable[Pair], + L: object, margin: int, observer: CutObserver) -> bool: + d = metric_matrix(distance) + ee = graph_edges(len(d), edges) + lipschitz = Fraction(L) + if lipschitz < 0 or margin < 1 or len(observer.words) != len(d): + return False + if any(cut not in canonical_cuts(len(d)) for cut in observer.cuts): + return False + if observer.words != words_from_cuts(len(d), observer.cuts): + return False + pairs = tuple(combinations(range(len(d)), 2)) + distances = tuple((observer.words[u] ^ observer.words[v]).bit_count() + for u, v in pairs) + caps = tuple(int(lipschitz * d[u][v]) for u, v in pairs) + return (observer.loads == distances and observer.capacities == caps + and all(value <= cap for value, cap in zip(distances, caps)) + and all((observer.words[u] ^ observer.words[v]).bit_count() >= margin + for u, v in ee)) + + +def minimum_l1_observer(distance: Sequence[Sequence[object]], + edges: Iterable[Pair], L: object, margin: int = 1, + max_states: int = 250_000) -> CutObserver | None: + """Exact minimum-width observer, or None when infeasible. + + BFS states record the total cut distance for *every* pair. Every nonconstant + coordinate crosses at least one pair, so capacities bound the finite search + depth by sum(capacities). We deduplicate equal distance vectors, retaining a + witness path. max_states is a resource guard, never an infeasibility proof. + """ + d = metric_matrix(distance) + n = len(d) + ee = graph_edges(n, edges) + lipschitz = Fraction(L) + if lipschitz < 0 or margin < 1 or max_states < 1: + raise ValueError("nonnegative L, positive margin and state cap required") + pairs = tuple(combinations(range(n), 2)) + caps = tuple(int(lipschitz * d[u][v]) for u, v in pairs) + target = {pair: i for i, pair in enumerate(pairs)} + target_indices = tuple(target[e] for e in ee) + initial = (0,) * len(pairs) + if not target_indices: + return CutObserver((0,) * n, (), initial, caps) + if any(caps[i] < margin for i in target_indices): + return None + patterns = tuple((cut, tuple(crossing(cut, u, v) for u, v in pairs)) + for cut in canonical_cuts(n)) + # State paths represent the ordered list of cut masks; equivalent load + # vectors are merged because every future move depends only on loads. + queue = deque([initial]) + path = {initial: ()} + while queue: + current = queue.popleft() + if all(current[i] >= margin for i in target_indices): + cuts = path[current] + result = CutObserver(words_from_cuts(n, cuts), cuts, current, caps) + assert verify_observer(d, ee, lipschitz, margin, result) + return result + for mask, incidence in patterns: + new = tuple(current[i] + incidence[i] for i in range(len(pairs))) + if new in path or any(a > b for a, b in zip(new, caps)): + continue + if len(path) >= max_states: + raise RuntimeError("exact finite search exceeded max_states; result unknown") + path[new] = path[current] + (mask,) + queue.append(new) + return None + + +def equilateral(n: int, side: object = 1) -> tuple[tuple[Fraction, ...], ...]: + if n < 1 or Fraction(side) <= 0: + raise ValueError("nonempty equilateral metric with positive side required") + return tuple(tuple(Fraction(0) if i == j else Fraction(side) + for j in range(n)) for i in range(n)) + + +def dual_width_lower_bound(distance: Sequence[Sequence[object]], + edges: Iterable[Pair], L: object, margin: int, + alpha: dict[Pair, object], + beta: dict[Pair, object]) -> int: + """Check a rational cut dual and return its rigorous integer width bound. + + For every canonical cut S, require + sum_e alpha[e] delta_S(e) <= 1 + sum_p beta[p] delta_S(p). + Then any valid observer has width at least + ceil(margin*sum_e alpha[e] - sum_p beta[p]*floor(L*d[p])). + """ + d = metric_matrix(distance) + n = len(d) + ee = graph_edges(n, edges) + pairs = tuple(combinations(range(n), 2)) + L = Fraction(L) + if L < 0 or margin < 1: + raise ValueError("invalid L or margin") + if any(p not in ee for p in alpha) or any(p not in pairs for p in beta): + raise ValueError("unknown dual edge") + a = {e: Fraction(alpha.get(e, 0)) for e in ee} + b = {p: Fraction(beta.get(p, 0)) for p in pairs} + if any(v < 0 for v in a.values()) or any(v < 0 for v in b.values()): + raise ValueError("dual weights must be nonnegative") + for cut in canonical_cuts(n): + lhs = sum(a[e] * crossing(cut, *e) for e in ee) + rhs = 1 + sum(b[p] * crossing(cut, *p) for p in pairs) + if lhs > rhs: + raise ValueError("cut dual inequality violated") + lower = margin * sum(a.values()) - sum(b[p] * int(L * d[p[0]][p[1]]) + for p in pairs) + return max(0, ceil(lower)) + + + +def balanced_fractional_certificate(n: int) -> tuple[tuple[int, ...], Fraction, Fraction]: + """Exact symmetric fractional cut-cover witness for equilateral K_n. + + The cut-relaxation optimum is binom(n,2) / floor(n*n/4). + All balanced cuts receive one rational weight, and every pair + receives fractional separation exactly one. This is not a binary + observer when the cut weight is nonintegral. + """ + if n < 2: + raise ValueError("at least two vertices are required") + cuts = tuple(c for c in canonical_cuts(n) + if c.bit_count() in {n // 2, (n + 1) // 2}) + pairs = tuple(combinations(range(n), 2)) + incidences = [sum(crossing(c, u, v) for c in cuts) for u, v in pairs] + assert len(set(incidences)) == 1 and incidences[0] > 0 + weight = Fraction(1, incidences[0]) + value = weight * len(cuts) + assert all(weight * c == 1 for c in incidences) + assert value == Fraction(len(pairs), (n * n) // 4) + return cuts, weight, value + + +def run_reference() -> None: + from itertools import combinations + for label, n, edges, L in ( + ("K5/equilateral/L2", 5, list(combinations(range(5), 2)), 2), + ("K5/equilateral/L3", 5, list(combinations(range(5), 2)), 3), + ("C5/equilateral/L1", 5, [(i, (i + 1) % 5) for i in range(5)], 1), + ("C5/equilateral/L2", 5, [(i, (i + 1) % 5) for i in range(5)], 2), + ): + result = minimum_l1_observer(equilateral(n), edges, L) + print(f"{label}: {'infeasible' if result is None else f'k={result.width}, words={result.words}'}") + + +if __name__ == '__main__': + run_reference() diff --git a/research/chromatic_observer_gym_v1/new_fit_phase_receipt.json b/research/chromatic_observer_gym_v1/new_fit_phase_receipt.json new file mode 100644 index 000000000..3473994dd --- /dev/null +++ b/research/chromatic_observer_gym_v1/new_fit_phase_receipt.json @@ -0,0 +1,288 @@ +{ + "context_warning": "Heldout contexts appeared in original base-model training, and earlier seeds were examined in COE-04", + "records": [ + { + "candidate_count": 8891, + "comparative_best_total_head": { + "candidate_index": 1179, + "fit_order_only_hits": 6, + "fit_stable_novel_edges": 2, + "fit_total_edge_hits": 96, + "heldout_count_only_hits": 81, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 81, + "threshold": 3.229399761798635, + "weight": [ + 0.07870438835523871, + 0.10551519373886488, + -0.2503455564032902, + 0.2666007128995384, + -0.11969788773994741, + -0.08386590259254875, + -0.03691121246996507, + -0.14624819844080147, + 0.22001463315939945, + 0.06035203802969419, + 0.4131268184057953, + 0.2765680733492115, + 0.06177091443829131, + -0.3731272301460824, + 0.2362633527330657, + 0.020201992369033743, + 0.059062304673133025, + 0.0013843850339575353, + 0.08315021762785481, + -0.29806155342212765, + -0.19772153322997396, + -0.21763204985464002, + -0.10843547424769395, + 0.3299546166805052 + ] + }, + "model_seed": 2411, + "primary_stable_order_head": { + "candidate_index": 1991, + "fit_order_only_hits": 7, + "fit_stable_novel_edges": 3, + "fit_total_edge_hits": 94, + "heldout_count_only_hits": 78, + "heldout_order_only_by_context": [ + 0, + 0, + 2, + 2 + ], + "heldout_order_only_hits": 4, + "heldout_total_edge_hits": 82, + "threshold": -1.9554859608618878, + "weight": [ + -0.2313894983249619, + 0.07073786905441526, + 0.07288864811353478, + 0.12520681238016756, + -0.2902815361041874, + 0.20656516683666054, + 0.004398872910619715, + -0.09697501604988641, + -0.34321525338067055, + -0.009790986852093913, + 0.23435351441597524, + 0.04093246908027991, + 0.11671836570590823, + -0.1626743804620293, + 0.32118181961612857, + -0.16300880076667196, + 0.5111988456085238, + 0.0812430678442078, + 0.08116409111698525, + 0.07858534388579393, + -0.322690689776349, + -0.22569764055663144, + 0.005116095610765198, + 0.06341369560458393 + ] + }, + "source_checkpoint_sha256": "bfebe1d7c15fc61b0516a93fd82ffa9a34ade170c62dca48734a27a9934c8c3e" + }, + { + "candidate_count": 9182, + "comparative_best_total_head": { + "candidate_index": 4140, + "fit_order_only_hits": 0, + "fit_stable_novel_edges": 0, + "fit_total_edge_hits": 94, + "heldout_count_only_hits": 81, + "heldout_order_only_by_context": [ + 2, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 2, + "heldout_total_edge_hits": 83, + "threshold": -1.0548292354521007, + "weight": [ + -0.24188897848598173, + -0.31720779282440686, + -0.0290033649351532, + 0.416832399229388, + 0.1543277136584376, + -0.03040088090832796, + -0.10813146711746245, + -0.10374921461990942, + 0.01401700033116021, + 0.06926798294513668, + 0.257486117653666, + 0.11579599618840938, + -0.3364813659898261, + 0.12411991108338256, + -0.24199938991795578, + -0.2317039270191077, + 0.16104541387148077, + -0.047457871841037294, + 0.17572911118352613, + 0.21371998695918032, + -0.10741335917112119, + 0.2150465021998433, + -0.16870504948393789, + 0.3201778473685685 + ] + }, + "model_seed": 2412, + "primary_stable_order_head": { + "candidate_index": 7727, + "fit_order_only_hits": 4, + "fit_stable_novel_edges": 2, + "fit_total_edge_hits": 82, + "heldout_count_only_hits": 69, + "heldout_order_only_by_context": [ + 0, + 1, + 0, + 0 + ], + "heldout_order_only_hits": 1, + "heldout_total_edge_hits": 70, + "threshold": -0.7038056439907898, + "weight": [ + 0.28267771295938027, + 0.1605907696536152, + 0.2671065723353037, + -0.19744419794385917, + 0.2042543013302848, + -0.007774159160697248, + -0.04315195264335016, + 0.1700897358854358, + 0.31619172453774025, + -0.038193286657695544, + 0.10509747989784572, + -0.05926099070053918, + -0.10350417607235665, + 0.598583294514148, + -0.059312745235331164, + 0.13796083448399454, + 0.007155919999011902, + -0.1712745585547668, + -0.10544497612316887, + -0.2235665787124478, + -0.15949410408620168, + 0.015566478143263968, + 0.23200943842050983, + 0.18397137068073344 + ] + }, + "source_checkpoint_sha256": "2af2207f5e56a09154122026c7e27ff1c74b7d682b98457a202ba2aba87a878f" + }, + { + "candidate_count": 8999, + "comparative_best_total_head": { + "candidate_index": 8219, + "fit_order_only_hits": 0, + "fit_stable_novel_edges": 0, + "fit_total_edge_hits": 94, + "heldout_count_only_hits": 85, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 85, + "threshold": -1.2166943982567542, + "weight": [ + 0.13184464916753388, + 0.04087502831253138, + -0.14074005293072125, + -0.25992959815278266, + -0.17380890491620934, + 0.28337075735980133, + 0.11060275167731132, + 0.29565208497792145, + -0.09494446061924193, + 0.1862894789622902, + 0.04921349942676413, + 0.27144735908626777, + -0.37846830612425364, + 0.0327623355761804, + -0.06090492847331631, + 0.20021314688181407, + -0.34197720954136146, + 0.3758384132629755, + 0.096726122540464, + -0.028942051223020154, + -0.04881304053905369, + -0.018454860311362658, + -0.25238372488390565, + 0.20168258605822018 + ] + }, + "model_seed": 2413, + "primary_stable_order_head": { + "candidate_index": 6584, + "fit_order_only_hits": 4, + "fit_stable_novel_edges": 1, + "fit_total_edge_hits": 82, + "heldout_count_only_hits": 86, + "heldout_order_only_by_context": [ + 2, + 1, + 2, + 0 + ], + "heldout_order_only_hits": 5, + "heldout_total_edge_hits": 91, + "threshold": -0.27698150014900363, + "weight": [ + 0.12423246532574422, + 0.023326091966535237, + 0.15547923467905073, + -0.1513776814423376, + 0.18931742552980946, + -0.08189587943000136, + -0.12633366940422008, + 0.2810475567284795, + -0.10929510026654916, + -0.2714576977972092, + 0.31598170789421, + 0.023335467190641224, + 0.027642871775314156, + 0.36975237348630235, + 0.23798281784629888, + -0.008319694809600015, + 0.4382985777631211, + 0.15867039937206803, + -0.12841713108210714, + -0.22018927943391448, + -0.17853962853141114, + -0.26507045034980536, + -0.1833083028260605, + 0.03508108043754818 + ] + }, + "source_checkpoint_sha256": "cf3a08068a13f52ab87f0123cc03b4fb352e409642bc229e81e49919fcc91e83" + } + ], + "schema": "COE-05-fit-only-phase-probe-exploratory-v1", + "selection": "lexmax (fit_novel_edges_seen_in_at_least_two_contexts, fit_novel_edge_hits, fit_all_edge_hits, -candidate_index)", + "split": { + "fit": [ + 0, + 1, + 2, + 3 + ], + "heldout": [ + 4, + 5, + 6, + 7 + ] + } +} diff --git a/research/chromatic_observer_gym_v1/observer_codes.py b/research/chromatic_observer_gym_v1/observer_codes.py new file mode 100644 index 000000000..c37e884cd --- /dev/null +++ b/research/chromatic_observer_gym_v1/observer_codes.py @@ -0,0 +1,269 @@ +"""COE-01: finite exact chromatic observers with Hamming-noise certificates. + +Standard-library reference. A vertex represents a unit vector e_v in R^n. +An edge marks a distinction an evaluator must preserve. Codewords are +binary probe outputs, with Hamming margin controlling adversarial flips. +""" + +from itertools import combinations +from math import dist +from typing import Iterable + + +def check_graph(n: int, edges: Iterable[tuple[int, int]]) -> tuple[tuple[int, int], ...]: + if n < 1: + raise ValueError("require at least one latent state") + clean = set() + for a, b in edges: + if not 0 <= a < n or not 0 <= b < n or a == b: + raise ValueError("undirected simple graph with vertices 0..n-1 required") + clean.add(tuple(sorted((a, b)))) + return tuple(sorted(clean)) + + +def _adjacency(n: int, edges: tuple[tuple[int, int], ...]) -> list[set[int]]: + a = [set() for _ in range(n)] + for u, v in edges: + a[u].add(v) + a[v].add(u) + return a + + +def optimal_coloring(n: int, edges: Iterable[tuple[int, int]]) -> tuple[int, ...]: + """Exact chromatic coloring via ordered branch and bound, small n only.""" + ee = check_graph(n, edges) + adj = _adjacency(n, ee) + order = sorted(range(n), key=lambda v: (-len(adj[v]), v)) + partial = [-1] * n + best = list(range(n)) + best_count = n + + def walk(i: int, used: int) -> None: + nonlocal best, best_count + if i == n: + if used < best_count: + best, best_count = partial.copy(), used + return + v = order[i] + blocked = {partial[u] for u in adj[v] if partial[u] >= 0} + for color in range(min(used + 1, best_count)): + if color in blocked: + continue + partial[v] = color + walk(i + 1, max(used, color + 1)) + partial[v] = -1 + + walk(0, 0) + return tuple(best) + + +def hamming(a: int, b: int) -> int: + return (a ^ b).bit_count() + + +def _search_margin(n: int, edges: tuple[tuple[int, int], ...], k: int, + margin: int) -> tuple[int, ...] | None: + adj = _adjacency(n, edges) + order = sorted(range(n), key=lambda v: (-len(adj[v]), v)) + assignment = [-1] * n + candidates = range(1 << k) + + def walk(i: int) -> bool: + if i == n: + return True + v = order[i] + # XOR with the first word is a global isometry of Hamming space. + words = (0,) if i == 0 else candidates + for word in words: + if all(assignment[u] < 0 or hamming(word, assignment[u]) >= margin + for u in adj[v]): + assignment[v] = word + if walk(i + 1): + return True + assignment[v] = -1 + return False + + return tuple(assignment) if walk(0) else None + + +def minimum_observer(n: int, edges: Iterable[tuple[int, int]], + margin: int = 1) -> tuple[int, tuple[int, ...]]: + """Return exact minimum binary width and an edge-margin witness. + + This exponential search is intended for n<=8, margin<=3. The ordinary + coloring construction gives a certified finite upper bound. + """ + ee = check_graph(n, edges) + if margin < 1: + raise ValueError("margin must be positive") + coloring = optimal_coloring(n, ee) + num_colors = max(coloring) + 1 + base_k = (num_colors - 1).bit_length() + if margin == 1: + return base_k, coloring + for k in range(base_k, margin * base_k + 1): + witness = _search_margin(n, ee, k, margin) + if witness is not None: + return k, witness + raise AssertionError("repeated color bits must yield a witness") + + +def validate_code(n: int, edges: Iterable[tuple[int, int]], + k: int, words: tuple[int, ...], margin: int = 1) -> bool: + ee = check_graph(n, edges) + return (len(words) == n and k >= 0 and margin >= 1 + and all(0 <= w < 1 << k for w in words) + and all(hamming(words[u], words[v]) >= margin for u, v in ee)) + + +def hamming_ball_volume(k: int, radius: int) -> int: + from math import comb + return sum(comb(k, j) for j in range(min(k, radius) + 1)) + + +def clique_bound_holds(clique_size: int, k: int, flips: int) -> bool: + """Sphere-packing necessary condition for complete-graph t-flip codes.""" + return clique_size * hamming_ball_volume(k, flips) <= (1 << k) + + +def vertex_point(vertex: int, n: int) -> tuple[float, ...]: + if vertex < 0 or vertex >= n: + raise ValueError("invalid vertex") + return tuple(1.0 if i == vertex else 0.0 for i in range(n)) + + +def extend_probe(x: tuple[float, ...], n: int, k: int, + words: tuple[int, ...]) -> tuple[float, ...]: + """Explicit coordinatewise McShane extension into [0,1]^k. + + On {0,e_0,...,e_(n-1)} the origin gets a half-vector and each + spoke its bitword. The finite map has ell_infinity Lipschitz <= 1. + Clipping an inf-of-cones preserves the 1-Lipschitz bound. + """ + if len(x) != n or len(words) != n: + raise ValueError("dimension mismatch") + radius = sum(v * v for v in x) ** 0.5 + leaf_radii = tuple(dist(x, vertex_point(v, n)) for v in range(n)) + output = [] + for j in range(k): + cones = [0.5 + radius] + cones.extend(float((words[v] >> j) & 1) + leaf_radii[v] + for v in range(n)) + output.append(min(1.0, max(0.0, min(cones)))) + return tuple(output) + + +def complete_edges(n: int) -> tuple[tuple[int, int], ...]: + return tuple(combinations(range(n), 2)) + + +if __name__ == "__main__": + for label, n, edges in ( + ("full-six", 6, complete_edges(6)), + ("path-eight", 8, tuple((i, i + 1) for i in range(7))), + ("cycle-five", 5, tuple((i, (i + 1) % 5) for i in range(5))), + ): + for margin in (1, 3): + k, code = minimum_observer(n, edges, margin) + assert validate_code(n, edges, k, code, margin) + print(f"{label}: margin={margin}, k={k}, words={code}") + + +def metric_quotient_observer( + distance: tuple[tuple[object, ...], ...], + edges: Iterable[tuple[int, int]], + lipschitz: object, + margin: int = 1, +) -> tuple[int, tuple[int, ...], tuple[int, ...]]: + """Exact task-relative bit width under an L-Lipschitz constraint. + + Assumes a finite *metric* (verified here), with exact rational distances. + Distances < 1/L force equal binary codes. Take their transitive closure, + reject tested edges inside a component, then color the quotient graph. + + Returns (minimum_bit_width, lifted_codewords, vertex_component_ids). + The binary code is 1-Lipschitz under output ell_infinity when L=1, + or L-Lipschitz at general positive L. + """ + from fractions import Fraction + + n = len(distance) + ee = check_graph(n, edges) + L = Fraction(lipschitz) + if L <= 0: + raise ValueError("Lipschitz constant must be positive") + d = tuple(tuple(Fraction(x) for x in row) for row in distance) + if any(len(row) != n for row in d): + raise ValueError("metric must be a square matrix") + for i in range(n): + for j in range(n): + if (d[i][j] < 0 or d[i][j] != d[j][i] or + (i == j and d[i][j] != 0) or + (i != j and d[i][j] == 0)): + raise ValueError("matrix must define a genuine metric") + for k in range(n): + if d[i][j] > d[i][k] + d[k][j]: + raise ValueError("triangle inequality violated") + + parent = list(range(n)) + + def find(i: int) -> int: + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + for i in range(n): + for j in range(i + 1, n): + if L * d[i][j] < 1: + parent[find(j)] = find(i) + roots = [find(i) for i in range(n)] + root_order = {r: i for i, r in enumerate(sorted(set(roots)))} + components = tuple(root_order[r] for r in roots) + quotient_edges = [] + for u, v in ee: + a, b = components[u], components[v] + if a == b: + raise ValueError("evaluator asks to distinguish forced-equivalent points") + quotient_edges.append((a, b)) + count = len(root_order) + k, codes = minimum_observer(count, quotient_edges, margin) + lifted = tuple(codes[components[i]] for i in range(n)) + assert validate_code(n, ee, k, lifted, margin) + assert all(lifted[i] == lifted[j] or L * d[i][j] >= 1 + for i in range(n) for j in range(n)) + return k, lifted, components + + +def critical_lipschitz( + distance: tuple[tuple[object, ...], ...], + edges: Iterable[tuple[int, int]], +): + """Exact positive L threshold for the existence of any binary observer. + + Floyd--Warshall in the (min,max) bottleneck semiring computes + rho(u,v) = min_{paths u->v} max_{edge in path} d(edge). + Feasibility is L >= max_{tested uv} 1 / rho(u,v), at equality too. + Returns Fraction(0) when there are no tested edges. + """ + from fractions import Fraction + n = len(distance) + ee = check_graph(n, edges) + d = [[Fraction(x) for x in row] for row in distance] + if any(len(row) != n for row in d): + raise ValueError("metric must be square") + for i in range(n): + for j in range(n): + if (d[i][j] < 0 or d[i][j] != d[j][i] or + (i == j and d[i][j] != 0) or + (i != j and d[i][j] == 0)): + raise ValueError("metric invalid") + for k in range(n): + if d[i][j] > d[i][k] + d[k][j]: + raise ValueError("triangle inequality violated") + for via in range(n): + for i in range(n): + for j in range(n): + d[i][j] = min(d[i][j], max(d[i][via], d[via][j])) + return max((Fraction(1) / d[i][j] for i, j in ee), + default=Fraction(0)) \ No newline at end of file diff --git a/research/chromatic_observer_gym_v1/old_fit_phase_receipt.json b/research/chromatic_observer_gym_v1/old_fit_phase_receipt.json new file mode 100644 index 000000000..b488c7d38 --- /dev/null +++ b/research/chromatic_observer_gym_v1/old_fit_phase_receipt.json @@ -0,0 +1,288 @@ +{ + "context_warning": "Heldout contexts appeared in original base-model training, and earlier seeds were examined in COE-04", + "records": [ + { + "candidate_count": 9208, + "comparative_best_total_head": { + "candidate_index": 3407, + "fit_order_only_hits": 3, + "fit_stable_novel_edges": 0, + "fit_total_edge_hits": 96, + "heldout_count_only_hits": 90, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 90, + "threshold": -0.013380859141644726, + "weight": [ + -0.0914024906157206, + -0.16040735176889975, + 0.32069835407137043, + -0.12113378199993026, + 0.15069117640182203, + -0.004398961899197071, + 0.09805816890852496, + -0.051712704228224715, + 0.19261519982111497, + 0.2953390880057344, + 0.18530284424524832, + -0.08594333006574303, + 0.1345486703926474, + 0.06810443990498506, + -0.05053553953120918, + 0.28620215340383753, + -0.42716245667477815, + -0.5166912720632082, + -0.06875742524629029, + 0.0874634682908486, + -0.14716451921066914, + 0.09738170827305617, + 0.19543028851810276, + -0.0947233692321388 + ] + }, + "model_seed": 2406, + "primary_stable_order_head": { + "candidate_index": 5555, + "fit_order_only_hits": 7, + "fit_stable_novel_edges": 1, + "fit_total_edge_hits": 49, + "heldout_count_only_hits": 37, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 37, + "threshold": 0.2490663549072516, + "weight": [ + -0.13725604557360352, + 0.02217992204777205, + -0.21337964470732906, + -0.2539165734189918, + 0.15519290477159953, + 0.12935394941198394, + -0.1178389280481954, + 0.0944058490701851, + 0.06089666281579438, + -0.290440949250979, + -0.036178338255069935, + 0.3149782806014192, + 0.16772394513684125, + -0.2969626209428101, + -0.0943772029277936, + -0.20326669478855994, + 0.27046773905756766, + 0.18029838859557287, + -0.16280660963931023, + -0.17041326633917123, + -0.3736194421422249, + -0.16381123402682565, + 0.34113161764993793, + -0.0889839219362548 + ] + }, + "source_checkpoint_sha256": "13b9c3c63f7d7d27ef9aac2144fd2dd5469e144d940bee97e0a975a38e1d1841" + }, + { + "candidate_count": 9228, + "comparative_best_total_head": { + "candidate_index": 5723, + "fit_order_only_hits": 6, + "fit_stable_novel_edges": 2, + "fit_total_edge_hits": 96, + "heldout_count_only_hits": 69, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 69, + "threshold": 1.111505563299672, + "weight": [ + -0.23763620662042345, + -0.01798887512131229, + -0.04149519495567329, + 0.3425231693800933, + 0.02860471226181845, + -0.06175614741245958, + -0.12600773440523833, + 0.3342396074766067, + -0.12248240153980312, + -0.03353670154558211, + -0.07069162678086334, + 0.11771002376230566, + 0.39284233289766085, + 0.257443728465213, + -0.1375129571950989, + 0.2561519991408456, + 0.07117824322235426, + -0.23881739164288412, + -0.11259550510779327, + 0.25724778851249913, + -0.4472334259215376, + 0.09004933119180317, + -0.05168999769721023, + -0.008773370961935725 + ] + }, + "model_seed": 2407, + "primary_stable_order_head": { + "candidate_index": 5723, + "fit_order_only_hits": 6, + "fit_stable_novel_edges": 2, + "fit_total_edge_hits": 96, + "heldout_count_only_hits": 69, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 69, + "threshold": 1.111505563299672, + "weight": [ + -0.23763620662042345, + -0.01798887512131229, + -0.04149519495567329, + 0.3425231693800933, + 0.02860471226181845, + -0.06175614741245958, + -0.12600773440523833, + 0.3342396074766067, + -0.12248240153980312, + -0.03353670154558211, + -0.07069162678086334, + 0.11771002376230566, + 0.39284233289766085, + 0.257443728465213, + -0.1375129571950989, + 0.2561519991408456, + 0.07117824322235426, + -0.23881739164288412, + -0.11259550510779327, + 0.25724778851249913, + -0.4472334259215376, + 0.09004933119180317, + -0.05168999769721023, + -0.008773370961935725 + ] + }, + "source_checkpoint_sha256": "46a99c7a348d2d0250ff9f7289ed2c3078cd847f506a65941d24dd5213e217ee" + }, + { + "candidate_count": 8751, + "comparative_best_total_head": { + "candidate_index": 6137, + "fit_order_only_hits": 3, + "fit_stable_novel_edges": 1, + "fit_total_edge_hits": 97, + "heldout_count_only_hits": 79, + "heldout_order_only_by_context": [ + 0, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 0, + "heldout_total_edge_hits": 79, + "threshold": 0.854664320647855, + "weight": [ + 0.2869751154156453, + -0.1080168608735992, + -0.33050138622487124, + 0.09302628528894769, + -0.22015971046339006, + -0.3454603867581149, + -0.2312814236416369, + 0.18569454687211256, + 0.07075509534009695, + 0.06292218601084326, + 0.03688836922353379, + 0.16554587381516467, + -0.04694596495797266, + -0.5041239891449918, + 0.31414619607266314, + -0.1717295453238383, + -0.042008165775190565, + -0.10190019282332959, + 0.07320698764481123, + -0.1490611558191296, + -0.241304921459875, + 0.06597140759465223, + 0.08422580509783541, + -0.02548096029927475 + ] + }, + "model_seed": 2408, + "primary_stable_order_head": { + "candidate_index": 4230, + "fit_order_only_hits": 4, + "fit_stable_novel_edges": 2, + "fit_total_edge_hits": 88, + "heldout_count_only_hits": 83, + "heldout_order_only_by_context": [ + 1, + 0, + 0, + 0 + ], + "heldout_order_only_hits": 1, + "heldout_total_edge_hits": 84, + "threshold": -0.8100840154208686, + "weight": [ + -0.0014172978379616919, + 0.021564073190913385, + 0.03710923152351813, + 0.07518321636255106, + -0.1412593602057424, + 0.24355971244953048, + -0.19484975120303855, + -0.039671811546157745, + 0.31645782238810916, + -0.4854594183511063, + -0.16337529778195392, + -0.31350744891304194, + 0.25179177809418873, + -0.031521854681495765, + -0.07301364381927451, + 0.10101882349877898, + -0.13855147938024603, + 0.03182106433020296, + -0.11465873138361779, + 0.28260194701777946, + -0.113711313021576, + -0.04025225934998859, + -0.29230605998604486, + 0.3460510142713016 + ] + }, + "source_checkpoint_sha256": "5bb8809a753e08f5ade9f3ff40b3ec50cecdb2aa8085c3a2624506d201196a88" + } + ], + "schema": "COE-05-fit-only-phase-probe-exploratory-v1", + "selection": "lexmax (fit_novel_edges_seen_in_at_least_two_contexts, fit_novel_edge_hits, fit_all_edge_hits, -candidate_index)", + "split": { + "fit": [ + 0, + 1, + 2, + 3 + ], + "heldout": [ + 4, + 5, + 6, + 7 + ] + } +} diff --git a/research/chromatic_observer_gym_v1/phase_code_receipt.json b/research/chromatic_observer_gym_v1/phase_code_receipt.json new file mode 100644 index 000000000..6b444bc24 --- /dev/null +++ b/research/chromatic_observer_gym_v1/phase_code_receipt.json @@ -0,0 +1,39 @@ +{ + "all_weight4_necklaces_width8": 10, + "book_necklace_multiplicities": [ + 2, + 4, + 4, + 4 + ], + "book_necklaces": 4, + "codes_decimal": [ + 85, + 170, + 51, + 204, + 153, + 102, + 15, + 240, + 165, + 90, + 195, + 60, + 105, + 150 + ], + "count_only_evaluator_edges": 0, + "dimension": 8, + "hamming_weight": 4, + "labels": 14, + "max_hamming_distance": 8, + "max_packing_upper_bound_width7": 7, + "min_hamming_distance": 4, + "ordered_evaluator_edges": 91, + "packing_upper_bound_width8": 14, + "schema": "COE-05-constant-weight-phase-code-v1", + "single_flip_correct": 112, + "single_flip_total": 112, + "unknown_uniform_rotation_bayes_accuracy": 0.2857142857142857 +} diff --git a/research/chromatic_observer_gym_v1/phase_gauge_replay.py b/research/chromatic_observer_gym_v1/phase_gauge_replay.py new file mode 100644 index 000000000..68062161e --- /dev/null +++ b/research/chromatic_observer_gym_v1/phase_gauge_replay.py @@ -0,0 +1,81 @@ +"""Evaluate whether already-selected frozen one-bit heads survive lost tick-zero. + +This is a pure post-hoc diagnostic on immutable COE-05 fit-only heads. It does +not refit, inspect labels to select a model, or touch holdout data while +constructing the observer. Original COE-05 metric remains the primary one. +""" +from __future__ import annotations +import argparse +import json +from pathlib import Path + +try: + from .gauge_orbit_codes import necklace +except ImportError: + from gauge_orbit_codes import necklace + +# Reuse COE-05 parser from the same package; deliberately no torch or numpy. +try: + from .phase_order_replay import code_by_label, load_json, verify_receipt, EDGES, HELDOUT, FIT +except ImportError: + from phase_order_replay import code_by_label, load_json, verify_receipt, EDGES, HELDOUT, FIT + + +def evaluate(item: dict, head: dict, contexts=HELDOUT) -> dict: + n = len(EDGES) * len(contexts) + counts = dict(ordered=0, count=0, cyclic=0, order_only=0, + cyclic_beyond_count=0, phase_sensitive_only=0, denominator=n) + breakdown = [] + for ctx in contexts: + words = code_by_label(item, head, ctx) + ordered = len({w for w in words}) + detail = dict(context=ctx, distinct_codes=ordered, + distinct_necklaces=len({necklace(w, 4) for w in words}), + distinct_counts=len({w.bit_count() for w in words})) + for a, b in EDGES: + aw, bw = words[a], words[b] + x = aw != bw + y = aw.bit_count() != bw.bit_count() + z = necklace(aw, 4) != necklace(bw, 4) + assert (not y or z) and (not z or x) + counts['ordered'] += x + counts['count'] += y + counts['cyclic'] += z + counts['order_only'] += x and not y + counts['cyclic_beyond_count'] += z and not y + counts['phase_sensitive_only'] += x and not z + breakdown.append(detail) + counts['context_details'] = breakdown + return counts + + +def evidence(activations: dict, receipt: dict) -> dict: + verify_receipt(activations, receipt) + items={i['model_seed']:i for i in activations['items']} + result=[] + for row in receipt['records']: + head=row['primary_stable_order_head'] + m=evaluate(items[row['model_seed']], head) + assert m['ordered']==head['heldout_total_edge_hits'] + assert m['count']==head['heldout_count_only_hits'] + assert m['order_only']==head['heldout_order_only_hits'] + result.append(dict(model_seed=row['model_seed'],model_checkpoint_sha256=row['source_checkpoint_sha256'],**m)) + sums={k:sum(r[k] for r in result) for k in + ('ordered','count','cyclic','order_only','cyclic_beyond_count', + 'phase_sensitive_only','denominator')} + return dict(schema='COE-06-posthoc-frozen-phase-gauge-v1', + source_schema=receipt['schema'], + cohort_results=result, pooled=sums, + interpretation='post-hoc on fit-only selected COE-05 heads; no new fitting') + + +if __name__=='__main__': + p=argparse.ArgumentParser() + p.add_argument('--activation',type=Path,required=True) + p.add_argument('--receipt',type=Path,required=True) + p.add_argument('--out',type=Path) + opts=p.parse_args() + result=evidence(load_json(opts.activation),load_json(opts.receipt)) + content=json.dumps(result,indent=2,sort_keys=True)+'\n' + if opts.out:opts.out.write_text(content,encoding='utf-8') + print(content) diff --git a/research/chromatic_observer_gym_v1/phase_order_replay.py b/research/chromatic_observer_gym_v1/phase_order_replay.py new file mode 100644 index 000000000..9e462b707 --- /dev/null +++ b/research/chromatic_observer_gym_v1/phase_order_replay.py @@ -0,0 +1,122 @@ +"""COE-05: independently replay selected heads, model/split gates and exact counts. + +Pure standard-library validator; full fit-only hyperplane search is a separate +optional NumPy runner. This module never performs model inference or fits heads. +""" +from __future__ import annotations +import gzip, hashlib, json, math +from pathlib import Path + +FIT = (0, 1, 2, 3) +HELDOUT = (4, 5, 6, 7) +N = 8 +T = 4 +D = 24 +EDGES = tuple((a,b) for a in range(N) for b in range(a+1,N)) + + +def load_json(path: Path) -> dict: + if str(path).endswith('.gz'): + with gzip.open(path,'rt',encoding='utf8') as file: + return json.load(file) + return json.loads(path.read_text(encoding='utf8')) + + +def digest_file(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def code_by_label(item, head, context): + weights=head['weight']; theta=head['threshold'] + if len(weights) != D or not all(math.isfinite(x) for x in weights+[theta]): + raise ValueError('invalid readout') + result=[] + for a in range(N): + history=item['activations'][f'{a}:{context}'] + if len(history)!=T or any(len(v)!=D for v in history): + raise ValueError('invalid trace shape') + word=0 + for t in range(T): + value=sum(weights[j]*history[t][j] for j in range(D)) + if value>theta: word |= (1 << t) + result.append(word) + return tuple(result) + + +def score_head(item, head): + counts={name:0 for name in ('fit_order_only_hits','fit_total_edge_hits', + 'heldout_order_only_hits','heldout_total_edge_hits','heldout_count_only_hits')} + stable_edges={edge:0 for edge in EDGES} + by_heldout_context=[] + for context in FIT+HELDOUT: + words=code_by_label(item,head,context) + novel=total=count=0 + for a,b in EDGES: + differs=words[a]!=words[b] + count_diff=words[a].bit_count()!=words[b].bit_count() + if differs: total+=1 + if count_diff: count+=1 + if differs and not count_diff: + novel+=1 + if context in FIT:stable_edges[(a,b)]+=1 + if context in FIT: + counts['fit_order_only_hits']+=novel + counts['fit_total_edge_hits']+=total + else: + counts['heldout_order_only_hits']+=novel + counts['heldout_total_edge_hits']+=total + counts['heldout_count_only_hits']+=count + by_heldout_context.append(novel) + counts['fit_stable_novel_edges']=sum(v>=2 for v in stable_edges.values()) + counts['heldout_order_only_by_context']=by_heldout_context + return counts + + +def verify_receipt(bundle: dict, receipt: dict): + if bundle['schema']!='COE-04-native-tied-loop-frozen-v1':raise ValueError('model source schema') + if receipt['schema']!='COE-05-fit-only-phase-probe-exploratory-v1':raise ValueError('receipt schema') + if tuple(bundle['probe_fit_contexts'])!=FIT or tuple(bundle['probe_heldout_contexts'])!=HELDOUT: + raise ValueError('source split changed') + if receipt['split']!={'fit':list(FIT),'heldout':list(HELDOUT)}: + raise ValueError('receipt split changed') + items={item['model_seed']:item for item in bundle['items']} + if len(items)!=len(bundle['items']) or len(items)!=len(receipt['records']): + raise ValueError('duplicate or missing seeds') + for r in receipt['records']: + item=items[r['model_seed']] + if r['source_checkpoint_sha256']!=item['model_checkpoint_sha256']: + raise ValueError('unmatched checkpoint SHA') + if item['train_steps'] !=160 or item['train_examples']!=64: + raise ValueError('changed base model') + if len(item['model_predictions'])!=64 or any(item['model_predictions'][8*a+b]!=a + for a in range(N) for b in range(N)): + raise ValueError('base model has not passed admission gate') + if set(item['activations'])!={f'{a}:{b}' for a in range(8) for b in range(8)}: + raise ValueError('missing activation cells') + for key in ('primary_stable_order_head','comparative_best_total_head'): + head=r[key] + actual=score_head(item,head) + for field,value in actual.items(): + if head[field]!=value: + raise ValueError(f'head scoreboard mismatch {r["model_seed"]}:{key}:{field}') + if r['candidate_count']<=0:raise ValueError('empty search pool') + return True + + +def pooled(receipt): + rows=[r['primary_stable_order_head'] for r in receipt['records']] + return {'model_seeds':[r['model_seed'] for r in receipt['records']], + 'heldout_total':sum(r['heldout_total_edge_hits'] for r in rows), + 'heldout_count_only':sum(r['heldout_count_only_hits'] for r in rows), + 'heldout_order_only':sum(r['heldout_order_only_hits'] for r in rows), + 'denominator':len(rows)*4*len(EDGES)} + + +if __name__=='__main__': + import argparse + p=argparse.ArgumentParser(); p.add_argument('--activation',type=Path,required=True) + p.add_argument('--receipt',type=Path,required=True) + args=p.parse_args() + r=load_json(args.receipt) + verify_receipt(load_json(args.activation),r) + print(json.dumps(pooled(r),indent=2,sort_keys=True)) diff --git a/research/chromatic_observer_gym_v1/phase_order_search.py b/research/chromatic_observer_gym_v1/phase_order_search.py new file mode 100644 index 000000000..4e10af35d --- /dev/null +++ b/research/chromatic_observer_gym_v1/phase_order_search.py @@ -0,0 +1,73 @@ +"""COE-05 exploratory fit-only phase-head search on frozen 4-visit traces. + +Requires numpy only for batched speed; the standalone replay verifier is stdlib. +No held-out activation or held-out label is used when generating or selecting heads. +""" +import argparse, json, gzip, sys, hashlib, time +from pathlib import Path +import numpy as np +try: + from .temporal_observers import candidate_projections, EDGES +except ImportError: + from temporal_observers import candidate_projections, EDGES + +A,B=np.array(EDGES).T +POWERS=np.array([1,2,4,8]) + +def load(path): + with gzip.open(path,'rt') as f: return json.load(f) + +def screen_model(item): + trace=np.array([[[item['activations'][f'{label}:{ctx}'][t] + for t in range(4)] for label in range(8)] + for ctx in range(8)],dtype=np.float64) + candidates=candidate_projections(item,seed=item['model_seed']+601) + weights=np.asarray([w for w,th in candidates],dtype=np.float64) + thresholds=np.asarray([th for w,th in candidates],dtype=np.float64) + bits=np.einsum('hd,catd->hcat',weights,trace,optimize=True)>thresholds[:,None,None,None] + words=(bits.astype(np.int16)*POWERS).sum(-1) + counts=bits.sum(-1) + separated=words[:,:,A]!=words[:,:,B] + novelty=separated & (counts[:,:,A]==counts[:,:,B]) + fit=novelty[:,:4] + stable=(fit.sum(1)>=2).sum(1) + train_novel=fit.sum((1,2)) + train_total=separated[:,:4].sum((1,2)) + # Fixed fit-only selection. `np.lexsort` last criterion has priority. + idx=int(np.lexsort((-np.arange(len(candidates)),train_total,train_novel,stable))[-1]) + idx_full=int(np.lexsort((-np.arange(len(candidates)),train_novel,train_total))[-1]) + def result(i): + return {'candidate_index':int(i),'weight':[float(v) for v in candidates[i][0]], + 'threshold':float(candidates[i][1]), + 'fit_stable_novel_edges':int(stable[i]), + 'fit_order_only_hits':int(train_novel[i]), + 'fit_total_edge_hits':int(train_total[i]), + 'heldout_order_only_hits':int(novelty[i,4:].sum()), + 'heldout_total_edge_hits':int(separated[i,4:].sum()), + 'heldout_count_only_hits':int((counts[i,4:,A]!=counts[i,4:,B]).sum()), + 'heldout_order_only_by_context':[int(v) for v in novelty[i,4:].sum(1)]} + return {'model_seed':item['model_seed'], + 'source_checkpoint_sha256':item['model_checkpoint_sha256'], + 'candidate_count':len(candidates), + 'primary_stable_order_head':result(idx), + 'comparative_best_total_head':result(idx_full)} + +def main(): + p=argparse.ArgumentParser() + p.add_argument('--input',type=Path,required=True) + p.add_argument('--out',type=Path,required=True) + args=p.parse_args() + data=load(args.input) + t0=time.monotonic() + rows=[] + for item in data['items']: + row=screen_model(item) + rows.append(row) + print(row['model_seed'], 'stable order', {k:v for k,v in row['primary_stable_order_head'].items() if k not in ('weight','threshold')}, 'full',{k:v for k,v in row['comparative_best_total_head'].items() if k not in ('weight','threshold')},flush=True) + out={'schema':'COE-05-fit-only-phase-probe-exploratory-v1','split':{'fit':[0,1,2,3],'heldout':[4,5,6,7]}, + 'selection':'lexmax (fit_novel_edges_seen_in_at_least_two_contexts, fit_novel_edge_hits, fit_all_edge_hits, -candidate_index)', + 'context_warning':'Heldout contexts appeared in original base-model training, and earlier seeds were examined in COE-04', + 'records':rows} + args.out.write_text(json.dumps(out,indent=2,sort_keys=True,allow_nan=False)+'\n') + print('time',time.monotonic()-t0) +if __name__=='__main__': main() diff --git a/research/chromatic_observer_gym_v1/phase_register.py b/research/chromatic_observer_gym_v1/phase_register.py new file mode 100644 index 000000000..81ba6b122 --- /dev/null +++ b/research/chromatic_observer_gym_v1/phase_register.py @@ -0,0 +1,150 @@ +"""COE-05: exact phase-sensitive coding with one tied recurrent readout. + +No model training and no external dependencies. Eight physical recurrent states +are successive cyclic rotations of a binary register. The readout is always +bit zero; the initial register is one of 14 affine F_2^3 hyperplanes. +""" +from __future__ import annotations + +from collections import Counter +from itertools import combinations +from math import comb + +WIDTH = 8 +MASK = (1 << WIDTH) - 1 + + +def dot_f2(a: int, x: int) -> int: + return ((a & x).bit_count() & 1) + + +def affine_word(normal: int, side: int) -> int: + """The 4-point affine hyperplane {x in F_2^3 : a.x == b}.""" + if normal not in range(1, 8) or side not in (0, 1): + raise ValueError('normal must be nonzero in F2^3 and side must be a bit') + return sum((1 << x) for x in range(WIDTH) if dot_f2(normal, x) == side) + + +def phase_codebook() -> tuple[int, ...]: + return tuple(affine_word(a, b) for a in range(1, 8) for b in range(2)) + + +def rotate_right(word: int, width: int = WIDTH) -> int: + """One *time-independent* recurrent transition, no lookup by label.""" + if not 0 <= word < (1 << width) or width < 1: + raise ValueError('word outside register alphabet') + return ((word >> 1) | ((word & 1) << (width - 1))) + + +def shared_readout(word: int) -> int: + return word & 1 + + +def ordered_trace(initial_state: int, visits: int = WIDTH) -> int: + state = initial_state + transcript = 0 + for step in range(visits): + transcript |= shared_readout(state) << step + state = rotate_right(state) + return transcript + + +def hamming(a: int, b: int) -> int: + return (a ^ b).bit_count() + + +def decode_nearest(trace: int, book: tuple[int, ...], max_flips: int = 1) -> int | None: + distances = tuple(hamming(trace, w) for w in book) + least = min(distances) + if least > max_flips or distances.count(least) != 1: + return None + return distances.index(least) + + +def rotation_orbit(word: int, width: int = WIDTH) -> frozenset[int]: + seen = set() + x = word + for _ in range(width): + seen.add(x) + x = rotate_right(x, width) + return frozenset(seen) + + +def orbit_id(word: int, width: int = WIDTH) -> int: + return min(rotation_orbit(word, width)) + + +def necklace_count(width: int, weight: int) -> int: + """Burnside enumeration of constant-weight cyclic binary necklaces.""" + if not (0 <= weight <= width) or width < 1: + raise ValueError('bad width/weight') + from math import gcd + fixed = 0 + for shift in range(width): + cycles = gcd(width, shift) + cycle_length = width // cycles + if weight % cycle_length == 0: + fixed += comb(cycles, weight // cycle_length) + assert fixed % width == 0 + return fixed // width + + +def triple_packing_bound(width: int, weight: int) -> int: + """Sharp pairwise-distance >=4 upper bound for constant weight. + + Each support (w-1)-subset belongs to at most one codeword. + Complement symmetry gives an independent bound. + """ + if not 0 <= weight <= width or width < 1: + raise ValueError('invalid params') + if weight == 0 or weight == width: + return 1 + if weight == 1 or weight == width - 1: + return 1 + return min(comb(width, weight - 1) // weight, + comb(width, width - weight - 1) // (width - weight)) + + +def evidence() -> dict: + book = phase_codebook() + assert len(book) == 14 and len(set(book)) == 14 + ds = [hamming(x, y) for x, y in combinations(book, 2)] + weight_set = {w.bit_count() for w in book} + assert weight_set == {4} + assert min(ds) == 4 and max(ds) == 8 + assert all(ordered_trace(x) == x for x in book) + error_hits = sum(decode_nearest(word ^ (1 << j), book) == i + for i, word in enumerate(book) for j in range(WIDTH)) + assert error_hits == 14 * WIDTH + orbits = Counter(orbit_id(w) for w in book) + # Without phase registration, uniform cyclic rotations yield identical + # distributions for labels belonging to the same orbit. + blind_bayes = len(orbits) / len(book) + assert necklace_count(WIDTH, 4) == 10 + assert triple_packing_bound(8, 4) == 14 + max_width7 = max(triple_packing_bound(7, w) for w in range(8)) + assert max_width7 == 7 + return { + 'schema': 'COE-05-constant-weight-phase-code-v1', + 'dimension': 8, + 'labels': len(book), + 'codes_decimal': list(book), + 'hamming_weight': 4, + 'min_hamming_distance': min(ds), + 'max_hamming_distance': max(ds), + 'ordered_evaluator_edges': len(ds), + 'count_only_evaluator_edges': 0, + 'single_flip_correct': error_hits, + 'single_flip_total': len(book) * WIDTH, + 'packing_upper_bound_width8': triple_packing_bound(8,4), + 'max_packing_upper_bound_width7': max_width7, + 'all_weight4_necklaces_width8': necklace_count(8,4), + 'book_necklaces': len(orbits), + 'book_necklace_multiplicities': sorted(orbits.values()), + 'unknown_uniform_rotation_bayes_accuracy': blind_bayes, + } + + +if __name__ == '__main__': + import json + print(json.dumps(evidence(), sort_keys=True, indent=2)) diff --git a/research/chromatic_observer_gym_v1/replication_activations.json.gz b/research/chromatic_observer_gym_v1/replication_activations.json.gz new file mode 100644 index 000000000..b851d6e7c Binary files /dev/null and b/research/chromatic_observer_gym_v1/replication_activations.json.gz differ diff --git a/research/chromatic_observer_gym_v1/replication_weights.json.gz b/research/chromatic_observer_gym_v1/replication_weights.json.gz new file mode 100644 index 000000000..32bb7fa56 Binary files /dev/null and b/research/chromatic_observer_gym_v1/replication_weights.json.gz differ diff --git a/research/chromatic_observer_gym_v1/resource_bound.py b/research/chromatic_observer_gym_v1/resource_bound.py new file mode 100644 index 000000000..865011022 --- /dev/null +++ b/research/chromatic_observer_gym_v1/resource_bound.py @@ -0,0 +1,62 @@ +"""Exact integer combinatorial upper bounds on phase-blind one-flip codes. + +Two different labels whose cyclic orbits have minimum Hamming distance >=4 +cannot share a rotated (w-1)-element sub-support. Each code orbit consumes +some number of (w-1)-necklace classes, which are disjoint across labels. +An integer count of the cheapest possible resource usage gives a *rigorous* +upper bound without an optimizer or SAT solver. +""" +from __future__ import annotations +from itertools import combinations +from math import comb +try: + from .gauge_orbit_codes import necklace +except ImportError: + from gauge_orbit_codes import necklace + + +def _subsets(T, w): + for bits in combinations(range(T), w): + yield sum(1 << b for b in bits) + + +def deletion_bound(T:int,w:int): + if T < 1 or not 0 <= w <= T:raise ValueError('bad width/weight') + if w==0:return {'T':T,'w':w,'total_resources':0,'usage_counts':{},'bound':1} + reps=sorted(set(necklace(word,T) for word in _subsets(T,w))) + subreps=set(necklace(word,T) for word in _subsets(T,w-1)) + resource_hist={} + for word in reps: + resource_count=len({necklace(word^(1< T//2:continue # complements yield identical bounds + b=deletion_bound(T,w) + # complement: superset (+1) necklace resource bound on original w + bc=deletion_bound(T,T-w) + b['complement_bound']=bc['bound'] + b['combined_bound']=min(b['bound'],bc['bound']) + full.append(b) + return full + + +if __name__=='__main__': + import json + for row in all_small_bounds(13): + if row['T']>=8: + print(row['T'],row['w'],row['total_resources'],row['usage_counts'],row['bound'],row['complement_bound'],row['combined_bound']) + print('maximum 1..13:',max(r['combined_bound'] for r in all_small_bounds(13))) diff --git a/research/chromatic_observer_gym_v1/run_cap2_control.py b/research/chromatic_observer_gym_v1/run_cap2_control.py new file mode 100644 index 000000000..25bfc8691 --- /dev/null +++ b/research/chromatic_observer_gym_v1/run_cap2_control.py @@ -0,0 +1,39 @@ +"""Post-hoc COE-04C: fit-only hard diameter-two constraint for temporal bits.""" +import argparse,json +from pathlib import Path +from frozen_loader import read_payload +from temporal_observers import candidate_projections,encode,covered_pairs,FIT_CONTEXTS,TEST_CONTEXTS,EDGES + +def diameter(observations): + return max((sum(x!=y for x,y in zip(row[a],row[b])) + for row in observations for a,b in EDGES),default=0) + +def fit_cap2(item): + candidates=candidate_projections(item,seed=item['model_seed']+601) + best=None; feasible=0 + for head in candidates: + train=encode(item,head,FIT_CONTEXTS,'temporal') + if diameter(train)>2:continue + feasible+=1 + score=covered_pairs(train) + if best is None or score>best['fit_edge_hits']: + best={'head':head,'fit_edge_hits':score} + if best is None:raise ValueError('no cap2 candidate') + held=encode(item,best['head'],TEST_CONTEXTS,'temporal') + return {'seed':item['model_seed'],'candidates_checked':len(candidates), + 'fit_feasible_candidates':feasible, + 'fit_edge_hits':best['fit_edge_hits'], + 'fit_diameter':diameter(encode(item,best['head'],FIT_CONTEXTS,'temporal')), + 'heldout_edge_hits':covered_pairs(held),'heldout_diameter':diameter(held), + 'weight':list(best['head'][0]),'threshold':best['head'][1]} + +if __name__=='__main__': + ap=argparse.ArgumentParser() + ap.add_argument('--input',type=Path,default=Path(__file__).with_name('frozen_loop_activations.json.gz')) + ap.add_argument('--out',type=Path,default=Path(__file__).with_name('cap2_receipt.json')) + args=ap.parse_args() + from frozen_loader import read_payload + data=read_payload(args.input.name,args.input.parent) + rows=[fit_cap2(item) for item in data['items']] + for row in rows:print(row['seed'], row['fit_edge_hits'],row['heldout_edge_hits'],row['heldout_diameter']) + args.out.write_text(json.dumps({'schema':'COE-04-cap2-diagnostic-v1','posthoc':True,'rows':rows},indent=2,sort_keys=True)+'\n') diff --git a/research/chromatic_observer_gym_v1/run_frozen_loop.py b/research/chromatic_observer_gym_v1/run_frozen_loop.py new file mode 100644 index 000000000..91820ee51 --- /dev/null +++ b/research/chromatic_observer_gym_v1/run_frozen_loop.py @@ -0,0 +1,142 @@ +"""COE-04: a small trained tied-attention looper, frozen before probe fitting. + +This is a CPU-only reproduction cell using the visit-state equations of +LoopedTransformers/research_gym/neural/looped_decoder.py (one physical block, +four unrolled visits, causal two-token inputs). It trains a deliberately small +synthetic copy-first-token task, then writes literal frozen hidden states. + +The native Qwen/Nanbeige/TRM pretrained checkpoint weights are not included. +The probes therefore test a locally trained and independently frozen small +transformer, not those external pretrained checkpoints. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import torch +from torch import nn +from torch.nn import functional as F + +VOCAB = 8 +DIM = 24 +VISITS = 4 +MODEL_SEEDS = (2406, 2407, 2408) +TRAIN_STEPS = 160 +LR = 0.010 + + +class TiedCausalBlock(nn.Module): + def __init__(self): + super().__init__() + self.norm1 = nn.LayerNorm(DIM) + self.attention = nn.MultiheadAttention(DIM, 3, bias=False, batch_first=True) + self.norm2 = nn.LayerNorm(DIM) + self.mlp = nn.Sequential( + nn.Linear(DIM, 4 * DIM, bias=False), + nn.GELU(), + nn.Linear(4 * DIM, DIM, bias=False), + ) + + def forward(self, state): + mask = torch.triu(torch.ones(2, 2, device=state.device, dtype=torch.bool), diagonal=1) + h = self.norm1(state) + att = self.attention(h, h, h, attn_mask=mask, need_weights=False)[0] + state = state + 0.7 * att + return state + 0.7 * self.mlp(self.norm2(state)) + + +class FrozenTiedLooper(nn.Module): + def __init__(self): + super().__init__() + self.embedding = nn.Embedding(VOCAB, DIM) + self.input_norm = nn.LayerNorm(DIM) + self.block = TiedCausalBlock() + self.final_norm = nn.LayerNorm(DIM) + + def forward(self, tokens, *, trace=False): + state = self.input_norm(self.embedding(tokens)) + histories = [] + for _ in range(VISITS): + state = self.block(state) + histories.append(state[:, 1, :]) + logits = F.linear(self.final_norm(state[:, 1, :]), self.embedding.weight) + return (logits, torch.stack(histories, dim=1)) if trace else logits + + +def canonical(obj): + return json.dumps(obj, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def train_one(seed: int, steps: int = TRAIN_STEPS): + torch.manual_seed(seed) + m = FrozenTiedLooper().float() + optimizer = torch.optim.AdamW(m.parameters(), lr=LR, weight_decay=0.0) + examples = torch.tensor([(a, b) for a in range(VOCAB) for b in range(VOCAB)], dtype=torch.long) + target = examples[:, 0] + for _ in range(steps): + output = m(examples) + loss = F.cross_entropy(output, target) + optimizer.zero_grad() + loss.backward() + optimizer.step() + m.eval() + with torch.no_grad(): + logits, trajectories = m(examples, trace=True) + predicted = logits.argmax(dim=1) + return m, examples, predicted, trajectories, float(loss.item()) + + +def freeze(seed: int): + m, examples, predicted, trajectories, loss = train_one(seed) + if any(a != y for (a, _), y in zip(examples.tolist(), predicted.tolist())): + raise RuntimeError("model failed pre-probe 64-cell admission gate") + # Model parameters are permanently frozen before any head search. + for p in m.parameters(): + p.requires_grad_(False) + model_weights = {name: weight.detach().cpu().tolist() for name, weight in m.state_dict().items()} + sha = hashlib.sha256(canonical(model_weights).encode()).hexdigest() + raw = trajectories.detach().cpu().tolist() + cells = {f"{a}:{b}": raw[8 * a + b] for a in range(8) for b in range(8)} + return { + "model_seed": seed, + "model_checkpoint_sha256": sha, + "architecture": "tied_causal_mha_1block_4visits_2tokens_d24_h3", + "train_examples": 64, + "train_steps": TRAIN_STEPS, + "train_loss": loss, + "model_predictions": predicted.tolist(), + "activations": cells, + }, model_weights + + +def freeze_all(out: Path): + torch.set_num_threads(1) + torch.use_deterministic_algorithms(True) + out.parent.mkdir(parents=True, exist_ok=True) + rows, weights = [], {} + for seed in MODEL_SEEDS: + row, w = freeze(seed) + rows.append(row) + weights[str(seed)] = w + doc = { + "schema": "COE-04-native-tied-loop-frozen-v1", + "task": "copy first token, with second token as a distracting query position", + "model_fit_pairs": "all 8 x 8 symbolic cases before probe fit", + "probe_fit_contexts": [0, 1, 2, 3], + "probe_heldout_contexts": [4, 5, 6, 7], + "evaluator_graph": "K8 on source-token labels 0..7, independently from probe bits", + "model_training_framework": {"torch": torch.__version__, "python": __import__("platform").python_version()}, + "items": rows, + } + out.write_text(json.dumps(doc, indent=2, sort_keys=True, allow_nan=False) + "\n") + weights_path = out.with_name("frozen_loop_weights.json") + weights_path.write_text(json.dumps(weights, separators=(",", ":"), sort_keys=True, allow_nan=False) + "\n") + print("frozen",len(rows), "seeds",out.stat().st_size,weights_path.stat().st_size,[(r["model_seed"],r["model_checkpoint_sha256"][:12],round(r["train_loss"],4)) for r in rows]) + +if __name__ == "__main__": + ap=argparse.ArgumentParser();ap.add_argument("--out",type=Path,default=Path(__file__).with_name("frozen_loop_activations.json")) + args=ap.parse_args();freeze_all(args.out) diff --git a/research/chromatic_observer_gym_v1/run_temporal_baselines.py b/research/chromatic_observer_gym_v1/run_temporal_baselines.py new file mode 100644 index 000000000..2df61e36e --- /dev/null +++ b/research/chromatic_observer_gym_v1/run_temporal_baselines.py @@ -0,0 +1,20 @@ +"""Post-registered bandwidth controls. Uses frozen fit-only data, then holdout.""" +import argparse,json +from pathlib import Path +from temporal_observers import fit_greedy_equal_bit_baseline + +if __name__=='__main__': + ap=argparse.ArgumentParser() + ap.add_argument('--input',type=Path,default=Path(__file__).with_name('frozen_loop_activations.json')) + ap.add_argument('--out',type=Path,default=Path(__file__).with_name('equal_budget_baselines.json')) + args=ap.parse_args() + from frozen_loader import read_payload + data=read_payload(args.input.name,args.input.parent) + rows=[] + for item in data['items']: + seed=item['model_seed'] + r=fit_greedy_equal_bit_baseline(item,k=4,untied=False) + u=fit_greedy_equal_bit_baseline(item,k=4,untied=True) + rows.append({'seed':seed,'final_four_bits':{k:v for k,v in r.items() if k!='heads'},'untied_four_visits':{k:v for k,v in u.items() if k!='heads'},'final_heads':[{'w':list(x[0][0]),'threshold':x[0][1],'visit':x[1]} for x in r['heads']],'untied_heads':[{'w':list(x[0][0]),'threshold':x[0][1],'visit':x[1]} for x in u['heads']]}) + print(seed,'final4',r['heldout_edge_hits'],'untied4',u['heldout_edge_hits'],'train',r['fit_edge_hits'],u['fit_edge_hits']) + args.out.write_text(json.dumps({'schema':'COE-04-equal-bits-baselines-v1','rows':rows},indent=2,sort_keys=True)+'\n') diff --git a/research/chromatic_observer_gym_v1/soft_precision_codes.py b/research/chromatic_observer_gym_v1/soft_precision_codes.py new file mode 100644 index 000000000..d5119bd0d --- /dev/null +++ b/research/chromatic_observer_gym_v1/soft_precision_codes.py @@ -0,0 +1,169 @@ +"""COE-03: exact-rational analog precision vs binary and temporal observer width. + +Mathematical reference for finite *equilateral* test-state metrics. Synthetic only. +No claim of an LLM checkpoint, SAE, or causal mechanism measurement. +""" +from __future__ import annotations + +from dataclasses import dataclass +from fractions import Fraction +from hashlib import sha256 +from itertools import combinations +from math import ceil, exp, log +from random import Random + + +@dataclass(frozen=True) +class SoftCode: + """Each word's 1-bits carry the exact positive rational `amplitude`.""" + n: int + k: int + words: tuple[int, ...] + amplitude: Fraction + + def __post_init__(self) -> None: + if self.n < 2 or self.k < 1 or len(self.words) != self.n: + raise ValueError('invalid nonempty finite code') + if not 0 < self.amplitude <= 1: + raise ValueError('amplitude must lie in (0,1]') + if any(word < 0 or word >= 1 << self.k for word in self.words): + raise ValueError('word outside declared coordinate width') + + def distance(self, u: int, v: int) -> Fraction: + return (self.words[u] ^ self.words[v]).bit_count() * self.amplitude + + def extreme_hamming(self) -> tuple[int, int]: + ds = [(u ^ v).bit_count() for u, v in combinations(self.words, 2)] + return min(ds), max(ds) + + def check(self, lower: object = 1, upper: object = 2) -> bool: + low, high = self.extreme_hamming() + return Fraction(lower) <= low * self.amplitude and high * self.amplitude <= Fraction(upper) + + def digest(self) -> str: + """Stable domain-separated digest: n/k/scale plus little-endian words.""" + h = sha256(b'coe03-soft-code-v1\x00') + h.update(self.n.to_bytes(4, 'little')) + h.update(self.k.to_bytes(4, 'little')) + h.update(str(self.amplitude).encode('ascii') + b'\x00') + for word in self.words: + h.update(word.to_bytes((self.k + 7)//8, 'little')) + return h.hexdigest() + + +def seeded_scaled_code(n: int, k: int, seed: int, amplitude: object) -> SoftCode: + if n < 2 or k < 1: + raise ValueError('n>=2 and k>=1 required') + rng = Random(seed) + return SoftCode(n, k, tuple(rng.getrandbits(k) for _ in range(n)), Fraction(amplitude)) + + +def hoeffding_sufficient_width(n: int, delta: Fraction = Fraction(1, 6)) -> int: + """Convenient float calculation of the rigorous union-bound sufficient width. + + If k > ln(n(n-1))/(2 delta^2), the probability that any pair's + Hamming fraction exits [1/2-delta,1/2+delta] is below one. + The analytic theorem is independent of floating-point rounding here. + """ + if n < 2 or not 0 < delta < Fraction(1, 2): + raise ValueError('n>=2 and delta in (0,1/2) required') + k = max(3, int(log(n * (n - 1)) / (2 * float(delta)**2)) + 1) + while n * (n-1) * exp(-2 * k * float(delta)**2) >= 1: + k += 1 + return k + + +def k5_soft_exact() -> tuple[tuple[Fraction, ...], ...]: + """An explicit 3-channel soft code for all ten edges of equilateral K5.""" + raw = ((0, 0, 0), (3, 0, 0), (0, 3, 0), + (0, 0, 3), (1, 1, 1)) + return tuple(tuple(Fraction(x, 3) for x in row) for row in raw) + + +def soft_l1(a: tuple[Fraction, ...], b: tuple[Fraction, ...]) -> Fraction: + if len(a) != len(b): + raise ValueError('coordinate dimensions disagree') + return sum((abs(u-v) for u, v in zip(a, b)), Fraction(0)) + + +def soft_distance_matrix(states: tuple[tuple[Fraction, ...], ...]): + return tuple(tuple(soft_l1(a,b) for b in states) for a in states) + + +def quantize_threshold(states: tuple[tuple[Fraction, ...], ...], + thresholds: tuple[Fraction, ...]) -> tuple[int, ...]: + if any(len(row) != len(thresholds) for row in states): + raise ValueError('threshold dimension mismatch') + return tuple(sum((int(x >= t) << j) for j, (x, t) + in enumerate(zip(row, thresholds))) for row in states) + + +def binary_diameter_two(words: tuple[int, ...]) -> bool: + return (len(set(words)) == len(words) and + all(1 <= (a ^ b).bit_count() <= 2 for a,b in combinations(words,2))) + + +def multiplex_onehot(n: int, channels: int) -> tuple[tuple[int, ...], ...]: + """The transcript is T blocks, each of `channels` bits, with one-hot codes. + + The *entire transcript* has Hamming diameter at most two and margin one. + This assumes the state stays accessible each step and the evaluator reads + the full transcript; it makes no recurrent hidden-memory claim. + """ + if n < 2 or channels < 1: + raise ValueError('n>=2 and channels>=1 required') + rounds = (n - 1 + channels - 1) // channels + rows = [] + for v in range(n): + bits = 0 if v == 0 else (1 << (v-1)) + rows.append(tuple((bits >> (t * channels)) & ((1 << channels)-1) + for t in range(rounds))) + return tuple(rows) + + +def transcript_distance(a: tuple[int, ...], b: tuple[int, ...]) -> int: + if len(a) != len(b): + raise ValueError('transcript length mismatch') + return sum((x ^ y).bit_count() for x, y in zip(a,b)) + + +def validate_transcript(transcripts: tuple[tuple[int, ...], ...], channels: int) -> bool: + return bool(transcripts) and all(len(row) == len(transcripts[0]) for row in transcripts) and all( + 0 <= word < (1 << channels) for row in transcripts for word in row + ) and all(1 <= transcript_distance(a,b) <= 2 for a,b in combinations(transcripts,2)) + + +# Pinned finite demonstration, independent of the existence theorem constants: +DEMO_N = 1024 +DEMO_K = 256 +DEMO_SEED = 2305 +DEMO_GRID_BITS = 10 +DEMO_GRID_AMPLITUDE = Fraction(12, (1 << DEMO_GRID_BITS) - 1) + + +def reference_report() -> dict: + code = seeded_scaled_code(DEMO_N, DEMO_K, DEMO_SEED, DEMO_GRID_AMPLITUDE) + low, high = code.extreme_hamming() + assert code.check(1, 2) + soft5 = k5_soft_exact() + d5 = soft_distance_matrix(soft5) + assert min(d5[i][j] for i in range(5) for j in range(i)) == 1 + assert max(d5[i][j] for i in range(5) for j in range(i)) == 2 + transcript = multiplex_onehot(17, 4) + assert validate_transcript(transcript, 4) + return { + 'format': 'coe03-reference-v1', 'provenance': 'deterministic synthetic, not checkpoint activations', + 'soft_k5_width': 3, 'soft_k5_pairwise_distances': sorted({str(d5[i][j]) for i in range(5) for j in range(i)}), + 'demo_states': code.n, 'demo_soft_channels': code.k, 'demo_seed': DEMO_SEED, + 'demo_grid_bits': DEMO_GRID_BITS, 'demo_amplitude': str(code.amplitude), + 'demo_hamming_min': low, 'demo_hamming_max': high, + 'demo_l1_min': str(low * code.amplitude), 'demo_l1_max': str(high * code.amplitude), + 'demo_digest': code.digest(), + 'binary_one_shot_min_channels': DEMO_N - 1, + 'mux_n17_k4_rounds': len(transcript[0]), + } + + +if __name__ == '__main__': + import json + print(json.dumps(reference_report(), indent=2, sort_keys=True)) diff --git a/research/chromatic_observer_gym_v1/temporal_capacity.py b/research/chromatic_observer_gym_v1/temporal_capacity.py new file mode 100644 index 000000000..b42893599 --- /dev/null +++ b/research/chromatic_observer_gym_v1/temporal_capacity.py @@ -0,0 +1,89 @@ +"""COE-04 constructive temporal tied-gate binary observers and finite oracles. + +Theorems for equilateral K_n, n >= 5, with aggregate binary Hamming +budget <=2: min total bits = n-1 at margin 1, n at margin 2; +margin >=3 is infeasible. Unrolling T visits with k bits per visit gives +k = ceil(total_bits / T). Tied recurrent implementation tracks phase. +""" +from itertools import combinations + + +def minimum_heads(n, visits, margin): + if n < 5 or visits < 1 or margin < 1: + raise ValueError('the exact large-clique theorem needs n>=5, T>=1, r>=1') + if margin > 2: + return None + required=n-1 if margin==1 else n + return (required+visits-1)//visits + + +def singleton_codes(n, visits, heads, margin=1): + width=visits*heads + minimum=n-1 if margin==1 else n + if n<5 or margin not in (1,2) or width=margin and max(ds)<=2 + assert len(set(stream))==n + return {'possible':True,'n':n,'visits':visits,'margin':margin, + 'heads':heads,'total_bits':heads*visits, + 'min_pair_distance':min(ds),'max_pair_distance':max(ds)} + + +def maximum_equidistant_binary_family(width): + """Independent exact clique oracle: count max 2-distance code size.""" + if width>4:raise ValueError('finite oracle restricted to <=4 bits') + words=tuple(range(1<w and (w^v).bit_count()==2) for w in words} + best=0 + def rec(chosen,remaining): + nonlocal best + best=max(best,len(chosen)) + if len(chosen)+len(remaining)<=best:return + for i,v in enumerate(remaining): + rec(chosen+(v,),tuple(w for w in remaining[i+1:] if w in distances[v])) + rec((),words) + return best + + +def contracting_late_code(inputs,alpha,delta,visits): + """Toy diagnostic: common fixed point zero, threshold delta > 0.""" + if not 0=delta:tstar+=1 + codes=[[int(alpha**t*x>=delta) for t in range(visits)] for x in inputs] + assert all(len({word[t] for word in codes})==1 for t in range(tstar,visits)) + return {'terminal_innovation_visit':tstar,'codes':codes} diff --git a/research/chromatic_observer_gym_v1/temporal_observers.py b/research/chromatic_observer_gym_v1/temporal_observers.py new file mode 100644 index 000000000..76ee6214e --- /dev/null +++ b/research/chromatic_observer_gym_v1/temporal_observers.py @@ -0,0 +1,256 @@ +"""COE-04: standard-library-only, frozen-trace, pre-split probe benchmark. + +Heads are selected solely on probe training contexts, and never fitted or +chosen against the 4 held-out distractor contexts. The evaluator is K8 on +frozen model's task labels, fixed independently of the selected probes. + +No checkpoint weights or model computations are needed for the scoring replay. +""" +from __future__ import annotations + +from itertools import combinations +import hashlib +import json +import math +import random +from pathlib import Path + +N = 8 +T = 4 +D = 24 +FIT_CONTEXTS = (0,1,2,3) +TEST_CONTEXTS = (4,5,6,7) +EDGES = tuple(combinations(range(N),2)) + + +def canonical(x): + return json.dumps(x,sort_keys=True,separators=(",",":"),allow_nan=False) + + +def trace_digest(item): + return hashlib.sha256(canonical(item["activations"]).encode()).hexdigest() + + +def validate_bundle(data): + if data["schema"] != "COE-04-native-tied-loop-frozen-v1": + raise ValueError("unexpected schema") + assert data["probe_fit_contexts"] == list(FIT_CONTEXTS) + assert data["probe_heldout_contexts"] == list(TEST_CONTEXTS) + seeds = set() + for item in data["items"]: + if item["model_seed"] in seeds:raise ValueError("duplicate model seed") + seeds.add(item["model_seed"]) + assert item["architecture"] == "tied_causal_mha_1block_4visits_2tokens_d24_h3" + assert item["train_steps"] == 160 + assert len(item["model_predictions"]) == N * N + assert all(item["model_predictions"][8*a+b] == a for a in range(N) for b in range(N)) + if set(item["activations"]) != {f"{a}:{b}" for a in range(N) for b in range(N)}: + raise ValueError("incomplete inputs") + for x in item["activations"].values(): + if len(x)!=T or any(len(step)!=D or not all(math.isfinite(v) for v in step) for step in x): + raise ValueError("invalid frozen activation tensor") + return True + + +def dot(w, x):return sum(a*b for a,b in zip(w,x)) + + +def normalize(v): + size=math.sqrt(sum(x*x for x in v)) + if size<1e-8:return None + return tuple(x/size for x in v) + + +def means(item,contexts=FIT_CONTEXTS): + return tuple(tuple(tuple(sum(item['activations'][f'{a}:{b}'][t][j] for b in contexts)/len(contexts) for j in range(D)) for t in range(T)) for a in range(N)) + + +def candidate_projections(item,seed=2204,limit_random=240): + """Generate fixed deterministic heads on fit contexts only.""" + avg=means(item) + directions=[] + for t in range(T): + for a,b in EDGES: + v=normalize(tuple(avg[a][t][j]-avg[b][t][j] for j in range(D))) + if v: directions.append(v) + rng=random.Random(seed) + for _ in range(limit_random): + vec=normalize([rng.gauss(0,1) for _ in range(D)]) + if vec:directions.append(vec) + # Each threshold comes from 1/8, 1/4, 1/2, 3/4, 7/8 quantiles of + # pooled fit-context projections; none depends on the holdout trace. + unique={} + for v in directions: + vals=sorted(dot(v,item['activations'][f'{a}:{c}'][t]) for a in range(N) for c in FIT_CONTEXTS for t in range(T)) + thresholds=[] + for fraction in (0.125,0.25,0.375,0.5,0.625,0.75,0.875): + idx=int((len(vals)-1)*fraction) + thresholds.append((vals[idx]+vals[idx+1])/2) + # Additional thresholds between sorted per-class means at each timestep + for t in range(T): + arr=sorted(dot(v,avg[a][t]) for a in range(N)) + for j in range(N-1):thresholds.append((arr[j]+arr[j+1])/2) + for threshold in thresholds: + words = {str(c):tuple(sum((int(dot(v,item['activations'][f'{a}:{c}'][t])>threshold)<threshold) for val in z) + else: + # fixed fit-only calibration for this head, shared across visits + fit=[dot(w,item['activations'][f'{aa}:{cc}'][tt]) for aa in range(N) for cc in FIT_CONTEXTS for tt in range(T)] + lo,hi=min(fit),max(fit) + levels=(1<lo else 0 for v in z) + row.append(code) + values.append(row) + return values + + +def covered_pairs(encoded): + return sum(int(row[a]!=row[b]) for row in encoded for a,b in EDGES) + + +def fit_candidate(item, mode, metric_bits=1, cache=None): + candidates = candidate_projections(item,seed=item['model_seed']+601) + if cache is None:cache={} + best=None + for head in candidates: + train=encode(item,head,FIT_CONTEXTS,mode=mode,quant_bits=metric_bits) + coverage=covered_pairs(train) + # stable codewords across train contexts a secondary preference + stability=sum(len(set(train[c][a] for c in range(len(FIT_CONTEXTS))))==1 for a in range(N)) + key=(coverage,stability) + if best is None or key>best['key']: + best={'head':head,'key':key,'candidates_examined':len(candidates)} + assert best is not None + return best + + +def head_report(item,head,mode,quant_bits=1): + fitted=encode(item,head,FIT_CONTEXTS,mode,quant_bits) + heldout=encode(item,head,TEST_CONTEXTS,mode,quant_bits) + return { + 'fit_edge_hits':covered_pairs(fitted), + 'fit_edge_total':len(FIT_CONTEXTS)*len(EDGES), + 'heldout_edge_hits':covered_pairs(heldout), + 'heldout_edge_total':len(TEST_CONTEXTS)*len(EDGES), + 'heldout_label_unique_per_context':[len(set(tuple(w) for w in row)) for row in heldout], + } + + +def run_study(doc): + validate_bundle(doc) + rows=[] + for item in doc['items']: + temporal=fit_candidate(item,'temporal') + final=fit_candidate(item,'last') + temporal_rep=head_report(item,temporal['head'],'temporal') + final_rep=head_report(item,final['head'],'last') + repeat_rep=head_report(item,final['head'],'repeat_last') + assert final_rep['heldout_edge_hits']==repeat_rep['heldout_edge_hits'] + rows.append({ + 'seed':item['model_seed'], + 'checkpoint_sha256':item['model_checkpoint_sha256'], + 'candidates_temporal':temporal['candidates_examined'], + 'candidates_final':final['candidates_examined'], + 'heads':{ + 'temporal_shared_1bit_x4':{**temporal_rep, 'weight':list(temporal['head'][0]),'threshold':temporal['head'][1]}, + 'final_1bit':{**final_rep,'weight':list(final['head'][0]),'threshold':final['head'][1]}, + 'repeat_final_1bit_x4':repeat_rep, + 'temporal_shared_2bit_x4':head_report(item,temporal['head'],'temporal',2), + 'final_shared_2bit':head_report(item,final['head'],'last',2), + } + }) + print(item['model_seed'],'temporal1',temporal_rep['heldout_edge_hits'],'final1',final_rep['heldout_edge_hits'],'temporal2',rows[-1]['heads']['temporal_shared_2bit_x4']['heldout_edge_hits'], 'candidates',temporal['candidates_examined']) + return {'schema':'COE-04-temporal-quantization-receipt-v1','split':{'fit':list(FIT_CONTEXTS),'holdout':list(TEST_CONTEXTS)},'total_pairs_per_seed':len(TEST_CONTEXTS)*len(EDGES),'rows':rows} + + +if __name__=='__main__': + import argparse + ap=argparse.ArgumentParser() + ap.add_argument('--input',type=Path,default=Path(__file__).with_name('frozen_loop_activations.json')) + ap.add_argument('--out',type=Path,default=Path(__file__).with_name('temporal_receipt.json')) + args=ap.parse_args() + import gzip + source=json.loads(gzip.open(args.input,'rt').read() if args.input.suffix=='.gz' else args.input.read_text()) + out=run_study(source) + args.out.write_text(json.dumps(out,indent=2,sort_keys=True,allow_nan=False)+'\n') + +# COE-04B fair-bit-budget baselines. The functions below are defined after the +# command-line entry for library use; the standalone CLI calls them in the +# separate `run_temporal_baselines.py` runner. + +def separation_mask(row_codes): + mask=0 + index=0 + for row in row_codes: + for a,b in EDGES: + if row[a]!=row[b]:mask|=1<threshold) for a in range(N)]) + return separation_mask(rows) + + +def fit_greedy_equal_bit_baseline(item,k=4,untied=False): + """Choose k one-bit heads on fixed fit cells; no holdout access.""" + candidates=candidate_projections(item,seed=item['model_seed']+601) + if untied and k!=T: + raise ValueError('untied control uses exactly one head per visit') + if untied: + choices=[(head,t) for t in range(T) for head in candidates] + else: + choices=[(head,T-1) for head in candidates] + separation=[candidate_mask(item,head,visit) for head,visit in choices] + covered=0 + selected=[] + if untied: + # Visit assignment fixed; choose the best incremental head for t=0..T-1. + for t in range(T): + offset=t*len(candidates) + j=max(range(offset,offset+len(candidates)),key=lambda idx:(separation[idx]&~covered).bit_count()) + selected.append(choices[j]);covered|=separation[j] + else: + for _ in range(k): + j=max(range(len(choices)),key=lambda idx:(separation[idx]&~covered).bit_count()) + selected.append(choices[j]);covered|=separation[j] + assert len(selected)==k + result={'heads':selected,'train_coverage':covered.bit_count(),'candidate_count':len(candidates)} + result.update(score_multi_heads(item,selected)) + return result + + +def score_multi_heads(item, heads): + results={} + for label,contexts in [('fit',FIT_CONTEXTS),('heldout',TEST_CONTEXTS)]: + obs=[] + for c in contexts: + row=[] + for a in range(N): + row.append(tuple(int(dot(w,item['activations'][f'{a}:{c}'][visit])>th) for ((w,th),visit) in heads)) + obs.append(row) + results[label+'_edge_hits']=covered_pairs(obs) + results[label+'_edge_total']=len(contexts)*len(EDGES) + results[label+'_unique_per_context']=[len(set(row)) for row in obs] + return results diff --git a/research/chromatic_observer_gym_v1/temporal_receipt.json b/research/chromatic_observer_gym_v1/temporal_receipt.json new file mode 100644 index 000000000..0352e07ec --- /dev/null +++ b/research/chromatic_observer_gym_v1/temporal_receipt.json @@ -0,0 +1,386 @@ +{ + "rows": [ + { + "candidates_final": 9208, + "candidates_temporal": 9208, + "checkpoint_sha256": "13b9c3c63f7d7d27ef9aac2144fd2dd5469e144d940bee97e0a975a38e1d1841", + "heads": { + "final_1bit": { + "fit_edge_hits": 64, + "fit_edge_total": 112, + "heldout_edge_hits": 64, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 2, + 2, + 2, + 2 + ], + "threshold": 1.5600467381744834, + "weight": [ + -0.00561919464417287, + 0.16151309717199716, + 0.4230175274763852, + -0.2736985648078286, + -0.024591792667305865, + -0.3564757180542284, + -0.09040279265427845, + 0.07430303792337395, + -0.10514408789298296, + 0.02215850647697226, + -0.021974803863923625, + -0.08041341584226873, + -0.02356679236737102, + -0.197198441097606, + -0.21225247231713065, + 0.024380325409565647, + -0.28592168998839246, + 0.17768987072143205, + -0.2123433575207236, + 0.524439555078322, + -0.12129646411799842, + -0.07877486504801279, + 0.11271887939869925, + 0.08941466895099542 + ] + }, + "final_shared_2bit": { + "fit_edge_hits": 81, + "fit_edge_total": 112, + "heldout_edge_hits": 82, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 3, + 3, + 4, + 3 + ] + }, + "repeat_final_1bit_x4": { + "fit_edge_hits": 64, + "fit_edge_total": 112, + "heldout_edge_hits": 64, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 2, + 2, + 2, + 2 + ] + }, + "temporal_shared_1bit_x4": { + "fit_edge_hits": 96, + "fit_edge_total": 112, + "heldout_edge_hits": 90, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 5, + 5, + 4, + 4 + ], + "threshold": -0.013380859141644726, + "weight": [ + -0.0914024906157206, + -0.16040735176889975, + 0.32069835407137043, + -0.12113378199993026, + 0.15069117640182203, + -0.004398961899197071, + 0.09805816890852496, + -0.051712704228224715, + 0.19261519982111497, + 0.2953390880057344, + 0.18530284424524832, + -0.08594333006574303, + 0.1345486703926474, + 0.06810443990498506, + -0.05053553953120918, + 0.28620215340383753, + -0.42716245667477815, + -0.5166912720632082, + -0.06875742524629029, + 0.0874634682908486, + -0.14716451921066914, + 0.09738170827305617, + 0.19543028851810276, + -0.0947233692321388 + ] + }, + "temporal_shared_2bit_x4": { + "fit_edge_hits": 102, + "fit_edge_total": 112, + "heldout_edge_hits": 102, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 5, + 7, + 6, + 6 + ] + } + }, + "seed": 2406 + }, + { + "candidates_final": 9228, + "candidates_temporal": 9228, + "checkpoint_sha256": "46a99c7a348d2d0250ff9f7289ed2c3078cd847f506a65941d24dd5213e217ee", + "heads": { + "final_1bit": { + "fit_edge_hits": 64, + "fit_edge_total": 112, + "heldout_edge_hits": 62, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 2, + 2, + 2, + 2 + ], + "threshold": -4.728956983803451, + "weight": [ + 0.06895654759449149, + 0.4306406810450028, + 0.05033380403370782, + 0.08315255595872263, + -0.054758909600874955, + -0.05975888282097973, + 0.18548048245186302, + 0.2541892292301981, + 0.11407427172866239, + 0.0033159356884175546, + 0.292047969775134, + 0.04577406741279415, + 0.10612996799046875, + 0.014983399849386536, + 0.19808385131509978, + -0.05464808676774127, + -0.2104065840831397, + -0.13814499707497255, + -0.2242767363280734, + -0.5614925227145561, + 0.11075818118527858, + -0.04565759164294441, + -0.16729169582920989, + -0.2633830445429923 + ] + }, + "final_shared_2bit": { + "fit_edge_hits": 82, + "fit_edge_total": 112, + "heldout_edge_hits": 83, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 3, + 3, + 3, + 3 + ] + }, + "repeat_final_1bit_x4": { + "fit_edge_hits": 64, + "fit_edge_total": 112, + "heldout_edge_hits": 62, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 2, + 2, + 2, + 2 + ] + }, + "temporal_shared_1bit_x4": { + "fit_edge_hits": 96, + "fit_edge_total": 112, + "heldout_edge_hits": 72, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 3, + 3, + 5, + 5 + ], + "threshold": 4.332980360265321, + "weight": [ + -0.22245032502605047, + -0.3362097230216812, + -0.37373645409604533, + 0.20347052584323053, + 0.06104737923816322, + 0.25038012588779696, + 0.05016872207334774, + -0.12394498349350777, + -0.22520819562366948, + -0.08952018413164901, + -0.12553320157911865, + -0.15437603106768275, + -0.31532386636909104, + -0.053016760134075865, + -0.1312074289940071, + -0.11931228842094026, + 0.21152848093061938, + 0.1244200562129013, + 0.2178173191774151, + 0.4166446142016643, + 0.15296684106209624, + -0.10533749239858176, + -0.13493710948726112, + 0.07826195065836622 + ] + }, + "temporal_shared_2bit_x4": { + "fit_edge_hits": 75, + "fit_edge_total": 112, + "heldout_edge_hits": 86, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 5, + 5, + 4, + 5 + ] + } + }, + "seed": 2407 + }, + { + "candidates_final": 8751, + "candidates_temporal": 8751, + "checkpoint_sha256": "5bb8809a753e08f5ade9f3ff40b3ec50cecdb2aa8085c3a2624506d201196a88", + "heads": { + "final_1bit": { + "fit_edge_hits": 64, + "fit_edge_total": 112, + "heldout_edge_hits": 61, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 2, + 2, + 2, + 2 + ], + "threshold": 0.6081804607283319, + "weight": [ + 0.18612832220805714, + 0.22807975815410264, + 0.09543100496799023, + 0.11300049847427085, + 0.3864768011341915, + -0.13707635305093274, + -0.026680300956215944, + -0.19412451722071739, + -0.18338401865051387, + -0.21462874960512116, + 0.4094011224145829, + 0.09696422860304942, + -0.14498891723909674, + 0.08186707360606454, + -0.17063628715019924, + -0.11245912701253408, + -0.05054888360295475, + 0.24905539532164003, + 0.32847411546034216, + 0.012845992049991555, + 0.10446368793210531, + 0.011250768555772171, + -0.19999310442032622, + -0.36747027521274195 + ] + }, + "final_shared_2bit": { + "fit_edge_hits": 78, + "fit_edge_total": 112, + "heldout_edge_hits": 83, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 3, + 3, + 3, + 3 + ] + }, + "repeat_final_1bit_x4": { + "fit_edge_hits": 64, + "fit_edge_total": 112, + "heldout_edge_hits": 61, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 2, + 2, + 2, + 2 + ] + }, + "temporal_shared_1bit_x4": { + "fit_edge_hits": 97, + "fit_edge_total": 112, + "heldout_edge_hits": 79, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 4, + 4, + 4, + 4 + ], + "threshold": 0.854664320647855, + "weight": [ + 0.2869751154156453, + -0.1080168608735992, + -0.33050138622487124, + 0.09302628528894769, + -0.22015971046339006, + -0.3454603867581149, + -0.2312814236416369, + 0.18569454687211256, + 0.07075509534009695, + 0.06292218601084326, + 0.03688836922353379, + 0.16554587381516467, + -0.04694596495797266, + -0.5041239891449918, + 0.31414619607266314, + -0.1717295453238383, + -0.042008165775190565, + -0.10190019282332959, + 0.07320698764481123, + -0.1490611558191296, + -0.241304921459875, + 0.06597140759465223, + 0.08422580509783541, + -0.02548096029927475 + ] + }, + "temporal_shared_2bit_x4": { + "fit_edge_hits": 98, + "fit_edge_total": 112, + "heldout_edge_hits": 97, + "heldout_edge_total": 112, + "heldout_label_unique_per_context": [ + 5, + 6, + 5, + 5 + ] + } + }, + "seed": 2408 + } + ], + "schema": "COE-04-temporal-quantization-receipt-v1", + "split": { + "fit": [ + 0, + 1, + 2, + 3 + ], + "holdout": [ + 4, + 5, + 6, + 7 + ] + }, + "total_pairs_per_seed": 112 +} diff --git a/research/chromatic_observer_gym_v1/test_frozen_temporal.py b/research/chromatic_observer_gym_v1/test_frozen_temporal.py new file mode 100644 index 000000000..f0a27b3e5 --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_frozen_temporal.py @@ -0,0 +1,122 @@ +"""Verified offline frozen model probe scores without needing torch installed.""" +import copy +import json +import unittest +from pathlib import Path + +from frozen_loader import read_payload,verify_frozen +from temporal_observers import ( + FIT_CONTEXTS,TEST_CONTEXTS,EDGES,N,T, + candidate_projections,encode,covered_pairs,head_report,score_multi_heads, +) +from visit_phase_controls import visit_scramble,layer_separation_diagnostic,count_only_score +from run_cap2_control import diameter + +ROOT=Path(__file__).resolve().parent + +class FrozenTemporalTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.data,cls.digests=verify_frozen() + cls.receipt=read_payload('temporal_receipt.json') + cls.baseline=read_payload('equal_budget_baselines.json') + + def test_weight_hash_and_admission(self): + self.assertEqual([x['seed'] for x in self.digests],[2406,2407,2408]) + for x in self.data['items']: + self.assertEqual(x['train_examples'],64) + self.assertEqual(x['model_predictions'],[a for a in range(8) for _ in range(8)]) + + def test_probe_splits_are_disjoint_and_complete(self): + self.assertEqual(set(FIT_CONTEXTS).intersection(TEST_CONTEXTS),set()) + self.assertEqual(set(FIT_CONTEXTS).union(TEST_CONTEXTS),set(range(8))) + self.assertEqual(len(EDGES),28) + self.assertEqual(len(self.data['items'][0]['activations']),64) + + def test_replay_frozen_temporal_head_scores(self): + expected={2406:(64,90,102),2407:(62,72,86),2408:(61,79,97)} + for x in self.data['items']: + row=next(r for r in self.receipt['rows'] if r['seed']==x['model_seed']) + for key,mode,bits in ( + ('final_1bit','last',1), + ('temporal_shared_1bit_x4','temporal',1), + ('temporal_shared_2bit_x4','temporal',2), + ('final_shared_2bit','last',2), + ): + if bits==2: source='temporal_shared_1bit_x4' if mode=='temporal' else 'final_1bit' + else:source=key + head=(row['heads'][source]['weight'],row['heads'][source]['threshold']) + actual=head_report(x,head,mode,bits) + for a in ('fit_edge_hits','heldout_edge_hits','heldout_label_unique_per_context'): + self.assertEqual(row['heads'][key][a],actual[a]) + self.assertEqual(tuple(row['heads'][z]['heldout_edge_hits'] for z in + ('final_1bit','temporal_shared_1bit_x4','temporal_shared_2bit_x4')), + expected[x['model_seed']]) + + def test_equal_total_bit_baseline_replay(self): + expected={2406:(112,105),2407:(106,111),2408:(111,111)} + for item in self.data['items']: + row=next(r for r in self.baseline['rows'] if r['seed']==item['model_seed']) + for kind,head_key in (('final_four_bits','final_heads'),('untied_four_visits','untied_heads')): + heads=[((h['w'],h['threshold']),h['visit']) for h in row[head_key]] + actual=score_multi_heads(item,heads) + for key in ('fit_edge_hits','heldout_edge_hits','heldout_unique_per_context'): + self.assertEqual(actual[key],row[kind][key]) + self.assertEqual((row['final_four_bits']['heldout_edge_hits'], + row['untied_four_visits']['heldout_edge_hits']),expected[item['model_seed']]) + + def test_temporal_order_does_not_improve_over_bit_counts(self): + # Post-hoc diagnostic, intentionally scored on the frozen holdout. + for item in self.data['items']: + row=next(r for r in self.receipt['rows'] if r['seed']==item['model_seed']) + obs=row['heads']['temporal_shared_1bit_x4'] + head=(obs['weight'],obs['threshold']) + count=count_only_score(item,head) + self.assertEqual(count['edge_hits'],obs['heldout_edge_hits']) + self.assertEqual(count['unique_counts'],obs['heldout_label_unique_per_context']) + + def test_last_replay_is_identical(self): + for row in self.receipt['rows']: + self.assertEqual(row['heads']['repeat_final_1bit_x4']['heldout_edge_hits'], + row['heads']['final_1bit']['heldout_edge_hits']) + + def test_cap2_posthoc_control_replay(self): + receipt=read_payload('cap2_receipt.json') + expected={2406:79,2407:59,2408:74} + self.assertTrue(receipt['posthoc']) + for item in self.data['items']: + row=next(r for r in receipt['rows'] if r['seed']==item['model_seed']) + head=(row['weight'],row['threshold']) + fit=encode(item,head,FIT_CONTEXTS,'temporal') + hold=encode(item,head,TEST_CONTEXTS,'temporal') + self.assertEqual(diameter(fit),row['fit_diameter']) + self.assertEqual(diameter(hold),row['heldout_diameter']) + self.assertEqual(diameter(hold),2) + self.assertEqual(covered_pairs(fit),row['fit_edge_hits']) + self.assertEqual(covered_pairs(hold),expected[item['model_seed']]) + + def test_heads_are_fit_only_on_observed_contexts(self): + item=self.data['items'][0] + # Freeze the entire fitting slice; scramble every held-out activation. + tampered=copy.deepcopy(item) + for a in range(N): + for c in TEST_CONTEXTS: + tampered['activations'][f'{a}:{c}']=[[999.0]*24 for _ in range(T)] + # Equal candidate pool and order certify the generator's fit-only use. + heads=candidate_projections(item,seed=item['model_seed']+601) + new_heads=candidate_projections(tampered,seed=item['model_seed']+601) + self.assertEqual(heads,new_heads) + + def test_visit_order_shuffle_and_distance_diagnostic(self): + for x in self.data['items']: + row=next(r for r in self.receipt['rows'] if r['seed']==x['model_seed']) + head=(row['heads']['temporal_shared_1bit_x4']['weight'], + row['heads']['temporal_shared_1bit_x4']['threshold']) + vals=[visit_scramble(x,head,j) for j in range(1,6)] + self.assertEqual(len(vals),5) + self.assertTrue(all(0<=v<=4*len(EDGES) for v in vals)) + diag=layer_separation_diagnostic(x) + self.assertEqual(len(diag),4) + self.assertTrue(all(v['minimum_l2']>0 for v in diag)) + +if __name__=='__main__':unittest.main() diff --git a/research/chromatic_observer_gym_v1/test_l1_cut_codes.py b/research/chromatic_observer_gym_v1/test_l1_cut_codes.py new file mode 100644 index 000000000..13fdb9e74 --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_l1_cut_codes.py @@ -0,0 +1,159 @@ +"""Independent exhaustive replay and exact-rational COE-02 witnesses.""" +import itertools +import unittest +from fractions import Fraction as F + +try: + from .l1_cut_codes import ( + metric_matrix, graph_edges, minimum_l1_observer, verify_observer, + canonical_cuts, crossing, equilateral, dual_width_lower_bound, + balanced_fractional_certificate) +except ImportError: + from l1_cut_codes import ( + metric_matrix, graph_edges, minimum_l1_observer, verify_observer, + canonical_cuts, crossing, equilateral, dual_width_lower_bound, + balanced_fractional_certificate) + + +def brute_words(d, edges, L, margin, max_width=4): + """Independent word-enumerator without cut-BFS, n <= 3.""" + n = len(d) + for k in range(max_width + 1): + for tail in itertools.product(range(1 << k), repeat=n - 1): + words = (0,) + tail + if all((words[u] ^ words[v]).bit_count() >= margin for u, v in edges): + if all((words[u] ^ words[v]).bit_count() <= F(L) * d[u][v] + for u in range(n) for v in range(u + 1, n)): + return k + return None + + +class TestCutObserver(unittest.TestCase): + def test_exhaustive_all_three_vertex_graphs(self): + n = 3 + pairs = tuple(itertools.combinations(range(n), 2)) + d = equilateral(n) + for mask in range(1 << len(pairs)): + edges = tuple(e for i, e in enumerate(pairs) if mask & (1 << i)) + for L in (F(0), F(1), F(2)): + for margin in (1, 2): + with self.subTest(mask=mask, L=L, margin=margin): + result = minimum_l1_observer(d, edges, L, margin) + expected = brute_words(d, edges, L, margin) + self.assertEqual(None if result is None else result.width, expected) + if result is not None: + self.assertTrue(verify_observer(d, edges, L, margin, result)) + + def test_equilateral_chromatic_vs_l1_obstructions(self): + n = 5 + clique = tuple(itertools.combinations(range(n), 2)) + cycle = tuple((i, (i + 1) % n) for i in range(n)) + d = equilateral(n) + self.assertIsNone(minimum_l1_observer(d, clique, 1)) + self.assertIsNone(minimum_l1_observer(d, cycle, 1)) + self.assertEqual(minimum_l1_observer(d, clique, 2).width, 4) + self.assertEqual(minimum_l1_observer(d, clique, 3).width, 3) + self.assertEqual(minimum_l1_observer(d, cycle, 2).width, 2) + self.assertEqual(minimum_l1_observer(equilateral(4), + tuple(itertools.combinations(range(4), 2)), 2).width, 2) + self.assertEqual(minimum_l1_observer(d, [], 0).width, 0) + self.assertEqual(minimum_l1_observer(equilateral(2), [(0,1)], F(1,2)), None) + + def test_explicit_pareto_witness(self): + d = equilateral(5) + edges = tuple(itertools.combinations(range(5), 2)) + best = minimum_l1_observer(d, edges, 2) + self.assertEqual(best.width, 4) + self.assertEqual(best.words, (0, 1, 2, 4, 8)) + self.assertEqual(max(best.loads), 2) + self.assertTrue(verify_observer(d, edges, 2, 1, best)) + + def test_line_metric_bottleneck_compatible(self): + x = [F(0), F(3,5), F(6,5)] + d = tuple(tuple(abs(a-b) for b in x) for a in x) + self.assertIsNone(minimum_l1_observer(d, [(0,2)], F(49,30))) + result = minimum_l1_observer(d, [(0,2)], F(5,3)) + self.assertIsNotNone(result) + self.assertEqual(result.width, 1) + self.assertTrue(verify_observer(d, [(0,2)], F(5,3), 1, result)) + + def test_graph_margin_and_pair_budget(self): + d = equilateral(3) + e = [(0,1), (1,2)] + self.assertIsNone(minimum_l1_observer(d, e, 1, margin=2)) + result = minimum_l1_observer(d, e, 2, margin=2) + self.assertEqual(result.width, 2) + self.assertTrue(verify_observer(d, e, 2, 2, result)) + + def test_dual_certificates(self): + d = equilateral(3) + edges = tuple(itertools.combinations(range(3), 2)) + self.assertEqual(dual_width_lower_bound(d, edges, 2, 1, + {e:F(1,2) for e in edges}, {}), 2) + self.assertEqual(dual_width_lower_bound(equilateral(2), [(0,1)], 3, 3, + {(0,1):1}, {}), 3) + with self.assertRaises(ValueError): + dual_width_lower_bound(equilateral(2), [(0,1)], 3, 3, + {(0,1):2}, {}) + + def test_balanced_fractional_lp_gap(self): + for n in range(2,10): + with self.subTest(n=n): + cuts, weight, value = balanced_fractional_certificate(n) + self.assertEqual(value, F(n*(n-1)//2, (n*n)//4)) + self.assertEqual(sum(weight*crossing(c,0,1) for c in cuts),1) + cuts, weight, v = balanced_fractional_certificate(5) + self.assertEqual((len(cuts),weight,v), (10,F(1,6),F(5,3))) + self.assertEqual(F(4,1)/v, F(12,5)) + + def test_errors_and_resource_guard(self): + with self.assertRaises(ValueError): + metric_matrix(((0,1,3),(1,0,1),(3,1,0))) + with self.assertRaises(ValueError): + graph_edges(3,[(1,1)]) + with self.assertRaises(ValueError): + minimum_l1_observer(equilateral(2), [(0,1)], -1) + with self.assertRaises(RuntimeError): + minimum_l1_observer(equilateral(5), tuple(itertools.combinations(range(5),2)), + 2, max_states=1) + self.assertEqual(canonical_cuts(1), ()) + + +if __name__ == '__main__': + unittest.main() + +class TestActivationAdapter(unittest.TestCase): + def test_fixed_prototype_report(self): + import json + from pathlib import Path + try: + from .activation_case import analyse + except ImportError: + from activation_case import analyse + path = Path(__file__).with_name('frozen_k5_onehot.json') + case = json.loads(path.read_text(encoding='utf8')) + result = analyse(case) + self.assertEqual(result['linf']['width'],3) + self.assertEqual(result['l1']['width'],4) + self.assertEqual(result['provenance'],case['provenance']) + self.assertEqual(result['distance'][0][1], '1') + case['lipschitz']='3' + self.assertEqual(analyse(case)['l1']['width'],3) + case['lipschitz']='1' + self.assertIsNone(analyse(case)['l1']) + self.assertEqual(analyse(case)['linf']['width'],3) + + def test_rejects_wrong_provenance_shape(self): + try: + from .activation_case import analyse + except ImportError: + from activation_case import analyse + base={'format':'coe02-activation-v1','lipschitz':'2', + 'states':[{'id':'a','activation':['1']},{'id':'b','activation':['1']}], + 'evaluator_edges':[['a','b']]} + with self.assertRaises(ValueError): + analyse(base) + base['states'][1]['activation']=['2'] + base['evaluator_edges']=[['a','unknown']] + with self.assertRaises(ValueError): + analyse(base) diff --git a/research/chromatic_observer_gym_v1/test_observer_codes.py b/research/chromatic_observer_gym_v1/test_observer_codes.py new file mode 100644 index 000000000..3ad8be2c0 --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_observer_codes.py @@ -0,0 +1,182 @@ +"""Deterministic exact search checks and explicit extension tests for COE-01.""" +import itertools +import math +import random +import unittest + +try: + from .observer_codes import (check_graph, optimal_coloring, minimum_observer, + validate_code, hamming, complete_edges, clique_bound_holds, + extend_probe, vertex_point, metric_quotient_observer, + critical_lipschitz) +except ImportError: + from observer_codes import (check_graph, optimal_coloring, minimum_observer, + validate_code, hamming, complete_edges, clique_bound_holds, + extend_probe, vertex_point, metric_quotient_observer, + critical_lipschitz) + + +class TestChromaticObserver(unittest.TestCase): + def test_chromatic_families(self): + cases = [ + ("complete", 6, complete_edges(6), 6, 3), + ("path", 8, [(i, i + 1) for i in range(7)], 2, 1), + ("odd cycle", 5, [(i, (i + 1) % 5) for i in range(5)], 3, 2), + ("edgeless", 6, [], 1, 0), + ] + for label, n, edges, chromatic, k_expected in cases: + with self.subTest(label=label): + coloring = optimal_coloring(n, edges) + self.assertEqual(max(coloring) + 1, chromatic) + k, words = minimum_observer(n, edges) + self.assertEqual(k, k_expected) + self.assertTrue(validate_code(n, edges, k, words)) + + def test_all_graphs_on_four_vertices(self): + edges = complete_edges(4) + for mask in range(1 << len(edges)): + chosen = [edge for i, edge in enumerate(edges) if mask & (1 << i)] + colors = optimal_coloring(4, chosen) + k, words = minimum_observer(4, chosen) + self.assertEqual(1 << k >= max(colors) + 1, True) + self.assertTrue(validate_code(4, chosen, k, words)) + if k: + self.assertLess(1 << (k - 1), max(colors) + 1) + + def test_robust_codes_and_packing(self): + for n, edges in [(2, [(0, 1)]), (4, complete_edges(4)), + (5, complete_edges(5)), + (6, [(i, i + 1) for i in range(5)])]: + k, words = minimum_observer(n, edges, margin=3) + self.assertTrue(validate_code(n, edges, k, words, margin=3)) + # Deleting any two coordinates still distinguishes adjacent nodes. + for a, b in edges: + xor = words[a] ^ words[b] + for removed in itertools.combinations(range(k), 2): + mask = sum(1 << i for i in removed) + self.assertNotEqual(xor & ~mask, 0) + # Balls of one bit-flip around adjacent codes are disjoint. + for a, b in edges: + ball_a = {words[a]} | {words[a] ^ (1 << i) for i in range(k)} + ball_b = {words[b]} | {words[b] ^ (1 << i) for i in range(k)} + self.assertFalse(ball_a & ball_b) + if len(edges) == len(complete_edges(n)): + self.assertTrue(clique_bound_holds(n, k, 1)) + + def test_mcshane_extension(self): + n = 6 + k, words = minimum_observer(n, complete_edges(n)) + self.assertEqual(extend_probe((0.0,) * n, n, k, words), (0.5,) * k) + for v in range(n): + actual = extend_probe(vertex_point(v, n), n, k, words) + expected = tuple(float((words[v] >> j) & 1) for j in range(k)) + self.assertEqual(actual, expected) + rng = random.Random(2198) + for _ in range(300): + x = tuple(rng.uniform(-2, 2) for _ in range(n)) + y = tuple(rng.uniform(-2, 2) for _ in range(n)) + fx, fy = extend_probe(x, n, k, words), extend_probe(y, n, k, words) + self.assertLessEqual(max(abs(a - b) for a, b in zip(fx, fy)), + math.dist(x, y) + 1e-12) + + + def test_metric_quotient_chain_and_boundary(self): + from fractions import Fraction as F + def line_metric(xs): + return tuple(tuple(abs(a - b) for b in xs) for a in xs) + xs = [F(0), F(3, 5), F(6, 5)] + d = line_metric(xs) + # The endpoints are more than one unit apart, but the intermediate + # node forces both into the same locally constant bit-observer class. + with self.assertRaises(ValueError): + metric_quotient_observer(d, [(0, 2)], 1) + k, code, comps = metric_quotient_observer(d, [], 1) + self.assertEqual((k, comps), (0, (0, 0, 0))) + self.assertEqual(code, (0, 0, 0)) + k, code, comps = metric_quotient_observer(d, [(0, 2)], 2) + self.assertEqual(k, 1) + self.assertEqual(len(set(comps)), 3) + # Equality d=1/L permits a one-bit step: the short-edge relation + # uses strict < rather than <=. + k, words, comps = metric_quotient_observer(line_metric([F(0), F(1)]), + [(0, 1)], 1) + self.assertEqual(k, 1) + self.assertNotEqual(*words) + self.assertEqual(comps, (0, 1)) + + def test_metric_quotient_robust_code(self): + from fractions import Fraction as F + xs = [F(0), F(2, 5), F(4, 5), F(2), F(13, 5)] + d = tuple(tuple(abs(a - b) for b in xs) for a in xs) + k, words, comps = metric_quotient_observer(d, [(0, 3)], 1, margin=3) + self.assertEqual(k, 3) + self.assertEqual(comps, (0, 0, 0, 1, 1)) + self.assertEqual(hamming(words[0], words[3]), 3) + with self.assertRaises(ValueError): + metric_quotient_observer(d, [(0, 2)], 1, margin=3) + + def test_invalid_metrics_rejected(self): + from fractions import Fraction as F + with self.assertRaises(ValueError): + metric_quotient_observer(((F(0), F(1)), (F(2), F(0))), [], 1) + with self.assertRaises(ValueError): + metric_quotient_observer(((F(0), F(1), F(3)), + (F(1), F(0), F(1)), + (F(3), F(1), F(0))), [], 1) + + def test_exact_bottleneck_feasibility_threshold(self): + from fractions import Fraction as F + xs = [F(0), F(3, 5), F(6, 5)] + d = tuple(tuple(abs(a - b) for b in xs) for a in xs) + self.assertEqual(critical_lipschitz(d, [(0, 2)]), F(5, 3)) + self.assertEqual(critical_lipschitz(d, []), 0) + with self.assertRaises(ValueError): + metric_quotient_observer(d, [(0, 2)], F(49, 30)) + k, words, _ = metric_quotient_observer(d, [(0, 2)], F(5, 3)) + self.assertEqual(k, 1) + self.assertNotEqual(words[0], words[2]) + + def test_chromatic_staircase_monotone(self): + from fractions import Fraction as F + # Merging the endpoints of P4 creates a triangle, raising χ from 2 + # to 3. Increasing the Lipschitz budget separates those endpoints. + xs = [F(0), F(3), F(6), F(1, 5)] + d = tuple(tuple(abs(a - b) for b in xs) for a in xs) + edges = [(0, 1), (1, 2), (2, 3)] + k1, _, comps1 = metric_quotient_observer(d, edges, 1) + k2, _, comps2 = metric_quotient_observer(d, edges, 5) + self.assertEqual((k1, k2), (2, 1)) + self.assertEqual(comps1[0], comps1[3]) + self.assertNotEqual(comps2[0], comps2[3]) + ks = [metric_quotient_observer(d, edges, F(L))[0] for L in (1, 2, 4, 5, 6)] + self.assertEqual(ks, sorted(ks, reverse=True)) + + def test_bottleneck_threshold_against_64_evaluator_graphs(self): + from fractions import Fraction as F + from itertools import combinations + xs = [F(0), F(2, 5), F(5, 7), F(13, 10)] + d = tuple(tuple(abs(a - b) for b in xs) for a in xs) + pairs = tuple(combinations(range(4), 2)) + for mask in range(1 << len(pairs)): + edges = tuple(edge for i, edge in enumerate(pairs) if (mask >> i) & 1) + threshold = critical_lipschitz(d, edges) + for L in (F(1, 10), F(2, 3), F(1), F(3), F(5), F(20), threshold): + if L == 0: + continue # E=empty has threshold zero, and positive probes are defined + if L < threshold: + with self.assertRaises(ValueError): + metric_quotient_observer(d, edges, L) + else: + k, words, _ = metric_quotient_observer(d, edges, L) + self.assertLessEqual(k, 2) + self.assertTrue(validate_code(4, edges, k, words)) + + def test_invalid_graph_rejected(self): + with self.assertRaises(ValueError): + check_graph(4, [(1, 1)]) + with self.assertRaises(ValueError): + minimum_observer(2, [(0, 1)], margin=0) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/research/chromatic_observer_gym_v1/test_phase_blind.py b/research/chromatic_observer_gym_v1/test_phase_blind.py new file mode 100644 index 000000000..24a075ced --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_phase_blind.py @@ -0,0 +1,104 @@ +"""COE-06: pure standard-library tests of phase-blind observer capacity.""" +from __future__ import annotations +import json +import random +import unittest +from pathlib import Path + +try: + from .gauge_orbit_codes import (WIDTH, WEIGHT, ORBIT_WORDS, certificate, + decode_under_unknown_phase, necklace, orbit, orbit_distance, rotate, trace) + from .resource_bound import all_small_bounds, deletion_bound + from .phase_gauge_replay import evidence, evaluate, load_json +except ImportError: + from gauge_orbit_codes import (WIDTH, WEIGHT, ORBIT_WORDS, certificate, + decode_under_unknown_phase, necklace, orbit, orbit_distance, rotate, trace) + from resource_bound import all_small_bounds, deletion_bound + from phase_gauge_replay import evidence, evaluate, load_json + +HERE=Path(__file__).resolve().parent + + +class TestGaugeInvariantCoding(unittest.TestCase): + def test_shared_time_independent_readout(self): + for word in ORBIT_WORDS: + self.assertEqual(trace(word),word) + self.assertEqual(trace(rotate(word)),rotate(word)) + self.assertEqual(rotate(word,WIDTH).bit_count(),WEIGHT) + + def test_cyclic_min_distance_and_21_labels(self): + self.assertEqual(len(ORBIT_WORDS),21) + self.assertEqual(len(set(necklace(x) for x in ORBIT_WORDS)),21) + for i,x in enumerate(ORBIT_WORDS): + self.assertEqual(x.bit_count(),6) + for j,y in enumerate(ORBIT_WORDS): + if i!=j: + self.assertGreaterEqual(orbit_distance(x,y),4) + + def test_every_phase_single_flip(self): + for i,word in enumerate(ORBIT_WORDS): + for shift in orbit(word): + self.assertEqual(decode_under_unknown_phase(shift),i) + for j in range(WIDTH): + self.assertEqual(decode_under_unknown_phase(shift ^ (1<>j&1} + for a,b in combinations(reps,2): + if resources(a)&resources(b): + self.assertEqual(orbit_distance(a,b,T),2) + + +class TestFrozenModelGaugeDiagnostic(unittest.TestCase): + def test_unaltered_probe_replay(self): + bundle=load_json(HERE/'replication_activations.json.gz') + receipt=load_json(HERE/'new_fit_phase_receipt.json') + result=evidence(bundle,receipt) + self.assertEqual(result['pooled'],{ + 'ordered':243,'cyclic':233,'count':233,'order_only':10, + 'cyclic_beyond_count':0,'phase_sensitive_only':10,'denominator':336}) + self.assertEqual(result,json.loads((HERE/'COE06_GAUGE_REPLAY.json').read_text())) + + def test_thresholds_unchanged_on_context_holdout(self): + r=evidence(load_json(HERE/'replication_activations.json.gz'), + load_json(HERE/'new_fit_phase_receipt.json')) + for item in r['cohort_results']: + self.assertLessEqual(item['count'],item['cyclic']) + self.assertLessEqual(item['cyclic'],item['ordered']) + + +if __name__=='__main__':unittest.main() diff --git a/research/chromatic_observer_gym_v1/test_phase_order.py b/research/chromatic_observer_gym_v1/test_phase_order.py new file mode 100644 index 000000000..7dc86188b --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_phase_order.py @@ -0,0 +1,137 @@ +"""COE-05: no-torch validation of exact phase codes and frozen probe evidence.""" +import gzip +import hashlib +import itertools +import json +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent +try: + from .phase_register import (WIDTH, affine_word, decode_nearest, evidence, + hamming, necklace_count, ordered_trace, orbit_id, phase_codebook, + rotate_right, triple_packing_bound) + from .phase_order_replay import load_json, pooled, verify_receipt, score_head +except ImportError: + from phase_register import (WIDTH, affine_word, decode_nearest, evidence, + hamming, necklace_count, ordered_trace, orbit_id, phase_codebook, + rotate_right, triple_packing_bound) + from phase_order_replay import load_json, pooled, verify_receipt, score_head + + +def source_folder(): + return HERE + + +class TestPhaseGaugeMath(unittest.TestCase): + def test_affine_generator_and_tied_dynamics(self): + codes = phase_codebook() + self.assertEqual(len(codes), 14) + self.assertEqual(len(set(codes)), 14) + for a in range(1, 8): + self.assertEqual(affine_word(a, 0) ^ affine_word(a, 1), 255) + for code in codes: + self.assertEqual(ordered_trace(code), code) + self.assertEqual(code.bit_count(), 4) + self.assertEqual(rotate_right(code, 8).bit_count(), 4) + + def test_one_flip_robustness_exact(self): + codes = phase_codebook() + pairs = list(itertools.combinations(codes, 2)) + self.assertEqual(len(pairs), 91) + self.assertEqual(min(hamming(a, b) for a, b in pairs), 4) + for label, code in enumerate(codes): + self.assertEqual(decode_nearest(code, codes), label) + for position in range(8): + self.assertEqual(decode_nearest(code ^ (1 << position), codes), label) + + def test_triple_packing_attains_upper_bound(self): + codes = phase_codebook() + supports = [tuple(i for i in range(8) if w & (1 << i)) for w in codes] + triples = [t for support in supports for t in itertools.combinations(support, 3)] + self.assertEqual((len(triples),len(set(triples))), (56,56)) + self.assertEqual(triple_packing_bound(8,4), 14) + self.assertEqual(max(triple_packing_bound(7,w) for w in range(8)),7) + # Padding a shorter code to 7 bits leaves all Hamming distances and + # its constant weight unchanged, so the 7-bit bound covers T<7. + + def test_unknown_phase_gauge_bayes(self): + codes = phase_codebook() + self.assertEqual(necklace_count(8,4), 10) + groups = {} + for label,code in enumerate(codes): + groups.setdefault(orbit_id(code),[]).append(label) + self.assertEqual(sorted(map(len,groups.values())),[2,4,4,4]) + # Under uniform random cyclic phase shifts each codeword in one orbit + # generates the identical distribution on the orbit. + for labels in groups.values(): + distributions=[] + for label in labels: + counter={} + state=codes[label] + for _ in range(8): + counter[state]=counter.get(state,0)+1 + state=rotate_right(state) + distributions.append(counter) + self.assertTrue(all(v==distributions[0] for v in distributions)) + self.assertEqual(len(groups),4) + self.assertEqual(evidence()['unknown_uniform_rotation_bayes_accuracy'], 4/14) + + def test_exact_witness_receipt(self): + witness = load_json(HERE/'phase_code_receipt.json') + self.assertEqual(evidence(),witness) + + +class TestFrozenPhaseExperiment(unittest.TestCase): + def test_replay_previous_and_replication(self): + previous=load_json(HERE/'frozen_loop_activations.json.gz') + old=load_json(HERE/'old_fit_phase_receipt.json') + verify_receipt(previous,old) + self.assertEqual(pooled(old)['heldout_order_only'],1) + newer=load_json(HERE/'replication_activations.json.gz') + new=load_json(HERE/'new_fit_phase_receipt.json') + verify_receipt(newer,new) + self.assertEqual(pooled(new),{ + 'model_seeds':[2411,2412,2413], 'heldout_total':243, + 'heldout_count_only':233, 'heldout_order_only':10, + 'denominator':336}) + + def test_full_weight_provenance(self): + bundle=load_json(HERE/'replication_activations.json.gz') + weights=load_json(HERE/'replication_weights.json.gz') + self.assertEqual(set(weights),{str(i['model_seed']) for i in bundle['items']}) + for item in bundle['items']: + payload=weights[str(item['model_seed'])] + canonical=json.dumps(payload,sort_keys=True,separators=(',',':'),allow_nan=False) + sha=hashlib.sha256(canonical.encode()).hexdigest() + self.assertEqual(sha,item['model_checkpoint_sha256']) + + def test_corruption_rejected(self): + previous=load_json(HERE/'frozen_loop_activations.json.gz') + old=load_json(HERE/'old_fit_phase_receipt.json') + old['records'][0]['primary_stable_order_head']['heldout_order_only_hits']+=1 + with self.assertRaises(ValueError): + verify_receipt(previous,old) + + def test_no_retrospective_fit_over_holdout(self): + bundle=load_json(HERE/'replication_activations.json.gz') + receipt=load_json(HERE/'new_fit_phase_receipt.json') + # The recorded fit-only metrics are independent of the heldout bytes: + # scrambling heldout activation vectors changes heldout scores but + # must leave fit selection input and fit scores exactly untouched. + from copy import deepcopy + tampered=deepcopy(bundle) + for item in tampered['items']: + for a in range(8): + for ctx in range(4,8): + item['activations'][f'{a}:{ctx}']=[[0.0]*24 for _ in range(4)] + for item,record in zip(tampered['items'],receipt['records']): + head=record['primary_stable_order_head'] + score=score_head(item,head) + for key in ('fit_stable_novel_edges','fit_order_only_hits','fit_total_edge_hits'): + self.assertEqual(score[key],head[key]) + self.assertEqual(score['heldout_total_edge_hits'],0) + + +if __name__=='__main__': unittest.main() diff --git a/research/chromatic_observer_gym_v1/test_soft_precision_codes.py b/research/chromatic_observer_gym_v1/test_soft_precision_codes.py new file mode 100644 index 000000000..e34a8cf70 --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_soft_precision_codes.py @@ -0,0 +1,165 @@ +"""COE-03 audit: exact rational certificates and separately labeled CPU pilot.""" +import itertools +import json +import math +import unittest +from fractions import Fraction as F + +try: + from .soft_precision_codes import ( + SoftCode, seeded_scaled_code, k5_soft_exact, soft_l1, + soft_distance_matrix, quantize_threshold, binary_diameter_two, + multiplex_onehot, validate_transcript, transcript_distance, + hoeffding_sufficient_width, reference_report, + DEMO_N, DEMO_K, DEMO_SEED, DEMO_GRID_BITS, DEMO_GRID_AMPLITUDE, + ) + from .train_soft_probe import fit_soft_probe, run_pilot +except ImportError: + from soft_precision_codes import ( + SoftCode, seeded_scaled_code, k5_soft_exact, soft_l1, + soft_distance_matrix, quantize_threshold, binary_diameter_two, + multiplex_onehot, validate_transcript, transcript_distance, + hoeffding_sufficient_width, reference_report, + DEMO_N, DEMO_K, DEMO_SEED, DEMO_GRID_BITS, DEMO_GRID_AMPLITUDE, + ) + from train_soft_probe import fit_soft_probe, run_pilot + + +EXPECTED_DIGEST_1024 = '2a99809deb1babd57d9d10e959775429470fafa90d390331b6d82f6f581dd5eb' + + +class TestSoftPrecision(unittest.TestCase): + def test_five_state_three_coordinate_exact_certificate(self): + z = k5_soft_exact() + self.assertEqual(len(z), 5) + self.assertTrue(all(len(x) == 3 for x in z)) + self.assertTrue(all(F(0) <= v <= 1 for x in z for v in x)) + d=soft_distance_matrix(z) + self.assertEqual(set(d[i][j] for i in range(5) for j in range(i)), + {F(1),F(4,3),F(2)}) + self.assertEqual(d[0][4], F(1)) + self.assertEqual(d[1][4], F(4,3)) + # The code is linear in the frozen one-hot state representation. + self.assertEqual([tuple(z[j][i] for i in range(3)) for j in range(5)], list(z)) + + def test_thresholds_any_coordinate_policy_cannot_preserve_k5(self): + z=k5_soft_exact() + # Between 0,1/3,1 there are four distinct threshold patterns per head. + selectors=(F(-1),F(1,6),F(2,3),F(2)) + patterns=set() + for thresholds in itertools.product(selectors, repeat=3): + hard=quantize_threshold(z,thresholds) + patterns.add(hard) + self.assertFalse(binary_diameter_two(hard)) + self.assertGreater(len(patterns),0) + self.assertEqual(quantize_threshold(z,(F(1,2),)*3)[0], 0) + self.assertEqual(quantize_threshold(z,(F(1,2),)*3)[4], 0) + # Independent combinatorial oracle: at most four vertices fit a + # diameter-two subset of the full three-dimensional Boolean cube. + self.assertTrue(all(not binary_diameter_two(tuple(subset)) + for subset in itertools.combinations(range(8),5))) + + def test_binary_four_coordinates_are_sharp_for_k5(self): + self.assertTrue(binary_diameter_two((0,1,2,4,8))) + + def test_pinned_1024_rational_grid(self): + code=seeded_scaled_code(DEMO_N,DEMO_K,DEMO_SEED,DEMO_GRID_AMPLITUDE) + self.assertEqual(code.digest(),EXPECTED_DIGEST_1024) + self.assertEqual(code.extreme_hamming(),(91,168)) + self.assertTrue(code.check(F(1),F(2))) + self.assertEqual(code.extreme_hamming()[0]*code.amplitude,F(364,341)) + self.assertEqual(code.extreme_hamming()[1]*code.amplitude,F(672,341)) + self.assertEqual(code.amplitude*DEMO_K,F(1024,341)) + self.assertLessEqual(code.amplitude,1) + self.assertEqual(code.amplitude.denominator,341) + self.assertLess(code.k,code.n-1) + self.assertEqual(DEMO_GRID_BITS,10) + self.assertEqual(code.amplitude*1023,12) + # A fixed conventional half-threshold zeroes all coordinates. + self.assertLess(code.amplitude,F(1,2)) + # A low threshold restores the Hamming code, violating L1<=2. + self.assertGreater(code.extreme_hamming()[1],2) + + def test_hoeffding_existence_window(self): + for n in (5,16,256,1024): + k=hoeffding_sufficient_width(n) + self.assertGreater(k,18*math.log(n*(n-1))) + self.assertLess(n*(n-1)*math.exp(-k/18),1) + # Grid variants use delta=1/10 and q>=2k, giving b=O(log log n). + n=1024 + k=hoeffding_sufficient_width(n,F(1,10)) + q=(1<<((2*k+1).bit_length()))-1 + self.assertGreaterEqual(q,2*k) + a=F((5*q + 2*k-1)//(2*k),q) + self.assertGreaterEqual(a,F(5,2*k)) + self.assertLessEqual(a,F(3,k)) + self.assertLessEqual(F(3,5)*k*a,F(9,5)) + self.assertGreaterEqual(F(2,5)*k*a,1) + + def test_recurrent_space_time_exact_witnesses(self): + for n,k in ((5,1),(6,2),(17,4),(65,8)): + transcript=multiplex_onehot(n,k) + self.assertEqual(len(transcript[0]),math.ceil((n-1)/k)) + self.assertTrue(validate_transcript(transcript,k)) + self.assertEqual(min(transcript_distance(a,b) + for a,b in itertools.combinations(transcript,2)),1) + self.assertEqual(max(transcript_distance(a,b) + for a,b in itertools.combinations(transcript,2)),2) + with self.assertRaises(ValueError): + multiplex_onehot(5,0) + + def test_bounded_coordinated_extension_cones(self): + # Finite input samples are regular-simplex Hilbert points e_i/sqrt(2). + # Each coordinate has scaled values 0 or a; its clipped McShane + # extension is a-Lipschitz; summing k heads costs k*a <= constant. + # Check sample interpolation and 100 deterministic nearby pairs. + from random import Random + code=seeded_scaled_code(8,32,119,F(3,32)) + n,k=code.n,code.k + points=[[1/math.sqrt(2) if i==j else 0.0 for j in range(n)] + for i in range(n)] + def extend(x): + ds=[math.dist(x,p) for p in points] + return tuple(min(float(code.amplitude), + min((float(code.amplitude)*((code.words[v]>>j)&1) + +float(code.amplitude)*ds[v]) for v in range(n))) + for j in range(k)) + for i,p in enumerate(points): + target=tuple(float(code.amplitude)*((code.words[i]>>j)&1) + for j in range(k)) + for actual,expected in zip(extend(p), target): + self.assertAlmostEqual(actual,expected,places=12) + rng=Random(3502) + for _ in range(100): + x=[rng.uniform(-2,2) for _ in range(n)] + y=[rng.uniform(-2,2) for _ in range(n)] + self.assertLessEqual(sum(abs(a-b) for a,b in zip(extend(x),extend(y))), + 3*math.dist(x,y)+1e-11) + + def test_training_exploratory_seed_replay(self): + all_pairs=run_pilot() + self.assertEqual(all_pairs['soft_feasible_count'],10) + self.assertEqual(all_pairs['threshold_half_hard_feasible_count'],0) + self.assertEqual(all_pairs['train_feasible_count'],10) + # Exploratory split, selected before this committed replay, not a + # preregistered estimate of real-model generalization performance. + heldout=((0,4),(1,3),(2,4)) + split=run_pilot(heldout_edges=heldout) + self.assertEqual(split['train_feasible_count'],10) + self.assertEqual(split['heldout_feasible_count'],2) + self.assertEqual(split['soft_feasible_count'],2) + self.assertEqual(split['threshold_half_hard_feasible_count'],0) + for p in (all_pairs,split): + self.assertEqual([x['seed'] for x in p['runs']],list(range(10))) + self.assertTrue(all(0<=v<=1 for x in p['runs'] for row in x['state'] for v in row)) + + def test_reference_receipt_stability(self): + r=reference_report() + self.assertEqual(r['demo_digest'],EXPECTED_DIGEST_1024) + self.assertEqual(r['soft_k5_pairwise_distances'],['1','2','4/3']) + self.assertEqual(r['binary_one_shot_min_channels'],1023) + self.assertEqual(r['demo_l1_max'],'672/341') + + +if __name__=='__main__': + unittest.main() diff --git a/research/chromatic_observer_gym_v1/test_temporal_capacity.py b/research/chromatic_observer_gym_v1/test_temporal_capacity.py new file mode 100644 index 000000000..33e6144ae --- /dev/null +++ b/research/chromatic_observer_gym_v1/test_temporal_capacity.py @@ -0,0 +1,59 @@ +import unittest +from itertools import product +from temporal_capacity import (minimum_heads,singleton_codes,tied_probe,tied_step,tied_trace, + verify_tied,maximum_equidistant_binary_family,contracting_late_code) + +class CapacityTests(unittest.TestCase): + def test_tied_five_margin_one(self): + self.assertEqual(minimum_heads(5,4,1),1) + x=verify_tied(5,4,1) + self.assertEqual((x['min_pair_distance'],x['max_pair_distance']),(1,2)) + + def test_tied_five_margin_two(self): + self.assertEqual(minimum_heads(5,4,2),2) + x=verify_tied(5,4,2) + self.assertEqual((x['min_pair_distance'],x['max_pair_distance']),(2,2)) + + def test_margin_three_infeasible(self): + self.assertIsNone(minimum_heads(5,4,3)) + self.assertFalse(verify_tied(5,4,3)['possible']) + + def test_many_n_and_visits(self): + for n in range(5,22): + for T in range(1,8): + for margin in (1,2): + with self.subTest(n=n,T=T,margin=margin): + x=verify_tied(n,T,margin) + self.assertEqual(x['heads'],(n-1+(margin==2)+T-1)//T) + + def test_independent_four_bit_anticode_oracle(self): + self.assertEqual([maximum_equidistant_binary_family(w) for w in (1,2,3,4)],[1,2,4,4]) + self.assertEqual(minimum_heads(5,1,2),5) + + def test_tied_step_uses_one_unchanged_probe(self): + codes=singleton_codes(5,4,1) + for label in range(5): + state=(label,0);history=[] + for _ in range(4): + history.extend(tied_probe(state,codes,1));state=tied_step(state) + self.assertEqual(tuple(history),tied_trace(label,codes,4,1)) + + def test_contractive_late_innovation_stops(self): + x=contracting_late_code([0.0,1.0,2.0,3.0],0.5,0.24,12) + self.assertEqual(x['terminal_innovation_visit'],4) + self.assertTrue(all(not any(code[t] for code in x['codes']) for t in range(4,12))) + +if __name__=='__main__':unittest.main() + +class CountOnlyBounds(unittest.TestCase): + def test_multiset_capacity(self): + from visit_phase_controls import unordered_qary_upper_bound + self.assertEqual(unordered_qary_upper_bound(4,1),5) + self.assertEqual(unordered_qary_upper_bound(4,2),35) + self.assertEqual(2**(4*1),16) + + def test_k8_count_only_max_edges(self): + from visit_phase_controls import clique_max_separated_with_categories + self.assertEqual(clique_max_separated_with_categories(8,5),25) + self.assertEqual(clique_max_separated_with_categories(8,8),28) + self.assertEqual(clique_max_separated_with_categories(8,1),0) diff --git a/research/chromatic_observer_gym_v1/train_soft_probe.py b/research/chromatic_observer_gym_v1/train_soft_probe.py new file mode 100644 index 000000000..c423c1f21 --- /dev/null +++ b/research/chromatic_observer_gym_v1/train_soft_probe.py @@ -0,0 +1,88 @@ +"""COE-03 synthetic CPU training pilot: one-hot states, continuous 3-head probe. + +No external packages. Linear one-hot probe weights are trained by projected +subgradient descent using *only* pairwise output-distance hinge loss. +By default all K5 pairs are used. An optional exploratory edge holdout can +measure transfer to missing evaluator distinctions; synthetic only. +""" +from __future__ import annotations +from itertools import combinations +from random import Random + +try: + from .soft_precision_codes import quantize_threshold, binary_diameter_two +except ImportError: + from soft_precision_codes import quantize_threshold, binary_diameter_two + + +def fit_soft_probe(seed: int, n: int = 5, k: int = 3, + steps: int = 4000, learning_rate: float = 0.45, + heldout_edges: tuple[tuple[int, int], ...] = ()) -> dict: + if n < 2 or k < 1 or steps < 1 or learning_rate <= 0: + raise ValueError('invalid pilot hyperparameters') + rng=Random(seed) + state=[[rng.random() for _ in range(k)] for _ in range(n)] + pairs=tuple(combinations(range(n),2)) + heldout = set(heldout_edges) + if any(e not in pairs for e in heldout): + raise ValueError('holdout must be an unordered canonical pair') + train_pairs = tuple(e for e in pairs if e not in heldout) + if not train_pairs: + raise ValueError('training edge set cannot be empty') + m=len(train_pairs) + history=[] + for step in range(steps): + grad=[[0.0]*k for _ in range(n)] + loss=0.0 + for u,v in train_pairs: + d=sum(abs(a-b) for a,b in zip(state[u],state[v])) + deviation=(d-1.0) if d<1.0 else ((d-2.0) if d>2.0 else 0.0) + loss+=deviation*deviation/m + if deviation: + for j in range(k): + sign=(1 if state[u][j]>state[v][j] else -1) if state[u][j]!=state[v][j] else 0 + grad[u][j]+=2*deviation*sign/m + grad[v][j]-=2*deviation*sign/m + for i in range(n): + for j in range(k): + state[i][j] = min(1.,max(0.,state[i][j]-learning_rate*grad[i][j])) + if step in (0,99,499,999,1999,steps-1): + history.append((step+1,round(loss,10))) + if loss < 1e-12: + break + ds=[sum(abs(a-b) for a,b in zip(state[u],state[v])) for u,v in pairs] + train_distances=[d for d,pair in zip(ds,pairs) if pair not in heldout] + heldout_distances=[d for d,pair in zip(ds,pairs) if pair in heldout] + lower=min(ds);upper=max(ds) + hard=[sum(int(x>=0.5)<=1-1e-3 and upper<=2+1e-3, + 'train_feasible_1e3':min(train_distances)>=1-1e-3 and max(train_distances)<=2+1e-3, + 'heldout_feasible_1e3':(min(heldout_distances)>=1-1e-3 and max(heldout_distances)<=2+1e-3) if heldout_distances else None, + 'train_edges':len(train_pairs),'heldout_edges':len(heldout), + 'hard_min':min(hard_d),'hard_max':max(hard_d), + 'hard_feasible':binary_diameter_two(tuple(hard)), + 'hard_codes':hard, + 'state':[[round(x,8) for x in v] for v in state], + 'history':history} + + +def run_pilot(seeds=range(10), heldout_edges: tuple[tuple[int, int], ...] = ()) -> dict: + outputs=[fit_soft_probe(seed, heldout_edges=heldout_edges) for seed in seeds] + return {'format':'coe03-training-pilot-v1', 'task':'synthetic K5 pair-distance hinge fit', + 'model':'3-channel linear probe on five frozen one-hot states', + 'hyperparameters':{'steps':4000,'learning_rate':0.45,'all_ten_pairs_in_train':True}, + 'seeds':[o['seed'] for o in outputs], + 'heldout_edges':[list(e) for e in heldout_edges], + 'soft_feasible_count':sum(o['soft_feasible_1e3'] for o in outputs), + 'threshold_half_hard_feasible_count':sum(o['hard_feasible'] for o in outputs), + 'train_feasible_count':sum(o['train_feasible_1e3'] for o in outputs), + 'heldout_feasible_count':sum(bool(o['heldout_feasible_1e3']) for o in outputs) if heldout_edges else None, + 'runs':outputs} + + +if __name__=='__main__': + import json + print(json.dumps(run_pilot(),indent=2)) diff --git a/research/chromatic_observer_gym_v1/visit_phase_controls.py b/research/chromatic_observer_gym_v1/visit_phase_controls.py new file mode 100644 index 000000000..ddb6ccfb0 --- /dev/null +++ b/research/chromatic_observer_gym_v1/visit_phase_controls.py @@ -0,0 +1,59 @@ +"""Fixed-parameter, diagnostic-only visit-order counterfactuals.""" +from __future__ import annotations +import random +from temporal_observers import EDGES, N, T, dot,covered_pairs,TEST_CONTEXTS + + +def visit_scramble(item,head,seed_offset): + w,threshold=head + observations=[] + for c in TEST_CONTEXTS: + row=[] + for a in range(N): + bits=[int(dot(w,item['activations'][f'{a}:{c}'][t])>threshold) for t in range(T)] + rng=random.Random(item['model_seed']*100000+c*100+a*10+seed_offset) + rng.shuffle(bits) + row.append(tuple(bits)) + observations.append(row) + return covered_pairs(observations) + + +def layer_separation_diagnostic(item): + from math import dist + # Same distractor context for each compared pair: frozen task label varies. + values=[] + for t in range(T): + pairs=[dist(item['activations'][f'{a}:{c}'][t], + item['activations'][f'{b}:{c}'][t]) + for c in TEST_CONTEXTS for a,b in EDGES] + values.append({'visit':t+1,'minimum_l2':min(pairs),'mean_l2':sum(pairs)/len(pairs),'maximum_l2':max(pairs)}) + return values + + +def count_only_score(item,head): + """Order-free count of threshold-positive visits, diagnostic control.""" + w,threshold=head + obs=[] + for c in TEST_CONTEXTS: + row=[] + for a in range(N): + row.append(sum(int(dot(w,item['activations'][f'{a}:{c}'][t])>threshold) for t in range(T))) + obs.append(row) + return {'edge_hits':covered_pairs(obs),'unique_counts':[len(set(row)) for row in obs]} + + +def unordered_qary_upper_bound(visits,heads): + """Number of T-element multisets over alphabet of size 2**heads.""" + from math import comb + if visits<0 or heads<0:raise ValueError + q=1<