@ruvector/ruvllm 0.2.3 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +298 -778
- package/dist/cjs/engine.js +7 -7
- package/dist/cjs/native.d.ts +3 -3
- package/dist/cjs/native.d.ts.map +1 -1
- package/dist/cjs/native.js +1 -1
- package/dist/esm/engine.js +7 -7
- package/dist/esm/native.d.ts +3 -3
- package/dist/esm/native.d.ts.map +1 -1
- package/dist/esm/native.js +1 -1
- package/package.json +7 -10
package/README.md
CHANGED
|
@@ -1,886 +1,406 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ruvector/ruvllm
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
[](LICENSE)
|
|
5
|
-
[](#testing)
|
|
6
|
-
[](#architecture)
|
|
7
|
-
[](#huggingface-export)
|
|
8
|
-
[](https://www.npmjs.com/package/@ruvector/ruvllm)
|
|
9
|
-
[](#trm-tiny-recursive-models)
|
|
3
|
+
**Build AI that learns and improves from every interaction.**
|
|
10
4
|
|
|
11
|
-
|
|
5
|
+
RuvLLM is a self-learning language model toolkit that gets smarter over time. Unlike traditional LLMs that remain static after training, RuvLLM continuously adapts to your use case while remembering what it learned before.
|
|
12
6
|
|
|
13
|
-
|
|
7
|
+
## What Makes RuvLLM Different?
|
|
14
8
|
|
|
15
|
-
|
|
9
|
+
Traditional LLMs forget old knowledge when learning new things (called "catastrophic forgetting"). RuvLLM solves this with three key innovations:
|
|
16
10
|
|
|
17
|
-
|
|
11
|
+
1. **It Learns Without Forgetting** - Uses tiny parameter updates (LoRA) and memory protection (EWC++) to learn new patterns while preserving existing knowledge
|
|
18
12
|
|
|
19
|
-
|
|
13
|
+
2. **It Remembers Context** - Built-in vector memory stores and retrieves relevant information instantly using similarity search
|
|
20
14
|
|
|
21
|
-
**
|
|
15
|
+
3. **It Routes Intelligently** - Automatically selects the right model size and parameters based on query complexity, saving resources on simple tasks
|
|
22
16
|
|
|
23
|
-
|
|
24
|
-
┌─────────────────────────────────────────────────────────────────────────┐
|
|
25
|
-
│ RuvLLM Architecture │
|
|
26
|
-
├─────────────────────────────────────────────────────────────────────────┤
|
|
27
|
-
│ │
|
|
28
|
-
│ Query ──► Embedding ──► Memory Search ──► Router Decision │
|
|
29
|
-
│ │ │ │
|
|
30
|
-
│ ▼ ▼ │
|
|
31
|
-
│ Graph Attention Model Selection │
|
|
32
|
-
│ │ │ │
|
|
33
|
-
│ └────────┬───────────┘ │
|
|
34
|
-
│ ▼ │
|
|
35
|
-
│ ┌─────────────────────┐ │
|
|
36
|
-
│ │ LLM Inference │ │
|
|
37
|
-
│ │ (Any LLM Backend) │ │
|
|
38
|
-
│ └─────────────────────┘ │
|
|
39
|
-
│ │ │
|
|
40
|
-
│ ▼ │
|
|
41
|
-
│ ┌───────────────────────────────────┐ │
|
|
42
|
-
│ │ SONA Learning (3 Temporal Loops) │ │
|
|
43
|
-
│ │ • Instant: Per-request MicroLoRA │ │
|
|
44
|
-
│ │ • Background: Hourly patterns │ │
|
|
45
|
-
│ │ • Deep: Weekly EWC++ updates │ │
|
|
46
|
-
│ └───────────────────────────────────┘ │
|
|
47
|
-
│ │
|
|
48
|
-
└─────────────────────────────────────────────────────────────────────────┘
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
---
|
|
52
|
-
|
|
53
|
-
## Features
|
|
54
|
-
|
|
55
|
-
### Core Components
|
|
56
|
-
|
|
57
|
-
| Component | Description | Implementation |
|
|
58
|
-
|-----------|-------------|----------------|
|
|
59
|
-
| **LFM2 Cortex** | Frozen reasoning engine (135M-2.6B params) | Mock, Candle, or external (llama.cpp/vLLM) |
|
|
60
|
-
| **Ruvector Memory** | Adaptive synaptic mesh with HNSW indexing | Full CPU implementation with graph expansion |
|
|
61
|
-
| **FastGRNN Router** | Intelligent model selection circuit | Sparse + low-rank matrices with EWC learning |
|
|
62
|
-
| **Graph Attention** | Multi-head attention with edge features | 8-head attention, layer normalization |
|
|
63
|
-
| **SONA Engine** | Self-optimizing neural architecture | LoRA + EWC++ + ReasoningBank |
|
|
64
|
-
| **TRM Engine** | Tiny Recursive Models (7M params) | Recursive latent refinement with SONA bridge |
|
|
65
|
-
|
|
66
|
-
### TRM (Tiny Recursive Models)
|
|
67
|
-
|
|
68
|
-
RuvLLM v0.2.3 introduces **TRM** - Samsung SAIL Montreal's parameter-efficient recursive reasoning approach. TRM achieves strong reasoning performance with only **7M parameters** through iterative latent refinement.
|
|
69
|
-
|
|
70
|
-
```
|
|
71
|
-
┌─────────────────────────────────────────────────────────────────────────┐
|
|
72
|
-
│ TRM Architecture │
|
|
73
|
-
├─────────────────────────────────────────────────────────────────────────┤
|
|
74
|
-
│ │
|
|
75
|
-
│ Question ──┬► Latent Update (n times) ──► Answer Refine ──┐ │
|
|
76
|
-
│ │ │ │
|
|
77
|
-
│ └───────────────────────────────────────────────┘ │
|
|
78
|
-
│ (repeat K times) │
|
|
79
|
-
│ │
|
|
80
|
-
│ Components: │
|
|
81
|
-
│ • MLP Latent Updater - Fast feed-forward updates │
|
|
82
|
-
│ • Attention Latent Updater - Multi-head attention refinement │
|
|
83
|
-
│ • Confidence Scorer - Early stopping based on convergence │
|
|
84
|
-
│ • Answer Refiner - Residual-based answer improvement │
|
|
85
|
-
│ • SONA Bridge - Integration with learning loops │
|
|
86
|
-
│ │
|
|
87
|
-
└─────────────────────────────────────────────────────────────────────────┘
|
|
88
|
-
```
|
|
89
|
-
|
|
90
|
-
**Key Features:**
|
|
91
|
-
- **7M parameters** - Achieves 83% on GSM8K with minimal compute
|
|
92
|
-
- **Recursive refinement** - Iteratively improves answers through K iterations
|
|
93
|
-
- **Adaptive K** - SONA routing determines optimal iteration count
|
|
94
|
-
- **Early stopping** - Confidence-based termination for efficiency
|
|
95
|
-
- **NaN-safe** - Robust numerical guards prevent gradient explosions
|
|
96
|
-
- **Buffer reuse** - Optimized memory allocation for production use
|
|
97
|
-
|
|
98
|
-
### SONA: Self-Optimizing Neural Architecture
|
|
99
|
-
|
|
100
|
-
RuvLLM introduces **SONA**, a three-tier temporal learning system:
|
|
101
|
-
|
|
102
|
-
```
|
|
103
|
-
┌──────────────────────────────────────────────────────────────────────────┐
|
|
104
|
-
│ Loop A: Instant (Per-Request) Latency: <100μs │
|
|
105
|
-
│ ────────────────────────────────────── │
|
|
106
|
-
│ • Records query trajectories with activation patterns │
|
|
107
|
-
│ • MicroLoRA adaptation (rank 1-2) for immediate improvement │
|
|
108
|
-
│ • SIMD-optimized: 2,236 ops/sec throughput │
|
|
109
|
-
├──────────────────────────────────────────────────────────────────────────┤
|
|
110
|
-
│ Loop B: Background (Hourly) │
|
|
111
|
-
│ ───────────────────────────── │
|
|
112
|
-
│ • K-means++ clustering extracts patterns (100 clusters = 1.3ms search) │
|
|
113
|
-
│ • Base LoRA updates (rank 4-16) from successful patterns │
|
|
114
|
-
│ • ReasoningBank stores learned strategies │
|
|
115
|
-
├──────────────────────────────────────────────────────────────────────────┤
|
|
116
|
-
│ Loop C: Deep (Weekly) │
|
|
117
|
-
│ ───────────────────── │
|
|
118
|
-
│ • Dream consolidation across all memory │
|
|
119
|
-
│ • EWC++ prevents catastrophic forgetting (λ=2000 optimal) │
|
|
120
|
-
│ • Concept hierarchies created, old nodes archived │
|
|
121
|
-
└──────────────────────────────────────────────────────────────────────────┘
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
### Advanced Features
|
|
125
|
-
|
|
126
|
-
| Feature | Description |
|
|
127
|
-
|---------|-------------|
|
|
128
|
-
| **SIMD Inference** | Native AVX2/AVX512/SSE4.1 operations for CPU optimization |
|
|
129
|
-
| **Q4 Quantization** | 4-bit weight quantization for memory efficiency |
|
|
130
|
-
| **MicroLoRA** | Per-request adaptation with rank 1-2 (benchmark: rank-2 is 5% faster) |
|
|
131
|
-
| **EWC++** | Enhanced elastic weight consolidation with online Fisher estimation |
|
|
132
|
-
| **ReasoningBank** | Pattern storage with K-means++ clustering |
|
|
133
|
-
| **HuggingFace Export** | Export LoRA weights, patterns, and preference pairs |
|
|
134
|
-
| **Real Inference** | Candle-based inference with HuggingFace model support |
|
|
135
|
-
| **Multi-Model Routing** | Automatic selection between SmolLM, Qwen2, TinyLlama |
|
|
136
|
-
| **Federated Learning** | Distributed learning across ephemeral agents with central coordinator |
|
|
137
|
-
| **WASM Support** | Run SONA in browsers and edge devices |
|
|
138
|
-
| **Training Pipelines** | Templated training for code, chat, reasoning, and custom agents |
|
|
139
|
-
| **Agent Factory** | Create and manage multiple specialized learning agents |
|
|
140
|
-
| **TRM Reasoning** | Recursive reasoning with only 7M parameters (83% GSM8K) |
|
|
141
|
-
| **Adaptive K Routing** | SONA-driven iteration count for optimal compute |
|
|
142
|
-
| **NaN Guards** | Robust numerical stability for production deployment |
|
|
143
|
-
|
|
144
|
-
### Federated Learning Architecture
|
|
145
|
-
|
|
146
|
-
RuvLLM supports **federated learning** where ephemeral agents collect trajectories and export to a central coordinator:
|
|
147
|
-
|
|
148
|
-
```
|
|
149
|
-
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
|
150
|
-
│ Agent A │ │ Agent B │ │ Agent C │
|
|
151
|
-
│ (ephemeral) │ │ (ephemeral) │ │ (ephemeral) │
|
|
152
|
-
└──────┬──────┘ └──────┬──────┘ └──────┬──────┘
|
|
153
|
-
│ │ │
|
|
154
|
-
│ export() │ export() │ export()
|
|
155
|
-
▼ ▼ ▼
|
|
156
|
-
┌────────────────────────────────────────────────┐
|
|
157
|
-
│ Federated Coordinator │
|
|
158
|
-
│ (persistent, large capacity) │
|
|
159
|
-
│ • Aggregates trajectories from all agents │
|
|
160
|
-
│ • Quality-filtered acceptance (threshold) │
|
|
161
|
-
│ • Auto-consolidation every N agents │
|
|
162
|
-
│ • Shares patterns with new agents │
|
|
163
|
-
└────────────────────────────────────────────────┘
|
|
164
|
-
```
|
|
165
|
-
|
|
166
|
-
**Key Components**:
|
|
167
|
-
- **EphemeralAgent**: Short-lived agents that process tasks and export learned state
|
|
168
|
-
- **FederatedCoordinator**: Central aggregator with 50K trajectory capacity
|
|
169
|
-
- **AgentExport**: Serializable state containing trajectories, stats, and patterns
|
|
170
|
-
- **Quality Filtering**: Only high-quality trajectories (>0.4 score) are aggregated
|
|
171
|
-
|
|
172
|
-
---
|
|
173
|
-
|
|
174
|
-
## Performance Benchmarks
|
|
175
|
-
|
|
176
|
-
### Orchestration Latency (CPU-Only)
|
|
177
|
-
|
|
178
|
-
| Metric | Value | Notes |
|
|
179
|
-
|--------|-------|-------|
|
|
180
|
-
| **Initialization** | 3.71ms | Full system startup |
|
|
181
|
-
| **Average Query** | 0.09ms | Single query latency |
|
|
182
|
-
| **Session Query** | 0.04ms | With context reuse |
|
|
183
|
-
| **Throughput** | ~38,000 q/s | 8 concurrent queries |
|
|
184
|
-
| **Memory Footprint** | ~50MB | Base system |
|
|
185
|
-
|
|
186
|
-
### Latency Breakdown
|
|
187
|
-
|
|
188
|
-
```
|
|
189
|
-
Embedding: ~0.02ms ████░░░░░░ (20%)
|
|
190
|
-
Retrieval: ~0.01ms ██░░░░░░░░ (10%)
|
|
191
|
-
Routing: ~0.01ms ██░░░░░░░░ (10%)
|
|
192
|
-
Attention: ~0.02ms ████░░░░░░ (20%)
|
|
193
|
-
Generation: ~0.04ms ████████░░ (40%)
|
|
194
|
-
```
|
|
195
|
-
|
|
196
|
-
### SONA Learning Performance
|
|
17
|
+
## Key Features
|
|
197
18
|
|
|
198
|
-
|
|
|
199
|
-
|
|
200
|
-
|
|
|
201
|
-
|
|
|
202
|
-
|
|
|
203
|
-
|
|
|
19
|
+
| Feature | What It Does | Why It Matters |
|
|
20
|
+
|---------|-------------|----------------|
|
|
21
|
+
| **Adaptive Learning** | Learns from user feedback in real-time | Improves accuracy over time without retraining |
|
|
22
|
+
| **Memory System** | Stores context with instant similarity search | Finds relevant information in microseconds |
|
|
23
|
+
| **Smart Routing** | Picks optimal model/settings per query | Reduces costs, improves response quality |
|
|
24
|
+
| **SIMD Acceleration** | Uses CPU vector instructions (AVX2/NEON) | 10-50x faster vector operations |
|
|
25
|
+
| **Federated Learning** | Train across devices without sharing data | Privacy-preserving distributed learning |
|
|
26
|
+
| **LoRA Adapters** | Parameter-efficient fine-tuning with low-rank matrices | Fast adaptation with minimal memory |
|
|
27
|
+
| **EWC++ Protection** | Elastic Weight Consolidation prevents forgetting | Learn new tasks without losing old knowledge |
|
|
28
|
+
| **SafeTensors Export** | HuggingFace-compatible model serialization | Share models with the ML ecosystem |
|
|
29
|
+
| **Training Pipeline** | Full training infrastructure with schedulers | Production-ready model training |
|
|
30
|
+
| **Session Management** | Stateful conversations with streaming | Build chat applications easily |
|
|
204
31
|
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
| System | P50 (ms) | P95 (ms) | vs GPT-4o |
|
|
208
|
-
|--------|----------|----------|-----------|
|
|
209
|
-
| GPT-4o (API) | 450.00 | 585.00 | 1.0x (baseline) |
|
|
210
|
-
| Claude 3.5 Sonnet | 380.00 | 456.00 | 1.2x |
|
|
211
|
-
| Gemini 2.0 Flash | 180.00 | 234.00 | 2.5x |
|
|
212
|
-
| Llama 3.3 70B (vLLM) | 120.00 | 168.00 | 3.8x |
|
|
213
|
-
| **RuvLLM Orchestration** | **0.06** | **0.08** | **~7,500x** |
|
|
214
|
-
|
|
215
|
-
> **Note**: RuvLLM orchestration latency measures memory retrieval, routing, and context preparation—NOT LLM generation. Actual response quality depends on your LLM backend.
|
|
216
|
-
|
|
217
|
-
---
|
|
218
|
-
|
|
219
|
-
## Feature Comparison
|
|
220
|
-
|
|
221
|
-
| Feature | GPT-4o | Claude | RAG | vLLM | RuvLLM |
|
|
222
|
-
|---------|--------|--------|-----|------|--------|
|
|
223
|
-
| On-device Inference | ✗ | ✗ | ✗ | ✓ | ✓ |
|
|
224
|
-
| Continuous Learning | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
225
|
-
| Graph-based Memory | ✗ | ✗ | △ | ✗ | ✓ |
|
|
226
|
-
| Adaptive Model Routing | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
227
|
-
| EWC Anti-Forgetting | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
228
|
-
| LoRA Adaptation | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
229
|
-
| Pattern Extraction | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
230
|
-
| HuggingFace Export | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
231
|
-
| SIMD Optimization | ✗ | ✗ | ✗ | △ | ✓ |
|
|
232
|
-
| Sub-ms Orchestration | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
233
|
-
| Federated Learning | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
234
|
-
| WASM/Browser Support | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
235
|
-
| Training Pipelines | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
236
|
-
| Works with ANY LLM | ✗ | ✗ | ✓ | ✗ | ✓ |
|
|
237
|
-
| **TRM Recursive Reasoning** | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
238
|
-
| **7M Param Efficiency** | ✗ | ✗ | ✗ | ✗ | ✓ |
|
|
239
|
-
|
|
240
|
-
*Legend: ✓ = Full Support, △ = Partial, ✗ = Not Supported*
|
|
241
|
-
|
|
242
|
-
---
|
|
243
|
-
|
|
244
|
-
## Quick Start
|
|
245
|
-
|
|
246
|
-
### Prerequisites
|
|
247
|
-
|
|
248
|
-
- Rust 1.77+
|
|
249
|
-
- Cargo
|
|
250
|
-
|
|
251
|
-
### Installation
|
|
32
|
+
## Installation
|
|
252
33
|
|
|
253
34
|
```bash
|
|
254
|
-
|
|
255
|
-
git clone https://github.com/ruvnet/ruvector.git
|
|
256
|
-
cd ruvector/examples/ruvLLM
|
|
257
|
-
|
|
258
|
-
# Build in release mode
|
|
259
|
-
cargo build --release
|
|
35
|
+
npm install @ruvector/ruvllm
|
|
260
36
|
```
|
|
261
37
|
|
|
262
|
-
|
|
38
|
+
Or run directly:
|
|
263
39
|
|
|
264
40
|
```bash
|
|
265
|
-
|
|
266
|
-
cargo run --bin ruvllm-demo --release
|
|
267
|
-
|
|
268
|
-
# SIMD capabilities demo
|
|
269
|
-
cargo run --bin ruvllm-simd-demo --release
|
|
270
|
-
|
|
271
|
-
# Quick benchmark
|
|
272
|
-
cargo run --bin ruvllm-bench --release
|
|
273
|
-
|
|
274
|
-
# Full benchmark suite
|
|
275
|
-
cargo run --bin ruvllm-benchmark-suite --release
|
|
276
|
-
|
|
277
|
-
# HTTP server (requires 'server' feature)
|
|
278
|
-
cargo run --bin ruvllm-server --release --features server
|
|
279
|
-
|
|
280
|
-
# Pretraining pipeline
|
|
281
|
-
cargo run --bin ruvllm-pretrain --release
|
|
282
|
-
|
|
283
|
-
# HuggingFace export (requires 'hf-export' feature)
|
|
284
|
-
cargo run --bin ruvllm-export --release --features hf-export -- help
|
|
41
|
+
npx @ruvector/ruvllm info
|
|
285
42
|
```
|
|
286
43
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
```rust
|
|
290
|
-
use ruvllm::{Config, RuvLLM, Result};
|
|
44
|
+
## Quick Start Tutorial
|
|
291
45
|
|
|
292
|
-
|
|
293
|
-
async fn main() -> Result<()> {
|
|
294
|
-
// Configure the system
|
|
295
|
-
let config = Config::builder()
|
|
296
|
-
.embedding_dim(768)
|
|
297
|
-
.router_hidden_dim(128)
|
|
298
|
-
.hnsw_params(32, 200, 64) // M, ef_construction, ef_search
|
|
299
|
-
.learning_enabled(true)
|
|
300
|
-
.build()?;
|
|
46
|
+
### 1. Basic Query
|
|
301
47
|
|
|
302
|
-
|
|
303
|
-
|
|
48
|
+
```typescript
|
|
49
|
+
import { RuvLLM } from '@ruvector/ruvllm';
|
|
304
50
|
|
|
305
|
-
|
|
306
|
-
let session = llm.new_session();
|
|
51
|
+
const llm = new RuvLLM();
|
|
307
52
|
|
|
308
|
-
|
|
309
|
-
|
|
53
|
+
// Ask a question - routing happens automatically
|
|
54
|
+
const response = llm.query('Explain neural networks simply');
|
|
55
|
+
console.log(response.text);
|
|
56
|
+
// Output: "Neural networks are computing systems inspired by..."
|
|
310
57
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
println!("Confidence: {:.2}%", response.confidence * 100.0);
|
|
314
|
-
|
|
315
|
-
// Provide feedback for learning
|
|
316
|
-
llm.feedback(Feedback {
|
|
317
|
-
request_id: response.request_id,
|
|
318
|
-
rating: Some(5),
|
|
319
|
-
correction: None,
|
|
320
|
-
task_success: Some(true),
|
|
321
|
-
}).await?;
|
|
322
|
-
|
|
323
|
-
Ok(())
|
|
324
|
-
}
|
|
58
|
+
console.log(`Used model: ${response.model}`);
|
|
59
|
+
console.log(`Confidence: ${(response.confidence * 100).toFixed(1)}%`);
|
|
325
60
|
```
|
|
326
61
|
|
|
327
|
-
###
|
|
328
|
-
|
|
329
|
-
```rust
|
|
330
|
-
use ruvllm::{SimdInferenceEngine, SimdGenerationConfig, SimdOps};
|
|
62
|
+
### 2. Teaching the System
|
|
331
63
|
|
|
332
|
-
|
|
333
|
-
|
|
64
|
+
```typescript
|
|
65
|
+
// Query and get a response
|
|
66
|
+
const response = llm.query('What is the capital of France?');
|
|
334
67
|
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
};
|
|
68
|
+
// Provide feedback - the system learns from this
|
|
69
|
+
llm.feedback({
|
|
70
|
+
requestId: response.requestId,
|
|
71
|
+
rating: 5, // 1-5 scale
|
|
72
|
+
correction: 'Paris is the capital and largest city of France'
|
|
73
|
+
});
|
|
342
74
|
|
|
343
|
-
//
|
|
344
|
-
let result = engine.generate("Once upon a time", &config)?;
|
|
75
|
+
// Future similar queries will be more accurate
|
|
345
76
|
```
|
|
346
77
|
|
|
347
|
-
###
|
|
78
|
+
### 3. Using Memory
|
|
348
79
|
|
|
349
|
-
```
|
|
350
|
-
|
|
80
|
+
```typescript
|
|
81
|
+
// Store important context
|
|
82
|
+
llm.addMemory('Company policy: All returns accepted within 30 days', {
|
|
83
|
+
category: 'policy',
|
|
84
|
+
department: 'customer-service'
|
|
85
|
+
});
|
|
351
86
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
pattern_clusters: 100,
|
|
357
|
-
..Default::default()
|
|
358
|
-
};
|
|
87
|
+
llm.addMemory('Product X launched in March 2024 with features A, B, C', {
|
|
88
|
+
category: 'product',
|
|
89
|
+
name: 'Product X'
|
|
90
|
+
});
|
|
359
91
|
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
// Background learning (hourly)
|
|
366
|
-
coordinator.background_loop().extract_patterns().await;
|
|
367
|
-
|
|
368
|
-
// Deep learning (weekly) - automatically handles EWC++
|
|
369
|
-
coordinator.deep_consolidation().await;
|
|
92
|
+
// Search memory for relevant context
|
|
93
|
+
const results = llm.searchMemory('return policy', 5);
|
|
94
|
+
console.log(results[0].content);
|
|
95
|
+
// Output: "Company policy: All returns accepted within 30 days"
|
|
96
|
+
console.log(`Relevance: ${(results[0].score * 100).toFixed(1)}%`);
|
|
370
97
|
```
|
|
371
98
|
|
|
372
|
-
###
|
|
373
|
-
|
|
374
|
-
```rust
|
|
375
|
-
use ruvllm::trm::{TrmEngine, TrmEngineBuilder, TrmConfig, RecursiveReasoner};
|
|
376
|
-
|
|
377
|
-
// Build TRM engine with custom configuration
|
|
378
|
-
let mut engine = TrmEngineBuilder::new()
|
|
379
|
-
.hidden_dim(256)
|
|
380
|
-
.embedding_dim(256)
|
|
381
|
-
.default_k(10) // Default K iterations
|
|
382
|
-
.n_inner(4) // Inner latent updates per K
|
|
383
|
-
.confidence_threshold(0.95) // Early stopping threshold
|
|
384
|
-
.build()
|
|
385
|
-
.unwrap();
|
|
386
|
-
|
|
387
|
-
// Prepare question and answer embeddings
|
|
388
|
-
let question = vec![0.5; 256]; // Question embedding
|
|
389
|
-
let mut answer = vec![0.1; 256]; // Initial answer (refined in-place)
|
|
390
|
-
|
|
391
|
-
// Perform recursive reasoning
|
|
392
|
-
let result = engine.reason(&question, &mut answer);
|
|
99
|
+
### 4. Computing Similarity
|
|
393
100
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
println!("Early stopped: {}", result.early_stopped);
|
|
101
|
+
```typescript
|
|
102
|
+
import { SimdOps } from '@ruvector/ruvllm';
|
|
397
103
|
|
|
398
|
-
|
|
399
|
-
use ruvllm::trm::SonaBridge;
|
|
104
|
+
const simd = new SimdOps();
|
|
400
105
|
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
println!("Adaptive K used: {}", routing.k);
|
|
406
|
-
```
|
|
407
|
-
|
|
408
|
-
### Federated Learning
|
|
409
|
-
|
|
410
|
-
```rust
|
|
411
|
-
use ruvector_sona::training::{EphemeralAgent, FederatedCoordinator, SonaConfig};
|
|
412
|
-
|
|
413
|
-
// Create central coordinator (persistent, large capacity)
|
|
414
|
-
let mut coordinator = FederatedCoordinator::default_coordinator("main", 3072);
|
|
415
|
-
coordinator.set_quality_threshold(0.4); // Only accept high-quality trajectories
|
|
416
|
-
coordinator.set_consolidation_interval(50); // Auto-consolidate every 50 agents
|
|
417
|
-
|
|
418
|
-
// Create ephemeral agents for distributed learning
|
|
419
|
-
let mut agent = EphemeralAgent::default_federated("agent-1", 3072);
|
|
420
|
-
|
|
421
|
-
// Agent processes tasks and learns locally
|
|
422
|
-
agent.process_trajectory(
|
|
423
|
-
embedding, // Query embedding
|
|
424
|
-
activations, // Hidden state activations
|
|
425
|
-
quality, // Quality score [0.0, 1.0]
|
|
426
|
-
Some("gpt-4".to_string()), // Model route
|
|
427
|
-
vec!["code".to_string()], // Context tags
|
|
106
|
+
// Compare two texts
|
|
107
|
+
const score = llm.similarity(
|
|
108
|
+
'How do I reset my password?',
|
|
109
|
+
'I forgot my login credentials'
|
|
428
110
|
);
|
|
111
|
+
console.log(`Similarity: ${(score * 100).toFixed(1)}%`);
|
|
112
|
+
// Output: "Similarity: 78.3%"
|
|
429
113
|
|
|
430
|
-
//
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
// Coordinator aggregates learning from all agents
|
|
435
|
-
let result = coordinator.aggregate(export);
|
|
436
|
-
println!("Accepted: {}, Rejected: {}",
|
|
437
|
-
result.trajectories_accepted,
|
|
438
|
-
result.trajectories_rejected
|
|
439
|
-
);
|
|
440
|
-
|
|
441
|
-
// Get patterns for warm-starting new agents
|
|
442
|
-
let patterns = coordinator.get_initial_patterns(10);
|
|
114
|
+
// Fast vector operations
|
|
115
|
+
const embedding1 = llm.embed('machine learning');
|
|
116
|
+
const embedding2 = llm.embed('deep learning');
|
|
117
|
+
const similarity = simd.cosineSimilarity(embedding1, embedding2);
|
|
443
118
|
```
|
|
444
119
|
|
|
445
|
-
###
|
|
120
|
+
### 5. Batch Processing
|
|
446
121
|
|
|
447
|
-
|
|
122
|
+
```typescript
|
|
123
|
+
// Process multiple queries efficiently
|
|
124
|
+
const batch = llm.batchQuery({
|
|
125
|
+
queries: [
|
|
126
|
+
'What is AI?',
|
|
127
|
+
'Explain machine learning',
|
|
128
|
+
'How do neural networks work?'
|
|
129
|
+
],
|
|
130
|
+
config: { temperature: 0.7 }
|
|
131
|
+
});
|
|
448
132
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
133
|
+
batch.responses.forEach((r, i) => {
|
|
134
|
+
console.log(`Query ${i + 1}: ${r.text.slice(0, 50)}...`);
|
|
135
|
+
});
|
|
136
|
+
console.log(`Total time: ${batch.totalLatencyMs}ms`);
|
|
453
137
|
```
|
|
454
138
|
|
|
455
|
-
|
|
139
|
+
## CLI Commands
|
|
456
140
|
|
|
457
|
-
```
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
async function main() {
|
|
461
|
-
await init();
|
|
462
|
-
|
|
463
|
-
// Create SONA engine
|
|
464
|
-
const engine = new WasmSonaEngine(256); // hidden_dim = 256
|
|
141
|
+
```bash
|
|
142
|
+
# Get system information
|
|
143
|
+
ruvllm info
|
|
465
144
|
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
hidden_dim: 256,
|
|
469
|
-
embedding_dim: 256,
|
|
470
|
-
micro_lora_rank: 2,
|
|
471
|
-
base_lora_rank: 16,
|
|
472
|
-
ewc_lambda: 1000.0,
|
|
473
|
-
pattern_clusters: 128,
|
|
474
|
-
});
|
|
145
|
+
# Query the model
|
|
146
|
+
ruvllm query "What is quantum computing?"
|
|
475
147
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
const trajectoryId = engine.startTrajectory(embedding);
|
|
148
|
+
# Generate text with custom settings
|
|
149
|
+
ruvllm generate "Write a product description for:" --temperature 0.8 --max-tokens 200
|
|
479
150
|
|
|
480
|
-
|
|
481
|
-
|
|
151
|
+
# Memory operations
|
|
152
|
+
ruvllm memory add "Important fact to remember"
|
|
153
|
+
ruvllm memory search "fact" --k 10
|
|
482
154
|
|
|
483
|
-
|
|
484
|
-
|
|
155
|
+
# Compare texts
|
|
156
|
+
ruvllm similarity "hello world" "hi there"
|
|
485
157
|
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
const output = engine.applyLora(input);
|
|
158
|
+
# Get embeddings
|
|
159
|
+
ruvllm embed "your text here"
|
|
489
160
|
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
if (engine.tick()) { // Background learning
|
|
493
|
-
console.log('Background learning completed');
|
|
494
|
-
}
|
|
161
|
+
# Run performance benchmark
|
|
162
|
+
ruvllm benchmark --dims 768 --iterations 5000
|
|
495
163
|
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
console.log('Patterns:', stats.patterns_stored);
|
|
499
|
-
}
|
|
164
|
+
# View statistics
|
|
165
|
+
ruvllm stats --json
|
|
500
166
|
```
|
|
501
167
|
|
|
502
|
-
|
|
168
|
+
## Benchmarks
|
|
503
169
|
|
|
504
|
-
|
|
170
|
+
*Benchmarked in Docker (node:20-alpine, x64) - December 2024*
|
|
505
171
|
|
|
506
|
-
|
|
172
|
+
### Core Operations
|
|
507
173
|
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
174
|
+
| Operation | Time | Throughput |
|
|
175
|
+
|-----------|------|------------|
|
|
176
|
+
| Query (short) | 1.49μs | **670K ops/s** |
|
|
177
|
+
| Query (long) | 874ns | **1.14M ops/s** |
|
|
178
|
+
| Generate | 88ns | **11.4M ops/s** |
|
|
179
|
+
| Route | 92ns | **10.9M ops/s** |
|
|
180
|
+
| Embed (256d) | 10.6μs | **94K ops/s** |
|
|
181
|
+
| Embed (768d) | 7.1μs | **140K ops/s** |
|
|
511
182
|
|
|
512
|
-
|
|
513
|
-
ruvllm-export patterns ./exports/patterns
|
|
183
|
+
### SIMD Vector Operations
|
|
514
184
|
|
|
515
|
-
|
|
516
|
-
|
|
185
|
+
| Operation | 128d | 256d | 512d | 768d |
|
|
186
|
+
|-----------|------|------|------|------|
|
|
187
|
+
| Dot Product | 214ns / **4.67M ops/s** | 318ns / **3.15M ops/s** | 609ns / **1.64M ops/s** | 908ns / **1.10M ops/s** |
|
|
188
|
+
| Cosine Similarity | 233ns / **4.30M ops/s** | 335ns / **2.99M ops/s** | 652ns / **1.53M ops/s** | 972ns / **1.03M ops/s** |
|
|
189
|
+
| L2 Distance | 195ns / **5.14M ops/s** | 315ns / **3.18M ops/s** | 612ns / **1.63M ops/s** | 929ns / **1.08M ops/s** |
|
|
517
190
|
|
|
518
|
-
|
|
519
|
-
ruvllm-export all ./exports
|
|
191
|
+
### LoRA Adapter Performance
|
|
520
192
|
|
|
521
|
-
|
|
522
|
-
|
|
193
|
+
| Operation | 64d | 128d | 256d |
|
|
194
|
+
|-----------|-----|------|------|
|
|
195
|
+
| Forward (r=4) | 6.09μs / **164K ops/s** | 2.74μs / **365K ops/s** | 4.83μs / **207K ops/s** |
|
|
196
|
+
| Forward (r=8) | 2.17μs / **462K ops/s** | 4.30μs / **233K ops/s** | 8.99μs / **111K ops/s** |
|
|
197
|
+
| Forward (r=16) | 4.85μs / **206K ops/s** | 9.05μs / **111K ops/s** | 18.3μs / **55K ops/s** |
|
|
198
|
+
| Backward (r=8) | - | 110μs / **9.1K ops/s** | - |
|
|
199
|
+
| Batch (100) | - | 467μs / **2.1K ops/s** | - |
|
|
523
200
|
|
|
524
|
-
|
|
525
|
-
ruvllm-export pretrain ./exports
|
|
526
|
-
```
|
|
201
|
+
### Memory Operations
|
|
527
202
|
|
|
528
|
-
|
|
203
|
+
| Operation | Time | Throughput |
|
|
204
|
+
|-----------|------|------------|
|
|
205
|
+
| Add Memory | 5.3μs | **189K ops/s** |
|
|
206
|
+
| Search (k=5) | 45.6μs | **21.9K ops/s** |
|
|
207
|
+
| Search (k=10) | 28.3μs | **35.3K ops/s** |
|
|
208
|
+
| Search (k=20) | 33.1μs | **30.2K ops/s** |
|
|
529
209
|
|
|
530
|
-
|
|
210
|
+
### SONA Learning System
|
|
531
211
|
|
|
532
|
-
|
|
212
|
+
| Operation | Time | Throughput |
|
|
213
|
+
|-----------|------|------------|
|
|
214
|
+
| Pattern Store | 14.4μs | **69.5K ops/s** |
|
|
215
|
+
| Pattern Find Similar | 224μs | **4.5K ops/s** |
|
|
216
|
+
| EWC Register Task | 6.5μs | **154K ops/s** |
|
|
217
|
+
| EWC Compute Penalty | 501μs | **2.0K ops/s** |
|
|
218
|
+
| Trajectory Build | 1.24μs | **807K ops/s** |
|
|
533
219
|
|
|
534
|
-
|
|
220
|
+
### Federated Learning
|
|
535
221
|
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
• M = 32 connections per node
|
|
544
|
-
• ef_construction = 200 for build quality
|
|
545
|
-
• ef_search = 64 for query speed
|
|
546
|
-
• O(log N) search complexity
|
|
547
|
-
```
|
|
222
|
+
| Operation | Time | Throughput |
|
|
223
|
+
|-----------|------|------------|
|
|
224
|
+
| Agent Create | 7.8μs | **128K ops/s** |
|
|
225
|
+
| Process Task | 7.9μs | **126K ops/s** |
|
|
226
|
+
| Apply LoRA | 12.6μs | **79.6K ops/s** |
|
|
227
|
+
| Export State | 48.9μs | **20.4K ops/s** |
|
|
228
|
+
| Aggregate | 5.26ms | **190 ops/s** |
|
|
548
229
|
|
|
549
|
-
###
|
|
230
|
+
### Session & Streaming
|
|
550
231
|
|
|
551
|
-
|
|
232
|
+
| Operation | Time | Throughput |
|
|
233
|
+
|-----------|------|------------|
|
|
234
|
+
| Session Create | 1.45μs | **690K ops/s** |
|
|
235
|
+
| Session Chat | 3.28μs | **305K ops/s** |
|
|
236
|
+
| Session Export | 3.91ms | **255 ops/s** |
|
|
237
|
+
| Session Import | 1.60ms | **625 ops/s** |
|
|
552
238
|
|
|
553
|
-
|
|
554
|
-
Input (128-dim)
|
|
555
|
-
│
|
|
556
|
-
┌───────┴───────┐
|
|
557
|
-
│ LayerNorm │
|
|
558
|
-
└───────┬───────┘
|
|
559
|
-
│
|
|
560
|
-
┌───────────┴───────────┐
|
|
561
|
-
│ FastGRNN Cell │
|
|
562
|
-
│ │
|
|
563
|
-
│ W_sparse (90% zero) │
|
|
564
|
-
│ U = A @ B (rank-8) │
|
|
565
|
-
│ │
|
|
566
|
-
│ z = σ(Wx + Uh + b) │
|
|
567
|
-
│ h' = z⊙h + (1-z)⊙ν │
|
|
568
|
-
└───────────┬───────────┘
|
|
569
|
-
│
|
|
570
|
-
┌───────┴───────┐
|
|
571
|
-
│ Output Heads │
|
|
572
|
-
├───────────────┤
|
|
573
|
-
│ Model Select │ → 4 classes
|
|
574
|
-
│ Context Size │ → 5 buckets
|
|
575
|
-
│ Temperature │ → continuous
|
|
576
|
-
│ Top-p │ → continuous
|
|
577
|
-
│ Confidence │ → continuous
|
|
578
|
-
└───────────────┘
|
|
579
|
-
```
|
|
239
|
+
### Training Pipeline
|
|
580
240
|
|
|
581
|
-
|
|
241
|
+
| Operation | Time |
|
|
242
|
+
|-----------|------|
|
|
243
|
+
| Pipeline Create | 70.6μs |
|
|
244
|
+
| Add Data (100 samples) | 70.6μs |
|
|
245
|
+
| Train (32 samples, 3 epochs) | 1.33s |
|
|
582
246
|
|
|
583
|
-
|
|
247
|
+
### Export/Import
|
|
584
248
|
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
│ Input ──► Down Proj ──► Up Proj ──► Scale ──► Add │
|
|
592
|
-
│ (dim) (dim→rank) (rank→dim) (α/r) to output │
|
|
593
|
-
│ │
|
|
594
|
-
│ Performance: <100μs latency, 2,236 ops/sec │
|
|
595
|
-
│ Rank-2 is ~5% faster than Rank-1 (better SIMD) │
|
|
596
|
-
└─────────────────────────────────────────────────────────────┘
|
|
597
|
-
|
|
598
|
-
┌─────────────────────────────────────────────────────────────┐
|
|
599
|
-
│ BaseLoRA (Rank 4-16) │
|
|
600
|
-
│ Background Adaptation │
|
|
601
|
-
├─────────────────────────────────────────────────────────────┤
|
|
602
|
-
│ │
|
|
603
|
-
│ Aggregated from successful MicroLoRA patterns │
|
|
604
|
-
│ Merged hourly into base weights │
|
|
605
|
-
│ EWC++ regularization prevents forgetting │
|
|
606
|
-
│ │
|
|
607
|
-
└─────────────────────────────────────────────────────────────┘
|
|
608
|
-
```
|
|
249
|
+
| Operation | Time | Throughput |
|
|
250
|
+
|-----------|------|------------|
|
|
251
|
+
| SafeTensors Write | 67.3μs | **14.9K ops/s** |
|
|
252
|
+
| SafeTensors Read | 102μs | **9.8K ops/s** |
|
|
253
|
+
| LoRA to JSON | 87.9μs | **11.4K ops/s** |
|
|
254
|
+
| LoRA from JSON | 86.0μs | **11.6K ops/s** |
|
|
609
255
|
|
|
610
|
-
###
|
|
256
|
+
### Performance Highlights
|
|
611
257
|
|
|
612
|
-
|
|
258
|
+
- **Fastest**: Generate at **11.4M ops/s**, Route at **10.9M ops/s**
|
|
259
|
+
- **Vector Ops**: Up to **5.14M ops/s** for L2 distance (128d)
|
|
260
|
+
- **LoRA Forward**: Up to **462K ops/s** (64d, rank-8)
|
|
261
|
+
- **Memory Search**: **35K ops/s** (k=10)
|
|
262
|
+
- **Session Create**: **690K ops/s**
|
|
613
263
|
|
|
614
|
-
|
|
615
|
-
Loss = Task_Loss + λ * Σᵢ Fᵢ(θᵢ - θ*ᵢ)²
|
|
616
|
-
|
|
617
|
-
Where:
|
|
618
|
-
• Fᵢ = Online Fisher information (EMA decay 0.999)
|
|
619
|
-
• θ*ᵢ = Optimal weights for previous tasks
|
|
620
|
-
• λ = Adaptive (2000 default, range 100-15000)
|
|
621
|
-
• Multi-task memory with circular buffer (10 tasks)
|
|
622
|
-
• Automatic task boundary detection
|
|
623
|
-
```
|
|
624
|
-
|
|
625
|
-
### SIMD Operations
|
|
264
|
+
## Configuration
|
|
626
265
|
|
|
627
|
-
|
|
266
|
+
```typescript
|
|
267
|
+
const llm = new RuvLLM({
|
|
268
|
+
// Embedding settings
|
|
269
|
+
embeddingDim: 768, // Vector dimensions (384, 768, 1024)
|
|
628
270
|
|
|
629
|
-
|
|
630
|
-
//
|
|
631
|
-
|
|
632
|
-
|
|
271
|
+
// Memory settings
|
|
272
|
+
hnswM: 16, // Graph connectivity (higher = better recall, more memory)
|
|
273
|
+
hnswEfConstruction: 100, // Build quality (higher = better index, slower build)
|
|
274
|
+
hnswEfSearch: 64, // Search quality (higher = better recall, slower search)
|
|
633
275
|
|
|
634
|
-
//
|
|
635
|
-
|
|
636
|
-
|
|
276
|
+
// Learning settings
|
|
277
|
+
learningEnabled: true, // Enable adaptive learning
|
|
278
|
+
qualityThreshold: 0.7, // Min confidence to skip learning
|
|
279
|
+
ewcLambda: 2000, // Memory protection strength
|
|
637
280
|
|
|
638
|
-
//
|
|
639
|
-
|
|
281
|
+
// Router settings
|
|
282
|
+
routerHiddenDim: 128, // Router network size
|
|
283
|
+
});
|
|
640
284
|
```
|
|
641
285
|
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
## Supported Models
|
|
286
|
+
## Platform Support
|
|
645
287
|
|
|
646
|
-
|
|
288
|
+
Native acceleration available on:
|
|
647
289
|
|
|
648
|
-
|
|
|
649
|
-
|
|
650
|
-
|
|
|
651
|
-
|
|
|
652
|
-
|
|
|
653
|
-
|
|
|
290
|
+
| Platform | Architecture | SIMD Support |
|
|
291
|
+
|----------|-------------|--------------|
|
|
292
|
+
| macOS | Apple Silicon (M1/M2/M3) | NEON |
|
|
293
|
+
| macOS | Intel x64 | AVX2, SSE4.1 |
|
|
294
|
+
| Linux | x64 | AVX2, AVX-512, SSE4.1 |
|
|
295
|
+
| Linux | ARM64 | NEON |
|
|
296
|
+
| Windows | x64 | AVX2, SSE4.1 |
|
|
654
297
|
|
|
655
|
-
|
|
298
|
+
Falls back to optimized JavaScript on unsupported platforms.
|
|
656
299
|
|
|
657
|
-
|
|
300
|
+
## Real-World Use Cases
|
|
658
301
|
|
|
659
|
-
|
|
302
|
+
### Customer Support Bot
|
|
303
|
+
```typescript
|
|
304
|
+
// Store FAQ and policies
|
|
305
|
+
faqs.forEach(faq => llm.addMemory(faq.answer, { question: faq.question }));
|
|
660
306
|
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
| `/stats` | GET | Get statistics |
|
|
668
|
-
| `/feedback` | POST | Submit feedback |
|
|
669
|
-
| `/session` | POST | Create new session |
|
|
670
|
-
|
|
671
|
-
```bash
|
|
672
|
-
# Example query
|
|
673
|
-
curl -X POST http://localhost:3000/query \
|
|
674
|
-
-H "Content-Type: application/json" \
|
|
675
|
-
-d '{"query": "What is Rust?", "session_id": null}'
|
|
307
|
+
// Answer questions with context
|
|
308
|
+
function answerQuestion(question: string) {
|
|
309
|
+
const context = llm.searchMemory(question, 3);
|
|
310
|
+
const prompt = `Context:\n${context.map(c => c.content).join('\n')}\n\nQuestion: ${question}`;
|
|
311
|
+
return llm.query(prompt);
|
|
312
|
+
}
|
|
676
313
|
```
|
|
677
314
|
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
cargo test -p ruvllm --lib
|
|
688
|
-
|
|
689
|
-
# Integration tests (15 tests)
|
|
690
|
-
cargo test -p ruvllm --test integration
|
|
315
|
+
### Document Search
|
|
316
|
+
```typescript
|
|
317
|
+
// Index documents
|
|
318
|
+
documents.forEach(doc => {
|
|
319
|
+
llm.addMemory(doc.content, {
|
|
320
|
+
title: doc.title,
|
|
321
|
+
path: doc.path
|
|
322
|
+
});
|
|
323
|
+
});
|
|
691
324
|
|
|
692
|
-
|
|
693
|
-
|
|
325
|
+
// Semantic search
|
|
326
|
+
const results = llm.searchMemory('quarterly revenue growth', 10);
|
|
694
327
|
```
|
|
695
328
|
|
|
696
|
-
###
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
| Embedding | 9 | Tokenization, caching, pooling |
|
|
704
|
-
| SONA | 10 | LoRA, EWC++, ReasoningBank, loops |
|
|
705
|
-
| Orchestrator | 2 | End-to-end pipeline |
|
|
706
|
-
| Integration | 15 | Full system tests |
|
|
707
|
-
|
|
708
|
-
---
|
|
709
|
-
|
|
710
|
-
## Project Structure
|
|
329
|
+
### Personalized Recommendations
|
|
330
|
+
```typescript
|
|
331
|
+
// Learn from user interactions
|
|
332
|
+
function recordInteraction(userId: string, itemId: string, rating: number) {
|
|
333
|
+
const response = llm.query(`User ${userId} rated ${itemId}`);
|
|
334
|
+
llm.feedback({ requestId: response.requestId, rating });
|
|
335
|
+
}
|
|
711
336
|
|
|
337
|
+
// Get recommendations
|
|
338
|
+
function recommend(userId: string) {
|
|
339
|
+
return llm.searchMemory(`preferences for user ${userId}`, 10);
|
|
340
|
+
}
|
|
712
341
|
```
|
|
713
|
-
examples/ruvLLM/
|
|
714
|
-
├── Cargo.toml # Dependencies and features
|
|
715
|
-
├── README.md # This file
|
|
716
|
-
├── src/
|
|
717
|
-
│ ├── lib.rs # Library entry point
|
|
718
|
-
│ ├── config.rs # Configuration system
|
|
719
|
-
│ ├── error.rs # Error types
|
|
720
|
-
│ ├── types.rs # Core domain types
|
|
721
|
-
│ ├── orchestrator.rs # Main RuvLLM coordinator
|
|
722
|
-
│ ├── memory.rs # HNSW memory service
|
|
723
|
-
│ ├── router.rs # FastGRNN router
|
|
724
|
-
│ ├── attention.rs # Graph attention engine
|
|
725
|
-
│ ├── embedding.rs # Embedding service
|
|
726
|
-
│ ├── inference.rs # Mock inference pool
|
|
727
|
-
│ ├── inference_real.rs # Candle-based real inference
|
|
728
|
-
│ ├── simd_inference.rs # SIMD-optimized transformer
|
|
729
|
-
│ ├── learning.rs # Self-learning service
|
|
730
|
-
│ ├── compression.rs # Memory compression
|
|
731
|
-
│ ├── training.rs # Pretraining pipeline
|
|
732
|
-
│ ├── trm/ # TRM (Tiny Recursive Models) module
|
|
733
|
-
│ │ ├── mod.rs # Module exports and traits
|
|
734
|
-
│ │ ├── engine.rs # Main TRM reasoning engine
|
|
735
|
-
│ │ ├── config.rs # Configuration and builder
|
|
736
|
-
│ │ ├── mlp.rs # MLP latent updater
|
|
737
|
-
│ │ ├── attention.rs # Attention latent updater
|
|
738
|
-
│ │ ├── refiner.rs # Answer refinement
|
|
739
|
-
│ │ ├── confidence.rs # Confidence scoring
|
|
740
|
-
│ │ ├── sona_bridge.rs # SONA integration
|
|
741
|
-
│ │ ├── types.rs # TRM types and results
|
|
742
|
-
│ │ └── error.rs # Error handling
|
|
743
|
-
│ ├── sona/ # SONA module
|
|
744
|
-
│ │ ├── mod.rs # Module exports
|
|
745
|
-
│ │ ├── types.rs # SONA types
|
|
746
|
-
│ │ ├── lora.rs # MicroLoRA & BaseLoRA
|
|
747
|
-
│ │ ├── ewc.rs # EWC++ implementation
|
|
748
|
-
│ │ ├── reasoning_bank.rs # Pattern storage
|
|
749
|
-
│ │ ├── trajectory.rs # Trajectory recording
|
|
750
|
-
│ │ ├── engine.rs # SONA engine
|
|
751
|
-
│ │ └── loops/ # Temporal learning loops
|
|
752
|
-
│ │ ├── instant.rs # Per-request loop
|
|
753
|
-
│ │ ├── background.rs # Hourly loop
|
|
754
|
-
│ │ └── coordinator.rs # Loop coordinator
|
|
755
|
-
│ └── bin/
|
|
756
|
-
│ ├── demo.rs # Interactive demo
|
|
757
|
-
│ ├── bench.rs # Quick benchmarks
|
|
758
|
-
│ ├── benchmark_suite.rs # Full benchmark suite
|
|
759
|
-
│ ├── simd_demo.rs # SIMD capabilities demo
|
|
760
|
-
│ ├── pretrain.rs # Pretraining pipeline
|
|
761
|
-
│ ├── export.rs # HuggingFace export
|
|
762
|
-
│ └── server.rs # HTTP server
|
|
763
|
-
├── tests/
|
|
764
|
-
│ └── integration.rs # Integration tests
|
|
765
|
-
├── benches/
|
|
766
|
-
│ ├── pipeline.rs # Full pipeline benchmarks
|
|
767
|
-
│ ├── router.rs # Router benchmarks
|
|
768
|
-
│ ├── memory.rs # Memory benchmarks
|
|
769
|
-
│ ├── attention.rs # Attention benchmarks
|
|
770
|
-
│ ├── sona_bench.rs # SONA benchmarks
|
|
771
|
-
│ └── trm_bench.rs # TRM benchmarks
|
|
772
|
-
├── config/ # Configuration files
|
|
773
|
-
└── docs/
|
|
774
|
-
└── sparc/ # SPARC methodology docs
|
|
775
|
-
```
|
|
776
|
-
|
|
777
|
-
---
|
|
778
|
-
|
|
779
|
-
## Feature Flags
|
|
780
|
-
|
|
781
|
-
### RuvLLM Features
|
|
782
|
-
|
|
783
|
-
| Feature | Default | Description |
|
|
784
|
-
|---------|---------|-------------|
|
|
785
|
-
| `storage` | ✓ | Persistent storage and HNSW indexing |
|
|
786
|
-
| `metrics` | ✓ | Prometheus metrics export |
|
|
787
|
-
| `server` | ✗ | HTTP server with Axum |
|
|
788
|
-
| `real-inference` | ✗ | Candle-based real LLM inference |
|
|
789
|
-
| `hf-export` | ✗ | HuggingFace export via ruvector-sona |
|
|
790
|
-
| `full` | ✗ | All features enabled |
|
|
791
342
|
|
|
343
|
+
## API Reference
|
|
344
|
+
|
|
345
|
+
### RuvLLM Class
|
|
346
|
+
|
|
347
|
+
| Method | Description |
|
|
348
|
+
|--------|-------------|
|
|
349
|
+
| `query(text, config?)` | Query with automatic model routing |
|
|
350
|
+
| `generate(prompt, config?)` | Generate text with given prompt |
|
|
351
|
+
| `route(text)` | Get routing decision without executing |
|
|
352
|
+
| `addMemory(content, metadata?)` | Store content in vector memory |
|
|
353
|
+
| `searchMemory(text, k?)` | Find similar content (default k=10) |
|
|
354
|
+
| `feedback(fb)` | Submit feedback for learning |
|
|
355
|
+
| `embed(text)` | Get embedding vector for text |
|
|
356
|
+
| `similarity(t1, t2)` | Compute similarity between texts |
|
|
357
|
+
| `stats()` | Get engine statistics |
|
|
358
|
+
| `forceLearn()` | Trigger immediate learning cycle |
|
|
359
|
+
|
|
360
|
+
### SimdOps Class
|
|
361
|
+
|
|
362
|
+
| Method | Description |
|
|
363
|
+
|--------|-------------|
|
|
364
|
+
| `dotProduct(a, b)` | Vector dot product |
|
|
365
|
+
| `cosineSimilarity(a, b)` | Cosine similarity (0-1) |
|
|
366
|
+
| `l2Distance(a, b)` | Euclidean distance |
|
|
367
|
+
| `normalize(v)` | Normalize to unit length |
|
|
368
|
+
| `softmax(v)` | Softmax activation |
|
|
369
|
+
| `relu(v)` | ReLU activation |
|
|
370
|
+
| `gelu(v)` | GELU activation |
|
|
371
|
+
| `layerNorm(v, eps?)` | Layer normalization |
|
|
372
|
+
| `matvec(m, v)` | Matrix-vector multiply |
|
|
373
|
+
|
|
374
|
+
## Troubleshooting
|
|
375
|
+
|
|
376
|
+
**Q: Native module not loading?**
|
|
792
377
|
```bash
|
|
793
|
-
#
|
|
794
|
-
cargo build --release --features full
|
|
378
|
+
ruvllm info # Check if native is loaded
|
|
795
379
|
```
|
|
796
|
-
|
|
797
|
-
### ruvector-sona Features (Dependency)
|
|
798
|
-
|
|
799
|
-
| Feature | Default | Description |
|
|
800
|
-
|---------|---------|-------------|
|
|
801
|
-
| `serde-support` | ✓ | Serialization for export, training, and federated learning |
|
|
802
|
-
| `wasm` | ✗ | WebAssembly bindings for browser/edge deployment |
|
|
803
|
-
| `napi` | ✗ | N-API bindings for Node.js integration |
|
|
804
|
-
|
|
380
|
+
If "Native: Fallback", install platform-specific package manually:
|
|
805
381
|
```bash
|
|
806
|
-
|
|
807
|
-
cd crates/sona
|
|
808
|
-
wasm-pack build --target web --features wasm
|
|
382
|
+
npm install @ruvector/ruvllm-darwin-arm64 # For Apple Silicon
|
|
809
383
|
```
|
|
810
384
|
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|--------|---------|-------------|
|
|
817
|
-
| `embedding.dimension` | 768 | Embedding vector size |
|
|
818
|
-
| `embedding.max_tokens` | 512 | Max tokens per input |
|
|
819
|
-
| `memory.hnsw_m` | 16 | HNSW connections per node |
|
|
820
|
-
| `memory.hnsw_ef_construction` | 100 | Build quality parameter |
|
|
821
|
-
| `memory.hnsw_ef_search` | 64 | Search quality parameter |
|
|
822
|
-
| `router.input_dim` | 128 | Router input features |
|
|
823
|
-
| `router.hidden_dim` | 64 | FastGRNN hidden size |
|
|
824
|
-
| `router.sparsity` | 0.9 | Weight matrix sparsity |
|
|
825
|
-
| `router.rank` | 8 | Low-rank decomposition |
|
|
826
|
-
| `learning.enabled` | true | Enable self-learning |
|
|
827
|
-
| `learning.quality_threshold` | 0.7 | Min quality for writeback |
|
|
828
|
-
| `learning.ewc_lambda` | 2000 | EWC regularization strength |
|
|
829
|
-
| `sona.pattern_clusters` | 100 | K-means++ clusters |
|
|
830
|
-
| `sona.micro_lora_rank` | 2 | MicroLoRA rank |
|
|
831
|
-
|
|
832
|
-
### Federated Learning Configuration
|
|
833
|
-
|
|
834
|
-
| Option | Default | Description |
|
|
835
|
-
|--------|---------|-------------|
|
|
836
|
-
| `federated.quality_threshold` | 0.4 | Min quality for trajectory acceptance |
|
|
837
|
-
| `federated.consolidation_interval` | 50 | Auto-consolidate every N agents |
|
|
838
|
-
| `federated.coordinator_capacity` | 50000 | Trajectory buffer size for coordinator |
|
|
839
|
-
| `federated.agent_capacity` | 500 | Trajectory buffer size per agent |
|
|
840
|
-
| `federated.base_lora_rank` | 16 | Coordinator LoRA rank (deeper for aggregation) |
|
|
841
|
-
|
|
842
|
-
---
|
|
843
|
-
|
|
844
|
-
## Self-Learning Improvement Over Time
|
|
845
|
-
|
|
846
|
-
| Epoch | Queries | Quality | Routing | Cache Hit | Memory | Improvement |
|
|
847
|
-
|-------|---------|---------|---------|-----------|--------|-------------|
|
|
848
|
-
| 0 | 0 | 65.0% | 50.0% | 0.0% | 0 | 0.0% (baseline) |
|
|
849
|
-
| 1 | 50 | 67.2% | 58.0% | 10.0% | 25 | +3.4% |
|
|
850
|
-
| 2 | 100 | 69.8% | 66.0% | 20.0% | 50 | +7.4% |
|
|
851
|
-
| 3 | 150 | 71.5% | 74.0% | 30.0% | 75 | +10.0% |
|
|
852
|
-
| 4 | 200 | 73.2% | 82.0% | 40.0% | 100 | +12.6% |
|
|
853
|
-
| 5 | 250 | 74.8% | 90.0% | 50.0% | 125 | +15.1% |
|
|
854
|
-
|
|
855
|
-
---
|
|
856
|
-
|
|
857
|
-
## References
|
|
858
|
-
|
|
859
|
-
- [TinyRecursiveModels](https://github.com/SamsungSAILMontreal/TinyRecursiveModels) - Samsung SAIL Montreal's recursive reasoning approach
|
|
860
|
-
- [LFM2: Liquid Foundation Models](https://arxiv.org/abs/2511.23404v1) - Gated convolutions + grouped query attention
|
|
861
|
-
- [FastGRNN](https://arxiv.org/abs/1901.02358) - Fast, Accurate, Stable and Tiny GRU
|
|
862
|
-
- [HNSW](https://arxiv.org/abs/1603.09320) - Hierarchical Navigable Small World Graphs
|
|
863
|
-
- [EWC](https://arxiv.org/abs/1612.00796) - Elastic Weight Consolidation
|
|
864
|
-
- [LoRA](https://arxiv.org/abs/2106.09685) - Low-Rank Adaptation of Large Language Models
|
|
865
|
-
|
|
866
|
-
---
|
|
867
|
-
|
|
868
|
-
## License
|
|
869
|
-
|
|
870
|
-
Licensed under either of:
|
|
871
|
-
|
|
872
|
-
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
|
|
873
|
-
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
|
|
385
|
+
**Q: Memory usage too high?**
|
|
386
|
+
Reduce HNSW parameters:
|
|
387
|
+
```typescript
|
|
388
|
+
const llm = new RuvLLM({ hnswM: 8, hnswEfConstruction: 50 });
|
|
389
|
+
```
|
|
874
390
|
|
|
875
|
-
|
|
391
|
+
**Q: Learning not improving results?**
|
|
392
|
+
Check that feedback is being processed:
|
|
393
|
+
```typescript
|
|
394
|
+
const stats = llm.stats();
|
|
395
|
+
console.log(`Patterns learned: ${stats.patternsLearned}`);
|
|
396
|
+
```
|
|
876
397
|
|
|
877
|
-
##
|
|
398
|
+
## License
|
|
878
399
|
|
|
879
|
-
|
|
400
|
+
MIT OR Apache-2.0
|
|
880
401
|
|
|
881
|
-
|
|
402
|
+
## Links
|
|
882
403
|
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
</p>
|
|
404
|
+
- [GitHub Repository](https://github.com/ruvnet/ruvector)
|
|
405
|
+
- [Documentation](https://github.com/ruvnet/ruvector/tree/main/examples/ruvLLM)
|
|
406
|
+
- [Issue Tracker](https://github.com/ruvnet/ruvector/issues)
|