@ruvector/ruvllm 0.2.4 → 2.4.0

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.
Files changed (100) hide show
  1. package/README.md +413 -293
  2. package/bin/cli.js +619 -2
  3. package/dist/cjs/benchmarks/embedding-benchmark.d.ts +102 -0
  4. package/dist/cjs/benchmarks/embedding-benchmark.d.ts.map +1 -0
  5. package/dist/cjs/benchmarks/embedding-benchmark.js +436 -0
  6. package/dist/cjs/benchmarks/index.d.ts +34 -0
  7. package/dist/cjs/benchmarks/index.d.ts.map +1 -0
  8. package/dist/cjs/benchmarks/index.js +132 -0
  9. package/dist/cjs/benchmarks/model-comparison.d.ts +71 -0
  10. package/dist/cjs/benchmarks/model-comparison.d.ts.map +1 -0
  11. package/dist/cjs/benchmarks/model-comparison.js +476 -0
  12. package/dist/cjs/benchmarks/routing-benchmark.d.ts +70 -0
  13. package/dist/cjs/benchmarks/routing-benchmark.d.ts.map +1 -0
  14. package/dist/cjs/benchmarks/routing-benchmark.js +289 -0
  15. package/dist/cjs/contrastive.d.ts +229 -0
  16. package/dist/cjs/contrastive.d.ts.map +1 -0
  17. package/dist/cjs/contrastive.js +589 -0
  18. package/dist/cjs/engine.d.ts +3 -0
  19. package/dist/cjs/engine.d.ts.map +1 -1
  20. package/dist/cjs/engine.js +26 -6
  21. package/dist/cjs/index.d.ts +4 -0
  22. package/dist/cjs/index.d.ts.map +1 -1
  23. package/dist/cjs/index.js +9 -1
  24. package/dist/cjs/models.d.ts +129 -0
  25. package/dist/cjs/models.d.ts.map +1 -0
  26. package/dist/cjs/models.js +323 -0
  27. package/dist/cjs/native.d.ts +3 -3
  28. package/dist/cjs/native.d.ts.map +1 -1
  29. package/dist/cjs/native.js +1 -1
  30. package/dist/cjs/rlm/controller.d.ts +245 -0
  31. package/dist/cjs/rlm/controller.d.ts.map +1 -0
  32. package/dist/cjs/rlm/controller.js +554 -0
  33. package/dist/cjs/rlm/index.d.ts +62 -0
  34. package/dist/cjs/rlm/index.d.ts.map +1 -0
  35. package/dist/cjs/rlm/index.js +97 -0
  36. package/dist/cjs/rlm/training.d.ts +333 -0
  37. package/dist/cjs/rlm/training.d.ts.map +1 -0
  38. package/dist/cjs/rlm/training.js +680 -0
  39. package/dist/cjs/rlm/types.d.ts +189 -0
  40. package/dist/cjs/rlm/types.d.ts.map +1 -0
  41. package/dist/cjs/rlm/types.js +10 -0
  42. package/dist/esm/benchmarks/embedding-benchmark.d.ts +102 -0
  43. package/dist/esm/benchmarks/embedding-benchmark.d.ts.map +1 -0
  44. package/dist/esm/benchmarks/embedding-benchmark.js +427 -0
  45. package/dist/esm/benchmarks/index.d.ts +34 -0
  46. package/dist/esm/benchmarks/index.d.ts.map +1 -0
  47. package/dist/esm/benchmarks/index.js +110 -0
  48. package/dist/esm/benchmarks/model-comparison.d.ts +71 -0
  49. package/dist/esm/benchmarks/model-comparison.d.ts.map +1 -0
  50. package/dist/esm/benchmarks/model-comparison.js +434 -0
  51. package/dist/esm/benchmarks/routing-benchmark.d.ts +70 -0
  52. package/dist/esm/benchmarks/routing-benchmark.d.ts.map +1 -0
  53. package/dist/esm/benchmarks/routing-benchmark.js +283 -0
  54. package/dist/esm/contrastive.d.ts +229 -0
  55. package/dist/esm/contrastive.d.ts.map +1 -0
  56. package/dist/esm/contrastive.js +578 -0
  57. package/dist/esm/engine.d.ts +3 -0
  58. package/dist/esm/engine.d.ts.map +1 -1
  59. package/dist/esm/engine.js +26 -6
  60. package/dist/esm/index.d.ts +4 -0
  61. package/dist/esm/index.d.ts.map +1 -1
  62. package/dist/esm/index.js +9 -1
  63. package/dist/esm/models.d.ts +129 -0
  64. package/dist/esm/models.d.ts.map +1 -0
  65. package/dist/esm/models.js +282 -0
  66. package/dist/esm/native.d.ts +3 -3
  67. package/dist/esm/native.d.ts.map +1 -1
  68. package/dist/esm/native.js +1 -1
  69. package/dist/esm/rlm/controller.d.ts +245 -0
  70. package/dist/esm/rlm/controller.d.ts.map +1 -0
  71. package/dist/esm/rlm/controller.js +550 -0
  72. package/dist/esm/rlm/index.d.ts +62 -0
  73. package/dist/esm/rlm/index.d.ts.map +1 -0
  74. package/dist/esm/rlm/index.js +71 -0
  75. package/dist/esm/rlm/training.d.ts +333 -0
  76. package/dist/esm/rlm/training.d.ts.map +1 -0
  77. package/dist/esm/rlm/training.js +672 -0
  78. package/dist/esm/rlm/types.d.ts +189 -0
  79. package/dist/esm/rlm/types.d.ts.map +1 -0
  80. package/dist/esm/rlm/types.js +9 -0
  81. package/package.json +13 -8
  82. package/scripts/ensemble-model-compare.js +287 -0
  83. package/scripts/huggingface/README.md +537 -0
  84. package/scripts/huggingface/publish.sh +112 -0
  85. package/scripts/hybrid-model-compare.js +373 -0
  86. package/scripts/improved-model-compare.js +288 -0
  87. package/scripts/optimized-model-compare.js +364 -0
  88. package/scripts/real-model-compare.js +280 -0
  89. package/scripts/training/agentic-flow-capabilities.json +329 -0
  90. package/scripts/training/claude-code-synth.js +505 -0
  91. package/scripts/training/claude-flow-capabilities.json +1322 -0
  92. package/scripts/training/claude-hard-negatives.js +222 -0
  93. package/scripts/training/contrastive-finetune.js +517 -0
  94. package/scripts/training/ecosystem-triplets.jsonl +1467 -0
  95. package/scripts/training/generate-ecosystem-triplets.js +1324 -0
  96. package/scripts/training/rlm-dataset.js +671 -0
  97. package/scripts/training/routing-dataset.js +634 -0
  98. package/scripts/training/ruvector-capabilities.json +798 -0
  99. package/scripts/training/validate-ecosystem.js +381 -0
  100. package/scripts/training/validation-results.json +23 -0
