From 0fcc81a99415d7f92bc2f8aa56c3bfa3a829975a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 12:34:39 +0800 Subject: [PATCH 1/6] Formalize Algernon instruction algebra, cycle sheaf and sparse repair --- .../workflows/algernon-algebraic-machine.yml | 53 ++++++ research/algernon/algebraic_machine/README.md | 90 +++++++++ .../algernon/algebraic_machine/THEOREMS.md | 64 +++++++ .../algernon/algebraic_machine/__init__.py | 1 + .../algernon/algebraic_machine/experiments.py | 71 +++++++ .../algebraic_machine/lean/Algernon.lean | 1 + .../lean/Algernon/Semiconjugacy.lean | 108 +++++++++++ .../algebraic_machine/lean/lakefile.toml | 6 + .../algebraic_machine/lean/lean-toolchain | 1 + .../algernon/algebraic_machine/machine.py | 107 +++++++++++ .../algebraic_machine/requirements.txt | 1 + .../algebraic_machine/results/reference.json | 64 +++++++ research/algernon/algebraic_machine/sheaf.py | 150 +++++++++++++++ research/algernon/algebraic_machine/sparse.py | 83 +++++++++ .../algebraic_machine/tests/test_algebra.py | 174 ++++++++++++++++++ 15 files changed, 974 insertions(+) create mode 100644 .github/workflows/algernon-algebraic-machine.yml create mode 100644 research/algernon/algebraic_machine/README.md create mode 100644 research/algernon/algebraic_machine/THEOREMS.md create mode 100644 research/algernon/algebraic_machine/__init__.py create mode 100644 research/algernon/algebraic_machine/experiments.py create mode 100644 research/algernon/algebraic_machine/lean/Algernon.lean create mode 100644 research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean create mode 100644 research/algernon/algebraic_machine/lean/lakefile.toml create mode 100644 research/algernon/algebraic_machine/lean/lean-toolchain create mode 100644 research/algernon/algebraic_machine/machine.py create mode 100644 research/algernon/algebraic_machine/requirements.txt create mode 100644 research/algernon/algebraic_machine/results/reference.json create mode 100644 research/algernon/algebraic_machine/sheaf.py create mode 100644 research/algernon/algebraic_machine/sparse.py create mode 100644 research/algernon/algebraic_machine/tests/test_algebra.py diff --git a/.github/workflows/algernon-algebraic-machine.yml b/.github/workflows/algernon-algebraic-machine.yml new file mode 100644 index 000000000..33fd524fa --- /dev/null +++ b/.github/workflows/algernon-algebraic-machine.yml @@ -0,0 +1,53 @@ +name: Algernon algebraic machine +on: + pull_request: + paths: + - 'research/algernon/algebraic_machine/**' + - '.github/workflows/algernon-algebraic-machine.yml' + push: + paths: + - 'research/algernon/algebraic_machine/**' + - '.github/workflows/algernon-algebraic-machine.yml' + workflow_dispatch: + +jobs: + cpu-algebra: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.11' + - name: Install NumPy + run: python -m pip install -r research/algernon/algebraic_machine/requirements.txt + - name: Unit tests + run: python -m unittest discover -s research/algernon/algebraic_machine/tests -v + - name: Reproduce frozen finite-field and monoid receipt + run: | + python -m research.algernon.algebraic_machine.experiments --out /tmp/algernon-algebra-reference.json + python - <<'PY' + import json + from pathlib import Path + expected=json.loads(Path('research/algernon/algebraic_machine/results/reference.json').read_text()) + observed=json.loads(Path('/tmp/algernon-algebra-reference.json').read_text()) + assert observed==expected, 'algebraic reference experiment drifted' + assert observed['monoid']['program_violations']==0 + assert observed['cyclic_sheaf']['monodromy_dim_mismatches']==0 + print('Reproduced exact deterministic reference') + PY + + lean-kernel: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Lean 4 standalone proofs + uses: leanprover/lean-action@v1 + with: + lake-package-directory: research/algernon/algebraic_machine/lean + auto-config: false + build: true + test: false + use-mathlib-cache: false + - name: Print Lean theorem axiom dependencies + working-directory: research/algernon/algebraic_machine/lean + run: lake env lean Algernon/Semiconjugacy.lean diff --git a/research/algernon/algebraic_machine/README.md b/research/algernon/algebraic_machine/README.md new file mode 100644 index 000000000..5ce64b123 --- /dev/null +++ b/research/algernon/algebraic_machine/README.md @@ -0,0 +1,90 @@ +# Algernon algebraic machine: executable mathematics (2026-11-04) + +**Status:** deterministic CPU tests were executed on constructed finite-state examples. These tests do not establish that LOTUS or Qwen implements these maps. Lean source is provided for a kernel audit and is only considered proved in Lean after its CI job passes. No Circom compiler or Qwenputer runtime is invoked by this package. + +## Research question + +Can a trained recurrent representation preserve the algebra of an instruction set, so that valid primitive transitions compose into correct deeper programs? This module isolates the formal interface before any GPU experiment. + +Mathematical roles: + +| Object | Algebraic interpretation | Executable artifact | +| --- | --- | --- | +| Instructions | Free monoid over instruction alphabet | `machine.py`, `lean/Algernon/Semiconjugacy.lean` | +| Decoder | Quotient/factor map π from hidden state H to machine state S | `machine.py` | +| Computation graph | Cellular sheaf with edge maps Aₑ and coboundary δ | `sheaf.py` | +| Inconsistent trace | Affine 1-cochain outside im(δ), yielding class in H¹ | `sheaf.py` | +| Sparse repair | Low-rank intervention supported on U in linearized dynamics | `sparse.py` | +| Depth robustness | One-step L¹ transition error accumulates at most linearly | `sparse.py` | + +## 1. Instruction algebra and semiconjugacy + +For each instruction `a`, let `Fₐ : H → H` be the hidden machine and `Tₐ : S → S` its exact semantics. A decoder π should obey `π ∘ Fₐ = Tₐ ∘ π` on every *reachable* hidden state. + +By induction on word length, the property extends to every program composed from those instructions. This is a **semiconjugacy** (a factor map when π is surjective); injectivity and complete state reconstruction are extra conditions. The kernel proof in `Semiconjugacy.lean` includes word compositionality, quotient congruence, invariant-subset iteration, and semantic periodic returns. It assumes the generator property; finite training examples alone do not prove it. + +`machine.py` exhaustively checks 27 deterministic three-state transitions lifted to six explicitly constructed hidden states and all words over two instructions of length 0–5. Corrupting one hidden transition creates a measurable defect. The finite tests are controls for a future learned neural decoder. + +**Conjugacy and period:** if `Fᵐ(h)=h` and π semiconjugates F and T then `Tᵐ(πh)=πh`. The minimum semantic period therefore divides m when a semantic cycle exists. A hidden cycle may be a multiple of a semantic cycle, since π can identify different hidden states. + +## 2. A finite-field cellular sheaf on an oriented cycle + +Let the cycle have m vertices with fiber `Fₚᵈ` at each vertex. Each edge carries a d×d linear transition `Aᵢ` and + +`(δs)ᵢ = sᵢ₊₁ − Aᵢ sᵢ`, with indices modulo m. + +`H⁰ = ker δ`, `H¹ = coker δ`. For a single directed cycle with `M=Aₘ₋₁...A₀`, eliminating the intermediate vertex variables gives: + +`H⁰ ≅ ker(I−M)` and `H¹ ≅ coker(I−M)`. + +For a prescribed affine 1-cochain b, a global state assignment exists **iff** b∈im δ. Equivalently `(I−M)s₀ = c`, where `c=bₘ₋₁ + Aₘ₋₁bₘ₋₂ + ... + Aₘ₋₁...A₁b₀`. This gives a computable obstruction over finite fields. + +A useful test is the three-edge identity cycle over F₅. Increments (1,1,1) sum to 3, so global consistency is impossible; increments (1,1,3) sum to 0 and admit a solution. A *twisted* cycle with monodromy 2 has H⁰=H¹=0. The sheaf invariants depend on transition maps as well as the graph topology. + +**Boundary:** This is a linear cellular sheaf, not the nonlinear Circom constraint variety. R1CS Boolean/one-hot/range constraints must be checked separately. This module uses a small-prime modular reference solver. A Circom witness is only considered accepted when its complete polynomial constraints and public-input binding pass the exact checker in `../spec.py`. + +## 3. Sparse weight repair as a linear intertwiner + +For local real-valued linear maps, decoder `P:[h]→[s]`, neural step `M:[h]→[h]`, semantic transition `A:[s]→[s]`, define `D=PM−AP`. A support subspace `U:[h]→[r]` permits edit `ΔM=UB`. The optimal residual is + +`min_B ||D+PUB||_F = ||(I−Π_{PU})D||_F`. + +An exact repair exists precisely when `im(D) ⊆ im(PU)`. `sparse.py` computes the least-squares edit and independently checks its residual. In the built example one edit direction removes a norm-3 defect; an orthogonal direction leaves norm 3. These are **local Jacobian algebra** statements, not weight-edit results for Qwen, and do not account for nonlinear state shifts or discrete quantization. + +## 4. Depth-error theorem + +For a column-stochastic transition A and decoded distributions qₖ, nonexpansiveness in L¹ yields + +`||qₙ−Aⁿq₀||₁ ≤ Σₖ ||qₖ₊₁−Aqₖ||₁`. + +If the true initial state is eₛ and `||q₀−eₛ||₁ ≤ ε₀`, then the target error is ≤ `ε₀+Σ εₖ`. When this total is <1 the correct target has majority mass, so argmax is correct. The guarantee needs accurate initialization and decoder semantics. A constant uniform state may have zero local defect and still represent no meaningful computation. + +## Commands + +From repository root, with NumPy installed: + +```bash +python -m pip install -r research/algernon/algebraic_machine/requirements.txt +python -m unittest discover -s research/algernon/algebraic_machine/tests -v +python -m research.algernon.algebraic_machine.experiments --out runs/algernon/algebraic_machine/reference.json +``` + +For the independent Lean project, from `research/algernon/algebraic_machine/lean/`: + +```bash +lake build +lake env lean Algernon/Semiconjugacy.lean +``` + +The GitHub Actions workflow runs CPU tests, compares the deterministic JSON receipt, and runs the Lean build. The Lean toolchain is pinned locally to `v4.28.0` with no Mathlib dependency. + +## Next use with LOTUS + +1. Capture genuine post-loop hidden states using `../lotus_bridge/` and train π on a frozen, group-disjoint roster. Measure one-step defect on held-out states, including counterfactual prompt changes. +2. Estimate local Jacobian `M` of the recurrent step and `P` of the decoder on calibrated states. Compare low-rank edit supports by `im(PU)` coverage of D. Include random and norm-matched controls. +3. Measure whether latent cycles are compatible with target periods and whether decoded transitions form globally consistent traces. A low linear defect is diagnostic and does not replace exact polynomial witness validation. +4. Audit GPU cost, quantization sensitivity, model skill retention, and depth generalization before attempting a real Qwen weight splice. + +## Evidence status + +The frozen CPU reference JSON in `results/reference.json` contains `execution_class: cpu_reference_only`. The finite models are constructed examples, and the least-squares repair uses NumPy. Lean CI is independently reported. This package contains no learned model parameters, trained decoder, zk proof, or measured neural gain. diff --git a/research/algernon/algebraic_machine/THEOREMS.md b/research/algernon/algebraic_machine/THEOREMS.md new file mode 100644 index 000000000..26288765e --- /dev/null +++ b/research/algernon/algebraic_machine/THEOREMS.md @@ -0,0 +1,64 @@ +# Algebraic program semantics, sheaf obstructions, and sparse circuit repair + +**Scope:** standard mathematical constructions instantiated on Algernon's pointer-machine interface. Formal Lean proofs of the composition/period claims live in `lean/Algernon/Semiconjugacy.lean`; finite-field sheaf examples and real-valued least-squares repairs are independently tested in Python. The Lean proofs are identified as kernel verified only after a successful Lean build in CI. + +## A. Free-monoid actions and the reasoning quotient + +Let `Σ` be the instruction alphabet, `Σ*` its word monoid, `T_a:S→S` an exact instruction, and `F_a:H→H` a neural instruction. A decoder `π:H→S` satisfies `π(F_a(h)) = T_a(π(h))` for every instruction on an invariant reachable region. Induction gives, for all words `w=a₁...aₙ`, + +`π(F_(aₙ) ... F_(a₁) h) = T_(aₙ) ... T_(a₁) π(h)`. + +The decoder's equality relation `h~h' ↔ πh=πh'` is a congruence on the reachable hidden system, because `π(F_a h)=T_a(πh)=T_a(πh')=π(F_a h')`. When π is surjective, S is a factor of the hidden algebra. If π is bijective, the systems are conjugate on that domain. + +A cycle provides a necessary condition for exact simulation: if `F^m h=h`, then `T^m πh=πh`. If the semantic state belongs to a cycle of least period r, then r divides m. The converse generally fails because π can identify several latent states with the same semantic state. + +**Practical caution:** proving composition requires the primitive correspondence on *every relevant reachable state*, including states encountered after previously unseen program prefixes. Training on steps 1–8, even with 100% accuracy, establishes a sample claim only. The deterministic example `machine.py` has a constructed projection, rather than a trained neural network. + +## B. Computational graph as a twisted local system + +On an m-edge directed cycle, assign `V_i=Fₚ^d` to vertices and a linear transport `A_i:V_i→V_(i+1)` to each edge. The cochain differential is + +`δ: ⊕_i V_i → ⊕_i V_i`, `(δs)_i=s_(i+1)-A_i s_i`. + +For this one-dimensional cellular cochain complex, `H⁰=ker δ` and `H¹=coker δ`. With `M=A_(m−1)...A_0`, solve the homogeneous edge relations in order: `s_i=A_(i−1)...A_0 s_0`. Closing the cycle requires `(I−M)s_0=0`, proving `H⁰ ≅ ker(I−M)`. + +For the inhomogeneous problem `s_(i+1)=A_i s_i+b_i`, write `c=b_(m−1)+A_(m−1)b_(m−2)+...+A_(m−1)...A_1b_0`. The closing equation is `(I−M)s_0=c`. This gives an isomorphism from the obstruction quotient `coker δ` to `coker(I−M)` by eliminating the m−1 intermediate states. Consequently, `H¹ ≅ coker(I−M)`. + +There are two useful distinctions: + +- The ordinary constant-coefficient graph cohomology measures the cycle, while this **twisted** cohomology incorporates the transition matrices. For example, on a one-dimensional 3-cycle over F₅, edge maps (1,1,2) give `M=2`, so H⁰ and H¹ vanish despite the topological loop. +- For affine constraints, the **class of b in H¹** is the obstruction to extending local states to a globally consistent computation. With all maps equal to 1, b=(1,1,1) has nonzero obstruction 3 mod 5, whereas b=(1,1,3) closes consistently. + +The analogous Circom/R1CS system uses quadratic constraints and Boolean/range checks over BN254 Fr. The linear sheaf is a separate exact model over Fₚ, or a *linearization* of nonlinear constraints when used for neural diagnosis; its Hⁱ alone does not imply an accepted R1CS witness. + +## C. Gauge changes and coordinate independence + +Change local bases by invertible `G_i`; the edge map becomes `A'_i=G_(i+1) A_i G_i⁻¹`. Around a cycle, with `G_m=G_0`, the monodromy transforms as `M' = G_0 M G_0⁻¹`. Thus ranks of `I−M` and `I−M'` coincide, and so do dimensions of H⁰ and H¹. + +This gives an interpretable question for latent representations: does a putative computational feature survive a change of basis in the hidden representation? The toy tests apply a fixed invertible 2×2 conjugation over F₇. Neural basis changes require attention to a learned decoder and possible nonlinearities. + +## D. The sparse intertwining repair theorem + +Let the local learned transition be `M∈R^{h×h}`, the target `A∈R^{s×s}`, decoder `P∈R^{s×h}`. The intertwining defect is `D=PM−AP`. A restricted edit `ΔM=UB`, `U∈R^{h×r}`, changes it to `D'=D+(PU)B`. + +Let `K=PU`. The projection theorem for least squares gives + +`min_B ||D+KB||_F = ||(I−KK†)D||_F`, + +where `K†` is the Moore–Penrose pseudoinverse. Exact repair is possible precisely when every column of D lies in `im K`, equivalently `rank[K | D]=rank K`. The least-squares choice `B=−K†D` achieves the minimum. This statement holds even if K is rank deficient; it makes *support choice* mathematically consequential. + +A projected residual can vanish while a nonlinear network still fails, since the theorem concerns one linearization and allows changes to the reachable state distribution. All edits must be tested on the complete neural model, with matching norms, support counts and held-out tasks. + +## E. Error amplification under repeated reasoning + +For a column-stochastic state operator A, `||Av||₁≤||v||₁`. Let `qₖ` be decoded probability distributions, and define `eₖ=q_(k+1)−Aqₖ`. Unrolling the recurrence yields + +`q_n−Aⁿq_0 = Σ_(k=0)^(n−1) A^(n−1−k)eₖ`, + +hence `||q_n−Aⁿq_0||₁≤Σ||eₖ||₁`. Relative to a true initial one-hot state, add `||q_0−e_s||₁` to the bound. When this total is below 1, the correct target receives more than half the probability mass. + +This theorem is compatible with a high apparent local score and poor generalization: small persistent errors can accumulate with depth. It also exposes a *vacuous solution*: for permutation A, a constant uniform q has zero step defect but carries no useful initial-state information. Initial-state binding and counterfactual tasks are therefore necessary. + +## Next experimental measurements + +LOTUS hidden-state captures will supply empirical decoders `πψ` and step maps. Register the task input and decoder range, estimate defects by depth and graph family, test whether hidden cycles preserve the semantic period spectrum, and fit local Jacobians for candidate edits. These measurements require genuine pretrained-model activations and are pending the GPU run. diff --git a/research/algernon/algebraic_machine/__init__.py b/research/algernon/algebraic_machine/__init__.py new file mode 100644 index 000000000..6264c07ed --- /dev/null +++ b/research/algernon/algebraic_machine/__init__.py @@ -0,0 +1 @@ +"""Algernon algebraic machine: reference semantics, topology and repair tests.""" diff --git a/research/algernon/algebraic_machine/experiments.py b/research/algernon/algebraic_machine/experiments.py new file mode 100644 index 000000000..16348a4f9 --- /dev/null +++ b/research/algernon/algebraic_machine/experiments.py @@ -0,0 +1,71 @@ +"""Deterministic algebraic reference experiment; no GPU, checkpoints or training.""" +from __future__ import annotations +import argparse +import hashlib +import itertools +import json +from pathlib import Path + +import numpy as np + +from .machine import exhaustive_word_check, lifted_actions +from .sheaf import affine_cocycle, cycle_cohomology +from .sparse import sparse_repair, step_error_bound + + +def run(): + maps = list(itertools.product(range(3), repeat=3)) + counts = {"target_maps": len(maps), "program_checks": 0, "program_violations": 0} + for t in maps: + symbolic = (t, (1, 2, 0)) + hidden, pi = lifted_actions(symbolic) + rep = exhaustive_word_check(hidden, symbolic, pi, 5) + counts["program_checks"] += rep["program_checks"] + counts["program_violations"] += rep["program_violations"] + sheaf = {"scalar_cycle_cases": 0, "monodromy_dim_mismatches": 0, + "examples": {}} + for p in (2, 3, 5, 7): + for a, b, c in itertools.product(range(p), repeat=3): + s = cycle_cohomology([[[a]], [[b]], [[c]]], p) + sheaf["scalar_cycle_cases"] += 1 + if s['H0_dimension'] != int((a*b*c)%p==1): + sheaf["monodromy_dim_mismatches"] += 1 + sheaf['examples']['inconsistent_affine_3cycle_F5'] = affine_cocycle([[[1]]]*3, [[1]]*3, 5) + sheaf['examples']['consistent_affine_3cycle_F5'] = affine_cocycle([[[1]]]*3, [[1],[1],[3]], 5) + P=np.eye(3) + A=np.eye(3) + M=A.copy() + M[0,2]=3 + support_good=np.array([[1.],[0.],[0.]]) + support_bad=np.array([[0.],[1.],[0.]]) + rgood=sparse_repair(P,M,A,support_good) + rbad=sparse_repair(P,M,A,support_bad) + sparse={"useful_support_residual":rgood['actual_residual_norm'], + "orthogonal_support_residual":rbad['actual_residual_norm'], + "useful_support_exact":rgood['exactly_repairable'], + "orthogonal_support_exact":rbad['exactly_repairable']} + transition=np.array([[0.,0.,1.],[1.,0.,0.],[0.,1.,0.]]) + q=np.array([1.,0.,0.]);states=[q] + for _ in range(8): + q = .98*(transition@q)+.02*np.ones(3)/3 + states.append(q) + bound=step_error_bound(transition,states,np.array([1.,0.,0.])) + return {"schema_version":"0.1.0", "execution_class":"cpu_reference_only", + "source_note":"No learned weights or LOTUS activations evaluated", + "monoid":counts, "cyclic_sheaf":sheaf, "sparse_intertwining":sparse, + "depth_bound":bound} + + +def main(): + p=argparse.ArgumentParser() + p.add_argument("--out",type=Path,default=Path("runs/algernon/algebraic_machine/reference.json")) + args=p.parse_args() + result=run() + raw=json.dumps(result,sort_keys=True,indent=2,allow_nan=False)+"\n" + args.out.parent.mkdir(parents=True,exist_ok=True) + args.out.write_text(raw,encoding="utf-8") + print(json.dumps({"results":str(args.out),"sha256":hashlib.sha256(raw.encode()).hexdigest(), + "checks":result['monoid']['program_checks'],"sheaf_cases":result['cyclic_sheaf']['scalar_cycle_cases']})) + +if __name__ == '__main__': + main() diff --git a/research/algernon/algebraic_machine/lean/Algernon.lean b/research/algernon/algebraic_machine/lean/Algernon.lean new file mode 100644 index 000000000..e35497960 --- /dev/null +++ b/research/algernon/algebraic_machine/lean/Algernon.lean @@ -0,0 +1 @@ +import Algernon.Semiconjugacy diff --git a/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean b/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean new file mode 100644 index 000000000..50b98553c --- /dev/null +++ b/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean @@ -0,0 +1,108 @@ +import Init + +/-! +Algernon machine-algebra laws, Lean 4 without Mathlib. +The semantic transition is an arbitrary function; no learned behavior is claimed. +The kernel checks these results when this file is compiled. +-/ + +universe u v w +namespace AlgernonAlgebra + +/-- Repeated execution of a deterministic step. -/ +def iterate {α : Type u} (f : α → α) : Nat → α → α + | 0, x => x + | n + 1, x => f (iterate f n x) + +/-- If a decoder commutes with one transition, it commutes with every iterate. -/ +theorem semiconjugacy_iterate {H : Type u} {S : Type v} + (F : H → H) (T : S → S) (π : H → S) + (commutes : ∀ h, π (F h) = T (π h)) + (n : Nat) (h : H) : + π (iterate F n h) = iterate T n (π h) := by + induction n with + | zero => rfl + | succ n ih => + calc + π (iterate F (n + 1) h) = π (F (iterate F n h)) := rfl + _ = T (π (iterate F n h)) := commutes _ + _ = T (iterate T n (π h)) := congrArg T ih + _ = iterate T (n + 1) (π h) := rfl + +/-- Semantic equality is a congruence under a commuting transition. -/ +theorem quotient_congruence {H : Type u} {S : Type v} + (F : H → H) (T : S → S) (π : H → S) + (commutes : ∀ h, π (F h) = T (π h)) + (h₁ h₂ : H) (eq : π h₁ = π h₂) : + π (F h₁) = π (F h₂) := by + calc + π (F h₁) = T (π h₁) := commutes h₁ + _ = T (π h₂) := congrArg T eq + _ = π (F h₂) := (commutes h₂).symm + +/-- A latent periodic return implies a semantic return at the same number of steps. -/ +theorem latent_period_projects {H : Type u} {S : Type v} + (F : H → H) (T : S → S) (π : H → S) + (commutes : ∀ h, π (F h) = T (π h)) + (h : H) (m : Nat) (periodic : iterate F m h = h) : + iterate T m (π h) = π h := by + calc + iterate T m (π h) = π (iterate F m h) := + (semiconjugacy_iterate F T π commutes m h).symm + _ = π h := congrArg π periodic + +/-- A finite instruction word is executed left-to-right. -/ +def execute {Σ : Type w} {H : Type u} + (act : Σ → H → H) : List Σ → H → H + | [], h => h + | a :: rest, h => execute act rest (act a h) + +/-- Generator-level semiconjugacy extends to *every instruction word*. -/ +theorem instruction_word_semiconjugacy {Σ : Type w} {H : Type u} {S : Type v} + (F : Σ → H → H) (T : Σ → S → S) (π : H → S) + (commutes : ∀ a h, π (F a h) = T a (π h)) + (word : List Σ) (h : H) : + π (execute F word h) = execute T word (π h) := by + induction word generalizing h with + | nil => rfl + | cons a rest ih => + calc + π (execute F (a :: rest) h) = π (execute F rest (F a h)) := rfl + _ = execute T rest (π (F a h)) := ih (F a h) + _ = execute T rest (T a (π h)) := congrArg (execute T rest) (commutes a h) + _ = execute T (a :: rest) (π h) := rfl + +/-- The domain of the local algebra must be invariant to apply local lemmas repeatedly. -/ +theorem invariant_iterate {H : Type u} + (F : H → H) (Valid : H → Prop) + (closed : ∀ h, Valid h → Valid (F h)) + (n : Nat) (h : H) (hv : Valid h) : + Valid (iterate F n h) := by + induction n with + | zero => exact hv + | succ n ih => exact closed _ ih + +/-- Local correctness on a forward-invariant set implies correctness at every depth. -/ +theorem invariant_semiconjugacy {H : Type u} {S : Type v} + (F : H → H) (T : S → S) (π : H → S) + (Valid : H → Prop) + (closed : ∀ h, Valid h → Valid (F h)) + (commutes : ∀ h, Valid h → π (F h) = T (π h)) + (n : Nat) (h : H) (hv : Valid h) : + π (iterate F n h) = iterate T n (π h) := by + induction n with + | zero => rfl + | succ n ih => + calc + π (iterate F (n + 1) h) = π (F (iterate F n h)) := rfl + _ = T (π (iterate F n h)) := + commutes _ (invariant_iterate F Valid closed n h hv) + _ = T (iterate T n (π h)) := congrArg T ih + _ = iterate T (n + 1) (π h) := rfl + +#print axioms semiconjugacy_iterate +#print axioms instruction_word_semiconjugacy +#print axioms latent_period_projects +#print axioms invariant_semiconjugacy + +end AlgernonAlgebra diff --git a/research/algernon/algebraic_machine/lean/lakefile.toml b/research/algernon/algebraic_machine/lean/lakefile.toml new file mode 100644 index 000000000..559f74939 --- /dev/null +++ b/research/algernon/algebraic_machine/lean/lakefile.toml @@ -0,0 +1,6 @@ +name = "algernon_algebra" +version = "0.1.0" +defaultTargets = ["Algernon"] + +[[lean_lib]] +name = "Algernon" diff --git a/research/algernon/algebraic_machine/lean/lean-toolchain b/research/algernon/algebraic_machine/lean/lean-toolchain new file mode 100644 index 000000000..4c685fa08 --- /dev/null +++ b/research/algernon/algebraic_machine/lean/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.28.0 diff --git a/research/algernon/algebraic_machine/machine.py b/research/algernon/algebraic_machine/machine.py new file mode 100644 index 000000000..c07bdad00 --- /dev/null +++ b/research/algernon/algebraic_machine/machine.py @@ -0,0 +1,107 @@ +"""Finite transition algebras and exact semantic decoders. + +A program is a word over instruction indices; each instruction acts as a total +finite-state transition. Semiconjugacy is checked exhaustively on all hidden +states before program-level claims are made. +""" +from __future__ import annotations + +from itertools import product +from typing import Sequence + + +def validate_transition(t: Sequence[int]) -> None: + if not t or any(type(v) is not int or not 0 <= v < len(t) for v in t): + raise ValueError("transition must be a nonempty finite endomorphism") + + +def run_word(transitions: Sequence[Sequence[int]], word: Sequence[int], start: int) -> int: + if not transitions: + raise ValueError("instruction set must be nonempty") + width = len(transitions[0]) + if not 0 <= start < width: + raise ValueError("invalid initial state") + for t in transitions: + validate_transition(t) + if len(t) != width: + raise ValueError("instruction transitions must share a state space") + s = start + for letter in word: + if type(letter) is not int or not 0 <= letter < len(transitions): + raise ValueError("invalid instruction") + s = transitions[letter][s] + return s + + +def semiconjugacy_defects(hidden: Sequence[Sequence[int]], + symbolic: Sequence[Sequence[int]], pi: Sequence[int]): + """All (letter, hidden_state) where pi(F h) differs from T(pi h).""" + if not symbolic or len(symbolic) != len(hidden) or not pi: + raise ValueError("missing or unmatched instructions") + for f in hidden: + validate_transition(f) + if len(f) != len(pi): + raise ValueError("hidden transition width differs from pi") + for t in symbolic: + validate_transition(t) + n = len(symbolic[0]) + if any(len(t) != n for t in symbolic) or any(type(v) is not int or not 0 <= v < n for v in pi): + raise ValueError("decoder and target have incompatible sizes") + return [(letter, h) for letter, (f, t) in enumerate(zip(hidden, symbolic)) + for h in range(len(pi)) if pi[f[h]] != t[pi[h]]] + + +def congruence_defects(hidden: Sequence[Sequence[int]], pi: Sequence[int]): + """Pairs sharing one decoded state whose successors decode differently.""" + return [(letter, h, g) for letter, f in enumerate(hidden) + for h in range(len(pi)) for g in range(h + 1, len(pi)) + if pi[h] == pi[g] and pi[f[h]] != pi[f[g]]] + + +def words(alphabet_size: int, max_length: int): + if alphabet_size < 1 or max_length < 0: + raise ValueError("invalid alphabet / length") + for length in range(max_length + 1): + yield from product(range(alphabet_size), repeat=length) + + +def lifted_actions(symbolic: Sequence[Sequence[int]], tag_count: int = 2): + """A transparent, *constructed* semiconjugate H=S×{0,...,tags-1} example.""" + if not symbolic or tag_count < 1: + raise ValueError("bad symbolic action or tag count") + n = len(symbolic[0]) + for t in symbolic: + validate_transition(t) + if len(t) != n: + raise ValueError("incompatible transitions") + pi = tuple(s for s in range(n) for _ in range(tag_count)) + hidden = [] + for f in symbolic: + hidden.append(tuple(f[s] * tag_count + ((tag + 1) % tag_count) + for s in range(n) for tag in range(tag_count))) + return tuple(hidden), pi + + +def exhaustive_word_check(hidden, symbolic, pi, max_length=5): + """Validate finite-word action equality on a fixed finite example.""" + defects = semiconjugacy_defects(hidden, symbolic, pi) + count = 0 + violations = 0 + for word in words(len(symbolic), max_length): + for h in range(len(pi)): + count += 1 + if pi[run_word(hidden, word, h)] != run_word(symbolic, word, pi[h]): + violations += 1 + return {"one_step_defects": len(defects), "program_checks": count, + "program_violations": violations} + + +def minimal_period(t: Sequence[int], start: int) -> int | None: + """Period of start if on a cycle; transient points return None.""" + validate_transition(t) + x = t[start] + k = 1 + while x != start and k <= len(t): + x = t[x] + k += 1 + return k if x == start else None diff --git a/research/algernon/algebraic_machine/requirements.txt b/research/algernon/algebraic_machine/requirements.txt new file mode 100644 index 000000000..726a10393 --- /dev/null +++ b/research/algernon/algebraic_machine/requirements.txt @@ -0,0 +1 @@ +numpy>=1.26,<3 diff --git a/research/algernon/algebraic_machine/results/reference.json b/research/algernon/algebraic_machine/results/reference.json new file mode 100644 index 000000000..9700823b9 --- /dev/null +++ b/research/algernon/algebraic_machine/results/reference.json @@ -0,0 +1,64 @@ +{ + "cyclic_sheaf": { + "examples": { + "consistent_affine_3cycle_F5": { + "obstruction": [ + 0 + ], + "solvable": true, + "states": [ + [ + 0 + ], + [ + 1 + ], + [ + 2 + ] + ] + }, + "inconsistent_affine_3cycle_F5": { + "obstruction": [ + 3 + ], + "solvable": false, + "states": null + } + }, + "monodromy_dim_mismatches": 0, + "scalar_cycle_cases": 503 + }, + "depth_bound": { + "accumulated_step_bound": 0.19898263655761914, + "certified_bound": 0.19898263655761914, + "correct_argmax_guaranteed": true, + "initial_error": 0.0, + "n": 8, + "one_step_errors": [ + 0.026666666666666644, + 0.026133333333333335, + 0.02561066666666667, + 0.02509845333333336, + 0.024596484266666635, + 0.024104554581333273, + 0.02362246348970666, + 0.023150014219912557 + ], + "truth_error": 0.19898263655761914 + }, + "execution_class": "cpu_reference_only", + "monoid": { + "program_checks": 10206, + "program_violations": 0, + "target_maps": 27 + }, + "schema_version": "0.1.0", + "source_note": "No learned weights or LOTUS activations evaluated", + "sparse_intertwining": { + "orthogonal_support_exact": false, + "orthogonal_support_residual": 3.0, + "useful_support_exact": true, + "useful_support_residual": 0.0 + } +} diff --git a/research/algernon/algebraic_machine/sheaf.py b/research/algernon/algebraic_machine/sheaf.py new file mode 100644 index 000000000..f6cc10eac --- /dev/null +++ b/research/algernon/algebraic_machine/sheaf.py @@ -0,0 +1,150 @@ +"""Finite-field cellular sheaf of a cyclic directed machine. + +C^0 = direct sum of vertex vector spaces; C^1 = direct sum of edge spaces. +(delta s)_i = s_(i+1 mod m) - A_i s_i over F_p. +A 1-cochain b has a global affine solution iff b belongs to im(delta). +For a single cycle ker(delta) and coker(delta) have the dimensions of +ker(I-M) and coker(I-M), M=A_(m-1)...A_0. +""" +from __future__ import annotations +from typing import Sequence + +Matrix = list[list[int]] +Vector = list[int] + + +def eye(n: int) -> Matrix: + if n < 1: + raise ValueError("dimension must be positive") + return [[int(i == j) for j in range(n)] for i in range(n)] + + +def matmul(a: Matrix, b: Matrix, p: int) -> Matrix: + if not a or not b or len(a[0]) != len(b) or any(len(row) != len(a[0]) for row in a) or any(len(row) != len(b[0]) for row in b): + raise ValueError("incompatible matrix shapes") + return [[sum(a[i][k] * b[k][j] for k in range(len(b))) % p + for j in range(len(b[0]))] for i in range(len(a))] + + +def matvec(a: Matrix, x: Vector, p: int) -> Vector: + if not a or any(len(row) != len(x) for row in a): + raise ValueError("incompatible dimensions") + return [sum(v * q for v, q in zip(row, x)) % p for row in a] + + +def rref(a: Matrix, p: int): + """Exact Gauss-Jordan elimination for a prime field. Returns RREF and pivot columns.""" + if type(p) is not int or not 2 <= p <= 1009 or any(p % d == 0 for d in range(2, int(p ** .5) + 1)): + raise ValueError("reference solver requires a prime p in [2, 1009]") + if not a or not a[0] or any(len(row) != len(a[0]) for row in a): + raise ValueError("nonempty rectangular matrix required") + t = [[int(x) % p for x in row] for row in a] + row = 0 + pivots = [] + for col in range(len(t[0])): + nz = next((r for r in range(row, len(t)) if t[r][col]), None) + if nz is None: + continue + t[row], t[nz] = t[nz], t[row] + inv = pow(t[row][col], -1, p) + t[row] = [v * inv % p for v in t[row]] + for r in range(len(t)): + if r != row and t[r][col]: + factor = t[r][col] + t[r] = [(u - factor * v) % p for u, v in zip(t[r], t[row])] + pivots.append(col) + row += 1 + if row >= len(t): + break + return t, pivots + + +def rank(a: Matrix, p: int) -> int: + return len(rref(a, p)[1]) + + +def solve(a: Matrix, b: Vector, p: int) -> Vector | None: + """Find any solution of Ax=b, with free variables set to zero.""" + if len(a) != len(b) or not a or not a[0] or any(len(row) != len(a[0]) for row in a): + raise ValueError("bad system size") + n = len(a[0]) + rr, pivots = rref([row + [b[i]] for i, row in enumerate(a)], p) + for row in rr: + if all(v == 0 for v in row[:n]) and row[n] != 0: + return None + x = [0] * n + for i, c in enumerate(pivots): + if c < n: + x[c] = rr[i][n] + return x + + +def _validate_edges(edges: Sequence[Matrix]): + if not edges or not edges[0] or not edges[0][0]: + raise ValueError("edges must be nonempty square matrices") + d = len(edges[0]) + if any(len(a) != d or any(len(row) != d for row in a) for a in edges): + raise ValueError("all edge maps must be d by d") + return d + + +def coboundary(edges: Sequence[Matrix], p: int) -> Matrix: + """Matrix of delta: C^0 -> C^1, for the oriented m-edge cycle.""" + d = _validate_edges(edges) + m = len(edges) + mat = [[0] * (m*d) for _ in range(m*d)] + for e, a in enumerate(edges): + for i in range(d): + mat[e*d+i][((e+1) % m)*d+i] = (mat[e*d+i][((e+1) % m)*d+i] + 1) % p + for j in range(d): + mat[e*d+i][e*d+j] = (mat[e*d+i][e*d+j] - a[i][j]) % p + return mat + + +def monodromy(edges: Sequence[Matrix], p: int) -> Matrix: + d = _validate_edges(edges) + m = eye(d) + for a in edges: + m = matmul(a, m, p) + return m + + +def cycle_cohomology(edges: Sequence[Matrix], p: int): + d = _validate_edges(edges) + delta = coboundary(edges, p) + r = rank(delta, p) + hol = monodromy(edges, p) + minus = [[(int(i == j) - hol[i][j]) % p for j in range(d)] for i in range(d)] + small_rank = rank(minus, p) + result = { + "p": p, "vertices": len(edges), "fiber_dim": d, + "rank_delta": r, + "H0_dimension": len(delta[0]) - r, + "H1_dimension": len(delta) - r, + "rank_identity_minus_monodromy": small_rank, + "ker_identity_minus_monodromy": d - small_rank, + "coker_identity_minus_monodromy": d - small_rank, + } + assert result["H0_dimension"] == result["ker_identity_minus_monodromy"] + assert result["H1_dimension"] == result["coker_identity_minus_monodromy"] + return result + + +def affine_cocycle(edges: Sequence[Matrix], b: Sequence[Vector], p: int): + """Solve local constraints s_(i+1) - A_i s_i=b_i around a full cycle.""" + d = _validate_edges(edges) + if len(b) != len(edges) or any(len(v) != d for v in b): + raise ValueError("bad cocycle length") + mon = monodromy(edges, p) + c = [0] * d + for a, v in zip(edges, b): + c = [(u+v[i]) % p for i,u in enumerate(matvec(a,c,p))] + matrix = [[(int(i == j)-mon[i][j]) % p for j in range(d)] for i in range(d)] + start = solve(matrix, c, p) + if start is None: + return {"solvable": False, "obstruction": c, "states": None} + states = [start] + for a, v in zip(edges, b): + states.append([(u+v[i]) % p for i,u in enumerate(matvec(a,states[-1],p))]) + assert states[-1] == states[0] + return {"solvable": True, "obstruction": c, "states": states[:-1]} diff --git a/research/algernon/algebraic_machine/sparse.py b/research/algernon/algebraic_machine/sparse.py new file mode 100644 index 000000000..be8352091 --- /dev/null +++ b/research/algernon/algebraic_machine/sparse.py @@ -0,0 +1,83 @@ +"""First-order intertwining defects and support-restricted linear repairs. + +Real-valued diagnostic only; independent of Qwen weights. Assumes matrices +represent local Jacobians of a fixed neural-state decoder and transition. +""" +from __future__ import annotations + +import numpy as np + + +def intertwining_defect(P, M, A): + P, M, A = (np.asarray(t, dtype=np.float64) for t in (P, M, A)) + if P.ndim != 2 or M.shape != (P.shape[1], P.shape[1]) or A.shape != (P.shape[0], P.shape[0]): + raise ValueError("expected decoder [s,h], neural [h,h], target [s,s]") + return P @ M - A @ P + + +def sparse_repair(P, M, A, U, atol=1e-9): + """Minimize ||(PM-AP) + (P U)B||_F over B with chosen columns U. + + Returns the optimal B, ΔM=U B, residual and relative defect reduction. + The best possible residual is (I-K K†)D where K=P U and D=PM-AP. + """ + P=np.asarray(P,dtype=np.float64) + U=np.asarray(U,dtype=np.float64) + D=intertwining_defect(P,M,A) + if U.ndim!=2 or U.shape[0]!=P.shape[1]: + raise ValueError("U must be [hidden,rank]") + K=P@U + if U.shape[1]: + B=np.linalg.lstsq(K,-D,rcond=None)[0] + projection=K@np.linalg.pinv(K)@D + else: + B=np.zeros((0,P.shape[1]),dtype=np.float64) + projection=np.zeros_like(D) + delta=U@B + repaired=intertwining_defect(P,np.asarray(M,dtype=np.float64)+delta,A) + theoretical=D-projection + if not np.allclose(repaired,theoretical,atol=atol,rtol=1e-7): + raise ArithmeticError("projected defect differs from direct repair") + original_norm=float(np.linalg.norm(D)) + optimal_norm=float(np.linalg.norm(theoretical)) + return {"B":B,"delta_M":delta,"defect":D,"repaired_defect":repaired, + "optimal_residual_norm":optimal_norm, + "actual_residual_norm":float(np.linalg.norm(repaired)), + "exactly_repairable":bool(optimal_norm<=atol), + "explained_energy_fraction":1-(optimal_norm**2/original_norm**2) if original_norm>0 else 1.0, + "rank_PU":int(np.linalg.matrix_rank(K)) if K.size else 0, + "rank_defect":int(np.linalg.matrix_rank(D))} + + +def step_error_bound(A, qs, initial): + """Numerical certificate for ||q_n-A^n q_0||_1 <= sum ||q_(k+1)-A q_k||_1. + + The nonexpansiveness claim requires a column-stochastic A. Returns the + evaluated bound and terminal deviation; initial truth error is separate. + """ + A=np.asarray(A,dtype=np.float64) + arr=[np.asarray(q,dtype=np.float64) for q in qs] + init=np.asarray(initial,dtype=np.float64) + n=A.shape[0] + if A.shape!=(n,n) or not arr or any(x.shape!=(n,) for x in arr) or init.shape!=(n,): + raise ValueError("bad transition dimensions") + if np.min(A)<-1e-12 or not np.allclose(A.sum(axis=0),1,atol=1e-12): + raise ValueError("bound requires a column-stochastic map") + if any(np.min(x)<-1e-12 or not np.isclose(x.sum(),1) for x in arr): + raise ValueError("states must be probability vectors") + eps=[float(np.linalg.norm(arr[i+1]-A@arr[i],ord=1)) for i in range(len(arr)-1)] + exact=arr[0] + for _ in eps: + exact=A@exact + deviation=float(np.linalg.norm(arr[-1]-exact,ord=1)) + truth=init + for _ in eps: + truth=A@truth + initial_error=float(np.linalg.norm(arr[0]-init,ord=1)) + truth_error=float(np.linalg.norm(arr[-1]-truth,ord=1)) + bound=initial_error+sum(eps) + if truth_error>bound+1e-9 or deviation>sum(eps)+1e-9: + raise ArithmeticError("telescoping error bound violated") + return {"n":len(eps),"one_step_errors":eps,"accumulated_step_bound":sum(eps), + "initial_error":initial_error,"truth_error":truth_error, + "certified_bound":bound,"correct_argmax_guaranteed":bound<1.0} diff --git a/research/algernon/algebraic_machine/tests/test_algebra.py b/research/algernon/algebraic_machine/tests/test_algebra.py new file mode 100644 index 000000000..1131e9109 --- /dev/null +++ b/research/algernon/algebraic_machine/tests/test_algebra.py @@ -0,0 +1,174 @@ +"""Finite, exact and first-order tests for Algernon's circuit-algebra program.""" +import itertools +import random +import unittest + +import numpy as np + +from research.algernon.algebraic_machine.machine import ( + congruence_defects, exhaustive_word_check, lifted_actions, minimal_period, + run_word, semiconjugacy_defects, words, +) +from research.algernon.algebraic_machine.sheaf import ( + affine_cocycle, coboundary, cycle_cohomology, eye, matmul, matvec, + monodromy, rank, solve, +) +from research.algernon.algebraic_machine.sparse import ( + intertwining_defect, sparse_repair, step_error_bound, +) + + +class TestInstructionMonoid(unittest.TestCase): + def test_exhaustive_composition_for_every_three_state_map(self): + maps = list(itertools.product(range(3), repeat=3)) + for t in maps: + actions = (t, (1, 2, 0)) + hidden, pi = lifted_actions(actions, tag_count=2) + self.assertFalse(semiconjugacy_defects(hidden, actions, pi)) + self.assertFalse(congruence_defects(hidden, pi)) + report = exhaustive_word_check(hidden, actions, pi, max_length=5) + self.assertEqual(report['program_checks'], 6 * sum(2 ** k for k in range(6))) + self.assertEqual(report['program_violations'], 0) + + def test_corrupted_hidden_transition_exposed(self): + actions = ((1, 2, 0), (2, 0, 1)) + hidden, pi = lifted_actions(actions) + broken = [list(f) for f in hidden] + broken[0][0] = 0 # semantic state 0 rather than correct state 1 + self.assertIn((0, 0), semiconjugacy_defects(broken, actions, pi)) + self.assertGreater(exhaustive_word_check(broken, actions, pi, 4)['program_violations'], 0) + self.assertTrue(congruence_defects(broken, pi)) + + def test_cycle_period_divisibility(self): + t = (1, 2, 3, 4, 0) + f, pi = lifted_actions((t,), tag_count=2) + self.assertEqual(minimal_period(t, 0), 5) + self.assertEqual(minimal_period(f[0], 0), 10) + self.assertEqual(minimal_period(f[0], 0) % minimal_period(t, pi[0]), 0) + self.assertNotEqual(minimal_period(t, 0) % 2, 0) + + def test_bad_word(self): + with self.assertRaises(ValueError): + run_word([(1, 0)], [1], 0) + with self.assertRaises(ValueError): + list(words(2, -1)) + + +class TestCyclicSheaf(unittest.TestCase): + def test_three_edge_affine_obstruction_mod_five(self): + edges = [[[1]] for _ in range(3)] + c = cycle_cohomology(edges, 5) + self.assertEqual(c['H0_dimension'], 1) + self.assertEqual(c['H1_dimension'], 1) + no = affine_cocycle(edges, [[1], [1], [1]], 5) + self.assertFalse(no['solvable']) + self.assertEqual(no['obstruction'], [3]) + yes = affine_cocycle(edges, [[1], [1], [3]], 5) + self.assertTrue(yes['solvable']) + self.assertEqual(len(yes['states']), 3) + + def test_twisted_cycle_has_vanishing_cohomology(self): + c = cycle_cohomology([[[1]], [[1]], [[2]]], 5) + self.assertEqual((c['H0_dimension'], c['H1_dimension']), (0, 0)) + self.assertTrue(affine_cocycle([[[1]], [[1]], [[2]]], [[1], [1], [1]], 5)['solvable']) + + def test_square_rank_and_monodromy_exhaustive_small(self): + for p in (2, 3, 5, 7): + for a, b, c in itertools.product(range(p), repeat=3): + edges = [[[a]], [[b]], [[c]]] + rep = cycle_cohomology(edges, p) + self.assertEqual(rep['H0_dimension'], int((a*b*c) % p == 1)) + self.assertEqual(rep['H1_dimension'], rep['H0_dimension']) + + def test_two_dimensional_random_monodromy(self): + rng = random.Random(20261104) + for p in (5, 7): + for _ in range(100): + edges = [[[rng.randrange(p) for _ in range(2)] for _ in range(2)] for _ in range(4)] + rep = cycle_cohomology(edges, p) + self.assertEqual(rep['H0_dimension'], 2 - rep['rank_identity_minus_monodromy']) + b = [[rng.randrange(p) for _ in range(2)] for _ in edges] + sol = affine_cocycle(edges, b, p) + if sol['solvable']: + states = sol['states'] + for i, a in enumerate(edges): + actual = matvec(a, states[i], p) + expected = [(v + b[i][j]) % p for j, v in enumerate(actual)] + self.assertEqual(states[(i+1) % len(edges)], expected) + + def test_gauge_invariance(self): + p = 7 + g = [[0, 1], [1, 1]] + gi = [[6, 1], [1, 0]] # g @ gi = I mod 7 + self.assertEqual(matmul(g, gi, p), eye(2)) + edges = [[[1, 2], [3, 0]], [[0, 1], [2, 1]], [[2, 1], [1, 1]]] + shifted = [matmul(g, matmul(a, gi, p), p) for a in edges] + self.assertEqual(cycle_cohomology(edges, p)['H0_dimension'], + cycle_cohomology(shifted, p)['H0_dimension']) + self.assertEqual(cycle_cohomology(edges, p)['H1_dimension'], + cycle_cohomology(shifted, p)['H1_dimension']) + self.assertEqual(monodromy(shifted, p), matmul(g, matmul(monodromy(edges, p), gi, p), p)) + + def test_single_self_loop(self): + self.assertEqual(coboundary([[[1]]], 5), [[0]]) + self.assertEqual(coboundary([[[2]]], 5), [[4]]) + + def test_unsolvable_linear_system(self): + self.assertIsNone(solve([[0]], [1], 5)) + self.assertEqual(rank([[1, 0], [0, 1]], 5), 2) + + +class TestSparseIntertwining(unittest.TestCase): + def test_exact_support_repair(self): + P = np.eye(3) + A = np.eye(3) + M = A.copy() + M[0, 2] = 3.0 + U = np.array([[1.0], [0.0], [0.0]]) + rep = sparse_repair(P, M, A, U) + self.assertTrue(rep['exactly_repairable']) + self.assertLess(rep['actual_residual_norm'], 1e-9) + self.assertEqual(rep['rank_PU'], 1) + self.assertAlmostEqual(rep['explained_energy_fraction'], 1.0) + + def test_orthogonal_support_cannot_repair(self): + P = np.eye(3) + A = np.eye(3) + M = A.copy() + M[0, 2] = 3.0 + U = np.array([[0.0], [1.0], [0.0]]) + rep = sparse_repair(P, M, A, U) + self.assertFalse(rep['exactly_repairable']) + self.assertAlmostEqual(rep['optimal_residual_norm'], 3.0) + self.assertAlmostEqual(rep['explained_energy_fraction'], 0.0) + + def test_rank_zero_site_and_dimensions(self): + P=np.array([[1.0, 0.0]]) + M=np.eye(2) + A=np.eye(1) + U=np.zeros((2,0)) + rep=sparse_repair(P,M,A,U) + self.assertTrue(rep['exactly_repairable']) + with self.assertRaises(ValueError): + intertwining_defect(P,np.eye(3),A) + + def test_error_bound(self): + A = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]],dtype=float) + q=np.array([1., 0., 0.]) + states=[q] + for _ in range(8): + q = 0.98 * A@q + 0.02 * np.ones(3)/3 + states.append(q) + rep = step_error_bound(A, states, np.array([1., 0., 0.])) + self.assertEqual(rep['n'], 8) + self.assertGreater(rep['truth_error'], 0) + self.assertLessEqual(rep['truth_error'], rep['certified_bound']+1e-10) + self.assertTrue(rep['correct_argmax_guaranteed']) + + def test_nonstochastic_rejected(self): + with self.assertRaises(ValueError): + step_error_bound(np.array([[2.0]]), [np.array([1.0])], np.array([1.0])) + + +if __name__ == '__main__': + unittest.main() From 895957eade040d5586fd40b292bb95d09ae10a61 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 12:36:11 +0800 Subject: [PATCH 2/6] Add standalone Lean Lake manifest for kernel CI --- .../algernon/algebraic_machine/lean/lake-manifest.json | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 research/algernon/algebraic_machine/lean/lake-manifest.json diff --git a/research/algernon/algebraic_machine/lean/lake-manifest.json b/research/algernon/algebraic_machine/lean/lake-manifest.json new file mode 100644 index 000000000..a697e0824 --- /dev/null +++ b/research/algernon/algebraic_machine/lean/lake-manifest.json @@ -0,0 +1,8 @@ +{ + "version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "algernon_algebra", + "lakeDir": ".lake", + "fixedToolchain": false +} From 945b38713f52c605cc583f527f0af9b019da8b9b Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 12:37:07 +0800 Subject: [PATCH 3/6] Fix Lean reserved Sigma binder in instruction-word proof --- .../algebraic_machine/lean/Algernon/Semiconjugacy.lean | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean b/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean index 50b98553c..5223a569f 100644 --- a/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean +++ b/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean @@ -52,16 +52,16 @@ theorem latent_period_projects {H : Type u} {S : Type v} _ = π h := congrArg π periodic /-- A finite instruction word is executed left-to-right. -/ -def execute {Σ : Type w} {H : Type u} - (act : Σ → H → H) : List Σ → H → H +def execute {Instr : Type w} {H : Type u} + (act : Instr → H → H) : List Instr → H → H | [], h => h | a :: rest, h => execute act rest (act a h) /-- Generator-level semiconjugacy extends to *every instruction word*. -/ -theorem instruction_word_semiconjugacy {Σ : Type w} {H : Type u} {S : Type v} - (F : Σ → H → H) (T : Σ → S → S) (π : H → S) +theorem instruction_word_semiconjugacy {Instr : Type w} {H : Type u} {S : Type v} + (F : Instr → H → H) (T : Instr → S → S) (π : H → S) (commutes : ∀ a h, π (F a h) = T a (π h)) - (word : List Σ) (h : H) : + (word : List Instr) (h : H) : π (execute F word h) = execute T word (π h) := by induction word generalizing h with | nil => rfl From c609655b117131a0b281cdd18510e761e5f5fd5a Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 12:37:34 +0800 Subject: [PATCH 4/6] Link Algernon's algebraic-machine formalization from research index --- research/algernon/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/research/algernon/README.md b/research/algernon/README.md index b82cb186d..3fa514d35 100644 --- a/research/algernon/README.md +++ b/research/algernon/README.md @@ -2,6 +2,8 @@ **Algernon-02 executable experiment:** [Circuit Mirror](circuit_mirror/README.md) combines a typed pointer-machine transition, an exact BN254 R1CS-style checker, generated Circom source, a tiny trained recurrent readout, and retained CPU-only experiment receipts. [Experimental falsification criteria](circuit_mirror/EXPERIMENT.md). +**Algebraic machine:** [Executable mathematics and Lean proofs](algebraic_machine/README.md) cover instruction-monoid semiconjugacy, twisted-cycle sheaf obstructions, sparse intertwining repair, and recurrent depth-error bounds; [derivations](algebraic_machine/THEOREMS.md). + > **2026-11-03 execution pivot:** Start from reproducible external implementations. Legacy LoopedTransformers checkpoint recovery is archived and optional. See [PIVOT_EXTERNAL_BASELINES.md](PIVOT_EXTERNAL_BASELINES.md) for the active priorities: training-free Qwen3 recurrence, independently tested latent recurrence, Qwenputer and sparse repair. **Status: research scaffold, 2026-11-03.** This folder specifies a proposed experiment. It does not claim a working Qwen graft, a trained recurrent processor, or an independently reproduced weight edit. From 261c7a9824b2a29cce3824d2becb61d73b7042a2 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 12:39:28 +0800 Subject: [PATCH 5/6] Prove cyclic monodromy closure and reconstruction in Lean --- .../lean/Algernon/Semiconjugacy.lean | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean b/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean index 5223a569f..c0e83458c 100644 --- a/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean +++ b/research/algernon/algebraic_machine/lean/Algernon/Semiconjugacy.lean @@ -51,6 +51,24 @@ theorem latent_period_projects {H : Type u} {S : Type v} (semiconjugacy_iterate F T π commutes m h).symm _ = π h := congrArg π periodic +/-- A consistent three-edge trajectory is a fixed point of its monodromy. -/ +theorem three_cycle_closes {S : Type u} + (A₀ A₁ A₂ : S → S) (s₀ s₁ s₂ : S) + (h₀ : s₁ = A₀ s₀) (h₁ : s₂ = A₁ s₁) + (h₂ : s₀ = A₂ s₂) : + s₀ = A₂ (A₁ (A₀ s₀)) := by + calc + s₀ = A₂ s₂ := h₂ + _ = A₂ (A₁ s₁) := congrArg A₂ h₁ + _ = A₂ (A₁ (A₀ s₀)) := congrArg (fun x => A₂ (A₁ x)) h₀ + +/-- Conversely a monodromy fixed point determines a consistent three-edge trace. -/ +theorem monodromy_fixed_yields_three_cycle {S : Type u} + (A₀ A₁ A₂ : S → S) (s₀ : S) + (h : s₀ = A₂ (A₁ (A₀ s₀))) : + ∃ s₁ s₂, s₁ = A₀ s₀ ∧ s₂ = A₁ s₁ ∧ s₀ = A₂ s₂ := by + exact ⟨A₀ s₀, A₁ (A₀ s₀), rfl, rfl, h⟩ + /-- A finite instruction word is executed left-to-right. -/ def execute {Instr : Type w} {H : Type u} (act : Instr → H → H) : List Instr → H → H @@ -104,5 +122,7 @@ theorem invariant_semiconjugacy {H : Type u} {S : Type v} #print axioms instruction_word_semiconjugacy #print axioms latent_period_projects #print axioms invariant_semiconjugacy +#print axioms three_cycle_closes +#print axioms monodromy_fixed_yields_three_cycle end AlgernonAlgebra From 6dd846418fdcbb9c945422ae932dbe7aaeba314e Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Wed, 4 Nov 2026 12:39:43 +0800 Subject: [PATCH 6/6] Document Lean monodromy fixed-point formalization --- research/algernon/algebraic_machine/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/research/algernon/algebraic_machine/README.md b/research/algernon/algebraic_machine/README.md index 5ce64b123..91818578e 100644 --- a/research/algernon/algebraic_machine/README.md +++ b/research/algernon/algebraic_machine/README.md @@ -21,7 +21,7 @@ Mathematical roles: For each instruction `a`, let `Fₐ : H → H` be the hidden machine and `Tₐ : S → S` its exact semantics. A decoder π should obey `π ∘ Fₐ = Tₐ ∘ π` on every *reachable* hidden state. -By induction on word length, the property extends to every program composed from those instructions. This is a **semiconjugacy** (a factor map when π is surjective); injectivity and complete state reconstruction are extra conditions. The kernel proof in `Semiconjugacy.lean` includes word compositionality, quotient congruence, invariant-subset iteration, and semantic periodic returns. It assumes the generator property; finite training examples alone do not prove it. +By induction on word length, the property extends to every program composed from those instructions. This is a **semiconjugacy** (a factor map when π is surjective); injectivity and complete state reconstruction are extra conditions. The kernel proof in `Semiconjugacy.lean` includes word compositionality, quotient congruence, invariant-subset iteration, semantic periodic returns, and a three-edge cycle's equivalence with a fixed point of its monodromy. It assumes the generator property; finite training examples alone do not prove it. `machine.py` exhaustively checks 27 deterministic three-state transitions lifted to six explicitly constructed hidden states and all words over two instructions of length 0–5. Corrupting one hidden transition creates a measurable defect. The finite tests are controls for a future learned neural decoder.