ruvllm 2.2.1

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Adapter Training Pipeline with Claude Dataset Support
//!
//! This module provides training infrastructure for task-specific adapters:
//! - Training from synthetic Claude datasets
//! - Gradient checkpointing for memory efficiency
//! - Mixed precision training (bf16/fp16)
//! - Early stopping based on validation loss
//! - Dataset generation utilities

use crate::error::{Result, RuvLLMError};
use crate::lora::adapters::{AdapterMetadata, LoraConfig};
use crate::lora::micro_lora::{AdaptFeedback, MicroLoRA};
use crate::lora::training::{LearningRateSchedule, TrainingConfig, TrainingPipeline};
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Training example for adapter fine-tuning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingExample {
    /// Input embedding or text representation
    pub input: Vec<f32>,
    /// Target output embedding
    pub target: Option<Vec<f32>>,
    /// Quality score for this example
    pub quality: f32,
    /// Optional task description
    pub task: Option<String>,
    /// Optional domain label
    pub domain: Option<String>,
}

impl TrainingExample {
    /// Create a new training example
    pub fn new(input: Vec<f32>, quality: f32) -> Self {
        Self {
            input,
            target: None,
            quality,
            task: None,
            domain: None,
        }
    }

    /// Set target output
    pub fn with_target(mut self, target: Vec<f32>) -> Self {
        self.target = Some(target);
        self
    }

    /// Set task description
    pub fn with_task(mut self, task: impl Into<String>) -> Self {
        self.task = Some(task.into());
        self
    }

    /// Set domain label
    pub fn with_domain(mut self, domain: impl Into<String>) -> Self {
        self.domain = Some(domain.into());
        self
    }
}

/// Dataset for adapter training
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdapterDataset {
    /// Training examples
    pub examples: Vec<TrainingExample>,
    /// Validation examples (optional)
    pub validation: Vec<TrainingExample>,
    /// Dataset name
    pub name: String,
    /// Dataset description
    pub description: String,
    /// Feature dimension
    pub feature_dim: usize,
}

impl AdapterDataset {
    /// Create a new empty dataset
    pub fn new(name: impl Into<String>, feature_dim: usize) -> Self {
        Self {
            examples: Vec::new(),
            validation: Vec::new(),
            name: name.into(),
            description: String::new(),
            feature_dim,
        }
    }

    /// Add a training example
    pub fn add_example(&mut self, example: TrainingExample) {
        self.examples.push(example);
    }

    /// Add a validation example
    pub fn add_validation(&mut self, example: TrainingExample) {
        self.validation.push(example);
    }

    /// Split into train/validation sets
    pub fn split(&mut self, validation_ratio: f32) {
        let total = self.examples.len();
        let val_size = (total as f32 * validation_ratio) as usize;

        if val_size > 0 && val_size < total {
            let split_idx = total - val_size;
            self.validation = self.examples.split_off(split_idx);
        }
    }

    /// Get dataset statistics
    pub fn stats(&self) -> DatasetStats {
        let avg_quality = self.examples.iter().map(|e| e.quality).sum::<f32>()
            / self.examples.len().max(1) as f32;

        let val_avg_quality = if !self.validation.is_empty() {
            self.validation.iter().map(|e| e.quality).sum::<f32>() / self.validation.len() as f32
        } else {
            0.0
        };

        DatasetStats {
            train_size: self.examples.len(),
            val_size: self.validation.len(),
            feature_dim: self.feature_dim,
            avg_quality,
            val_avg_quality,
        }
    }

    /// Save dataset to file
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let bytes = bincode::serde::encode_to_vec(self, bincode::config::standard())
            .map_err(|e| RuvLLMError::Serialization(e.to_string()))?;
        std::fs::write(path, bytes)?;
        Ok(())
    }

    /// Load dataset from file
    pub fn load(path: impl AsRef<Path>) -> Result<Self> {
        let bytes = std::fs::read(path)?;
        let (dataset, _): (Self, usize) =
            bincode::serde::decode_from_slice(&bytes, bincode::config::standard())
                .map_err(|e| RuvLLMError::Serialization(e.to_string()))?;
        Ok(dataset)
    }
}