package/README.md CHANGED
@@ -1,406 +1,526 @@
1
- # @ruvector/ruvllm
1
+ # @ruvector/ruvllm v2.4
2
2
 
3
- **Build AI that learns and improves from every interaction.**
3
+ Self-learning LLM orchestration with SONA adaptive learning, HNSW memory, RLM recursive retrieval, and SIMD inference for Node.js.
4
4
 
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.
6
-
7
- ## What Makes RuvLLM Different?
8
-
9
- Traditional LLMs forget old knowledge when learning new things (called "catastrophic forgetting"). RuvLLM solves this with three key innovations:
5
+ ## Installation
10
6
 
11
- 1. **It Learns Without Forgetting** - Uses tiny parameter updates (LoRA) and memory protection (EWC++) to learn new patterns while preserving existing knowledge
7
+ ```bash
8
+ npm install @ruvector/ruvllm
9
+ ```
12
10
 
13
- 2. **It Remembers Context** - Built-in vector memory stores and retrieves relevant information instantly using similarity search
11
+ ## Quick Start
14
12
 
15
- 3. **It Routes Intelligently** - Automatically selects the right model size and parameters based on query complexity, saving resources on simple tasks
13
+ ```typescript
14
+ import { RuvLLM, RuvLLMConfig } from '@ruvector/ruvllm';
16
15
 
17
- ## Key Features
16
+ // Initialize with default configuration
17
+ const llm = new RuvLLM();
18
18
 
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 |
19
+ // Or with custom configuration
20
+ const llm = new RuvLLM({
21
+ modelPath: './models/ruvltra-small-q4km.gguf',
22
+ sonaEnabled: true,
23
+ flashAttention: true,
24
+ maxTokens: 256,
25
+ });
31
26
 
32
- ## Installation
27
+ // Generate text
28
+ const response = await llm.query('Explain quantum computing');
29
+ console.log(response.text);
33
30
 
34
- ```bash
35
- npm install @ruvector/ruvllm
31
+ // Stream generation
32
+ for await (const token of llm.stream('Write a haiku about Rust')) {
33
+ process.stdout.write(token);
34
+ }
36
35
  ```
37
36
 
38
- Or run directly:
37
+ ## What's New in v2.4
39
38
 
40
- ```bash
41
- npx @ruvector/ruvllm info
42
- ```
39
+ | Feature | Description |
40
+ |---------|-------------|
41
+ | **RLM (Recursive Language Model)** | Query decomposition with recursive retrieval and synthesis |
42
+ | **100% Routing Accuracy** | Hybrid keyword-first strategy achieves 100% on Claude Code tasks |
43
+ | **145 Tests Passing** | Comprehensive test coverage across all modules |
44
+ | **Contrastive Fine-tuning** | LoRA-based training with 793 contrastive pairs |
45
+ | **Training Scripts** | Generate routing datasets and fine-tune models |
46
+ | **HuggingFace Models** | Pre-trained RuvLTRA models available |
47
+
48
+ ## RLM (Recursive Language Model)
43
49
 
44
- ## Quick Start Tutorial
50
+ RLM provides recursive retrieval-augmented generation that breaks down complex queries into sub-queries and synthesizes answers from retrieved context.
45
51
 
46
- ### 1. Basic Query
52
+ ### Basic Usage
47
53
 
48
54
  ```typescript
