Skip to main content

O(1) memory for infinite context โ€” drop-in Transformer replacement with holographic toroidal attention

Project description

๐Ÿง  Engram

Persistent Systolic Continuous State Engine

O(1) Memory for Infinite Context โ€” Drop-In Transformer Replacement

Stop passing tokens. Start sharing consciousness.

License: Research Use Python 3.10+ PyTorch 2.0+ Patent Pending


The Problem

Every LLM today is trapped behind two walls:

  1. The Memory Wall. A 1M-token context requires $O(N)$ KV-Cache memory. A single H100 allocates 40+ GB of VRAM just to remember a conversation. At 500K tokens, it crashes.

  2. The Forgetting Wall. State-space models (Mamba, RWKV) compress context to $O(1)$, but they can't recall a specific API key buried 100K tokens deep. They forget.

Engram solves both. It replaces sparse Attention with a dual-memory architecture inspired by the 2D bivariate torus topology used in Quantum Error Correction:

Component Role Behavior
Liquid Torus Working memory $O(1)$ IIR fluid state โ€” handles syntax and recent context
Crystalline Engram Long-term memory $O(1)$ Hebbian weight matrix โ€” permanently etches facts
Holographic Recall Retrieval Resonance query โ€” only matching memories amplify

The result: 0.83 recall at 10K tokens on 1 MB of fixed memory. No KV cache. No vector database. No forgetting.


Benchmarks (RTX 4060 8GB)

Needle-in-a-Haystack: 10,000-Token Recall

Memory Architecture Recall @ 10K Memory Scaling
Standard Attention (KV Cache) 1.000 10,001 KB ๐Ÿ’ฅ $O(N)$ โ€” OOM
Liquid Torus Only (SSM) ~0.000 4 KB $O(1)$ โ€” amnesia
Engram Systolic Engram > 0.83 1,028 KB ๐Ÿš€ $O(1)$ โ€” permanent

10x less memory at 10K tokens. 10,000x less at 1M tokens. The model learns the document the first time it reads it.

Needle Recall Benchmark

The Von Neumann Memory Wall

A standard transformer's KV cache crashes a $40,000 H100 at 500K tokens. Engram runs to 1,000,000+ tokens on an $800 laptop GPU at constant 0.2 GB.

Memory Wall Benchmark


Architecture

Engram Architecture

How it works:

  1. Liquid Torus (Working Memory): Tokens are spatially convoluted across a fixed $O(1)$ 2D toroidal grid via systolic shift kernels. Immediate syntactic context is maintained through IIR temporal inertia. Memory never grows.

  2. Systolic Engram (Long-Term Memory): As tokens flow through the torus, a continuous Hebbian outer product etches their high-dimensional signature into a fixed-size weight matrix. Top-K sparse orthogonalization (10% peaks) + Oja's leaky decay prevent crosstalk.

  3. Holographic Resonance (Recall): The query torus state acts as a holographic laser. Due to high-dimensional orthogonality, irrelevant tokens destructively cancel. Only the matching memory constructively resonates.

  4. Reward-Modulated Etching: The Hebbian update is scaled by a reward signal โ€” enabling zero-shot forward-pass RL without backpropagation:

    W_engram += (reward ร— ฮท) ยท (token โŠ— sparse_torus_state)
    

Quick Start

pip install engram

Or from source:

git clone https://github.com/justinarndt/Engram.git
cd Engram
pip install -e .          # Core + CLI
pip install -e ".[all]"   # + FastAPI server + HuggingFace
engram --help
engram info                        # Architecture & memory report

# Demos
engram run swarm                   # Multi-agent weight sharing
engram run kung-fu                 # Zero-shot skill transfer
engram run lobotomy                # Transformer attention replacement
engram run cartridge               # Knowledge Cartridge save/load
engram run recall                  # Needle-in-a-haystack benchmark
engram run memory-wall             # The OOM benchmark

# Knowledge Cartridges
engram save my_codebase.cart        # Save engram to portable file
engram inspect my_codebase.cart     # View metadata
engram inject my_codebase.cart      # Load on any machine, <1ms

# OpenAI-compatible server
engram serve                        # Launch on port 8000

Docker Compose (Instant UI)