/// Dataset statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetStats {
    pub train_size: usize,
    pub val_size: usize,
    pub feature_dim: usize,
    pub avg_quality: f32,
    pub val_avg_quality: f32,
}

/// Configuration for adapter training
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdapterTrainingConfig {
    /// Base training configuration
    pub training: TrainingConfig,
    /// Number of epochs
    pub epochs: usize,
    /// Validation interval (in steps)
    pub validation_interval: usize,
    /// Early stopping patience (epochs)
    pub early_stopping_patience: usize,
    /// Minimum improvement for early stopping
    pub min_improvement: f32,
    /// Enable gradient checkpointing
    pub gradient_checkpointing: bool,
    /// Use mixed precision (bf16/fp16)
    pub mixed_precision: bool,
    /// Save best model
    pub save_best: bool,
    /// Output directory for checkpoints
    pub output_dir: String,
}

impl Default for AdapterTrainingConfig {
    fn default() -> Self {
        Self {
            training: TrainingConfig::default(),
            epochs: 3,
            validation_interval: 100,
            early_stopping_patience: 3,
            min_improvement: 0.001,
            gradient_checkpointing: true,
            mixed_precision: false,
            save_best: true,
            output_dir: "./adapters".to_string(),
        }
    }
}

impl AdapterTrainingConfig {
    /// Create config for quick training (fewer epochs, higher LR)
    pub fn quick() -> Self {
        Self {
            training: TrainingConfig {
                learning_rate: 0.005,
                lr_schedule: LearningRateSchedule::Constant,
                ..Default::default()
            },
            epochs: 1,
            early_stopping_patience: 1,
            ..Default::default()
        }
    }

    /// Create config for stable training (more epochs, lower LR)
    pub fn stable() -> Self {
        Self {
            training: TrainingConfig::stable(),
            epochs: 5,
            early_stopping_patience: 5,
            min_improvement: 0.0001,
            ..Default::default()
        }
    }
}

/// Adapter trainer
pub struct AdapterTrainer {
    /// Training configuration
    config: AdapterTrainingConfig,
    /// Training pipeline
    pipeline: TrainingPipeline,
    /// Best validation loss seen
    best_val_loss: f32,
    /// Epochs without improvement
    epochs_without_improvement: usize,
    /// Training history
    history: TrainingHistory,
}

impl AdapterTrainer {
    /// Create a new adapter trainer
    pub fn new(config: AdapterTrainingConfig) -> Self {
        let pipeline = TrainingPipeline::new(config.training.clone());

        Self {
            config,
            pipeline,
            best_val_loss: f32::MAX,
            epochs_without_improvement: 0,
            history: TrainingHistory::default(),
        }
    }

    /// Train an adapter on a dataset
    pub fn train(&mut self, lora: &MicroLoRA, dataset: &AdapterDataset) -> Result<TrainingResult> {
        self.pipeline.init_for_lora(lora);

        let mut best_loss = f32::MAX;
        let mut global_step = 0;

        for epoch in 0..self.config.epochs {
            eprintln!("Epoch {}/{}", epoch + 1, self.config.epochs);

            // Training loop
            let mut epoch_loss = 0.0;
            let mut num_batches = 0;

            for example in &dataset.examples {
                let feedback = AdaptFeedback::from_quality(example.quality);
                self.pipeline.train_step(lora, &example.input, feedback)?;

                epoch_loss += 1.0 - example.quality;
                num_batches += 1;
                global_step += 1;

                // Validation
                if global_step % self.config.validation_interval == 0
                    && !dataset.validation.is_empty()
                {
                    let val_loss = self.validate(lora, &dataset.validation)?;
                    eprintln!("  Step {}: val_loss = {:.4}", global_step, val_loss);

                    self.history.val_losses.push(val_loss);

                    if val_loss < best_loss - self.config.min_improvement {
                        best_loss = val_loss;
                        self.epochs_without_improvement = 0;

                        if self.config.save_best {
                            self.save_checkpoint(lora, epoch, val_loss)?;
                        }
                    }
                }
            }

            let avg_loss = epoch_loss / num_batches as f32;
            self.history.train_losses.push(avg_loss);
            eprintln!("  Avg train loss: {:.4}", avg_loss);

            // Epoch-end validation
            if !dataset.validation.is_empty() {
                let val_loss = self.validate(lora, &dataset.validation)?;
                eprintln!("  Validation loss: {:.4}", val_loss);

                if val_loss < self.best_val_loss - self.config.min_improvement {
                    self.best_val_loss = val_loss;
                    self.epochs_without_improvement = 0;
                } else {
                    self.epochs_without_improvement += 1;
                }

                // Early stopping check
                if self.epochs_without_improvement >= self.config.early_stopping_patience {
                    eprintln!("Early stopping triggered after {} epochs", epoch + 1);
                    break;
                }
            }

            // Start new task for EWC
            self.pipeline.start_new_task(lora);
        }

        Ok(TrainingResult {
            final_loss: self.history.train_losses.last().copied().unwrap_or(0.0),
            best_val_loss: self.best_val_loss,
            epochs_completed: self.history.train_losses.len(),
            total_steps: global_step,
            history: self.history.clone(),
        })
    }