49
- import { RuvLLM } from '@ruvector/ruvllm';
55
+ import { RlmController } from '@ruvector/ruvllm';
50
56
 
51
- const llm = new RuvLLM();
57
+ const rlm = new RlmController({
58
+ maxDepth: 5,
59
+ retrievalTopK: 10,
60
+ enableCache: true,
61
+ });
52
62
 
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..."
63
+ // Add knowledge to memory
64
+ await rlm.addMemory('TypeScript adds static typing to JavaScript.');
65
+ await rlm.addMemory('React is a library for building user interfaces.');
57
66
 
58
- console.log(`Used model: ${response.model}`);
59
- console.log(`Confidence: ${(response.confidence * 100).toFixed(1)}%`);
67
+ // Query with recursive retrieval
68
+ const answer = await rlm.query('What are causes and solutions for type errors in React?');
69
+ console.log(answer.text);
70
+ console.log('Sources:', answer.sources);
71
+ console.log('Quality Score:', answer.qualityScore);
72
+ console.log('Confidence:', answer.confidence);
60
73
  ```
61
74
 
62
- ### 2. Teaching the System
75
+ ### Streaming
63
76
 
64
77
  ```typescript
65
- // Query and get a response
66
- const response = llm.query('What is the capital of France?');
67
-
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
- });
78
+ import { RlmController } from '@ruvector/ruvllm';
79
+
80
+ const rlm = new RlmController();
74
81
 
75
- // Future similar queries will be more accurate
82
+ for await (const event of rlm.queryStream('Explain machine learning')) {
83
+ if (event.type === 'token') {
84
+ process.stdout.write(event.text);
85
+ } else {
86
+ console.log('\n\nQuality:', event.answer.qualityScore);
87
+ }
88
+ }
76
89
  ```
77
90
 
78
- ### 3. Using Memory
91
+ ### With Reflection
79
92
 
80
93
  ```typescript
81
- // Store important context
82
- llm.addMemory('Company policy: All returns accepted within 30 days', {
83
- category: 'policy',
84
- department: 'customer-service'
85
- });
94
+ import { RlmController } from '@ruvector/ruvllm';
86
95
 
