@ruvector/ruvllm 0.2.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 (75) hide show
  1. package/README.md +406 -0
  2. package/bin/cli.js +387 -0
  3. package/dist/cjs/engine.d.ts +90 -0
  4. package/dist/cjs/engine.d.ts.map +1 -0
  5. package/dist/cjs/engine.js +301 -0
  6. package/dist/cjs/export.d.ts +182 -0
  7. package/dist/cjs/export.d.ts.map +1 -0
  8. package/dist/cjs/export.js +422 -0
  9. package/dist/cjs/federated.d.ts +233 -0
  10. package/dist/cjs/federated.d.ts.map +1 -0
  11. package/dist/cjs/federated.js +525 -0
  12. package/dist/cjs/index.d.ts +64 -0
  13. package/dist/cjs/index.d.ts.map +1 -0
  14. package/dist/cjs/index.js +96 -0
  15. package/dist/cjs/lora.d.ts +240 -0
  16. package/dist/cjs/lora.d.ts.map +1 -0
  17. package/dist/cjs/lora.js +494 -0
  18. package/dist/cjs/native.d.ts +83 -0
  19. package/dist/cjs/native.d.ts.map +1 -0
  20. package/dist/cjs/native.js +70 -0
  21. package/dist/cjs/session.d.ts +80 -0
  22. package/dist/cjs/session.d.ts.map +1 -0
  23. package/dist/cjs/session.js +203 -0
  24. package/dist/cjs/simd.d.ts +90 -0
  25. package/dist/cjs/simd.d.ts.map +1 -0
  26. package/dist/cjs/simd.js +209 -0
  27. package/dist/cjs/sona.d.ts +187 -0
  28. package/dist/cjs/sona.d.ts.map +1 -0
  29. package/dist/cjs/sona.js +500 -0
  30. package/dist/cjs/streaming.d.ts +55 -0
  31. package/dist/cjs/streaming.d.ts.map +1 -0
  32. package/dist/cjs/streaming.js +131 -0
  33. package/dist/cjs/training.d.ts +254 -0
  34. package/dist/cjs/training.d.ts.map +1 -0
  35. package/dist/cjs/training.js +480 -0
  36. package/dist/cjs/types.d.ts +599 -0
  37. package/dist/cjs/types.d.ts.map +1 -0
  38. package/dist/cjs/types.js +6 -0
  39. package/dist/esm/engine.d.ts +90 -0
  40. package/dist/esm/engine.d.ts.map +1 -0
  41. package/dist/esm/engine.js +297 -0
  42. package/dist/esm/export.d.ts +182 -0
  43. package/dist/esm/export.d.ts.map +1 -0
  44. package/dist/esm/export.js +414 -0
  45. package/dist/esm/federated.d.ts +233 -0
  46. package/dist/esm/federated.d.ts.map +1 -0
  47. package/dist/esm/federated.js +520 -0
  48. package/dist/esm/index.d.ts +64 -0
  49. package/dist/esm/index.d.ts.map +1 -0
  50. package/dist/esm/index.js +76 -0
  51. package/dist/esm/lora.d.ts +240 -0
  52. package/dist/esm/lora.d.ts.map +1 -0
  53. package/dist/esm/lora.js +489 -0
  54. package/dist/esm/native.d.ts +83 -0
  55. package/dist/esm/native.d.ts.map +1 -0
  56. package/dist/esm/native.js +65 -0
  57. package/dist/esm/session.d.ts +80 -0
  58. package/dist/esm/session.d.ts.map +1 -0
  59. package/dist/esm/session.js +199 -0
  60. package/dist/esm/simd.d.ts +90 -0
  61. package/dist/esm/simd.d.ts.map +1 -0
  62. package/dist/esm/simd.js +205 -0
  63. package/dist/esm/sona.d.ts +187 -0
  64. package/dist/esm/sona.d.ts.map +1 -0
  65. package/dist/esm/sona.js +494 -0
  66. package/dist/esm/streaming.d.ts +55 -0
  67. package/dist/esm/streaming.d.ts.map +1 -0
  68. package/dist/esm/streaming.js +126 -0
  69. package/dist/esm/training.d.ts +254 -0
  70. package/dist/esm/training.d.ts.map +1 -0
  71. package/dist/esm/training.js +473 -0
  72. package/dist/esm/types.d.ts +599 -0
  73. package/dist/esm/types.d.ts.map +1 -0
  74. package/dist/esm/types.js +5 -0
  75. package/package.json +121 -0