    /// Validate on validation set
    fn validate(&self, lora: &MicroLoRA, validation: &[TrainingExample]) -> Result<f32> {
        let mut total_loss = 0.0;

        for example in validation {
            // Simple loss: 1 - quality
            total_loss += 1.0 - example.quality;
        }

        Ok(total_loss / validation.len() as f32)
    }

    /// Save checkpoint
    fn save_checkpoint(&self, lora: &MicroLoRA, epoch: usize, val_loss: f32) -> Result<()> {
        std::fs::create_dir_all(&self.config.output_dir)?;

        let path = format!(
            "{}/adapter_epoch{}_loss{:.4}.bin",
            self.config.output_dir, epoch, val_loss
        );

        lora.save(&path)?;
        eprintln!("  Saved checkpoint: {}", path);

        Ok(())
    }

    /// Get training history
    pub fn history(&self) -> &TrainingHistory {
        &self.history
    }

    /// Reset trainer state
    pub fn reset(&mut self) {
        self.best_val_loss = f32::MAX;
        self.epochs_without_improvement = 0;
        self.history = TrainingHistory::default();
        self.pipeline.reset();
    }
}

/// Training history
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TrainingHistory {
    /// Training losses per epoch
    pub train_losses: Vec<f32>,
    /// Validation losses
    pub val_losses: Vec<f32>,
    /// Learning rates per epoch
    pub learning_rates: Vec<f32>,
}

/// Training result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingResult {
    /// Final training loss
    pub final_loss: f32,
    /// Best validation loss
    pub best_val_loss: f32,
    /// Number of epochs completed
    pub epochs_completed: usize,
    /// Total training steps
    pub total_steps: usize,
    /// Training history
    pub history: TrainingHistory,
}

/// Generate synthetic training data for adapter pre-training
pub struct SyntheticDataGenerator {
    feature_dim: usize,
    seed: u64,
}

impl SyntheticDataGenerator {
    /// Create a new generator
    pub fn new(feature_dim: usize, seed: u64) -> Self {
        Self { feature_dim, seed }
    }

    /// Generate dataset for a specific task type
    pub fn generate(&self, task_type: &str, num_examples: usize) -> AdapterDataset {
        use rand::rngs::StdRng;
        use rand::{Rng, SeedableRng};

        let mut rng = StdRng::seed_from_u64(self.seed);
        let mut dataset = AdapterDataset::new(format!("{}_synthetic", task_type), self.feature_dim);

        for _ in 0..num_examples {
            let input: Vec<f32> = (0..self.feature_dim)
                .map(|_| rng.gen_range(-1.0..1.0))
                .collect();

            let quality = match task_type {
                "coder" => {
                    // Higher quality for code-like patterns (structured)
                    let structure_score = input
                        .iter()
                        .take(self.feature_dim / 4)
                        .map(|x| x.abs())
                        .sum::<f32>()
                        / (self.feature_dim / 4) as f32;
                    (0.6 + structure_score * 0.4).min(1.0)
                }
                "researcher" => {
                    // Quality based on information density
                    let density =
                        input.iter().map(|x| x.abs()).sum::<f32>() / self.feature_dim as f32;
                    (0.5 + density * 0.5).min(1.0)
                }
                "security" => {
                    // High quality for security-critical patterns
                    let critical_score = input.iter().step_by(2).map(|x| x.abs()).sum::<f32>()
                        / (self.feature_dim / 2) as f32;
                    (0.7 + critical_score * 0.3).min(1.0)
                }
                "architect" => {
                    // Quality based on architectural coherence
                    let coherence = input.windows(2).map(|w| (w[0] - w[1]).abs()).sum::<f32>()
                        / (self.feature_dim - 1) as f32;
                    (0.6 + (1.0 - coherence) * 0.4).min(1.0)
                }
                "reviewer" => {
                    // Balanced quality for review patterns
                    let balance = 1.0 - (input.iter().sum::<f32>() / self.feature_dim as f32).abs();
                    (0.5 + balance * 0.5).min(1.0)
                }
                _ => rng.gen_range(0.5..1.0),
            };

            let example = TrainingExample::new(input, quality)
                .with_task(task_type)
                .with_domain(task_type);

            dataset.add_example(example);
        }

        // Split 80/20 train/val
        dataset.split(0.2);

        dataset
    }