87
- llm.addMemory('Product X launched in March 2024 with features A, B, C', {
88
- category: 'product',
89
- name: 'Product X'
96
+ const rlm = new RlmController({
97
+ enableReflection: true,
98
+ maxReflectionIterations: 2,
99
+ minQualityScore: 0.8,
90
100
  });
91
101
 
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)}%`);
102
+ // Answers will be iteratively refined until quality >= 0.8
103
+ const answer = await rlm.query('Complex multi-part technical question...');
97
104
  ```
98
105
 
99
- ### 4. Computing Similarity
106
+ ### RLM Configuration
100
107
 
101
108
  ```typescript
102
- import { SimdOps } from '@ruvector/ruvllm';
103
-
104
- const simd = new SimdOps();
109
+ interface RlmConfig {
110
+ maxDepth?: number; // Max recursion depth (default: 3)
111
+ maxSubQueries?: number; // Max sub-queries per level (default: 5)
112
+ tokenBudget?: number; // Token budget (default: 4096)
113
+ enableCache?: boolean; // Enable caching (default: true)
114
+ cacheTtl?: number; // Cache TTL in ms (default: 300000)
115
+ retrievalTopK?: number; // Memory spans to retrieve (default: 10)
116
+ minQualityScore?: number; // Min quality threshold (default: 0.7)
117
+ enableReflection?: boolean; // Enable self-reflection (default: false)
118
+ maxReflectionIterations?: number; // Max reflection loops (default: 2)
119
+ }
120
+ ```
105
121
 
106
- // Compare two texts
107
- const score = llm.similarity(
108
- 'How do I reset my password?',
109
- 'I forgot my login credentials'
110
- );
111
- console.log(`Similarity: ${(score * 100).toFixed(1)}%`);
112
- // Output: "Similarity: 78.3%"
122
+ ## Exports
113
123
 
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);
124
+ ```typescript
125
+ import {
126
+ // Core
127
+ RuvLLM,
128
+ RuvLLMConfig,
129
+
130
+ // RLM - Recursive Language Model
131
+ RlmController,
132
+ RlmConfig,
133
+ RlmAnswer,
134
+ MemorySpan,
135
+ StreamToken,
136
+
137
+ // RLM Training
138
+ RlmTrainer,
139
+ RlmTrainingConfig,
140
+ RlmTrainingExample,
141
+ createRlmTrainer,
142
+ DEFAULT_RLM_CONFIG,
143
+ FAST_RLM_CONFIG,
144
+ THOROUGH_RLM_CONFIG,
145
+ ROUTING_FOCUSED_CONFIG,
146
+
147
+ // SONA Learning
148
+ SonaCoordinator,
149
+ TrajectoryBuilder,
150
+
151
+ // Federated Learning
152
+ EphemeralAgent,
153
+ FederatedCoordinator,
154
+
155
+ // LoRA Adapters
156
+ LoraAdapter,
157
+ LoraManager,
158
+
159
+ // Sessions
160
+ SessionManager,
161
+
162
+ // Contrastive Training
163
+ ContrastiveTrainer,
164
+
165
+ // Benchmarks
166
+ ModelComparisonBenchmark,
167
+ RoutingBenchmark,
168
+ EmbeddingBenchmark,
169
+ } from '@ruvector/ruvllm';
118
170
  ```
119
171
 
120
- ### 5. Batch Processing
172
+ ## Performance
121
173
 
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
- });
174
+ ### Test Results
132
175
 
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`);
176
+ ```
177
+ 145 tests passing
178
+ - RLM Controller: 24 tests
179
+ - Routing Accuracy: 18 tests
180
+ - Contrastive Training: 15 tests
181
+ - SIMD Operations: 22 tests
182
+ - SONA Learning: 19 tests
183
+ - Memory/HNSW: 21 tests
184
+ - Benchmarks: 26 tests
137
185
  ```
138
186
 
139
- ## CLI Commands
187
+ ### Routing Accuracy (Claude Code Tasks)
140
188
 
141
- ```bash
142
- # Get system information
143
- ruvllm info
189
+ | Strategy | RuvLTRA | Qwen Base |
190
+ |----------|---------|-----------|
191
+ | Embedding Only | 45% | 40% |
192
+ | Keyword-First (Hybrid) | **100%** | 95% |
144
193
 
