Harry00's picture
docs: comprehensive README with architecture, benchmarks, and examples
51b2aff verified
# MLE β€” Morpho-Logic Engine
> **A novel energy-based reasoning AI architecture, CPU-native, gradient-free, built on hyperdimensional computing.**
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Tests: 7/7](https://img.shields.io/badge/tests-7%2F7%20passing-brightgreen.svg)]()
```
β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—
β–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β•β•β•
β–ˆβ–ˆβ•”β–ˆβ–ˆβ–ˆβ–ˆβ•”β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— Morpho-Logic Engine v0.1.0
β–ˆβ–ˆβ•‘β•šβ–ˆβ–ˆβ•”β•β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ•”β•β•β• Energy-Based Reasoning AI
β–ˆβ–ˆβ•‘ β•šβ•β• β–ˆβ–ˆβ•‘ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—
β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β•β•β•šβ•β•β•β•β•β•β•
```
---
## 🧠 What is MLE?
MLE is a **new class of reasoning engine** that replaces neural network backpropagation with energy-based dynamics operating on hyperdimensional binary vectors. It draws from:
- **Kanerva's Sparse Distributed Memory** β€” memory indexed by proximity in Hamming space
- **Holographic Reduced Representations** (Plate 1995) β€” circular convolution for semantic binding
- **Modern Hopfield Networks** (Ramsauer et al. 2020) β€” energy-based pattern completion
- **Binary Spatter Codes** β€” ultra-fast XOR binding for CPU-native computation
The result is a system that can reason about concepts, solve analogies, compose meanings, and traverse knowledge graphs β€” all **without GPU, without gradients, without training** β€” using pure bitwise operations optimized for CPU SIMD instructions.
---
## πŸ—οΈ Architecture
```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Query │───▢│ Routing │───▢│ Binding │───▢│ Energy β”‚
β”‚ Encoder β”‚ β”‚ (JIT Beam) β”‚ β”‚ (Compose) β”‚ β”‚ (Relax) β”‚
β”‚ β”‚ β”‚ Top-500 β”‚ β”‚ XOR / FFT β”‚ β”‚ Hopfield + β”‚
│ str→4096b │ │ LSH+Expand │ │ Conv Circ. │ │ Bit-flip │
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
└───────────│ Response │◀───│ Decode β”‚β—€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”‚ β”‚ β”‚ NN + Role β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```
### 5 Modules
| Module | File | Description |
|--------|------|-------------|
| **`memory`** | `sparse_address_table.py` | Sparse Address Table: 4096-bit binary vectors, SoA layout, LSH index (32 tables Γ— 8-bit signatures), multi-probe search, activation tracking |
| **`routing`** | `recursive_jit_router.py` | Recursive JIT Routing: LSH init β†’ beam-500 refinement β†’ neighbor expansion β†’ convergence check. Multi-hop chaining for chain-of-thought |
| **`binding`** | `semantic_binding.py` | Dual binding: **Binary (XOR)** O(N/64) exact recovery + **HRR (FFT)** O(N log N) approximate. Triple encoding, analogy queries, sequence binding via permutation |
| **`energy`** | `energy_model.py` | Composite energy: compatibility + binding coherence + sparsity + smoothness. **Hopfield** (continuous, attention-based) + **Binary relaxation** (simulated annealing). Hybrid mode for best results |
| **`inference`** | `reasoning_engine.py` | Full pipeline: encode β†’ route β†’ bind β†’ relax β†’ decode. Association, analogy, composition, structured queries. Multi-step reasoning with convergence detection |
### SIMD-Optimized Core (`utils/simd_ops.py`)
All core operations are backed by a **GCC-compiled C library** with `-march=native` for automatic SIMD vectorization:
```c
// Compiles to AVX-512 VPOPCNTQ or AVX2 POPCNT automatically
int hamming_single(const uint64_t *a, const uint64_t *b, int n) {
int cnt = 0;
for (int i = 0; i < n; i++)
cnt += __builtin_popcountll(a[i] ^ b[i]);
return cnt;
}
```
| Operation | Throughput | Notes |
|-----------|-----------|-------|
| Hamming distance (single) | ~100M ops/s | 64 Γ— `POPCNT` per pair |
| Hamming batch (100K vectors) | 25-41M vecs/s | Vectorized XOR + popcount |
| Top-500 selection | O(N log K) | Max-heap in C |
| Binary bind (XOR) | ~95K ops/s | 64 Γ— `XOR` per op |
| HRR bind (FFT) | ~10K ops/s | `numpy.fft.rfft` |
**Fallback**: Pure NumPy LUT-based popcount when GCC isn't available β€” portable across all platforms.
---
## πŸ“ Core Concepts
### 4096-bit Binary Vectors
Every concept, relation, and memory address is a **4096-bit binary vector** stored as 64 Γ— `uint64` words (512 bytes):
```python
# Each vector: 4096 bits = 512 bytes = 64 Γ— uint64
# Storage layout: Structure of Arrays (SoA) for cache locality
# addresses: (N, 64) uint64 β€” contiguous, cache-aligned
# contents: (N, 64) uint64 β€” separate for SIMD batch ops
```
**Key property**: Random vectors have Hamming distance β‰ˆ 2048 (50%). Semantic similarity is encoded as deviation from this baseline. Vectors with distance << 2048 are "similar"; vectors at ~2048 are orthogonal.
### Sparse Address Table
Memory entries are indexed by binary vectors. Access uses **Hamming distance** as the proximity metric:
```python
from mle import SparseAddressTable
sat = SparseAddressTable(capacity=100_000)
sat.store(address_vec, content_vec, metadata={'name': 'cat'})
results = sat.query_nearest(query_vec, k=10) # [(index, distance), ...]
```
**LSH Index**: 32 hash tables with 8-bit random-bit-sampling signatures. Multi-probe search (1-bit and 2-bit flips) for high recall. Sub-linear search time for large memories.
### Binding Operations
**Binary (XOR)**: `bind(A, B) = A βŠ• B`. Self-inverse (exact recovery), quasi-orthogonal to inputs, O(N/64).
**HRR (FFT)**: `bind(A, B) = IFFT(FFT(A) Β· FFT(B))`. Circular convolution, approximate recovery, similarity-preserving, O(N log N).
```python
from mle.binding import BinaryBinding
# Encode: "king IS_A man"
triple = BinaryBinding.encode_triple(king_vec, is_a_vec, man_vec)
# Decode: recover man from triple
decoded = BinaryBinding.unbind(BinaryBinding.unbind(triple, king_vec), is_a_vec)
# decoded == man_vec (exact with XOR!)
# Analogy: king:man :: queen:?
query = BinaryBinding.create_analogy_query(king_vec, man_vec, queen_vec)
# query β‰ˆ woman_vec (find nearest in codebook)
```
### Energy-Based Reasoning
**No backpropagation. No gradients stored.** Reasoning is energy minimization:
```
E(state) = α·E_compat + β·E_binding + γ·E_sparse + δ·E_smooth
```
| Component | Formula | Purpose |
|-----------|---------|---------|
| Compatibility | -Ξ£ wα΅’ Β· sim(state, contextα΅’) | State agrees with activated memories |
| Binding coherence | Ξ£ hamming(unbind(bα΅’, rα΅’), fα΅’) / N | Stored relations remain intact |
| Sparsity | β€–activations‖₁ | Focused, not diffuse, activation |
| Smoothness | hamming(current, previous) / N | Stable reasoning trajectory |
**Two-phase minimization**:
1. **Hopfield update**: `ΞΎ_new = X @ softmax(Ξ² Β· X^T @ ΞΎ)` β€” fast coarse convergence via attention over patterns
2. **Binary relaxation**: bit-flip search with simulated annealing β€” fine discrete refinement
---
## πŸš€ Quick Start
```python
from mle import MorphoLogicEngine
# Initialize
engine = MorphoLogicEngine(beam_width=500, energy_mode='hybrid')
# Build knowledge
engine.add_concept("cat")
engine.add_concept("dog")
engine.add_concept("animal")
engine.add_relation("cat", "is_a", "animal")
engine.add_relation("dog", "is_a", "animal")
# Reason
result = engine.reason("cat", max_steps=3)
print(result['response']['nearest_concepts'])
# β†’ [('cat', 0.99), ('animal', 0.75), ...]
# Associations
assocs = engine.associate("cat", top_k=5)
# β†’ [('cat_is_a_animal', 0.74), ('dog', 0.52), ...]
# Analogy: king:man :: queen:?
analogy = engine.solve_analogy("king", "man", "queen")
print(analogy['codebook_ranking'][:3])
# Composition: water + animal β†’ ?
comp = engine.compose("water", "animal")
print(comp['response']['nearest_concepts'][:3])
```
---
## πŸ“Š Benchmarks
Measured on a 2-vCPU machine (cpu-basic), single-threaded:
### SIMD Throughput
| Corpus Size | Batch Hamming | Top-500 |
|-------------|--------------|---------|
| 1,000 | 0.04ms (28M/s) | 0.06ms |
| 10,000 | 0.29ms (35M/s) | 0.32ms |
| 100,000 | 4.56ms (22M/s) | 4.79ms |
### Routing Latency
| Memory Size | Avg Latency | P99 | Candidates |
|-------------|-------------|-----|------------|
| 1,000 | 3.8ms | 5.4ms | 953 |
| 10,000 | 2.5ms | 3.2ms | 3,335 |
| 50,000 | 2.7ms | 3.5ms | 2,679 |
### Memory Efficiency
- **1,024 bytes/entry** (512 address + 512 content)
- **1,000 entries = 1 MB**
- **100,000 entries = 100 MB**
### Binding Performance
- Binary (XOR): **95,000 ops/sec**
- HRR (FFT): **10,500 ops/sec**
---
## πŸ§ͺ Tests
```bash
pip install numpy scipy
python -m mle.tests.test_full_system
```
**7/7 test groups passing:**
- βœ… SIMD Operations (correctness + performance)
- βœ… Memory & LSH (storage, retrieval, 100% cluster recall)
- βœ… Routing (beam width, convergence, scalability)
- βœ… Binding (XOR exact recovery, HRR approximate recovery, triple encoding)
- βœ… Energy Convergence (monotonic decrease, Hopfield attention concentration)
- βœ… Reasoning (association, query, analogy, composition, structured queries)
- βœ… Integration (500+ concept KB, batch queries, memory efficiency)
---
## 🎯 Demo
```bash
python -m mle.demo
```
Runs a full demonstration with 40+ concepts, 42 relations, and tests for concept queries, associations, analogies, compositions, structured queries, and multi-step reasoning.
---
## πŸ“ Project Structure
```
mle/
β”œβ”€β”€ __init__.py # Package init, public API
β”œβ”€β”€ demo.py # Interactive demonstration
β”œβ”€β”€ utils/
β”‚ β”œβ”€β”€ __init__.py
β”‚ └── simd_ops.py # SIMD C library + NumPy fallback
β”œβ”€β”€ memory/
β”‚ β”œβ”€β”€ __init__.py
β”‚ └── sparse_address_table.py # SparseAddressTable + HammingLSH
β”œβ”€β”€ routing/
β”‚ β”œβ”€β”€ __init__.py
β”‚ └── recursive_jit_router.py # RecursiveJITRouter
β”œβ”€β”€ binding/
β”‚ β”œβ”€β”€ __init__.py
β”‚ └── semantic_binding.py # HRRBinding + BinaryBinding + BindingEngine
β”œβ”€β”€ energy/
β”‚ β”œβ”€β”€ __init__.py
β”‚ └── energy_model.py # EnergyFunction + Relaxation + Hopfield
β”œβ”€β”€ inference/
β”‚ β”œβ”€β”€ __init__.py
β”‚ └── reasoning_engine.py # ReasoningEngine (full pipeline)
└── tests/
β”œβ”€β”€ __init__.py
└── test_full_system.py # Comprehensive test suite
```
---
## πŸ”¬ Theoretical Foundations
| Paper | Contribution to MLE |
|-------|-------------------|
| Kanerva (1988) "Sparse Distributed Memory" | Binary vector addressing, Hamming distance proximity |
| Plate (1995) "Holographic Reduced Representations" | Circular convolution binding, FFT implementation |
| Gayler (2003) "Vector Symbolic Architectures" | XOR binding (BSC), majority-vote bundling |
| Ramsauer et al. (2020) "Hopfield Networks Is All You Need" | Modern Hopfield energy, exponential capacity, attention ≑ update rule |
| Frady et al. (2021) "SDM and Transformers" | SDM Hamming threshold β‰ˆ transformer attention |
| Thomas et al. (2023) "Efficient HDC with Static Optimization" | Optimal BSC dimensions, analytical thresholds |
| Langford et al. (2024) "Linear Codes for HDC" | GF(2) factorization, 100% XOR recovery |
---
## πŸ›€οΈ Roadmap
- [ ] **Persistent storage**: Serialize memory to disk (mmap for instant loading)
- [ ] **Learned embeddings**: Pre-encode concepts from text corpora (word2vec β†’ binary projection)
- [ ] **Multi-threaded SIMD**: Parallel batch Hamming with OpenMP
- [ ] **Graph walk reasoning**: Follow relation chains for multi-hop inference
- [ ] **Incremental learning**: Hebbian-style weight updates from experience
- [ ] **Benchmark suite**: Standardized reasoning tasks (bAbI, CLUTRR, etc.)
---
## πŸ“œ License
MIT
---
## πŸ™ Acknowledgments
Inspired by the vision of frugal, explainable AI that reasons rather than retrieves. Built on decades of research in hyperdimensional computing, energy-based models, and sparse distributed memory.