Get a full ChatGPT-like interface backed by the Engram engine:

docker compose up -d
# Open http://localhost:3000 for the chat UI
# Open http://localhost:8000/docs for the API docs

This spins up the FastAPI backend + Open-WebUI frontend. All chat sessions share a single Engram matrix in memory.

Use in 5 Lines

from engram import HolographicLM
import torch

model = HolographicLM().cuda()
input_ids = torch.randint(0, 50257, (1, 512)).cuda()
output = model(input_ids)
print(f"Logits: {output['logits'].shape}")  # [1, 512, 50257]

HuggingFace Integration

from engram import AutoHolographicModel, HolographicConfig

config = HolographicConfig(d_model=512, n_layers=6)
model = AutoHolographicModel(config).cuda()

# Standard HF interface โ€” works with Trainer, pipeline, etc.
outputs = model(input_ids=ids, labels=labels)
print(outputs.logits.shape)       # [B, T, 50257]
print(outputs.loss)               # Cross-entropy loss
print(outputs.past_key_values)    # None โ€” no KV cache

Swarm-Chat Server

engram serve --port 8000

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "engram-hive", "messages": [{"role": "user", "content": "Hello"}]}'

curl http://localhost:8000/v1/engram/status

Systolic Engram in 10 Lines

from engram import SystolicEngramCache

engram = SystolicEngramCache(d_model=512, channels=8, grid_l=64, grid_m=64).cuda()
print(engram)  # O(1) memory breakdown

token_emb = torch.randn(1, 8 * 64 * 64, device="cuda")
output = engram(token_emb, reward=1.0)

# output["liquid"]   โ€” fluid working memory (syntax)
# output["engram"]   โ€” crystalline fact recall (permanent)
# output["combined"] โ€” the full readout

What Engram Enables

Multi-Agent Weight Sharing

Standard multi-agent systems (AutoGen, CrewAI) share knowledge by serializing state to JSON strings and injecting them into each other's prompts. This blows up context limits.

Engram agents share the exact same Engram matrix in VRAM. Agent A etches a fact, Agent B recalls it via tensor resonance. Zero JSON. Zero latency.

engram run swarm
Metric KV-Cache Agents Engram
2 agents, 10K tokens each 20,002 KB 8,622 KB
1,000 agents, 10K tokens each 10.2 GB (OOM) 24.6 MB
Knowledge sharing JSON serialization Tensor resonance

Zero-Shot Forward-Pass RL

The Engram supports reward-modulated etching โ€” no gradient descent, no backpropagation:

  • reward > 0 โ†’ Strengthen (constructive etch)
  • reward < 0 โ†’ Anti-etch (suppress failed actions)
  • reward = 0 โ†’ Pure inference
engram run kung-fu

Agent 0 tries 5 API actions, fails 3 times (reward=-1.0), succeeds once (reward=+2.0). Agent 4, with a blank context, instantly knows the correct action via policy resonance.


Knowledge Cartridges

Your entire context compressed into a portable .cart file. Save it, share it, load it in under 1ms.

engram run cartridge

Uses safetensors โ€” fast, safe, no pickle. Upload a .cart to Discord. Any agent with the same architecture loads it and instantly possesses the accumulated knowledge.


Drop-In Transformer Grafting

Load any pre-trained Transformer, remove nn.MultiheadAttention, graft the O(1) Engram in its place, retain all FFN weights. Run a cheap LoRA fine-tune to adapt.

engram run lobotomy
Context Length Standard Attention Engram Engram
1,000 tokens 2.0 MB 4.1 KB
10,000 tokens 20.5 MB 4.1 KB
100,000 tokens 204.8 MB 4.1 KB
1,000,000 tokens 2,048 MB 4.1 KB

Repository Structure