145
- # Query the model
146
- ruvllm query "What is quantum computing?"
194
+ ### Inference Performance (M4 Pro)
147
195
 
148
- # Generate text with custom settings
149
- ruvllm generate "Write a product description for:" --temperature 0.8 --max-tokens 200
196
+ | Operation | Performance |
197
+ |-----------|-------------|
198
+ | Inference | 88-135 tok/s |
199
+ | Flash Attention | 320us (seq=2048) |
200
+ | HNSW Search | 17-62us |
201
+ | SONA Adapt | <1ms |
202
+ | RLM Query | 50-200ms |
150
203
 
151
- # Memory operations
152
- ruvllm memory add "Important fact to remember"
153
- ruvllm memory search "fact" --k 10
204
+ ### SIMD Optimizations
154
205
 
155
- # Compare texts
156
- ruvllm similarity "hello world" "hi there"
206
+ - AVX2/AVX-512 on x86_64
207
+ - NEON on ARM64
208
+ - 4-8x speedup on vector operations
157
209
 
158
- # Get embeddings
159
- ruvllm embed "your text here"
210
+ ## CLI Usage
160
211
 
161
- # Run performance benchmark
162
- ruvllm benchmark --dims 768 --iterations 5000
212
+ ```bash
213
+ # Query a model
214
+ ruvllm query "What is machine learning?"
163
215
 
164
- # View statistics
165
- ruvllm stats --json
166
- ```
216
+ # Stream output
217
+ ruvllm query --stream "Write a poem"
167
218
 
168
- ## Benchmarks
219
+ # Download a model
220
+ ruvllm download ruvector/ruvltra-small-q4km
169
221
 
170
- *Benchmarked in Docker (node:20-alpine, x64) - December 2024*
222
+ # Benchmark
223
+ ruvllm bench ./models/model.gguf
171
224
 
172
- ### Core Operations
225
+ # Run evaluation (SWE-Bench)
226
+ ruvllm eval --model ./models/model.gguf --subset lite --max-tasks 50
227
+ ```
173
228
 
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** |
229
+ ## Training
182
230
 
183
- ### SIMD Vector Operations
231
+ ### Routing Dataset Generation
184
232
 
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** |
233
+ Generate training data for agent routing:
190
234
 
191
- ### LoRA Adapter Performance
235
+ ```bash
236
+ # Generate routing dataset
237
+ node scripts/training/routing-dataset.js
192
238
 
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** | - |
239
+ # Output: 381 examples, 793 contrastive pairs
240
+ ```
200
241
 
201
- ### Memory Operations
242
+ ### Contrastive Fine-tuning
202
243
 
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** |
244
+ Fine-tune models with LoRA adapters:
209
245
 
210
- ### SONA Learning System
246
+ ```typescript
247
+ import { ContrastiveTrainer, ContrastivePair } from '@ruvector/ruvllm';
211
248
 
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** |
249
+ const trainer = new ContrastiveTrainer({
250
+ modelPath: './models/base.gguf',
251
+ loraRank: 8,
252
+ loraAlpha: 16,
253
+ learningRate: 1e-4,
254
+ });
219
255
 
