diff --git a/.github/workflows/fhc-01.yml b/.github/workflows/fhc-01.yml new file mode 100644 index 000000000..14f660822 --- /dev/null +++ b/.github/workflows/fhc-01.yml @@ -0,0 +1,68 @@ +name: FHC-01 finite horizon and metric obstruction controls +permissions: + contents: read +on: + push: + paths: + - 'research/finite_horizon_gap_v1/**' + - '.github/workflows/fhc-01.yml' + pull_request: + paths: + - 'research/finite_horizon_gap_v1/**' + - '.github/workflows/fhc-01.yml' + workflow_dispatch: +jobs: + finite-geometry: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Exact rational moment, packing, net and observability tests + run: python -m unittest discover -s research/finite_horizon_gap_v1 -p 'test_reference.py' -v + - name: Emit finite control receipt + run: python research/finite_horizon_gap_v1/reference.py --check --out /tmp/fhc01_control.json + - uses: actions/upload-artifact@v4 + with: + name: fhc01-finite-controls + path: /tmp/fhc01_control.json + future-observation-benchmark: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install fixed numeric dependency + run: python -m pip install numpy==2.1.3 + - name: Full-space GF2 and heldout future metric regression + run: python -m unittest discover -s research/finite_horizon_gap_v1 -p 'test_horizon_geometry.py' -v + - name: Measure frozen future-metric frontier + run: python research/finite_horizon_gap_v1/bench_future_metric.py --seed 940198 --horizons 1 2 4 6 8 16 32 63 --widths 2 4 6 8 16 32 --out /tmp/fhc01b_heldout.json + - name: Upload source-locked finite pilot receipt + uses: actions/upload-artifact@v4 + with: + name: fhc01b-heldout-future-metric + path: /tmp/fhc01b_heldout.json + trained-rrc25-future-geometry: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Install fixed numeric dependency + run: python -m pip install numpy==2.1.3 + - name: Verify original RRC25 checkpoint and native zero-continuation adapter + run: python -m unittest discover -s research/finite_horizon_gap_v1 -p 'test_rrc25_future.py' -v + - name: Measure frozen trained RRC25 future-logit frontier + run: python research/finite_horizon_gap_v1/bench_rrc25_future.py --seed 940199 --horizons 1 2 4 8 16 --widths 2 4 8 12 16 --out /tmp/fhc01c_trained_rrc25.json + - name: Upload source-locked RRC25 geometry receipt + uses: actions/upload-artifact@v4 + with: + name: fhc01c-trained-rrc25-geometry + path: /tmp/fhc01c_trained_rrc25.json diff --git a/research/finite_horizon_gap_v1/PROTOCOL.md b/research/finite_horizon_gap_v1/PROTOCOL.md new file mode 100644 index 000000000..d74a062b0 --- /dev/null +++ b/research/finite_horizon_gap_v1/PROTOCOL.md @@ -0,0 +1,46 @@ +# FHC-01 experimental protocol + +Status: prospective; no trained model experiment is claimed here. + +## Target + +Measure minimum empirical encoder dimension at distortion D as the +future observation horizon T and semantic state-cover resolution change. +Define Phi_T(h)=(w_1 G(F(h)),...,w_T G(F^T(h))) with explicit bounded +observable G, recurrent map F, nonzero weights and declared task input. + +The metric d_T(h,k)=||Phi_T(h)-Phi_T(k)||_2 may be a pseudometric. +When the infinite future limit is used, require square-summable weights. +Raw hidden-state Euclidean geometry already lives in a fixed dimension; +the #098 compact doubling obstruction is relevant only after the +future-observation geometry is independently shown to have those properties. + +## Frozen variables + +Store checkpoint/tokenizer SHA-256 and full-state accounting, including +external clock, prompts, caches and recurrence. Freeze random seeds, +independent prompt families, intervention grammar and future metric. +Hold out complete prompt/trajectory families before fitting embeddings. + +Sweep T=1,2,4,8,16 and supported widths d=2,4,8,16,32,64. +Prespecify D=1.5 and D=2.0. Compare dimension-matched PCA, Gaussian +projection, SAE and nonlinear encoders at the same parameter budget, +precision, fitted sample count and compute. Record any lookup table +and stateful encoder side memory in the RC-01 resource ledger. + +## Interpretation + +On each finite held-out set, report pairwise semantic distances, +encoded distances, a single calibration-only global scale, +worst-case multiplicative distortion and every violating pair. +A random finite sample supplies an empirical statistic. Uniform +guarantees require a proved epsilon-net or explicit covering certificate. +Any one violation certifies failure of that particular candidate. + +The reversible shift-register control gives exact linear rank +min(T,m). Confirm it before neural trials. Use a non-doubling equilateral +finite packing control to check the volume obstruction. No experiment +can claim recreation of #098 without reproducing its compact witness. + +A future prospective model-level finding requires new frozen training +seeds and a decision rule published before inspecting outcomes. diff --git a/research/finite_horizon_gap_v1/PROTOCOL_RRC25.md b/research/finite_horizon_gap_v1/PROTOCOL_RRC25.md new file mode 100644 index 000000000..40d09f321 --- /dev/null +++ b/research/finite_horizon_gap_v1/PROTOCOL_RRC25.md @@ -0,0 +1,77 @@ +# FHC-01C: trained RRC-25 future-observation geometry + +**Registration:** 2026-11-13, before evaluating this FHC-01C code. +**Evidence status:** exploratory retrospective frozen-model pilot. +**Original model:** RRC-25 recurrent GRU template ranker, 1,000 trained +parameters, source-locked JSON state dictionary in +research/rrc_compactification/results/rrc25_recurrent.json. +The existing bench25.checkpoints() gate validates model kind, +architecture, source hashes and training-step count. + +## Construction + +Build the RRC-25 case roster with the original generator, selecting +train_per=1, dev_per=12, test_per=8. Only the dev cases supply +the new geometry calibration; only the named six test families +signed/sparse/product/rational/squared/late_source enter test +metrics. The original model's training process precedes this study. + +Each case supplies two public demonstrations and a known public +header. Call compound25.features(case, header) to get the same +9x8 feature sequence used by the source model. Run the source +portable GRU recurrence exactly, with zero initial hidden state. +Verify the final 16 logits against model25.logits on every case. + +The represented recurrent state is the final hidden vector h9, +dimension 12, after processing all nine input rows. Freeze a +specific intervention: every later input vector is identically +zero, and no public query features are re-injected. For +T in {1,2,4,8,16}, repeatedly apply the trained GRU transition +to h9 with that zero input and concatenate the 16 logit outputs. + +This future-logit metric is distinct from the native task's +suffix-class accuracy; it is a controlled extrapolation of a +learned recurrent state under an intentionally artificial +continuation. The experiment does not infer a physical or +natural-language semantic metric from these logits. + +## Comparators and scoring + +- Native hidden 12-dimensional code, paired with its exact + recurrent continuation decoder. It is dynamically sufficient + for this continuation, subject to floating numerical precision. +- Full future trace, dimension 16T, exact metric identity. +- PCA of future traces fitted only on dev cases. +- Fixed-seed Gaussian projection of future traces, independent + of test features. +- Widths d={2,4,8,12,16}, restricted to d<=16T and + d<=number of usable PCA components as appropriate. + +Use a median positive calibration-pair ratio to fit the global +scale per representation. Record all test-pair distortion ratios, +source-near-zero exclusions, calibration D=1.5 and D=2.0 +violation counts and worst replayable case-ID pair. +Also report each held-out family separately. The primary unit is +one source-generator case, not a pair of cases. + +Retain model JSON SHA256, source hashes from bench25, +the exact feature roster identifier hash, independent source +file hashes, fitting seed, number of parameters, native hidden +width and number of oracle future steps consumed to construct +PCA/projected representations. Projection matrices are charged +as 16*T*d coefficients; PCA mean vectors are extra. + +The native hidden state's 12 float32 coordinates do not count +as 12 **bits**. Its state description is at least 384 bits +under an fp32 storage model, separate from approximately 1,000 +trained weights and the decoder program. + +The absolute size of geometric distortion on one generated +case set does not establish a global Lipschitz or bi-Lipschitz +bound. A code that passes tested pair distances need not pass +the source distribution's support. The #098 theorem applies +to an infinite-dimensional compact doubling witness, which +the native twelve-dimensional GRU does not instantiate. + +Results will be added after CI passes. This protocol does not +modify source checkpoints, RRC-25 scoring or its stored receipts. diff --git a/research/finite_horizon_gap_v1/README.md b/research/finite_horizon_gap_v1/README.md new file mode 100644 index 000000000..d61b91b2a --- /dev/null +++ b/research/finite_horizon_gap_v1/README.md @@ -0,0 +1,54 @@ +# FHC-01: finite-horizon compactification gap + +Research started 2026-11-13. Sources: OpenAI Math [#094](https://github.com/openai/math/blob/main/lean/docs/094.md) and [#098](https://github.com/openai/math/blob/main/lean/docs/098.md). + +## Main theorem + +Conditional on the two published source results, a compact doubling Hilbert subset has N-point dense prefixes whose distortion-D embedding dimension must diverge with N, while l4 admits the upper bound exp(C_D sqrt(log N)). + +[THEORY.md](THEORY.md) supplies the Gaussian transfer, finite obstruction compactness, robust epsilon-net obstruction, additive coarse embedding and exact linear shift-register observability rank min(T,m). + +## Repeatable finite controls + +Python 3.10+ and standard library: + + python -m unittest discover -s research/finite_horizon_gap_v1 -p 'test_*.py' -v + python research/finite_horizon_gap_v1/reference.py --check --out /tmp/fhc01_control.json + +The finite controls check Gaussian fourth moments, equilateral packing, distortion-transfer tolerance epsilon=delta/6, doubling cover arithmetic, rational finite l2->l4 maps and shift observability ranks. + +The source papers' compact doubling witness is not reproduced by these finite checks, and no trained neural checkpoint is tested. + +[PROTOCOL.md](PROTOCOL.md) defines the future-observation metric experiment, owned separately from RC-01, IC-01, IRC-02 and SUD-01. + +The independently kernel-checked discrete bridge is in [MathCan PR #31](https://github.com/patrickdugan/MathCan/pull/31). It covers the integer one-sixth clearance and full-prefix recovery lemmas only. + + +## Executed extensions: RC-01B and trained RRC-25 + +[FHC-01B results](RESULTS_B.md) derive and measure the gap between +exact semantic binary memory and the Euclidean dimension required +for preserving full future-observation distances. The six-bit +primitive looper needs just six predictive bits at horizon 63, +while its exact 64-state future-trace isometry requires 63 real +coordinates. A 48/16 calibration/heldout PCA split has the +full-regular-simplex unseen-state collapse proved by FHC-8. +The frozen CI pilot includes PCA, Gaussian projection and exact +binary quotient comparisons with held-out pair witnesses. + +[FHC-01C results](RESULTS_C.md) evaluate the existing source-locked +1,000-parameter RRC-25 trained recurrent GRU checkpoint. The +benchmark [protocol](PROTOCOL_RRC25.md) defines a fixed zero-input +recurrent continuation and measures the geometry of future logits. +At horizon 16 the native hidden-state 12-coordinate norm exhibits +39.528 worst-pair distortion on the frozen held-out cases, versus +1.230 for a 12-coordinate PCA of future-logit traces fitted on +separate dev cases. The latter has a significant future-computation +and projection-description cost, which is charged in the receipt. + +All results retain distinct evidence labels: exact finite theorem, +synthetic recurrent pilot, and trained-model retrospective geometry. +They are not a construction of the #098 compact doubling counterexample. +The companion [MathCan Lean PR #31](https://github.com/patrickdugan/MathCan/pull/31) +checks the discrete one-sixth tolerance lemma, full-horizon prefix +recovery and an explicit six-bit observable-mask orbit. diff --git a/research/finite_horizon_gap_v1/RESULTS_B.md b/research/finite_horizon_gap_v1/RESULTS_B.md new file mode 100644 index 000000000..c2ae6149a --- /dev/null +++ b/research/finite_horizon_gap_v1/RESULTS_B.md @@ -0,0 +1,105 @@ +# FHC-01B: executed future-observation geometry pilot + +Date: 2026-11-13. This is a **FROZEN_SYNTHETIC_RECURRENT_PILOT** using +the existing RC-01 affine GF(2) recurrence. It is a measured +finite-state/PCA experiment, not a trained neural checkpoint run. + +## Reproduction + +Source CLI: bench_future_metric.py. Exact primitive recurrence: +horizon_geometry.py, which directly imports the RC-01 Affine, +row_times_matrix, row_basis and coordinates implementations. +Random seed 940198, NumPy 2.1.3, 48 calibration states, 16 +independent held-out state IDs, 120 possible held-out pairs. +All 64 six-bit states have a source-generated future trace. + +At every T the finite future metric is the Euclidean distance +between T Boolean observations of the primitive six-bit looper. +Scale is fitted as inverse median positive pairwise code/source +ratio on calibration pairs only. The primary D=2.0 violation count +uses that frozen scale and the interval [1/sqrt(D),sqrt(D)]. +The separately reported optimal D is the ratio of the largest to +the smallest nonzero held-out distance ratio. A collapsed pair +gives infinite optimal D (recorded as null in the JSON receipt). + +Reproduce on Python 3.12 with NumPy 2.1.3: + + python -m unittest discover -s research/finite_horizon_gap_v1 -p test_horizon_geometry.py -v + python research/finite_horizon_gap_v1/bench_future_metric.py --seed 940198 --horizons 1 2 4 6 8 16 32 63 --widths 2 4 6 8 16 32 --out /tmp/fhc01b_heldout.json + +The JSON receipt is uploaded as a GitHub Actions artifact. The +original printed run can be inspected at +https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43405190674 . +Program source SHA-256 at that run: +3245bd638b4da90da06b46b13c79a905ff18dbdd9f395b203cfff63b2b01a5f0 . + +## Exact finite rank frontier + +| Horizon T | Minimal predictive binary bits | Exact isometric Euclidean dimension | +|---:|---:|---:| +| 1 | 1 | 1 | +| 2 | 2 | 2 | +| 4 | 4 | 4 | +| 6 | 6 | 6 | +| 8 | 6 | 8 | +| 16 | 6 | 16 | +| 32 | 6 | 32 | +| 63 | 6 | 63 | + +The binary rank counts every possible exact semantic code, including +nonlinear ones, if the code holds a fixed B-bit word. The real +dimension is a lower bound for *exact Euclidean isometry* on all 64 +source states. Its proof uses the 63 pairwise orthogonal nontrivial +Walsh characters. At T=63, all distinct source points have squared +Euclidean distance exactly 32 in future-trace space. + +## Held-out geometry at T=63 + +| Encoder | Code dimension | Optimal held-out distortion D | Violating pairs at fixed calibrated D=2 | +|---|---:|---:|---:| +| Exact predictive quotient | 6 binary bits | 2.449 | 13/120 | +| PCA trained on 48 states | 6 real coordinates | infinity | 120/120 | +| Gaussian random projection | 6 real coordinates | 5.081 | 30/120 | +| PCA trained on 48 states | 32 real coordinates | infinity | 120/120 | +| Gaussian random projection | 32 real coordinates | 1.972 | 3/120 | +| Full future trace | 63 real coordinates | 1.000 | 0/120 | + +PCA returns identical codes for all 16 unseen states, within floating +point error, for every tested dimension d=2,4,6,8,16,32. FHC-8 proves +this collapse for *any positive-variance PCA component fitted on any +proper subset of regular simplex vertices*. + +Gaussian-32's optimal D=1.972 is a descriptive held-out rescaling +statistic. With the scale frozen on calibration data, three of the +120 distinct held-out pairs fail the D=2 condition. Both quantities +are retained because reselecting the scale on test pairs would +leak information. + +At horizon T=32, the quotient has optimal distortion 2.291, versus +1.954 for Gaussian-16 and 2.116 for Gaussian-32. Both Gaussian-16 +and Gaussian-32 still have calibrated D=2 failures (9 and 1, +respectively). PCA-32 is the full metric dimension there and +reproduces pairwise distances exactly. + +## Geometric interpretation + +The source recurrence is invertible and every length-63 trace +contains all six source bits. Predictive-memory sufficiency is a +lossless *finite-state decoder* contract. PCA projects a future +feature space and is fitted on a disjoint subset of states; its +failure is a generalization property of that fitted subspace. +Random projections preserve distances approximately by a +different mechanism. + +The candidate bit encoder requires a basis description and a +future-bit decoder table. PCA and Gaussian projections require T +oracle observations per state to assemble their input feature +vectors, plus matrix parameters and a calibration scale. The JSON +resource ledger records these costs explicitly. A cheap encoder +from a native neural hidden state has not been established. + +None of the finite geometry results constructs the OpenAI #098 +compact doubling witness; an N-point equilateral family has +doubling constant at least N. Source #094 concerns existential +finite-set embeddings and does not promise that sample-trained +PCA will generalize. diff --git a/research/finite_horizon_gap_v1/RESULTS_C.md b/research/finite_horizon_gap_v1/RESULTS_C.md new file mode 100644 index 000000000..707de64b6 --- /dev/null +++ b/research/finite_horizon_gap_v1/RESULTS_C.md @@ -0,0 +1,111 @@ +# FHC-01C: executed trained RRC-25 future-logit geometry pilot + +Date: 2026-11-13. Status: **FROZEN_TRAINED_RRC25_DEVELOPMENT**. +Source-locked original recurrent checkpoint: +SHA-256 54f225f2a61c52fee5a740576eaab3bcbc5280a595fc1ac1ac115ec8ac26c41b. + +[Experimental registration](PROTOCOL_RRC25.md) and +[source benchmark](bench_rrc25_future.py). +GitHub Actions receipt: https://github.com/MoralityLabAI/Compactification-Theory/actions/runs/43406537505 + +## Frozen native computation + +The checkpoint is the existing RRC-25 1,000-parameter GRU, trained +to rank sixteen suffix-template pairs. The public source gate +bench25.checkpoints() verifies the committed JSON weight SHA-256, +training source hashes, step count and model structure before the +new benchmark can execute. + +Using each case's first publicly inferred header, the benchmark +replays all nine original source feature rows through the portable +GRU. Its final 16 logits agree exactly with the existing portable +model25.logits implementation (maximum absolute difference 0.0). +No hidden true suffix label or case.future is consulted; a targeted +test mutates the entire case.future and confirms identical states +and outputs. + +The analysis freezes the post-input 12-dimensional recurrent +hidden state h9 and feeds zero 8-vectors as artificial continuations +for horizons T=1,2,4,8,16. The observable G is the trained model's +16-dimensional logit head, so the future feature dimension is 16T. +The trained checkpoint's native task never asked for zero-input +continuations. This study measures **the resulting controlled +recurrent geometry**, not native future-task accuracy. + +The original checkpoint was trained using PyTorch float32. The +portable reference converts stored JSON weights to Python floats +and uses double-precision scalar arithmetic, matching the source +portable inference exactly. The nominal storage ledger quotes +12*32=384 bits for float32 live hidden-state storage and +1000*32=32,000 bits of checkpoint weights; the actual Python +reference object and arithmetic costs are separate. + +## Split and metric + +The source roster produces 36 calibration cases, twelve from each +of the signed/sparse/product development families, and 48 held-out +cases, eight from each of signed/sparse/product/rational/squared/ +late_source. No held-out case enters PCA fitting or scale fitting. +The benchmark retains full roster fingerprints, source hashes, +family labels and replayable worst-pair IDs. + +For each horizon T define the future logit vector as concatenation +of the 16-dimensional native logit heads at the next T zero-input +transitions. The tested distance is Euclidean in this 16T-dimensional +space. One calibration scale per method is frozen from dev pairwise +ratios. + +The held-out cohort contains 48 cases and 1128 distinct case pairs. +The table's "best D" is the descriptive optimal-rescaling distortion +computed on held-out pairs, while the violation count is the primary +calibration-only D=2 test. + +## Measured future metric + +| T | Native hidden 12D, best D | Native hidden, D=2 failures | PCA 12D, best D | PCA 12D, D=2 failures | +|---:|---:|---:|---:|---:| +| 1 | 7.820 | 193/1128 | 1.000 | 0/1128 | +| 2 | 9.527 | 210/1128 | 1.059 | 0/1128 | +| 4 | 13.832 | 309/1128 | 1.087 | 0/1128 | +| 8 | 30.087 | 441/1128 | 1.102 | 0/1128 | +| 16 | 39.528 | 839/1128 | 1.230 | 0/1128 | + +At T=16, PCA with 8 coordinates has descriptive D=1.457, +with one of 1128 held-out pairs violating the calibration-scaled +D=2 rule. Gaussian-12 has descriptive D=2.515 and 13 calibrated +D=2 failures. The original hidden 12D code exactly determines the +future logit trajectory when paired with its original recurrent +transition and trained readout; its raw Euclidean metric has +substantial distortion relative to this particular future logit +metric. + +A compact representation's *dynamic sufficiency* and the +distances implied by its unmodified coordinate norm are different +properties. The projection may better preserve the chosen metric +because it consumes the future logit vectors themselves. + +## Experimental caveats + +- PCA and Gaussian projections receive all T recurrent future + logit vectors as their input, at a cost of T native recurrent + transitions per case. The projections then store a matrix of + 16T*d real coefficients. The native hidden code has twelve + coordinates and access to the already trained recurrent decoder. +- A run on fixed generated cases is a descriptive empirical test, + with no global bi-Lipschitz certificate. It does not instantiate + the #098 infinite-dimensional compact doubling witness. +- Results are sensitive to the definition and units of the + observable G. The output is a 16-dimensional logit vector from + an experimentally imposed zero-input continuation. +- All dev/test case measurements are retrospective relative to + the previously trained RRC25 checkpoint. A new neural training + cohort and frozen source-generation protocol are necessary + before a prospective model-level claim. +- The code records every held-out pair's worst witness and + family-level statistics in the workflow JSON artifact. The + optimal test rescaling statistic is descriptive and cannot + be used to select the calibration scale. + +The source-lock and native replay tests passed in GitHub Actions, +including a six-test dedicated RRC25 FHC-01C suite. Existing RRC25 +research decisions are unaffected. diff --git a/research/finite_horizon_gap_v1/THEORY.md b/research/finite_horizon_gap_v1/THEORY.md new file mode 100644 index 000000000..65c06a993 --- /dev/null +++ b/research/finite_horizon_gap_v1/THEORY.md @@ -0,0 +1,484 @@ +# FHC-01: Finite-horizon compactification gap + +Date: 2026-11-13. **Status:** conditional mathematical derivations, exact +finite rational reference, and a proposed recurrent-semantic experiment. +The proofs here have not been Lean-checked. The OpenAI manuscripts are research +claims at different stages of external review. We import only the stated +results, and label the new elementary deductions separately. + +## 0. Two source statements and their scopes + +**OpenAI Math family #094**, *Subpolynomial dimension reduction in Lp* +(2026-09-23). For fixed 11, every N-point subset of +real Lp has an embedding into finite-dimensional l_p^d of distortion D with + +\[ +d\le\exp(C_{p,D}(\log N)^{\gamma(p)}),\qquad +\gamma(p)=\begin{cases}2-p,&p<2\\1-2/p,&p>2.\end{cases} +\] + +At p=4 the exponent is 1/2. Scope: https://github.com/openai/math/blob/main/lean/docs/094.md . +The comparator challenge has admitted statements; it is not itself a +finished kernel proof. + +**OpenAI Math family #098**, *Compact counterexamples to bi-Lipschitz +dimension reduction* (2026-09-25). The released scope includes a compact +doubling subset K of an infinite-dimensional real Banach space (hence +one may choose Hilbert space) with no bi-Lipschitz embedding into any +finite-dimensional normed space at any finite distortion. +Scope: https://github.com/openai/math/blob/main/lean/docs/098.md . +Use the CompactBanach companion for compactness; the separate +DoublingHilbert comparator statement omits that hypothesis. + +## 1. Gaussian transfer into L4 (FHC-G) + +Let H=l_2(N), with independent standard Gaussian random variables +G_j on a common probability space. Define, initially for finitely +supported x, + +\[ +Jx=3^{-1/4}\sum_jx_jG_j. +\] + +Fourth moments give + +\[ +E|\sum_j(x_j-y_j)G_j|^4 +=3(\sum_j|x_j-y_j|^2)^2,\quad +\boxed{\|Jx-Jy\|_{L4}=\|x-y\|_2}.\tag{FHC-G} +\] + +The series extends by completion in L4 to all H. We can therefore +apply the p=4 case of #094 to finite subsets of the Hilbert-space +witness in #098. This explicitly uses #094's p != 2 scope. + +## 2. Finite witness compactness lemma (FHC-C) + +Let K be compact metric, Y a finite-dimensional normed space, and D>=1. +If every finite F subset K admits some map f_F:F->Y and scale a_F>0 with + +\[ +a_Fd(x,y)\le\|f_F(x)-f_F(y)\|\le Da_Fd(x,y), +\] + +then all K admits a D-bi-Lipschitz embedding into Y. + +**Proof.** Pick dense x_0,x_1,... . On each finite prefix scale the +embedding by 1/a_F and translate its image of x_0 to zero. Every +image is bounded by D diam(K). Finite-dimensional closed bounded +balls are compact, so diagonalize to get convergent images for every +fixed x_j. Both pairwise distance inequalities survive limits. +The resulting D-Lipschitz map on the dense sequence extends to K, +and its lower inequality gives injectivity. QED. + +**Finite obstruction:** If K admits no D embedding into Y, some +finite A subset K already has no D embedding. No cardinality +bound follows without further quantitative geometry. + +## 3. Main combined theorem (FHC-1) + +Assume #094 and #098. There exists a compact doubling +K subset l_2 such that, for every fixed D>1 and any dense +sequence x_1,x_2,... in K, the least dimension d_D(N) needed +to embed the first N points into l_4^{d_D(N)} at distortion D obeys + +\[ +\boxed{d_D(N)\to\infty,\qquad +d_D(N)\le\exp(C_D\sqrt{\log N})\quad(N\ge2).}\tag{FHC-1} +\] + +Apply FHC-G and #094 for the upper bound. Prefix containment makes +d_D(N) nondecreasing. If it stayed bounded by d, zero-pad the +coordinate embeddings to l_4^d; FHC-C would give a D embedding of K, +contradicting #098. The lower result is qualitative. Do not copy +#094's universal worst-case lower bound to this specific K. QED. + +## 4. Robust net obstruction with explicit tolerance (FHC-2) + +Fix d, D>=1 and alpha>1. FHC-C gives a finite +A subset K lacking any (alpha D)-embedding into l_4^d. +Let delta_A=min_{a!=a' in A}d(a,a')>0. + +Suppose Q is an epsilon-net in K and f:Q->l_4^d has distortion D. +Choose q(a)∈Q within epsilon of each a∈A. Normalize the embedding +so its lower Lipschitz bound is one. Then + +\[ +d(a,a')-2\epsilon\le\|f(q(a))-f(q(a'))\| +\le D(d(a,a')+2\epsilon). +\] + +The induced map on A has distortion at most + +\[ +D_{\rm transfer} +=D\frac{\delta_A+2\epsilon}{\delta_A-2\epsilon} +\quad (2\epsilon<\delta_A). +\] + +Solving D_transfer<=alpha D yields + +\[ +\boxed{ +\epsilon<\frac{\delta_A(\alpha-1)}{2(\alpha+1)} +\implies\text{every finite epsilon-net of K fails D-embedding into l_4^d}. +}\tag{FHC-2} +\] + +For alpha=2 the sufficient threshold is epsilonl_4^d, select q(x)∈Q with d(x,q(x))<=epsilon +and let E(x)=f(q(x)). The triangle inequality gives + +\[ +\boxed{ +\max(0,d(x,y)-2\epsilon) +\le\|E(x)-E(y)\|_4 +\le D(d(x,y)+2\epsilon). +}\tag{FHC-3} +\] + +This is an additive-error representation of all K at scale epsilon. +It requires a charged nearest-net lookup or a learned selection map. +The fixed-d obstruction concerns a uniform multiplicative guarantee +as epsilon goes to zero. QED. + +## 6. Doubling scale frontier (FHC-4) + +Let Lambda be an intrinsic doubling constant of K and +R=diam(K)>0. A ball of radius 2R covers K. Repeatedly +halving its radius L=max(0,ceil(log_2(4R/epsilon))) times +gives an epsilon-net Q_epsilon with + +\[ +|Q_\epsilon|\le\Lambda^L. +\] + +Since log|Q_epsilon|=O(log(1/epsilon)), #094 and +FHC-G produce a choice of finite net satisfying + +\[ +\boxed{ +d_D(Q_\epsilon) +\le\exp(O_D(\sqrt{\log(1/\epsilon)})) +\quad(\epsilon\downarrow0). +}\tag{FHC-4} +\] + +Every sufficiently fine net nevertheless needs more than any +preassigned finite d, by FHC-2. **Covering entropy can stay +logarithmic in resolution while bounded-distortion dimension +diverges.** Embedding existence does not bound model parameter bits +or the work needed to compute an encoder. + +## 7. Explicit non-doubling control: equilateral packing (FHC-P) + +Take N Hilbert vectors e_i/sqrt(2): all distinct pair distances +are one. An arbitrary d-dimensional normed embedding with distances +normalized into [1,D] places N disjoint radius-1/2 balls inside +a radius-(D+1/2) ball. Volume comparison gives + +\[ +\boxed{N\le(1+2D)^d,\quad +d\ge\log N/\log(1+2D).}\tag{FHC-P} +\] + +For a one-dimensional target the optimal distortion is exactly N-1: +order real image points and add consecutive gaps of at least one. +The set of N equilateral points has doubling constant N, so this is +an **explicit non-doubling calibration**, not a recreation of #098. + +## 8. Interface and neural evaluation contract + +Apply to RC-01 and IC-01, with optional SEM-ECHO transfer. Build a +task metric from future observations, separate from raw activation +Euclidean distances, e.g. + +\[ +\Phi_T(h)=(w_1 G(F(h)),\ldots,w_T G(F^T(h))). +\] + +For an infinite-horizon Hilbert metric require square-summable +weights, bounded observables, and declared state support. + +At horizons 1,2,4,8,16,... measure pairwise relative distances, +maximum distortion, near-fiber failures and held-out interventions. +Compare PCA, SAE, random projections and interface-relative encoders +at matched d, numeric precision, trained parameter budget and +inference cost. Every claimed failure must retain actual state pairs +and the declared observation metric. + +A fixed finite neural checkpoint lives in finite-dimensional hidden +space under its raw Euclidean metric, which trivially embeds at that +same dimension. The #098 obstruction is only relevant to an +infinite-dimensional limit geometry or separately defined future +semantic metric. No property of current Qwen, Q5 or other checkpoints +is assumed. + +Status ledger: +- FHC-G, FHC-C, FHC-2, FHC-3, FHC-P: elementary supplied proofs. +- FHC-1 and FHC-4: conditional on source results #094 and #098. +- Synthetic rational checks: finite validation, not the #098 witness. +- Checkpoint experiments: protocol only until actual assets and + preregistered run receipts exist. + + +## 9. Constructive recurrent control: horizon observability rank (FHC-5) + +Let the latent state h belong to R^m. Define the reversible cyclic +shift F(h_0,...,h_{m-1})=(h_1,...,h_{m-1},h_0) and a scalar +readout G(h)=h_0. At horizon T, retain the observation tuple + +\[ +O_T(h)=(G(h),G(Fh),\ldots,G(F^{T-1}h)). +\] + +Its matrix has row t equal to standard basis vector e_(t mod m). +The first min(T,m) rows are independent and every later row repeats +one of the first m. Therefore + +\[ +\boxed{\mathrm{rank}(O_T)=\min(T,m).}\tag{FHC-5} +\] + +Suppose a linear d-coordinate encoder E and a linear future decoder +R exactly factor the observation map on all R^m, i.e. +O_T=R E. Then rank(O_T)<=rank(E)<=d, hence + +\[ +\boxed{d\ge\min(T,m).} +\] + +Equality is attained by retaining exactly the first min(T,m) +coordinates, and for T>=m by the full state. At fixed width m=8, +the required linear ranks at T=1,2,4,8,16 are exactly 1,2,4,8,8. + +This is an exact **finite-dimensional linear** lower bound. +It supplies an executable toy regression for an observation +metric that refines with horizon. Unlike FHC-1, the rank +saturates at the actual state width. Nonlinear encoders and +finite-sample approximate reconstruction have separate +constraints; FHC-5 states a linear factorization theorem. + + +## 10. FHC-6: Binary predictive sufficiency versus exact metric dimension + +We now instantiate the recurrent-observation problem on RC-01's +six-bit affine circuit class. This is a finite result independent of +the deep #094/#098 source claims; it tests the *distinction* those +claims encourage us to measure. + +Let x be uniform over GF(2)^6, let F be the reversible companion +transition + +\[ +F(x)_i=x_{i+1}\quad(0\le i<5),\qquad +F(x)_5=x_0\oplus x_1, +\quad G(x)=x_0. +\] + +The underlying polynomial \(z^6+z+1\) is primitive over GF(2). +Equivalently, direct exact enumeration of the dual recurrence +\(r_{t+1}=r_t A\), \(r_0=e_0\), visits all 63 nonzero six-bit row +masks before repeating. Our reference enumerates and verifies this +claim without importing a finite-field library. + +Write the length-T future trace as + +\[ +\Phi_T(x)=\bigl(G(x),G(Fx),\ldots,G(F^{T-1}x)\bigr) +\in\{0,1\}^T. +\] + +**FHC-6a (minimal predictive bits, any deterministic binary code).** +For \(1\le T\le63\), the GF(2) rank of the first T row masks +is \(r_T=\min(T,6)\). Therefore \(\Phi_T\) takes exactly +\(2^{r_T}\) distinct values. Any exact future decoder receiving only +a fixed B-bit code E(x) requires + +\[ +\boxed{B\ge r_T=\min(T,6).}\tag{FHC-6a} +\] + +A basis encoding of those row masks attains this bound and the +reference verifies its decoding on every one of the 64 states. +The cardinality argument covers nonlinear encoders too, provided +they are limited to B finite binary bits. It does not constrain a +single arbitrary-precision real coordinate. + +**FHC-6b (exact Euclidean metric dimension).** +For each nonzero mask r let \(\chi_r(x)=(-1)^{r\cdot x}\). +Under uniform x the characters obey + +\[ +\mathbb E\,\chi_r=0,\qquad +\mathbb E\,\chi_r\chi_s=\mathbf1[r=s]. +\] + +The centered real-valued future coordinates satisfy +\(\Phi_T(x)_t-\tfrac12=-\tfrac12\chi_{r_t}(x)\). +Because the row masks are distinct until period 63, + +\[ +\boxed{\mathrm{Cov}(\Phi_T(X))=\frac14 I_T.}\tag{FHC-6b} +\] + +Hence the full 64-point trace configuration has affine dimension T. +Pairwise squared Euclidean distances determine its centered Gram +matrix, so any *exact Euclidean isometry* of these 64 points into +\(\mathbb R^d\) requires + +\[ +\boxed{d\ge T,\quad 1\le T\le63.}\tag{FHC-6c} +\] + +In particular the exact predictive quotient has **six binary bits** +at T=63, while exact Euclidean isometry of its 64 future traces +requires **63 real coordinates**. These are different resources and +different fidelity contracts. + +**FHC-6d (equilateral terminal horizon).** +When T=63, every nonzero six-bit mask is present. For any x≠y, +exactly half of the 64 masks have odd dot product with x xor y, and +the zero mask is among those with even dot product. Thus exactly 32 +of the 63 future bits differ: + +\[ +\boxed{\|\Phi_{63}(x)-\Phi_{63}(y)\|_2^2=32,\quad x\ne y.} +\tag{FHC-6d} +\] + +These 64 points are the vertices of a regular simplex in its +63-dimensional affine span. The family is **not uniformly doubling** +as m increases; its finite packing obstruction is distinct from +the compact doubling witness in #098. + +At distortion D>1, approximate Euclidean embedding may take far +fewer coordinates. Standard finite-set random projection estimates +depend logarithmically on N=64 rather than linearly on T, with +constants depending on D. This is the exact-isometry versus +bounded-distortion phenomenon being measured by FHC-01B. + +## 11. FHC-7: Intervention alphabet expands the predictive quotient + +At a one-step observation horizon, if the only permitted readout is +\(G(x)=x_0\), the equivalence partition has two classes and needs +one binary bit. If the observer may apply one of six distinct cyclic +coordinate rotations before reading x0, the available readouts are + +\[ +\{x_0,x_1,\ldots,x_5\}. +\] + +Their GF(2) span has rank six. The minimal exact binary code for +all allowed one-step interventions therefore has six bits: + +\[ +\boxed{B_{\mathrm{single\ read}}=1,\qquad +B_{\mathrm{six\ reads}}=6.}\tag{FHC-7} +\] + +The pair x=0, y=2 is observationally equivalent under the original +bit-zero readout and distinguishable by the bit-one probe. +This witnesses a concrete interface-dependent quotient refinement. +The reference checks the pair and all action masks, reusing the RC-01 +GF(2) algebra. + +## 12. Empirical FHC-01B finite pilot + +The new executable benchmark fits a PCA projector from 48 +preselected calibration states and compares Gaussian random +projectors and the exact minimal binary quotient. It evaluates +every pair among 16 disjoint held-out states, across the frozen +horizons 1,2,4,6,8,16,32,63. All target future traces come from +the exact RC-01 source recurrence. + +The metric is Euclidean distance between finite future output +traces. Each embedding uses one scale chosen from calibration +pairs. Pairwise test ratios are retained, along with a concrete +worst-pair witness, calibrated failures at D=1.5 and D=2.0, +and the descriptive optimum rescaling distortion of the held-out +pairs. The optimum scale derived from held-out data is never used +for the primary calibrated gate. + +The **exact semantic quotient code** can decode all T future +bits on every state, although its Euclidean geometry need not +preserve the future-output metric. Computing the PCA or Gaussian +code from the full future traces requires T oracle operations +per state. Its projection matrix and mean vector are charged to +the resource ledger; these baselines do not establish a cheap +neural implementation from the original recurrent state. + +PCA is trained on synthetic oracle data. The pilot is neither a +trained language-model experiment nor a replication of the source +OpenAI papers. Its exact results distinguish predictive +sufficiency, exact metric isometry and approximate sampled +distortion. Additional real-checkpoint studies remain a distinct +gate. + + +## 13. FHC-8: Disjoint held-out simplex vertices are invisible to PCA + +Let \(v_1,\ldots,v_N\) be the vertices of a regular Euclidean simplex, +with the same positive distance between every distinct pair. Choose a +proper training subset \(A\subset\{1,\ldots,N\}\) of at least two +vertices, and suppose there are at least two vertices outside A. +Write + +\[ +\bar v_A=|A|^{-1}\sum_{a\in A}v_a,\qquad +U_A=\operatorname{span}\{v_a-\bar v_A:a\in A\}. +\] + +For any i,j outside A and any a inside A, the simplex identity gives + +\[ +\begin{aligned} +\langle v_i-v_j, v_a-\bar v_A\rangle +&=\langle v_i,v_a\rangle-\langle v_j,v_a\rangle\\ +&\quad-\frac1{|A|}\sum_{b\in A} +(\langle v_i,v_b\rangle-\langle v_j,v_b\rangle)=0. +\end{aligned} +\] + +Each parenthesized difference vanishes because i and j are both +distinct from every a,b in A, and all pairwise distinct-simplex +inner products are the same after translation to the global center. +Thus + +\[ +\boxed{P_{U_A}v_i=P_{U_A}v_j +\quad\text{for every }i,j\notin A.}\tag{FHC-8} +\] + +Every positive-variance PCA component fitted to the centered training +vertices belongs to U_A. Consequently *any PCA code restricted to +positive-variance training components collapses all held-out vertices +to a single point*, however many such components are retained. +If its true future metric distinguishes any two unseen vertices, +its worst-case test distortion is infinite. + +**Concrete RC-01 result.** At T=63 the 64 future traces in FHC-6 form +a regular simplex. Fit PCA to 48 calibration vertices and evaluate +the remaining 16 vertices. Its nonzero training span has dimension +47. For every d<=47, PCA projects all 16 held-out vertices to one +point up to floating-point roundoff. The frozen empirical pilot +tests d=2,4,6,8,16,32; all 120 nontrivial held-out pairs collapse +at every tested PCA width. The exact finite proof is independent +of random seed and applies to any disjoint training subset with +at least two unseen vertices. + +This is a negative control for *training-subset PCA on maximally +symmetric data*. It does not assert a general weakness of PCA on +ordinary hidden states. A random projection selected independently +of the training subset has a different inductive bias and can +preserve many unseen distances. Source result #094 allows +nonlinear embeddings and does not require them to be trained using +PCA. The comparison motivates finite-set, held-out geometry +checks before interpreting a compact representation as sufficient +for new semantic states. diff --git a/research/finite_horizon_gap_v1/bench_future_metric.py b/research/finite_horizon_gap_v1/bench_future_metric.py new file mode 100644 index 000000000..7f2f99993 --- /dev/null +++ b/research/finite_horizon_gap_v1/bench_future_metric.py @@ -0,0 +1,275 @@ +"""FHC-01B: measured finite future-metric compression of a frozen RC-01 looper. + +PCA is fitted on 48 calibration states; random projection has a fixed seed; +the exact GF(2) quotient is a certified symbolic encoder/decoder. The 16 +held-out states and all their pair distances are used only for evaluation. +All 64 source states are enumerated by the independent symbolic oracle. + +This uses NumPy. It does not train/evaluate a language model checkpoint or +verify the infinite-dimensional #098 witness. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from research.finite_horizon_gap_v1.horizon_geometry import ( + HORIZONS, WIDTH, full_certificate, observation_masks, symbolic_quotient, + trace_from_state, +) + +SCHEMA_VERSION = "fhc01b.future_metric.v1" +SEED = 940198 +SPLIT = 48 +D_THRESHOLDS = (1.5, 2.0) +WIDTHS = (2, 4, 6, 8, 16, 32) +DEFAULT_HORIZONS = HORIZONS + + +def features(horizon: int) -> np.ndarray: + masks = observation_masks(horizon) + return np.array([ + trace_from_state(x, masks) for x in range(1 << WIDTH) + ], dtype=np.float64) + + +def split_indices(seed: int = SEED) -> tuple[np.ndarray, np.ndarray]: + rng = np.random.default_rng(seed) + perm = rng.permutation(1 << WIDTH) + train, test = np.sort(perm[:SPLIT]), np.sort(perm[SPLIT:]) + if set(train) & set(test): + raise AssertionError("calibration/heldout state leak") + return train, test + + +def _positive_pairs(original: np.ndarray, encoded: np.ndarray): + if (original.ndim != 2 or encoded.ndim != 2 or + original.shape[0] != encoded.shape[0]): + raise ValueError("mismatched 2D source and code arrays") + if not (np.isfinite(original).all() and np.isfinite(encoded).all()): + raise ValueError("nonfinite code or future features") + ii, jj = np.triu_indices(len(original), k=1) + d_source = np.linalg.norm(original[ii] - original[jj], axis=1) + d_code = np.linalg.norm(encoded[ii] - encoded[jj], axis=1) + valid = d_source > 1e-12 + if np.any((~valid) & (d_code > 1e-10)): + raise AssertionError("same semantic trace maps to distinct encoder codes") + if not np.any(valid): + raise ValueError("no distinct semantic pairs") + return ii[valid], jj[valid], d_source[valid], d_code[valid] + + +def calibration_scale(source, code) -> float: + _, _, a, b = _positive_pairs(source, code) + values = b / a + nonzero = values[values > 1e-12] + if len(nonzero) == 0: + return 1.0 + return float(1 / np.median(nonzero)) + + +def distortion_metrics(source: np.ndarray, code: np.ndarray, + scale: float, state_ids: np.ndarray) -> dict: + """Heldout pair metric with a calibration-only fixed code scaling.""" + if scale <= 0 or len(state_ids) != len(source): + raise ValueError("invalid scale or ids") + ii, jj, a, b = _positive_pairs(source, code) + ratios = scale * b / a + min_ratio = float(ratios.min()) + max_ratio = float(ratios.max()) + optimized_distortion = (None if min_ratio <= 1e-12 + else float(max_ratio / min_ratio)) + residual = np.abs(np.log(np.maximum(ratios, 1e-300))) + worst = int(np.argmax(residual)) + count = {} + witnesses = {} + for D in D_THRESHOLDS: + cutoff = math.sqrt(D) + fails = np.flatnonzero((ratios < 1/cutoff - 1e-12) | + (ratios > cutoff + 1e-12)) + key = str(D) + count[key] = int(len(fails)) + if len(fails): + ix = int(fails[np.argmax(residual[fails])]) + witnesses[key] = { + "state_a": int(state_ids[int(ii[ix])]), + "state_b": int(state_ids[int(jj[ix])]), + "ratio_scaled": float(ratios[ix]), + "source_distance": float(a[ix]), + "code_distance": float(b[ix]), + } + return { + "pairs_distinct": len(ratios), + "min_ratio_scaled": min_ratio, + "max_ratio_scaled": max_ratio, + "optimal_rescaling_distortion_heldout": optimized_distortion, + "max_log_distortion_magnitude": float(residual[worst]), + "worst_pair": [int(state_ids[int(ii[worst])]), + int(state_ids[int(jj[worst])])], + "violation_counts_calibration_scale": count, + "violation_witnesses": witnesses, + } + + +def exact_binary_code(horizon: int) -> np.ndarray: + quotient = symbolic_quotient(horizon) + basis = quotient["basis_masks"] + return np.array([ + [(mask & state).bit_count() % 2 for mask in basis] + for state in range(1 << WIDTH) + ], dtype=np.float64) + + +def _fit_pca(source_train: np.ndarray, d: int): + center = source_train.mean(axis=0, keepdims=True) + _, _, vt = np.linalg.svd(source_train - center, full_matrices=False) + return center, vt[:d].T + + +def _random_embedding(T: int, d: int, seed: int): + rng = np.random.default_rng(seed) + return rng.standard_normal((T, d)) / math.sqrt(d) + + +def run_one(horizon: int, train: np.ndarray, test: np.ndarray, + widths: tuple[int, ...] = WIDTHS) -> dict: + x = features(horizon) + exact = symbolic_quotient(horizon) + rows = [] + methods = [("exact_binary_quotient", exact_binary_code(horizon), { + "binary_live_bits": exact["rank_gf2"], + "basis_description_bits_upper": WIDTH * exact["rank_gf2"], + "decoder_description_bits_upper": horizon * exact["rank_gf2"], + "exact_future_bit_reconstruction_all_64_states": True, + "trained": False, + })] + methods.append(("full_trace_identity", x.copy(), { + "binary_live_bits": horizon, + "basis_description_bits_upper": 0, + "decoder_description_bits_upper": 0, + "exact_future_bit_reconstruction_all_64_states": True, + "trained": False, + })) + center_all = x[train].mean(axis=0, keepdims=True) + for d in widths: + if d > horizon: + continue + if d <= min(len(train), horizon): + center, matrix = _fit_pca(x[train], d) + methods.append((f"pca_{d}", (x-center) @ matrix, { + "coordinates": d, "trained": True, + "fit_states": len(train), "oracle_future_steps_per_state": horizon, + "matrix_parameters": horizon*d, + "mean_parameters": horizon, + })) + mat = _random_embedding(horizon, d, seed=SEED + 100* horizon + d) + methods.append((f"gaussian_{d}", (x-center_all) @ mat, { + "coordinates": d, "trained": False, + "matrix_parameters": horizon*d, + "oracle_future_steps_per_state": horizon, + })) + for name, code, ledger in methods: + scale = calibration_scale(x[train], code[train]) + metric = distortion_metrics(x[test], code[test], scale, test) + rows.append({"method": name, "encoded_dimension": int(code.shape[1]), + "calibration_scale": scale, "resource_ledger": ledger, + "heldout": metric}) + return { + "horizon": horizon, + "source_dimension": horizon, + "exact_binary_memory_minimum": exact["rank_gf2"], + "exact_real_isometric_dimension_minimum": horizon, + "train_size": len(train), + "heldout_size": len(test), + "methods": rows, + } + + +def run(seed: int = SEED, horizons: tuple[int, ...] = DEFAULT_HORIZONS, + widths: tuple[int, ...] = WIDTHS) -> dict: + if not horizons or any(T < 1 or T > 63 for T in horizons): + raise ValueError("horizon must be in 1..63") + if not widths or any(d < 1 for d in widths): + raise ValueError("widths must be positive") + train, test = split_indices(seed) + records = [run_one(T, train, test, widths) for T in horizons] + source_digest = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() + exact_digest = hashlib.sha256( + (Path(__file__).parent / "horizon_geometry.py").read_bytes() + ).hexdigest() + return { + "schema_version": SCHEMA_VERSION, + "status": "FROZEN_SYNTHETIC_RECURRENT_PILOT", + "model": "RC-01 GF2 primitive linear feedback shift register, width 6", + "source_python_sha256": source_digest, + "exact_reference_sha256": exact_digest, + "numpy_version": np.__version__, + "seed": seed, + "calibration_state_ids": list(map(int, train)), + "heldout_state_ids": list(map(int, test)), + "horizons": list(horizons), + "widths": list(widths), + "scale_fit": "median positive calibration code/source pair ratio", + "metric": "Euclidean distance of finite future output bit traces", + "random_projector": "Gaussian standard_normal/sqrt(d), seed=940198+100*T+d", + "finite_exact_certificate": full_certificate(), + "records": records, + "checkpoint_evaluated": False, + "proof_of_infinite_doubling_obstruction": False, + } + + +def main(argv=None) -> int: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--seed", type=int, default=SEED) + p.add_argument("--horizons", type=int, nargs="+", default=list(DEFAULT_HORIZONS)) + p.add_argument("--widths", type=int, nargs="+", default=list(WIDTHS)) + p.add_argument("--out", type=Path) + args = p.parse_args(argv) + result = run(args.seed, tuple(args.horizons), tuple(args.widths)) + if args.out: + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(result, indent=2, sort_keys=True, + allow_nan=False) + "\n") + brief = [] + for row in result["records"]: + chosen = {} + for method in row["methods"]: + name = method["method"] + if (name in {"exact_binary_quotient", "full_trace_identity"} or + name in {"pca_6", "pca_8", "pca_16", "pca_32", + "gaussian_6", "gaussian_8", "gaussian_16", + "gaussian_32"}): + metric = method["heldout"] + chosen[name] = { + "d": method["encoded_dimension"], + "heldout_optimal_D": metric["optimal_rescaling_distortion_heldout"], + "fixed_scale_D2_violating_pairs": + metric["violation_counts_calibration_scale"]["2.0"], + "distinct_heldout_pairs": metric["pairs_distinct"], + "witness_D2": metric["violation_witnesses"].get("2.0"), + } + brief.append({ + "T": row["horizon"], + "minimum_binary_bits": row["exact_binary_memory_minimum"], + "minimum_real_isometry_dimension": + row["exact_real_isometric_dimension_minimum"], + "methods": chosen, + }) + print(json.dumps({"status": result["status"], "sha256": result["source_python_sha256"], + "cases": brief}, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/research/finite_horizon_gap_v1/bench_rrc25_future.py b/research/finite_horizon_gap_v1/bench_rrc25_future.py new file mode 100644 index 000000000..774833b88 --- /dev/null +++ b/research/finite_horizon_gap_v1/bench_rrc25_future.py @@ -0,0 +1,285 @@ +"""FHC-01C: trained source-locked RRC-25 GRU future-logit geometry pilot. + +Uses the committed recurrent GRU checkpoint in rrc_compactification/results, +verifies its original source/train hashes, independently recomputes the +nine-step GRU state, and then applies a *common zero-input continuation* +to expose a measured future-observation metric. + +PCA uses only dev cases. Tests are separate original source-generator +families. This is a retrospective neural-state analysis, NOT a measure +of native proof-ranking accuracy at repeated zero inputs. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from research.rrc_compactification import bench25 as receipt_gate +from research.rrc_compactification import compound25 as source +from research.rrc_compactification import model25 as network +from research.finite_horizon_gap_v1.bench_future_metric import ( + calibration_scale, distortion_metrics, +) + +SCHEMA = "fhc01c.rrc25_trained_future_logits.v1" +SEED = 940199 +HORIZONS = (1, 2, 4, 8, 16) +WIDTHS = (2, 4, 8, 12, 16) +TRAIN_PER, DEV_PER, TEST_PER = 1, 12, 8 + + +def source_header(case): + """Use only public observations; select first positive public header.""" + candidates = source.possible_headers(case) + if not candidates: + raise RuntimeError("source case has no publicly inferred header") + return candidates[0], len(candidates) + + +def gru_step(h: list[float], row: list[float], checkpoint: dict) -> list[float]: + s = checkpoint["state_dict"] + a = network.affine(s["rnn.weight_ih_l0"], s["rnn.bias_ih_l0"], row) + v = network.affine(s["rnn.weight_hh_l0"], s["rnn.bias_hh_l0"], h) + result = [] + for i in range(network.HIDDEN): + reset = network.sigmoid(a[i] + v[i]) + update = network.sigmoid(a[i + network.HIDDEN] + v[i + network.HIDDEN]) + new = math.tanh(a[i + 2*network.HIDDEN] + reset*v[i + 2*network.HIDDEN]) + result.append((1 - update)*new + update*h[i]) + return result + + +def logits(h: list[float], checkpoint: dict) -> list[float]: + s=checkpoint["state_dict"] + return network.affine(s["head.weight"], s["head.bias"], h) + + +def native_case(case, checkpoint: dict, max_horizon: int): + header, head_count = source_header(case) + inputs = source.features(case, header) + if len(inputs) != 9 or any(len(row) != 8 for row in inputs): + raise RuntimeError("original RRC25 public features changed shape") + h = [0.] * network.HIDDEN + for row in inputs: + h = gru_step(h, row, checkpoint) + direct = network.logits(case, header, checkpoint) + recovered = logits(h, checkpoint) + parity = max(abs(a-b) for a,b in zip(direct, recovered)) + if parity > 1e-11: + raise AssertionError("trained RRC25 native readout parity failed") + hidden = h[:] + future = [] + zero = [0.] * 8 + for _ in range(max_horizon): + h = gru_step(h, zero, checkpoint) + future.extend(logits(h, checkpoint)) + if not all(math.isfinite(v) for v in hidden + future): + raise RuntimeError("nonfinite trained recurrent state or logits") + return hidden, future, parity, head_count + + +def _stack_cases(cases: list, checkpoint: dict, max_horizon: int): + hidden, future = [], [] + parity_max = 0.0 + multicandidate = 0 + for case in cases: + h, f, parity, n = native_case(case, checkpoint, max_horizon) + hidden.append(h) + future.append(f) + parity_max = max(parity_max, parity) + multicandidate += int(n != 1) + return (np.asarray(hidden, dtype=np.float64), + np.asarray(future, dtype=np.float64), + parity_max, multicandidate) + + +def _fit_methods(train, test, hidden_train, hidden_test, T: int, d_list, + seed: int) -> list[tuple]: + dims=16*T + methods=[ + ("native_hidden_12", hidden_train, hidden_test, { + "coordinates": network.HIDDEN, + "stored_state_bits_fp32": network.HIDDEN*32, + "native_recurrent_decoder": True, + "trained": "frozen RRC25 original training", + "oracle_future_queries_to_form_code": 0, + }), + ("full_trace_identity", train.copy(), test.copy(), { + "coordinates":dims, + "oracle_future_queries_to_form_code":T, + "projection_parameters":0, + "trained":False, + }), + ] + center = np.mean(train,axis=0,keepdims=True) + _,_,vt=np.linalg.svd(train-center, full_matrices=False) + for d in d_list: + if d > dims: + continue + if d <= len(vt): + matrix=vt[:d].T + methods.append((f"pca_{d}",(train-center)@matrix, + (test-center)@matrix,{ + "coordinates":d,"trained":"PCA on dev cases only", + "fit_cases":len(train), + "projection_parameters":dims*d, + "mean_parameters":dims, + "oracle_future_queries_to_form_code":T, + })) + rng=np.random.default_rng(seed+1000+T*101+d) + matrix=rng.standard_normal((dims,d))/math.sqrt(d) + methods.append((f"gaussian_{d}",(train-center)@matrix, + (test-center)@matrix,{ + "coordinates":d,"trained":False, + "projection_parameters":dims*d, + "oracle_future_queries_to_form_code":T, + })) + return methods + + +def run(seed: int = SEED, horizons=HORIZONS, widths=WIDTHS) -> dict: + if (not horizons or not widths or any(t < 1 or t > 16 for t in horizons) + or any(d < 1 or d > 128 for d in widths)): + raise ValueError("invalid frozen horizon or projection widths") + trained,digests=receipt_gate.checkpoints() + checkpoint=trained["recurrent"] + if checkpoint["parameters"] != 1000: + raise AssertionError("source recurrent checkpoint parameter count changed") + roster=source.roster(include_test=True,train_per=TRAIN_PER, + dev_per=DEV_PER,test_per=TEST_PER) + calibration=roster["dev"] + heldout=[x for fam in source.TEST_FAMILIES for x in roster[fam]] + if len(calibration)!=3*DEV_PER or len(heldout)!=6*TEST_PER: + raise RuntimeError("RRC25 source roster lengths changed") + if set(x.identifier for x in calibration)&set(x.identifier for x in heldout): + raise AssertionError("RRC25 source identities leaked across splits") + + max_horizon=max(horizons) + htr, ftr, ptrain, ctrain=_stack_cases(calibration,checkpoint,max_horizon) + hte, fte, ptest, ctest=_stack_cases(heldout,checkpoint,max_horizon) + cases=[] + family_order=[x.family for x in heldout] + for T in horizons: + dim=16*T + train=ftr[:,:dim] + test=fte[:,:dim] + methods=_fit_methods(train,test,htr,hte,T,widths,seed) + scored=[] + for name,code_train,code_test,ledger in methods: + scale=calibration_scale(train,code_train) + ids=np.arange(len(heldout),dtype=np.int64) + score=distortion_metrics(test,code_test,scale,ids) + mapped={} + if "worst_pair" in score: + mapped["worst_pair_case_ids"]=[ + heldout[index].identifier for index in score["worst_pair"]] + for k,witness in score["violation_witnesses"].items(): + witness["case_a_id"]=heldout[witness["state_a"]].identifier + witness["case_b_id"]=heldout[witness["state_b"]].identifier + by_family={} + for fam in source.TEST_FAMILIES: + mask=np.array([i for i,f in enumerate(family_order) if f==fam], + dtype=np.int64) + try: + sub=distortion_metrics(test[mask],code_test[mask], + scale,mask) + by_family[fam]={ + "pairs":sub["pairs_distinct"], + "D2_calibrated_violations": + sub["violation_counts_calibration_scale"]["2.0"], + "test_optimal_D": + sub["optimal_rescaling_distortion_heldout"]} + except ValueError: + by_family[fam]={"reason":"no_distinct_future_pairs"} + scored.append({ + "method":name, + "dimension":int(code_train.shape[1]), + "calibration_scale":scale, + "ledger":ledger, + "heldout":score, + "by_family":by_family, + **mapped, + }) + cases.append({"horizon":T,"future_feature_dimension":dim, + "methods":scored}) + path=Path(__file__) + return { + "schema":SCHEMA, + "status":"FROZEN_TRAINED_RRC25_DEVELOPMENT", + "neural_model":"RRC25 portable trained 1000-parameter GRU", + "checkpoint_sha256":digests["recurrent"], + "checkpoint_source_hashes":checkpoint["source_sha256"], + "experiment_source_sha256":hashlib.sha256(path.read_bytes()).hexdigest(), + "source_reuse":"bench25.checkpoints original SHA-256 source gate", + "calibration_roster_sha256":source.fingerprint(calibration), + "heldout_roster_sha256":source.fingerprint(heldout), + "train_per":TRAIN_PER, + "dev_per":DEV_PER, + "test_per":TEST_PER, + "seed":seed, + "hidden_width":network.HIDDEN, + "network_parameters":checkpoint["parameters"], + "native_head_parity_max_abs_error":max(ptrain,ptest), + "public_header_multiple_candidates":{ + "calibration":ctrain,"heldout":ctest}, + "calibration_case_ids":[x.identifier for x in calibration], + "heldout_cases":[{"id":x.identifier,"family":x.family} + for x in heldout], + "continuation":"frozen GRU with 8-vector zeros after nine native feature rows", + "continuation_is_native_task_training_distribution":False, + "horizons":list(horizons), + "widths":list(widths), + "cases":cases, + "full_space_geometry_certificate":False, + "source_family_098_infinite_witness_tested":False, + } + + +def main(argv=None)->int: + p=argparse.ArgumentParser(description=__doc__) + p.add_argument("--out",type=Path) + p.add_argument("--seed",type=int,default=SEED) + p.add_argument("--horizons",type=int,nargs="+",default=list(HORIZONS)) + p.add_argument("--widths",type=int,nargs="+",default=list(WIDTHS)) + a=p.parse_args(argv) + report=run(seed=a.seed,horizons=tuple(a.horizons),widths=tuple(a.widths)) + if a.out: + a.out.parent.mkdir(parents=True,exist_ok=True) + a.out.write_text(json.dumps(report,indent=2,sort_keys=True, + allow_nan=False)+"\n") + compact=[] + for row in report["cases"]: + out={"T":row["horizon"],"methods":{}} + for method in row["methods"]: + if method["method"] in ( + "native_hidden_12","full_trace_identity", + "pca_4","pca_8","pca_12","gaussian_4","gaussian_8", + "gaussian_12" + ): + out["methods"][method["method"]]={ + "heldout_D":method["heldout"]["optimal_rescaling_distortion_heldout"], + "calibrated_D2_fails": + method["heldout"]["violation_counts_calibration_scale"]["2.0"], + "pair":method.get("worst_pair_case_ids"), + } + compact.append(out) + print(json.dumps({"status":report["status"], + "checkpoint_sha256":report["checkpoint_sha256"], + "max_native_logit_parity_error": + report["native_head_parity_max_abs_error"], + "cases":compact},indent=2,allow_nan=False)) + return 0 + + +if __name__=="__main__": + raise SystemExit(main()) diff --git a/research/finite_horizon_gap_v1/horizon_geometry.py b/research/finite_horizon_gap_v1/horizon_geometry.py new file mode 100644 index 000000000..c539a0cec --- /dev/null +++ b/research/finite_horizon_gap_v1/horizon_geometry.py @@ -0,0 +1,171 @@ +"""FHC-01B: exact future-observation rank for an existing RC-01 affine looper. + +Uses the RC-01 GF(2) reference directly. A primitive degree-six +linear feedback shift register has 63 distinct nonzero output masks. +The 64 full states are a *finite*, uniformly sampled certificate. + +No claim about infinite doubling witnesses or learned neural models. +""" +from __future__ import annotations + +import hashlib +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from research.recurrent_circuits_v1.reference import ( + Affine, coordinates, row_basis, row_times_matrix, +) + +WIDTH = 6 +PERIOD = (1 << WIDTH) - 1 +HORIZONS = (1, 2, 4, 6, 8, 16, 32, 63) + + +def primitive_shift6() -> Affine: + """Companion recurrence h_i'=h_{i+1}, h_5'=h_0 xor h_1.""" + return Affine(tuple(1 << (i+1) for i in range(WIDTH-1)) + (3,)) + + +def observation_masks(horizon: int) -> tuple[int, ...]: + if type(horizon) is not int or not 0 <= horizon <= PERIOD: + raise ValueError("require horizon in 0..63") + step = primitive_shift6() + mask = 1 + masks = [] + for _ in range(horizon): + masks.append(mask) + mask = row_times_matrix(mask, step) + return tuple(masks) + + +def trace_from_state(state: int, masks: tuple[int, ...]) -> tuple[int, ...]: + if type(state) is not int or not 0 <= state < (1 << WIDTH): + raise ValueError("state outside 6-bit register") + return tuple((mask & state).bit_count() & 1 for mask in masks) + + +def symbolic_quotient(horizon: int) -> dict: + """Minimal number of BINARY code bits for exact horizon prediction.""" + masks = observation_masks(horizon) + basis = row_basis(masks, WIDTH) + decoder_masks = tuple(coordinates(mask, basis, WIDTH) for mask in masks) + codes = { + state: tuple((b & state).bit_count() & 1 for b in basis) + for state in range(1 << WIDTH) + } + for state in range(1 << WIDTH): + packed = sum(bit << i for i, bit in enumerate(codes[state])) + reconstructed = tuple((packed & decoder).bit_count() & 1 + for decoder in decoder_masks) + assert reconstructed == trace_from_state(state, masks), ( + "RC-01 quotient failed exact future reconstruction" + ) + return { + "horizon": horizon, + "rank_gf2": len(basis), + "distinct_traces": len(set(trace_from_state(x, masks) + for x in range(1 << WIDTH))), + "basis_masks": list(basis), + "output_masks": list(masks), + "decoder_masks": list(decoder_masks), + } + + +def walsh_orthogonality(horizon: int) -> dict: + """Exact real covariance of full 64-state future traces, no numpy.""" + masks = observation_masks(horizon) + states = list(range(1 << WIDTH)) + sums = [ + sum((-1 if (x & mask).bit_count() & 1 else 1) + for x in states) + for mask in masks + ] + if any(value != 0 for value in sums): + raise AssertionError("nonzero observable is unexpectedly unbalanced") + gram_diag = True + for i, a in enumerate(masks): + for j, b in enumerate(masks): + correlation = sum( + (1 if (x & (a ^ b)).bit_count() % 2 == 0 else -1) + for x in states + ) + if correlation != (64 if i == j else 0): + gram_diag = False + if not gram_diag: + raise AssertionError("Walsh characters fail exact orthogonality") + return { + "horizon": horizon, + "distinct_masks": len(set(masks)), + "all_nonzero_masks": all(masks), + "real_centered_feature_rank": horizon, + "centered_covariance_diagonal": "1/4", + "centered_covariance_off_diagonal": "0", + } + + +def action_refinement(horizon: int = 1) -> dict: + """One-shot interface: observer may rotate before reading bit0. + + Rotation by k produces the mask e_k. Adding action access to all + six rotations makes the single-step predictive quotient 6 bits. + """ + if horizon != 1: + raise ValueError("this interface fixture has exactly one readout") + plain = row_basis((1,), WIDTH) + allowed = tuple(1 << i for i in range(WIDTH)) + enlarged = row_basis(allowed, WIDTH) + return { + "horizon": horizon, + "plain_observation_bits": len(plain), + "all_rotations_observation_bits": len(enlarged), + "action_masks": list(allowed), + "counterexample_pair": [0, 2], + "plain_pair_equal": trace_from_state(0, (1,)) == + trace_from_state(2, (1,)), + "post_rotation_pair_differs": trace_from_state(0, (2,)) != + trace_from_state(2, (2,)), + } + + +def full_certificate() -> dict: + step = primitive_shift6() + masks = observation_masks(PERIOD) + if not (len(set(masks)) == PERIOD and + set(masks) == set(range(1, 1 << WIDTH)) and + row_times_matrix(masks[-1], step) == 1): + raise AssertionError("expected maximal LFSR period 63") + records = [] + for T in HORIZONS: + quotient = symbolic_quotient(T) + real = walsh_orthogonality(T) + assert quotient["rank_gf2"] == min(T, WIDTH) + assert quotient["distinct_traces"] == 1 << quotient["rank_gf2"] + records.append({ + "horizon": T, + "minimum_binary_semantic_memory_bits": + quotient["rank_gf2"], + "minimum_exact_euclidean_isometry_dimension": + real["real_centered_feature_rank"], + "distinct_semantic_traces": quotient["distinct_traces"], + }) + return { + "status": "EXACT_FINITE_CONTROL", + "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "rc01_dependency": "research.recurrent_circuits_v1.reference", + "state_width": WIDTH, + "full_state_count": 1 << WIDTH, + "lfsr_period": PERIOD, + "results": records, + "action_refinement": action_refinement(), + "source_family_098_witness_constructed": False, + "trained_checkpoint_evaluated": False, + } + + +if __name__ == "__main__": + print(json.dumps(full_certificate(), indent=2)) diff --git a/research/finite_horizon_gap_v1/reference.py b/research/finite_horizon_gap_v1/reference.py new file mode 100644 index 000000000..928b0452b --- /dev/null +++ b/research/finite_horizon_gap_v1/reference.py @@ -0,0 +1,275 @@ +"""FHC-01 exact finite controls for horizon-dependent compactification. + +Only the Python standard library is required. These are exact-rational +checks of Gaussian 4th moments, covering, distortion-transfer, and finite +packing. They DO NOT construct the compact doubling witness of OpenAI #098. +""" +from __future__ import annotations + +import argparse +import hashlib +import itertools +import json +from fractions import Fraction +from pathlib import Path + + +def rational(value: int | str | Fraction) -> Fraction: + return Fraction(value) + + +def fourth_gaussian_moment(weights) -> Fraction: + """Wick expansion of E[(sum_i a_i Z_i)^4] for iid N(0,1) variables.""" + a = tuple(map(rational, weights)) + total = Fraction() + for i, j, k, l in itertools.product(range(len(a)), repeat=4): + pairings = int(i == j and k == l) + int(i == k and j == l) + int(i == l and j == k) + total += a[i] * a[j] * a[k] * a[l] * pairings + return total + + +def gaussian_isometry_moment_identity(weights) -> bool: + a = tuple(map(rational, weights)) + square_norm = sum((v * v for v in a), Fraction()) + return fourth_gaussian_moment(a) == 3 * square_norm * square_norm + + +def packing_upper_cardinality(d: int, distortion) -> Fraction: + """Volume packing bound N <= (1+2D)^d for any d-dimensional norm.""" + D = rational(distortion) + if d < 1 or D < 1: + raise ValueError("need integer target dimension >=1 and distortion >=1") + return (1 + 2 * D) ** d + + +def first_forbidden_equilateral_size(d: int, distortion) -> int: + """Smallest N strictly above the universal volume packing limit.""" + value = packing_upper_cardinality(d, distortion) + return value.numerator // value.denominator + 1 + + +def equilateral_packing_obstruction(n: int, d: int, distortion) -> bool: + """A True result rigorously rules out D-embedding of N equilateral points.""" + if n < 2: + raise ValueError("need >=2 equilateral points") + return rational(n) > packing_upper_cardinality(d, distortion) + + +def exact_line_equilateral_distortion(n: int) -> int: + """Optimal 1D distortion of N equilateral points: D=N-1.""" + if n < 2: + raise ValueError("need >=2 distinct points") + return n - 1 + + +def net_transfer_distortion(delta, epsilon, distortion) -> Fraction: + """D*(delta+2eps)/(delta-2eps) for approximating a finite witness.""" + delta, epsilon, D = map(rational, (delta, epsilon, distortion)) + if delta <= 0 or epsilon < 0 or 2 * epsilon >= delta or D < 1: + raise ValueError("require delta>2epsilon>=0 and D>=1") + return D * (delta + 2 * epsilon) / (delta - 2 * epsilon) + + +def robust_net_threshold(delta, distortion, forbidden_distortion) -> Fraction: + """If A forbids Dprime, every eps-net with eps <= returned bound forbids D.""" + delta, D, Dprime = map(rational, (delta, distortion, forbidden_distortion)) + if delta <= 0 or D < 1 or Dprime <= D: + raise ValueError("require delta>0 and 1<=D dict: + """Finite epsilon-net count bound using intrinsic doubling of compact K. + + Start with open ball radius 2*diameter, halve until radius <= eps/2. + A strict epsilon-cover then follows from its centers in K. + """ + R, eps = map(rational, (diameter, epsilon)) + if lam < 1 or R <= 0 or eps <= 0: + raise ValueError("require Lambda>=1 and R,epsilon>0") + r = 2 * R + steps = 0 + while r > eps / 2: + r /= 2 + steps += 1 + return {"steps": steps, "net_count_upper": lam ** steps, + "final_radius": r} + + +def squared_l2_distance(a, b) -> Fraction: + if len(a) != len(b): + raise ValueError("vectors must have matching dimension") + return sum(((rational(x)-rational(y))**2 for x,y in zip(a,b)), Fraction()) + + +def fourth_l4_distance(a, b) -> Fraction: + if len(a) != len(b): + raise ValueError("vectors must have matching dimension") + return sum(((rational(x)-rational(y))**4 for x,y in zip(a,b)), Fraction()) + + +def exact_l2_to_l4_certificate(source, encoded, scale, distortion) -> dict: + """Check every pair after raising positive norm bounds to 4th powers. + + Normalized claim: scale*||x-y||_2 <= ||code(x)-code(y)||_4 + <= scale*D*||x-y||_2 . + """ + source, encoded = list(source), list(encoded) + s, D = map(rational, (scale, distortion)) + if len(source) < 2 or len(source) != len(encoded) or s <= 0 or D < 1: + raise ValueError("need matched finite samples, positive scale, D>=1") + if len(set(map(tuple, source))) != len(source): + raise ValueError("source states must be distinct") + pairs = [] + for i in range(len(source)): + for j in range(i+1,len(source)): + a = squared_l2_distance(source[i],source[j]) + b = fourth_l4_distance(encoded[i],encoded[j]) + lower = s**4 * a**2 + upper = (s*D)**4 * a**2 + pairs.append({"pair":[i,j], "passed":lower<=b<=upper, + "source_distance_squared":str(a), + "target_distance_fourth":str(b), + "lower_fourth":str(lower), + "upper_fourth":str(upper)}) + return {"passed":all(p["passed"] for p in pairs), + "pairs_checked":len(pairs), + "failed_pairs":[p for p in pairs if not p["passed"]]} + + +def nearest_net_point(x, net): + """Choose closest point in a finite rational line net; ties by index.""" + return min(net, key=lambda q:abs(rational(x)-rational(q))) + + +def coarse_embedding_1d_certificate(states, net, images: dict, epsilon, + distortion) -> dict: + """Exact FHC-3 additive-bound check on a finite line-metric example.""" + states = tuple(map(rational,states)) + net = tuple(map(rational,net)) + eps,D = map(rational,(epsilon,distortion)) + if not states or not net or eps<0 or D<1: + raise ValueError("nonempty states/net, eps>=0, D>=1") + if set(net)-set(images): + raise ValueError("missing encoded net coordinates") + if any(min(abs(x-q) for q in net)>eps for x in states): + raise ValueError("net does not epsilon-cover supplied states") + for q in net: + for r in net: + target=abs(rational(images[q])-rational(images[r])) + if not abs(q-r)<=target<=D*abs(q-r): + raise ValueError("net map is not a normalized D-embedding") + rows=[] + for x,y in itertools.combinations(states,2): + qx,qy=nearest_net_point(x,net),nearest_net_point(y,net) + original=abs(x-y) + observed=abs(rational(images[qx])-rational(images[qy])) + lo=max(Fraction(),original-2*eps) + hi=D*(original+2*eps) + rows.append((lo<=observed<=hi, x, y)) + return {"passed":all(row[0] for row in rows), + "pairs_checked":len(rows), + "violations":[[str(x),str(y)] for ok,x,y in rows if not ok]} + + + +def shift_observation_matrix(width: int, horizon: int) -> list[list[Fraction]]: + """O_T rows e_(t mod width), t=0,...,T-1, for a cyclic shift.""" + if width < 1 or horizon < 0: + raise ValueError("width>=1 and horizon>=0 required") + return [[Fraction(int(j == t % width)) for j in range(width)] + for t in range(horizon)] + + +def exact_rational_rank(rows) -> int: + """Fractional row elimination, proving rank for a finite supplied matrix.""" + a = [[rational(v) for v in row] for row in rows] + if not a: + return 0 + n = len(a[0]) + if any(len(row) != n for row in a): + raise ValueError("ragged matrix") + pivot_row = 0 + for col in range(n): + next_pivot = next((i for i in range(pivot_row,len(a)) + if a[i][col] != 0),None) + if next_pivot is None: + continue + a[pivot_row],a[next_pivot]=a[next_pivot],a[pivot_row] + pivot=a[pivot_row][col] + a[pivot_row]=[v/pivot for v in a[pivot_row]] + for k in range(len(a)): + if k!=pivot_row and a[k][col]!=0: + factor=a[k][col] + a[k]=[u-factor*v for u,v in zip(a[k],a[pivot_row])] + pivot_row+=1 + if pivot_row==len(a): + break + return pivot_row + + +def finite_shift_rank_frontier(width: int, horizons) -> list[dict]: + """Linear encoder dimension min(T,width) to preserve all future readouts.""" + out=[] + for T in horizons: + rank=exact_rational_rank(shift_observation_matrix(width,T)) + if rank!=min(width,T): + raise AssertionError("shift-register observability rank mismatch") + out.append({"horizon":T, "required_linear_dimension":rank}) + return out + + +def control_report() -> dict: + """Reference cases fixed before using neural data.""" + weights=[Fraction(1,2),Fraction(-2,3),Fraction(5,4)] + assert gaussian_isometry_moment_identity(weights) + assert first_forbidden_equilateral_size(2,Fraction(6,5))==12 + assert equilateral_packing_obstruction(12,2,Fraction(6,5)) + assert not equilateral_packing_obstruction(11,2,Fraction(6,5)) + assert exact_line_equilateral_distortion(4)==3 + assert robust_net_threshold(1,1,2)==Fraction(1,6) + assert net_transfer_distortion(1,Fraction(1,6),1)==2 + assert doubling_cover_bound(4,1,Fraction(1,8))["net_count_upper"]==1024 + cert=exact_l2_to_l4_certificate([[0,0],[1,0],[0,1]], + [[0,0],[1,0],[0,1]], + Fraction(1,2), 2) + assert cert["passed"] + net=coarse_embedding_1d_certificate( + list(range(5)), [0,2,4], + {Fraction(0):0,Fraction(2):2,Fraction(4):4},1,1) + assert net["passed"] + frontier=finite_shift_rank_frontier(8,[1,2,4,8,16]) + assert [r["required_linear_dimension"] for r in frontier]==[1,2,4,8,8] + return { + "status":"CONTROL_ONLY", + "source_sha256":hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "gaussian_fourth_moment":str(fourth_gaussian_moment(weights)), + "gaussian_expected_fourth_moment": + str(3*sum(w*w for w in weights)**2), + "equilateral_N_first_forbidden_d2_D6over5":12, + "equilateral_one_dim_min_D_at_N4":3, + "robust_epsilon_at_delta1_D1_Dprime2":"1/6", + "doubling_example_net_cardinality_upper":1024, + "exact_geometry_pairs_checked":cert["pairs_checked"], + "finite_net_pairs_checked":net["pairs_checked"], + "shift_register_linear_frontier_width8":frontier, + "constructs_compact_doubling_witness":False, + "runs_trained_models":False, + } + + +def main(argv=None)->int: + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check",action="store_true") + parser.add_argument("--out",type=Path) + args=parser.parse_args(argv) + out=control_report() + if args.out: + args.out.parent.mkdir(parents=True,exist_ok=True) + args.out.write_text(json.dumps(out,indent=2,sort_keys=True)+"\n") + print(json.dumps(out,indent=2,sort_keys=True)) + return 0 + + +if __name__=="__main__": + raise SystemExit(main()) diff --git a/research/finite_horizon_gap_v1/test_horizon_geometry.py b/research/finite_horizon_gap_v1/test_horizon_geometry.py new file mode 100644 index 000000000..9ce0f64af --- /dev/null +++ b/research/finite_horizon_gap_v1/test_horizon_geometry.py @@ -0,0 +1,184 @@ +"""FHC-01B exact + empirical regression tests.""" +from __future__ import annotations + +import math +import unittest + +import numpy as np + +from horizon_geometry import ( + HORIZONS, PERIOD, WIDTH, action_refinement, full_certificate, + observation_masks, primitive_shift6, symbolic_quotient, + trace_from_state, walsh_orthogonality, +) +from bench_future_metric import ( + SEED, calibration_scale, distortion_metrics, exact_binary_code, + features, run, run_one, split_indices, +) +from research.recurrent_circuits_v1.reference import row_times_matrix + + +class ExactFutureGeometry(unittest.TestCase): + def test_primitive_period_exhausts_every_nonzero_mask(self): + masks = observation_masks(63) + self.assertEqual(len(masks), 63) + self.assertEqual(set(masks), set(range(1, 64))) + self.assertEqual(row_times_matrix(masks[-1], primitive_shift6()), 1) + + def test_exact_minimum_binary_bits_and_trace_counts(self): + for t in HORIZONS: + q = symbolic_quotient(t) + self.assertEqual(q["rank_gf2"], min(WIDTH, t)) + self.assertEqual(q["distinct_traces"], 2 ** min(WIDTH, t)) + + def test_independent_walsh_features_have_exact_real_rank(self): + for t in HORIZONS: + witness = walsh_orthogonality(t) + self.assertEqual(witness["real_centered_feature_rank"], t) + self.assertEqual(witness["distinct_masks"], t) + self.assertEqual(witness["centered_covariance_diagonal"], "1/4") + + def test_exact_regular_simplex_at_63(self): + x = features(63) + self.assertEqual(x.shape, (64, 63)) + for i in range(64): + for j in range(i+1, 64): + self.assertEqual(float(np.sum((x[i]-x[j])**2)), 32.0) + matrix = np.cov(x, rowvar=False, bias=True) + self.assertTrue(np.allclose(matrix, np.eye(63) / 4, atol=1e-12)) + + def test_intervention_interface_exposes_all_coordinates(self): + receipt = action_refinement() + self.assertEqual(receipt["plain_observation_bits"], 1) + self.assertEqual(receipt["all_rotations_observation_bits"], 6) + self.assertTrue(receipt["plain_pair_equal"]) + self.assertTrue(receipt["post_rotation_pair_differs"]) + + def test_binary_code_and_every_future_trace_decodable(self): + for t in (1, 4, 6, 16, 63): + c = exact_binary_code(t) + self.assertEqual(c.shape, (64, min(t, 6))) + self.assertEqual(len(set(map(tuple, c))), 2**min(t, 6)) + masks = symbolic_quotient(t)["decoder_masks"] + for x in range(64): + state = sum(int(bit) << i for i, bit in enumerate(c[x])) + prediction = tuple((state & row).bit_count()%2 for row in masks) + self.assertEqual(prediction, + trace_from_state(x, observation_masks(t))) + + def test_rejects_invalid_horizons(self): + for T in (-1, 64, 1.5, True): + with self.assertRaises(ValueError): + observation_masks(T) + + def test_receipt_provenance(self): + record = full_certificate() + self.assertEqual(record["rc01_dependency"], + "research.recurrent_circuits_v1.reference") + self.assertEqual(record["full_state_count"], 64) + self.assertFalse(record["source_family_098_witness_constructed"]) + + +class MeasuredFiniteMetric(unittest.TestCase): + def test_holdout_state_split_is_deterministic_and_disjoint(self): + a, b = split_indices(SEED) + c, d = split_indices(SEED) + self.assertTrue(np.array_equal(a, c)) + self.assertTrue(np.array_equal(b, d)) + self.assertEqual((len(a), len(b)), (48, 16)) + self.assertEqual(set(a).union(set(b)), set(range(64))) + self.assertFalse(set(a).intersection(set(b))) + + def test_calibration_only_scale_free_of_test_data(self): + train, test = split_indices() + x = features(16) + c = exact_binary_code(16) + scale = calibration_scale(x[train], c[train]) + _ = distortion_metrics(x[test], c[test], scale, test) + self.assertEqual(scale, calibration_scale(x[train], c[train])) + + def test_identity_embedding_never_has_violations(self): + train, test = split_indices() + for T in HORIZONS: + x = features(T) + scale = calibration_scale(x[train], x[train]) + m = distortion_metrics(x[test], x[test], scale, test) + self.assertAlmostEqual(scale, 1.0) + self.assertEqual(m["violation_counts_calibration_scale"], + {"1.5": 0, "2.0": 0}) + self.assertEqual(m["optimal_rescaling_distortion_heldout"], 1.0) + + def test_some_exact_semantic_code_distorts_future_metric(self): + train, test = split_indices() + full = features(63) + code = exact_binary_code(63) + scale = calibration_scale(full[train], code[train]) + m = distortion_metrics(full[test], code[test], scale, test) + self.assertGreater(m["optimal_rescaling_distortion_heldout"], 2) + self.assertLessEqual(m["optimal_rescaling_distortion_heldout"], + math.sqrt(6) + 1e-10) + + def test_full_run_contains_pca_gaussian_and_exact_code(self): + result = run(horizons=(1, 4, 16, 63), widths=(2, 4, 8, 16)) + self.assertEqual(result["status"], + "FROZEN_SYNTHETIC_RECURRENT_PILOT") + for row in result["records"]: + names = {x["method"] for x in row["methods"]} + self.assertIn("exact_binary_quotient", names) + self.assertIn("full_trace_identity", names) + if row["horizon"] >= 16: + self.assertIn("pca_8", names) + self.assertIn("gaussian_8", names) + for method in row["methods"]: + metric = method["heldout"] + self.assertEqual( + metric["pairs_distinct"], + sum(1 for i in range(16) for j in range(i+1, 16) + if np.linalg.norm(features(row["horizon"])[ + result["heldout_state_ids"][i]] - + features(row["horizon"])[ + result["heldout_state_ids"][j]]) > 0)) + self.assertFalse(result["checkpoint_evaluated"]) + + def test_heldout_simplex_is_invisible_to_training_pca(self): + # Exact simplex geometry: training-centered differences are + # perpendicular to differences among any entirely unseen vertices. + train, test = split_indices() + future = features(63) + centered_train = future[train] - future[train].mean(axis=0) + for i in range(len(test)): + for j in range(i+1, len(test)): + unseen_difference = future[test[i]] - future[test[j]] + self.assertTrue(np.allclose( + centered_train @ unseen_difference, 0, atol=1e-12)) + _, s, vt = np.linalg.svd(centered_train, full_matrices=False) + self.assertEqual(int(np.sum(s > 1e-10)), len(train)-1) + # Every positive-variance PCA component annihilates every + # difference between two held-out vertices. + for d in (2, 4, 6, 8, 16, 32): + projected = future[test] @ vt[:d].T + self.assertLess(np.max(np.abs(projected - projected[:1])), 1e-12) + + def test_failed_pair_is_reproducible(self): + train, test = split_indices() + full, code = features(63), exact_binary_code(63) + scale = calibration_scale(full[train], code[train]) + m = distortion_metrics(full[test], code[test], scale, test) + for D, pair in m["violation_witnesses"].items(): + i, j = pair["state_a"], pair["state_b"] + da = float(np.linalg.norm(full[i]-full[j])) + db = float(np.linalg.norm(code[i]-code[j])) + self.assertAlmostEqual(pair["source_distance"], da) + self.assertAlmostEqual(pair["code_distance"], db) + self.assertAlmostEqual(pair["ratio_scaled"], scale*db/da) + + def test_input_validation(self): + with self.assertRaises(ValueError): + run(horizons=(64,)) + with self.assertRaises(ValueError): + distortion_metrics(np.zeros((3,2)), np.zeros((2,1)), + 1, np.arange(3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/research/finite_horizon_gap_v1/test_reference.py b/research/finite_horizon_gap_v1/test_reference.py new file mode 100644 index 000000000..c2596c1bb --- /dev/null +++ b/research/finite_horizon_gap_v1/test_reference.py @@ -0,0 +1,153 @@ +"""FHC-01 exact finite controls; no external Python dependencies.""" +import itertools +import random +import unittest +from fractions import Fraction + +from reference import ( + control_report, + coarse_embedding_1d_certificate, + doubling_cover_bound, + equilateral_packing_obstruction, + exact_l2_to_l4_certificate, + exact_line_equilateral_distortion, + first_forbidden_equilateral_size, + fourth_gaussian_moment, + gaussian_isometry_moment_identity, + net_transfer_distortion, + robust_net_threshold, + shift_observation_matrix, + exact_rational_rank, + finite_shift_rank_frontier, +) + + +class TestFHC01(unittest.TestCase): + def test_wick_identity_for_rational_vectors(self): + values = [ + [], [0], [Fraction(1, 3)], [1, 2], [-2, 3, 4], + [Fraction(-7, 11), Fraction(4, 9), Fraction(3, 5)], + ] + for vector in values: + self.assertTrue(gaussian_isometry_moment_identity(vector)) + expected = 3 * sum((Fraction(x)**2 for x in vector), Fraction())**2 + self.assertEqual(fourth_gaussian_moment(vector), expected) + + def test_random_wick_controls(self): + rng = random.Random(940198) + for n in range(1, 6): + for _ in range(7): + xs = [Fraction(rng.randrange(-6, 7), rng.randrange(1, 8)) + for _ in range(n)] + self.assertTrue(gaussian_isometry_moment_identity(xs)) + + def test_exact_volume_packing_witnesses(self): + for d in (1, 2, 3, 4): + for D in (Fraction(1), Fraction(6, 5), Fraction(3, 2), Fraction(2)): + n = first_forbidden_equilateral_size(d, D) + self.assertTrue(equilateral_packing_obstruction(n, d, D)) + self.assertFalse(equilateral_packing_obstruction(n-1, d, D)) + self.assertEqual(first_forbidden_equilateral_size(2, Fraction(6, 5)), 12) + + def test_equilateral_optimal_one_dim_distortion(self): + for n in range(2, 30): + self.assertEqual(exact_line_equilateral_distortion(n), n-1) + with self.assertRaises(ValueError): + exact_line_equilateral_distortion(1) + + def test_robust_epsilon_ratio_exact(self): + for D in (Fraction(1), Fraction(5,4), Fraction(17,7)): + delta = Fraction(3, 4) + Dprime = 2 * D + epsilon = robust_net_threshold(delta, D, Dprime) + self.assertEqual(epsilon, delta/6) + self.assertEqual(net_transfer_distortion(delta, epsilon, D), Dprime) + self.assertLess( + net_transfer_distortion(delta, epsilon/2, D), Dprime) + self.assertGreater( + net_transfer_distortion(delta, epsilon*Fraction(6,5), D), Dprime) + + def test_robust_general_factors(self): + delta = Fraction(7, 5) + D = Fraction(4, 3) + for alpha in (Fraction(3,2), Fraction(7,4), Fraction(5)): + e = robust_net_threshold(delta, D, alpha*D) + self.assertEqual( + net_transfer_distortion(delta, e, D), alpha*D) + self.assertLess(e, delta/2) + + def test_epsilon_cover_refinement(self): + cap = doubling_cover_bound(4, 1, Fraction(1,8)) + self.assertEqual(cap["steps"], 5) + self.assertEqual(cap["net_count_upper"], 1024) + for eps in (Fraction(1,2), Fraction(1,4), Fraction(1,8)): + c = doubling_cover_bound(8, 1, eps) + self.assertLessEqual(c["final_radius"], eps/2) + self.assertEqual(c["net_count_upper"], 8**c["steps"]) + + def test_rational_l2_to_l4_pair_certificate(self): + source = [[0, 0], [1, 0], [0, 1], [1, 1]] + good = exact_l2_to_l4_certificate(source, source, Fraction(1,2), 2) + self.assertTrue(good["passed"]) + self.assertEqual(good["pairs_checked"], 6) + bad = exact_l2_to_l4_certificate(source, [[0,0]]*4, Fraction(1,2), 2) + self.assertFalse(bad["passed"]) + self.assertEqual(len(bad["failed_pairs"]), 6) + + def test_coarse_additive_distortion_toy(self): + states = [Fraction(i,2) for i in range(9)] + net = [Fraction(i) for i in range(5)] + code = {x: x for x in net} + result = coarse_embedding_1d_certificate( + states,net,code,Fraction(1,2),1) + self.assertTrue(result["passed"]) + self.assertEqual(result["pairs_checked"], 36) + + def test_rejects_invalid_geometry_and_source(self): + with self.assertRaises(ValueError): + doubling_cover_bound(0,1,Fraction(1,4)) + with self.assertRaises(ValueError): + net_transfer_distortion(1,Fraction(1,2),1) + with self.assertRaises(ValueError): + robust_net_threshold(1,2,2) + with self.assertRaises(ValueError): + exact_l2_to_l4_certificate([[0],[0]], [[0],[0]], 1, 2) + with self.assertRaises(ValueError): + coarse_embedding_1d_certificate( + [0,1,2],[0,2],{Fraction(0):0,Fraction(2):2}, + Fraction(1,4),1) + with self.assertRaises(ValueError): + coarse_embedding_1d_certificate( + [0,1,2],[0,2],{Fraction(0):0,Fraction(2):1}, + 1,1) + + def test_shift_future_observability_rank_grows_and_saturates(self): + for width in range(1, 14): + for horizon in range(0, width * 2 + 3): + matrix = shift_observation_matrix(width, horizon) + self.assertEqual(exact_rational_rank(matrix), min(width, horizon)) + frontier = finite_shift_rank_frontier(8, [1, 2, 4, 8, 16]) + self.assertEqual([r["required_linear_dimension"] for r in frontier], + [1, 2, 4, 8, 8]) + + def test_shift_null_direction_disappears_at_horizon(self): + width = 7 + for horizon in range(width): + probe = [int(j == horizon) for j in range(width)] + observations = shift_observation_matrix(width,horizon) + self.assertTrue(all(sum(a*b for a,b in zip(row,probe))==0 + for row in observations)) + next_row = shift_observation_matrix(width,horizon+1)[-1] + self.assertEqual(sum(a*b for a,b in zip(next_row,probe)),1) + + def test_fixed_reference_receipt(self): + r = control_report() + self.assertEqual(r["status"], "CONTROL_ONLY") + self.assertEqual(r["equilateral_N_first_forbidden_d2_D6over5"], 12) + self.assertEqual(r["robust_epsilon_at_delta1_D1_Dprime2"], "1/6") + self.assertFalse(r["constructs_compact_doubling_witness"]) + self.assertFalse(r["runs_trained_models"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/research/finite_horizon_gap_v1/test_rrc25_future.py b/research/finite_horizon_gap_v1/test_rrc25_future.py new file mode 100644 index 000000000..a970069f4 --- /dev/null +++ b/research/finite_horizon_gap_v1/test_rrc25_future.py @@ -0,0 +1,91 @@ +"""FHC-01C trained model source lock and future metric smoke checks.""" +from __future__ import annotations + +import random +import unittest +from dataclasses import replace + +import numpy as np + +from bench_rrc25_future import ( + HORIZONS, native_case, gru_step, logits, run, source_header, +) +from research.rrc_compactification import bench25, compound25, model25 + + +class TrainedRRC25Geometry(unittest.TestCase): + @classmethod + def setUpClass(cls): + checkpoints, hashes=bench25.checkpoints() + cls.checkpoint=checkpoints["recurrent"] + cls.checkpoint_sha=hashes["recurrent"] + cls.case=compound25.make_case( + random.Random(940199),"signed","fhc01c-generated-control") + + def test_original_training_source_and_native_model_contract(self): + self.assertEqual(self.checkpoint["kind"], "recurrent") + self.assertEqual(self.checkpoint["parameters"], 1000) + self.assertEqual(len(self.checkpoint_sha), 64) + self.assertEqual(model25.HIDDEN, 12) + + def test_public_header_and_native_logits(self): + header, count=source_header(self.case) + self.assertGreaterEqual(count, 1) + self.assertEqual(len(compound25.features(self.case,header)), 9) + hidden, future, diff, _=native_case(self.case,self.checkpoint,4) + self.assertEqual(len(hidden),12) + self.assertEqual(len(future),64) + self.assertLess(diff, 1e-11) + self.assertTrue(np.isfinite(future).all()) + + def test_constant_zero_continuation_and_hidden_replay(self): + hidden,future,_,_=native_case(self.case,self.checkpoint,4) + replay=gru_step(hidden,[0.]*8,self.checkpoint) + self.assertTrue(np.allclose( + future[:16],logits(replay,self.checkpoint),atol=1e-12)) + + def test_hidden_input_does_not_consult_future_truth(self): + changed=replace(self.case,future=tuple( + 1000000 if i%2 else -1000000 + for i in range(len(self.case.future)))) + a=native_case(self.case,self.checkpoint,3) + b=native_case(changed,self.checkpoint,3) + self.assertEqual(a,b) + + def test_small_trained_pilot_is_holdout_and_deterministic(self): + a=run(horizons=(1,2),widths=(2,4)) + b=run(horizons=(1,2),widths=(2,4)) + self.assertEqual(a["status"],"FROZEN_TRAINED_RRC25_DEVELOPMENT") + self.assertEqual(a["checkpoint_sha256"],self.checkpoint_sha) + self.assertEqual(a["calibration_roster_sha256"], + b["calibration_roster_sha256"]) + self.assertEqual(a["heldout_roster_sha256"], + b["heldout_roster_sha256"]) + self.assertEqual(len(a["calibration_case_ids"]),36) + self.assertEqual(len(a["heldout_cases"]),48) + self.assertEqual(a["public_header_multiple_candidates"], + b["public_header_multiple_candidates"]) + self.assertFalse(set(a["calibration_case_ids"]) & + {x["id"] for x in a["heldout_cases"]}) + for row in a["cases"]: + names={x["method"] for x in row["methods"]} + self.assertIn("native_hidden_12",names) + self.assertIn("full_trace_identity",names) + self.assertIn("pca_2",names) + self.assertIn("gaussian_2",names) + identity=next(x for x in row["methods"] + if x["method"]=="full_trace_identity") + self.assertEqual( + identity["heldout"]["violation_counts_calibration_scale"]["2.0"],0) + self.assertAlmostEqual( + identity["heldout"]["optimal_rescaling_distortion_heldout"],1.0, + places=9) + self.assertEqual(a["source_family_098_infinite_witness_tested"],False) + + def test_rejects_bad_horizons(self): + with self.assertRaises(ValueError): + run(horizons=(17,),widths=(2,)) + + +if __name__=="__main__": + unittest.main()