Engram/
โ”œโ”€โ”€ src/engram/                      # Core engine
โ”‚   โ”œโ”€โ”€ torus.py                    # O(1) toroidal state
โ”‚   โ”œโ”€โ”€ attention.py                # Holographic attention (MHA replacement)
โ”‚   โ”œโ”€โ”€ model.py                    # HolographicLM language model
โ”‚   โ”œโ”€โ”€ engram.py                   # Systolic Engram Cache
โ”‚   โ”œโ”€โ”€ cartridge.py                # .cart format (safetensors)
โ”‚   โ””โ”€โ”€ auto_model.py               # HuggingFace PreTrainedModel wrapper
โ”œโ”€โ”€ cli/                            # Typer/Rich CLI
โ”‚   โ””โ”€โ”€ main.py                     # engram run / save / inject / inspect / serve
โ”œโ”€โ”€ server/                         # FastAPI backend
โ”‚   โ””โ”€โ”€ swarm_chat.py               # OpenAI-compatible API
โ”œโ”€โ”€ benchmarks/
โ”‚   โ”œโ”€โ”€ memory_wall.py              # OOM benchmark
โ”‚   โ”œโ”€โ”€ long_context_recall.py      # Needle-in-a-haystack
โ”‚   โ”œโ”€โ”€ hybrid_inference.py         # GPT-2 + holographic adapter
โ”‚   โ””โ”€โ”€ perplexity.py               # Perplexity benchmark
โ”œโ”€โ”€ demo/
โ”‚   โ”œโ”€โ”€ hive_mind.py                # Multi-agent weight sharing
โ”‚   โ”œโ”€โ”€ swarm_rl.py                 # Zero-shot RL
โ”‚   โ”œโ”€โ”€ knowledge_cartridge.py      # Cartridge save/load
โ”‚   โ”œโ”€โ”€ lobotomy.py                 # Transformer grafting
โ”‚   โ””โ”€โ”€ generate.py                 # Text generation
โ”œโ”€โ”€ train/
โ”‚   โ””โ”€โ”€ train_holographic_lm.py     # Training script
โ”œโ”€โ”€ Dockerfile                      # Container image
โ”œโ”€โ”€ docker-compose.yml              # Engine + Open-WebUI
โ”œโ”€โ”€ demo.tape                       # VHS terminal recording script
โ”œโ”€โ”€ pyproject.toml                  # Package config
โ”œโ”€โ”€ plots/                          # Benchmark plots
โ””โ”€โ”€ LICENSE.md

Hardware

Configuration Hardware Notes
โœ… Development Any CUDA GPU RTX 3060+ recommended
โœ… Benchmarked RTX 4060 Laptop (8GB) All results in this repo
โœ… Training RTX 4060+ ~30min for 30M param model
โœ… Full suite H100 / TPU v5e For paper-grade results

Citation

@software{arndt2026engram,
  author    = {Arndt, Justin},
  title     = {{Engram}: Persistent Systolic Continuous State Engine},
  year      = {2026},
  url       = {https://github.com/justinarndt/Engram},
  note      = {O(1) holographic memory with Hebbian crystalline recall}
}

License

Research & Academic Use License

โœ… Academic research, publication, experimentation ยท โŒ Commercial use requires separate license

Patent Notice

The Engram architecture is the subject of U.S. Provisional Patent Application No. 63/989,566, filed February 24, 2026.


Contact

Justin Arndt ยท ๐Ÿ“ง justinarndt05@gmail.com

For commercial licensing, partnership, or research collaboration.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

engram_engine-0.1.0.tar.gz (30.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

engram_engine-0.1.0-py3-none-any.whl (32.3 kB view details)

Uploaded Python 3

File details

Details for the file engram_engine-0.1.0.tar.gz.

File metadata

  • Download URL: engram_engine-0.1.0.tar.gz
  • Upload date:
  • Size: 30.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for engram_engine-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9ba60c6c6ef527b085f25ef26d699ddcfbd0f103fc9fa19ba421c4ecad94874e
MD5 e1ce29466ba7c70fdfef9db91892e95e
BLAKE2b-256 32a97239ff338148b578f6cd3f05359ccc47840ba028397543e175690702894e

See more details on using hashes here.

File details

Details for the file engram_engine-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: engram_engine-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 32.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for engram_engine-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1257242f39f2a5253fbd6f3e906c6a9adad608438757546a3c12280107391883
MD5 6326c2b6a47464a5b256a8fd5c33ef37
BLAKE2b-256 f043452204c4274ad11cd4d1935629a1664b803eaab19d92e9e4180161242e7d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page