220
- ### Federated Learning
256
+ // Training pairs from routing dataset
257
+ const pairs: ContrastivePair[] = [
258
+ {
259
+ anchor: 'Fix the authentication bug in login.ts',
260
+ positive: 'coder',
261
+ negative: 'researcher',
262
+ },
263
+ // ... more pairs
264
+ ];
265
+
266
+ await trainer.train(pairs, { epochs: 10, batchSize: 32 });
267
+ await trainer.save('./adapters/routing-lora');
268
+ ```
221
269
 
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** |
270
+ ### Training Scripts
229
271
 
230
- ### Session & Streaming
272
+ Located in `scripts/training/`:
231
273
 
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** |
274
+ | Script | Description |
275
+ |--------|-------------|
276
+ | `routing-dataset.js` | Generate 381 routing examples |
277
+ | `claude-code-synth.js` | Synthetic data generation |
278
+ | `contrastive-finetune.js` | LoRA fine-tuning pipeline |
238
279
 
239
- ### Training Pipeline
280
+ ## Model Links
240
281
 
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 |
282
+ ### HuggingFace Repository
246
283
 
247
- ### Export/Import
284
+ **URL**: [https://huggingface.co/ruv/ruvltra](https://huggingface.co/ruv/ruvltra)
248
285
 
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** |
286
+ ### Available Models
255
287
 
256
- ### Performance Highlights
288
+ | Model | File | Size | Purpose |
289
+ |-------|------|------|---------|
290
+ | RuvLTRA Claude Code 0.5B | `ruvltra-claude-code-0.5b-q4_k_m.gguf` | ~400MB | Agent routing (100% with hybrid) |
291
+ | RuvLTRA Small 0.5B | `ruvltra-0.5b-q4_k_m.gguf` | ~400MB | General embeddings |
292
+ | RuvLTRA Medium 3B | `ruvltra-3b-q4_k_m.gguf` | ~2GB | Full LLM inference |
257
293
 
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**
294
+ ### Download Models
263
295
 
264
- ## Configuration
296
+ ```bash
297
+ # Using CLI
298
+ ruvllm download ruv/ruvltra
265
299
 
266
- ```typescript
267
- const llm = new RuvLLM({
268
- // Embedding settings
269
- embeddingDim: 768, // Vector dimensions (384, 768, 1024)
300
+ # Using HuggingFace CLI
301
+ huggingface-cli download ruv/ruvltra ruvltra-claude-code-0.5b-q4_k_m.gguf
270
302
 
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)
303
+ # Programmatic download
304
+ import { downloadModel } from '@ruvector/ruvllm';
305
+ await downloadModel('ruv/ruvltra', { quantization: 'q4_k_m' });
306
+ ```
275
307
 
276
- // Learning settings
277
- learningEnabled: true, // Enable adaptive learning
278
- qualityThreshold: 0.7, // Min confidence to skip learning
279
- ewcLambda: 2000, // Memory protection strength
308
+ ### Environment Variables
280
309
 
281
- // Router settings
282
- routerHiddenDim: 128, // Router network size
283
- });
310
+ ```bash
311
+ # HuggingFace authentication (any of these)
312
+ HF_TOKEN=hf_xxx
313
+ HUGGING_FACE_HUB_TOKEN=hf_xxx
314
+ HUGGINGFACE_API_KEY=hf_xxx
284
315
  ```
285
316
 
286
- ## Platform Support
287
-
288
- Native acceleration available on:
317
+ ### Local Model Storage
289
318
 
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 |
319
+ ```bash
320
+ ~/.ruvllm/models/ # Downloaded GGUF models
321
+ ~/.ruvllm/training/ # Training data and configs
322
+ ```
297
323
 
298
- Falls back to optimized JavaScript on unsupported platforms.
324
+ ## API Reference
299
325
 
300
- ## Real-World Use Cases
326
+ ### RuvLLM Class
301
327
 
302
- ### Customer Support Bot
303
328
  ```typescript
304
- // Store FAQ and policies
305
- faqs.forEach(faq => llm.addMemory(faq.answer, { question: faq.question }));
306
-
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);
329
+ class RuvLLM {
330
+ constructor(config?: RuvLLMConfig);
331
+
332
+ // Generate text
333
+ query(prompt: string, params?: GenerateParams): Promise<Response>;
334
+
335
+ // Stream generation
336
+ stream(prompt: string, params?: GenerateParams): AsyncIterable<string>;
337
+
338
+ // Load a model
339
+ loadModel(path: string): Promise<void>;
340
+
341
+ // Memory operations
342
+ addMemory(text: string, metadata?: Record<string, unknown>): number;
343
+ searchMemory(query: string, topK?: number): MemoryResult[];
344
+
345
+ // Get SONA learning stats
346
+ sonaStats(): SonaStats | null;
347
+
348
+ // Adapt on feedback
349
+ adapt(input: Float32Array, quality: number): void;
312
350
  }
313
351
  ```