package/README.md ADDED
@@ -0,0 +1,406 @@
1
+ # @ruvector/ruvllm
2
+
3
+ **Build AI that learns and improves from every interaction.**
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:
10
+
11
+ 1. **It Learns Without Forgetting** - Uses tiny parameter updates (LoRA) and memory protection (EWC++) to learn new patterns while preserving existing knowledge
12
+
13
+ 2. **It Remembers Context** - Built-in vector memory stores and retrieves relevant information instantly using similarity search
14
+
15
+ 3. **It Routes Intelligently** - Automatically selects the right model size and parameters based on query complexity, saving resources on simple tasks
16
+
17
+ ## Key Features
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 |
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ npm install @ruvector/ruvllm
36
+ ```
37
+
38
+ Or run directly:
39
+
40
+ ```bash
41
+ npx @ruvector/ruvllm info
42
+ ```
43
+
44
+ ## Quick Start Tutorial
45
+
46
+ ### 1. Basic Query
47
+
48
+ ```typescript
49
+ import { RuvLLM } from '@ruvector/ruvllm';
50
+
51
+ const llm = new RuvLLM();
52
+
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..."
57
+
58
+ console.log(`Used model: ${response.model}`);
59
+ console.log(`Confidence: ${(response.confidence * 100).toFixed(1)}%`);
60
+ ```
61
+
62
+ ### 2. Teaching the System
63
+
64
+ ```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
+ });
74
+
75
+ // Future similar queries will be more accurate
76
+ ```
77
+
78
+ ### 3. Using Memory
79
+
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
+ });
86
+
87
+ llm.addMemory('Product X launched in March 2024 with features A, B, C', {
88
+ category: 'product',
89
+ name: 'Product X'
90
+ });
91
+
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)}%`);
97
+ ```
98
+
99
+ ### 4. Computing Similarity
100
+
101
+ ```typescript
102
+ import { SimdOps } from '@ruvector/ruvllm';
103
+
104
+ const simd = new SimdOps();
105
+
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%"
113
+
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);
118
+ ```
119
+
120
+ ### 5. Batch Processing
121
+
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
+ });
132
+
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`);
137
+ ```
138
+
139
+ ## CLI Commands
140
+
141
+ ```bash
142
+ # Get system information
143
+ ruvllm info
144
+
145
+ # Query the model
146
+ ruvllm query "What is quantum computing?"
147
+
148
+ # Generate text with custom settings
149
+ ruvllm generate "Write a product description for:" --temperature 0.8 --max-tokens 200
150
+
151
+ # Memory operations
152
+ ruvllm memory add "Important fact to remember"
153
+ ruvllm memory search "fact" --k 10
154
+
155
+ # Compare texts
156
+ ruvllm similarity "hello world" "hi there"
157
+
158
+ # Get embeddings
159
+ ruvllm embed "your text here"
160
+
161
+ # Run performance benchmark
162
+ ruvllm benchmark --dims 768 --iterations 5000
163
+
164
+ # View statistics
165
+ ruvllm stats --json
166
+ ```
167
+
168
+ ## Benchmarks
169
+
170
+ *Benchmarked in Docker (node:20-alpine, x64) - December 2024*
171
+
172
+ ### Core Operations
173
+
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** |
182
+
183
+ ### SIMD Vector Operations
184
+
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** |
190
+
191
+ ### LoRA Adapter Performance
192
+
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** | - |
200
+
201
+ ### Memory Operations
202
+
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** |
209
+
210
+ ### SONA Learning System
211
+
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** |
219
+
220
+ ### Federated Learning
221
+
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** |
229
+
230
+ ### Session & Streaming
231
+
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** |
238
+
239
+ ### Training Pipeline
240
+
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 |
246
+
247
+ ### Export/Import
248
+
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** |
255
+
256
+ ### Performance Highlights
257
+
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**
263
+
264
+ ## Configuration
265
+
266
+ ```typescript
267
+ const llm = new RuvLLM({
268
+ // Embedding settings
269
+ embeddingDim: 768, // Vector dimensions (384, 768, 1024)
270
+
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)
275
+
276
+ // Learning settings
277
+ learningEnabled: true, // Enable adaptive learning
278
+ qualityThreshold: 0.7, // Min confidence to skip learning
279
+ ewcLambda: 2000, // Memory protection strength
280
+
281
+ // Router settings
282
+ routerHiddenDim: 128, // Router network size
283
+ });
284
+ ```
285
+
286
+ ## Platform Support
287
+
288
+ Native acceleration available on:
289
+
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 |
297
+
298
+ Falls back to optimized JavaScript on unsupported platforms.
299
+
300
+ ## Real-World Use Cases
301
+
302
+ ### Customer Support Bot
303
+ ```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);
312
+ }
313
+ ```
314
+
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
+ });
324
+
325
+ // Semantic search
326
+ const results = llm.searchMemory('quarterly revenue growth', 10);
327
+ ```
328
+
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
+ }
336
+
337
+ // Get recommendations
338
+ function recommend(userId: string) {
339
+ return llm.searchMemory(`preferences for user ${userId}`, 10);
340
+ }
341
+ ```
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?**
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
383
+ ```
384
+
385
+ **Q: Memory usage too high?**
386
+ Reduce HNSW parameters:
387
+ ```typescript
388
+ const llm = new RuvLLM({ hnswM: 8, hnswEfConstruction: 50 });
389
+ ```
390
+
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
+ ```
397
+
398
+ ## License
399
+
400
+ MIT OR Apache-2.0
401
+
402
+ ## Links
403
+
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)