    /// Generate datasets for all task types
    pub fn generate_all(&self, examples_per_task: usize) -> Vec<(String, AdapterDataset)> {
        vec![
            (
                "coder".to_string(),
                self.generate("coder", examples_per_task),
            ),
            (
                "researcher".to_string(),
                self.generate("researcher", examples_per_task),
            ),
            (
                "security".to_string(),
                self.generate("security", examples_per_task),
            ),
            (
                "architect".to_string(),
                self.generate("architect", examples_per_task),
            ),
            (
                "reviewer".to_string(),
                self.generate("reviewer", examples_per_task),
            ),
        ]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lora::adapters::RuvLtraAdapters;

    #[test]
    fn test_training_example() {
        let example = TrainingExample::new(vec![0.1; 64], 0.8)
            .with_task("test")
            .with_domain("testing");

        assert_eq!(example.input.len(), 64);
        assert_eq!(example.quality, 0.8);
        assert_eq!(example.task, Some("test".to_string()));
    }

    #[test]
    fn test_dataset_creation() {
        let mut dataset = AdapterDataset::new("test", 64);

        for i in 0..100 {
            let example = TrainingExample::new(vec![i as f32; 64], 0.5 + i as f32 * 0.005);
            dataset.add_example(example);
        }

        assert_eq!(dataset.examples.len(), 100);
    }

    #[test]
    fn test_dataset_split() {
        let mut dataset = AdapterDataset::new("test", 64);

        for i in 0..100 {
            let example = TrainingExample::new(vec![i as f32; 64], 0.8);
            dataset.add_example(example);
        }

        dataset.split(0.2);

        assert_eq!(dataset.examples.len(), 80);
        assert_eq!(dataset.validation.len(), 20);
    }

    #[test]
    fn test_synthetic_data_generator() {
        let generator = SyntheticDataGenerator::new(64, 42);
        let dataset = generator.generate("coder", 100);

        assert_eq!(dataset.feature_dim, 64);
        assert!(dataset.examples.len() > 0);
        assert!(dataset.validation.len() > 0);

        // Check that examples have reasonable quality
        for example in &dataset.examples {
            assert!(example.quality >= 0.0 && example.quality <= 1.0);
        }
    }

    #[test]
    fn test_adapter_trainer() {
        let adapters = RuvLtraAdapters::new();
        let lora = adapters.create_lora("coder", 64).unwrap();

        let generator = SyntheticDataGenerator::new(64, 42);
        let dataset = generator.generate("coder", 50);

        let config = AdapterTrainingConfig::quick();
        let mut trainer = AdapterTrainer::new(config);

        let result = trainer.train(&lora, &dataset).unwrap();

        assert!(result.epochs_completed > 0);
        assert!(result.total_steps > 0);
    }

    #[test]
    fn test_generate_all_datasets() {
        let generator = SyntheticDataGenerator::new(64, 42);
        let datasets = generator.generate_all(100);

        assert_eq!(datasets.len(), 5);

        for (name, dataset) in datasets {
            assert!(dataset.examples.len() > 0);
            println!(
                "{}: {} train, {} val",
                name,
                dataset.examples.len(),
                dataset.validation.len()
            );
        }
    }
}