314
352
 
315
- ### Document Search
353
+ ### RlmController Class
354
+
316
355
  ```typescript
317
- // Index documents
318
- documents.forEach(doc => {
319
- llm.addMemory(doc.content, {
320
- title: doc.title,
321
- path: doc.path
322
- });
323
- });
356
+ class RlmController {
357
+ constructor(config?: RlmConfig, engine?: RuvLLM);
358
+
359
+ // Query with recursive retrieval
360
+ query(input: string): Promise<RlmAnswer>;
361
+
362
+ // Stream query
363
+ queryStream(input: string): AsyncGenerator<StreamToken>;
364
+
365
+ // Memory management
366
+ addMemory(text: string, metadata?: Record<string, unknown>): Promise<string>;
367
+ searchMemory(query: string, topK?: number): Promise<MemorySpan[]>;
324
368
 
325
- // Semantic search
326
- const results = llm.searchMemory('quarterly revenue growth', 10);
369
+ // Cache management
370
+ clearCache(): void;
371
+ getCacheStats(): { size: number; entries: number };
372
+
373
+ // Configuration
374
+ updateConfig(config: Partial<RlmConfig>): void;
375
+ getConfig(): Required<RlmConfig>;
376
+ }
327
377
  ```
328
378
 
329
- ### Personalized Recommendations
379
+ ### Configuration
380
+
330
381
  ```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 });
382
+ interface RuvLLMConfig {
383
+ modelPath?: string; // Path to GGUF model
384
+ sonaEnabled?: boolean; // Enable SONA learning (default: true)
385
+ flashAttention?: boolean; // Use Flash Attention 2 (default: true)
386
+ maxTokens?: number; // Max generation tokens (default: 256)
387
+ temperature?: number; // Sampling temperature (default: 0.7)
388
+ topP?: number; // Top-p sampling (default: 0.9)
335
389
  }
390
+ ```
391
+
392
+ ### Generate Parameters
336
393
 
