Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions .github/workflows/algernon-algebraic-machine.yml
Original file line number Diff line number Diff line change
@@ -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:
Comment on lines +15 to +39
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
Comment on lines +40 to +53
2 changes: 2 additions & 0 deletions research/algernon/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
90 changes: 90 additions & 0 deletions research/algernon/algebraic_machine/README.md
Original file line number Diff line number Diff line change
@@ -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, 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.

**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.
64 changes: 64 additions & 0 deletions research/algernon/algebraic_machine/THEOREMS.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions research/algernon/algebraic_machine/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Algernon algebraic machine: reference semantics, topology and repair tests."""
71 changes: 71 additions & 0 deletions research/algernon/algebraic_machine/experiments.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 1 addition & 0 deletions research/algernon/algebraic_machine/lean/Algernon.lean
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import Algernon.Semiconjugacy
Loading
Loading