337
- // Get recommendations
338
- function recommend(userId: string) {
339
- return llm.searchMemory(`preferences for user ${userId}`, 10);
394
+ ```typescript
395
+ interface GenerateParams {
396
+ maxTokens?: number;
397
+ temperature?: number;
398
+ topP?: number;
399
+ topK?: number;
400
+ repetitionPenalty?: number;
401
+ stopSequences?: string[];
340
402
  }
341
403
  ```
342
404
 
343
- ## API Reference
405
+ ## SIMD Module
344
406
 
345
- ### RuvLLM Class
407
+ For direct access to optimized SIMD kernels:
346
408
 
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?**
377
- ```bash
378
- ruvllm info # Check if native is loaded
379
- ```
380
- If "Native: Fallback", install platform-specific package manually:
381
- ```bash
382
- npm install @ruvector/ruvllm-darwin-arm64 # For Apple Silicon
409
+ ```typescript
410
+ import { simd } from '@ruvector/ruvllm/simd';
411
+
412
+ // Dot product
413
+ const result = simd.dotProduct(vecA, vecB);
414
+
415
+ // Matrix multiplication
416
+ const output = simd.matmul(matrix, vector);
417
+
418
+ // Flash Attention
419
+ const attended = simd.flashAttention(query, key, value, scale);
420
+
421
+ // RMS Normalization
422
+ simd.rmsNorm(hidden, weights, epsilon);
383
423
  ```
384
424
 
385
- **Q: Memory usage too high?**
386
- Reduce HNSW parameters:
425
+ ## Evaluation Harness
426
+
427
+ Run model evaluations with SWE-Bench integration:
428
+
387
429
  ```typescript
388
- const llm = new RuvLLM({ hnswM: 8, hnswEfConstruction: 50 });
430
+ import { RuvLLM, EvaluationHarness, AblationMode } from '@ruvector/ruvllm';
431
+
432
+ const harness = new EvaluationHarness({
433
+ modelPath: './models/model.gguf',
434
+ enableHnsw: true,
435
+ enableSona: true,
436
+ });
437
+
438
+ // Run single evaluation
439
+ const result = await harness.evaluate(
440
+ 'Fix the null pointer exception',
441
+ 'def process(data): return data.split()',
442
+ AblationMode.Full
443
+ );
444
+
445
+ console.log(`Success: ${result.success}, Quality: ${result.qualityScore}`);
446
+
447
+ // Run ablation study (Baseline, RetrievalOnly, AdaptersOnly, R+A, Full)
448
+ const report = await harness.runAblationStudy(tasks);
449
+ for (const [mode, metrics] of Object.entries(report.modeMetrics)) {
450
+ console.log(`${mode}: ${metrics.successRate * 100}% success`);
451
+ }
389
452
  ```
390
453
 
391
- **Q: Learning not improving results?**
392
- Check that feedback is being processed:
454
+ ## mistral-rs Backend (Production Serving)
455
+
456
+ For production deployments with 10-100+ concurrent users, use the mistral-rs backend:
457
+
393
458
  ```typescript
394
- const stats = llm.stats();
395
- console.log(`Patterns learned: ${stats.patternsLearned}`);
459
+ import { RuvLLM, MistralBackend, PagedAttentionConfig } from '@ruvector/ruvllm';
460
+
461
+ // Configure for production serving
462
+ const backend = new MistralBackend({
463
+ // PagedAttention: 5-10x more concurrent users
464
+ pagedAttention: {
465
+ blockSize: 16,
466
+ maxBlocks: 4096,
467
+ gpuMemoryFraction: 0.9,
468
+ prefixCaching: true,
469
+ },
470
+ // X-LoRA: Per-token adapter routing
471
+ xlora: {
472
+ adapters: ['./adapters/coder', './adapters/researcher'],
473
+ topK: 2,
474
+ },
475
+ // ISQ: Runtime quantization
476
+ isq: {
477
+ bits: 4,
478
+ method: 'awq',
479
+ },
480
+ });
481
+
482
+ const llm = new RuvLLM({ backend });
483
+ await llm.loadModel('mistralai/Mistral-7B-Instruct-v0.2');
484
+
485
+ // Serve multiple concurrent requests
486
+ const response = await llm.query('Write production code');
396
487
  ```
397
488
 
398
- ## License
489
+ > **Note**: mistral-rs features require the Rust backend with `mistral-rs` feature enabled. Native bindings will use mistral-rs when available.
399
490
 
400
- MIT OR Apache-2.0
491
+ ## Supported Models
492
+
493
+ - **RuvLTRA-Small** (494M) - Q4K, Q5K, Q8
494
+ - **RuvLTRA-Medium** (3B) - Q4K, Q5K, Q8
495
+ - **Qwen 2.5** (0.5B-72B)
496
+ - **Llama 3.x** (8B-70B)
497
+ - **Mistral** (7B-22B)
498
+ - **Phi-3** (3.8B-14B)
499
+ - **Gemma-2** (2B-27B)
500
+
501
+ ## Platform Support
502
+
503
+ | Platform | Architecture | Status |
504
+ |----------|--------------|--------|
505
+ | macOS | arm64 (M1-M4) | Full support |
506
+ | macOS | x64 | Supported |
507
+ | Linux | x64 | Supported |
508
+ | Linux | arm64 | Supported |
509
+ | Windows | x64 | Supported |
510
+
511
+ ## Related Packages
512
+
513
+ - [@ruvector/core](https://www.npmjs.com/package/@ruvector/core) - Vector operations
514
+ - [@ruvector/sona](https://www.npmjs.com/package/@ruvector/sona) - SONA learning engine
515
+ - [@ruvector/ruvector](https://www.npmjs.com/package/@ruvector/ruvector) - Full Ruvector SDK
401
516
 
402
517
  ## Links
403
518
 
404
519
  - [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)
520
+ - [HuggingFace Models](https://huggingface.co/ruv/ruvltra)
521
+ - [API Documentation](https://docs.rs/ruvllm)
522
+ - [Crate (Rust)](https://crates.io/crates/ruvllm)
523
+
524
+ ## License
525
+
526
+ MIT OR Apache-2.0