ruvllm 2.1.0

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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Training Pipeline: Fine-tuning Loop with EWC++ Regularization
//!
//! This module provides the training infrastructure for MicroLoRA:
//! - Single-example gradient computation
//! - EWC++ regularization to prevent catastrophic forgetting
//! - Learning rate scheduling
//! - Async adaptation support

use crate::error::{Result, RuvLLMError};
use crate::lora::micro_lora::{AdaptFeedback, EwcState, MicroLoRA, TargetModule};
use ndarray::{Array1, Array2};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// Configuration for the training pipeline
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrainingConfig {
    /// Base learning rate
    pub learning_rate: f32,
    /// Minimum learning rate
    pub min_learning_rate: f32,
    /// Maximum learning rate
    pub max_learning_rate: f32,
    /// EWC regularization strength (lambda)
    pub ewc_lambda: f32,
    /// Fisher information decay factor (EMA)
    pub fisher_decay: f32,
    /// Batch size for gradient accumulation
    pub batch_size: usize,
    /// Quality threshold for learning (skip low-quality samples)
    pub quality_threshold: f32,
    /// Learning rate schedule
    pub lr_schedule: LearningRateSchedule,
    /// Warmup steps for learning rate
    pub warmup_steps: usize,
    /// Maximum gradient norm (for clipping)
    pub max_grad_norm: f32,
    /// Weight decay factor
    pub weight_decay: f32,
    /// Enable async adaptation
    pub async_adaptation: bool,
    /// Buffer size for async adaptation
    pub async_buffer_size: usize,
}

impl Default for TrainingConfig {
    fn default() -> Self {
        Self {
            learning_rate: 0.002, // Optimized from benchmarks
            min_learning_rate: 1e-5,
            max_learning_rate: 0.01,
            ewc_lambda: 2000.0, // Optimized for forgetting prevention
            fisher_decay: 0.999,
            batch_size: 1, // Single-example by default for real-time
            quality_threshold: 0.3,
            lr_schedule: LearningRateSchedule::Cosine,
            warmup_steps: 100,
            max_grad_norm: 1.0,
            weight_decay: 0.01,
            async_adaptation: true,
            async_buffer_size: 64,
        }
    }
}

impl TrainingConfig {
    /// Create config for real-time adaptation (single-example)
    pub fn realtime() -> Self {
        Self {
            learning_rate: 0.001,
            batch_size: 1,
            async_adaptation: true,
            async_buffer_size: 32,
            ..Default::default()
        }
    }

    /// Create config for batch adaptation
    pub fn batch(batch_size: usize) -> Self {
        Self {
            learning_rate: 0.002,
            batch_size,
            async_adaptation: false,
            ..Default::default()
        }
    }

    /// Create config optimized for stability
    pub fn stable() -> Self {
        Self {
            learning_rate: 0.0005,
            ewc_lambda: 5000.0,
            max_grad_norm: 0.5,
            weight_decay: 0.02,
            quality_threshold: 0.5,
            ..Default::default()
        }
    }
}

/// Learning rate schedule types
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum LearningRateSchedule {
    /// Constant learning rate
    Constant,
    /// Linear decay
    Linear,
    /// Cosine annealing
    Cosine,
    /// Exponential decay
    Exponential,
    /// Step decay (reduce by factor at milestones)
    Step,
    /// Warmup then constant
    WarmupConstant,
    /// One-cycle policy
    OneCycle,
}

impl Default for LearningRateSchedule {
    fn default() -> Self {
        Self::Cosine
    }
}

/// Gradient accumulator for batch processing
pub struct GradientAccumulator {
    /// Accumulated gradients per module
    gradients: HashMap<TargetModule, ModuleGradients>,
    /// Number of accumulated samples
    sample_count: usize,
    /// Total quality of accumulated samples
    total_quality: f32,
}

/// Gradients for a single module
struct ModuleGradients {
    grad_a: Array2<f32>,
    grad_b: Array2<f32>,
}

impl GradientAccumulator {
    /// Create a new accumulator
    pub fn new() -> Self {
        Self {
            gradients: HashMap::new(),
            sample_count: 0,
            total_quality: 0.0,
        }
    }

    /// Initialize for a module with dimensions
    pub fn init_module(
        &mut self,
        module: TargetModule,
        in_features: usize,
        rank: usize,
        out_features: usize,
    ) {
        self.gradients.insert(
            module,
            ModuleGradients {
                grad_a: Array2::zeros((in_features, rank)),
                grad_b: Array2::zeros((rank, out_features)),
            },
        );
    }

    /// Accumulate gradients
    pub fn accumulate(
        &mut self,
        module: TargetModule,
        grad_a: &Array2<f32>,
        grad_b: &Array2<f32>,
        quality: f32,
    ) {
        if let Some(grads) = self.gradients.get_mut(&module) {
            grads.grad_a.zip_mut_with(grad_a, |a, g| *a += g * quality);
            grads.grad_b.zip_mut_with(grad_b, |b, g| *b += g * quality);
        }
        self.sample_count += 1;
        self.total_quality += quality;
    }

    /// Get average gradients
    pub fn average(&self) -> HashMap<TargetModule, (Array2<f32>, Array2<f32>)> {
        if self.sample_count == 0 {
            return HashMap::new();
        }

        let scale = 1.0 / self.sample_count as f32;
        self.gradients
            .iter()
            .map(|(module, grads)| {
                let avg_a = grads.grad_a.mapv(|v| v * scale);
                let avg_b = grads.grad_b.mapv(|v| v * scale);
                (*module, (avg_a, avg_b))
            })
            .collect()
    }

    /// Clear accumulated gradients
    pub fn clear(&mut self) {
        for grads in self.gradients.values_mut() {
            grads.grad_a.fill(0.0);
            grads.grad_b.fill(0.0);
        }
        self.sample_count = 0;
        self.total_quality = 0.0;
    }

    /// Get sample count
    pub fn count(&self) -> usize {
        self.sample_count
    }

    /// Get average quality
    pub fn average_quality(&self) -> f32 {
        if self.sample_count == 0 {
            0.0
        } else {
            self.total_quality / self.sample_count as f32
        }
    }
}

impl Default for GradientAccumulator {
    fn default() -> Self {
        Self::new()
    }
}

/// EWC++ regularizer for preventing catastrophic forgetting
pub struct EwcRegularizer {
    /// EWC state per module
    states: HashMap<TargetModule, EwcState>,
    /// Regularization strength
    lambda: f32,
    /// Fisher decay factor
    decay: f32,
    /// Task count
    task_count: usize,
    /// Samples since last consolidation
    samples_since_consolidation: usize,
    /// Consolidation interval
    consolidation_interval: usize,
}

impl EwcRegularizer {
    /// Create a new EWC regularizer
    pub fn new(lambda: f32, decay: f32) -> Self {
        Self {
            states: HashMap::new(),
            lambda,
            decay,
            task_count: 0,
            samples_since_consolidation: 0,
            consolidation_interval: 1000,
        }
    }

    /// Initialize state for a module from adapter
    pub fn init_module(
        &mut self,
        module: TargetModule,
        adapter: &crate::lora::micro_lora::LoraAdapter,
    ) {
        self.states.insert(module, EwcState::from_adapter(adapter));
    }

    /// Update Fisher information with new gradients
    pub fn update_fisher(
        &mut self,
        module: &TargetModule,
        grad_a: &Array2<f32>,
        grad_b: &Array2<f32>,
    ) {
        if let Some(state) = self.states.get_mut(module) {
            state.update_fisher(grad_a, grad_b, self.decay);
        }
        self.samples_since_consolidation += 1;
    }

    /// Get EWC penalty for a module
    pub fn penalty(
        &self,
        module: &TargetModule,
        current_a: &Array2<f32>,
        current_b: &Array2<f32>,
    ) -> f32 {
        if let Some(state) = self.states.get(module) {
            let mut penalty = 0.0f32;

            // Penalty for A: sum(F_a * (w_a - w*_a)^2)
            for ((f, w), w_opt) in state
                .fisher_a
                .iter()
                .zip(current_a.iter())
                .zip(state.optimal_a.iter())
            {
                let diff = w - w_opt;
                penalty += f * diff * diff;
            }

            // Penalty for B: sum(F_b * (w_b - w*_b)^2)
            for ((f, w), w_opt) in state
                .fisher_b
                .iter()
                .zip(current_b.iter())
                .zip(state.optimal_b.iter())
            {
                let diff = w - w_opt;
                penalty += f * diff * diff;
            }

            self.lambda * penalty / 2.0
        } else {
            0.0
        }
    }

    /// Get EWC gradient adjustment
    pub fn gradient_adjustment(
        &self,
        module: &TargetModule,
        current_a: &Array2<f32>,
        current_b: &Array2<f32>,
    ) -> Option<(Array2<f32>, Array2<f32>)> {
        self.states.get(module).map(|state| {
            // Gradient of penalty: lambda * F * (w - w*)
            let adj_a = Array2::from_shape_fn(current_a.dim(), |(i, j)| {
                self.lambda * state.fisher_a[[i, j]] * (current_a[[i, j]] - state.optimal_a[[i, j]])
            });

            let adj_b = Array2::from_shape_fn(current_b.dim(), |(i, j)| {
                self.lambda * state.fisher_b[[i, j]] * (current_b[[i, j]] - state.optimal_b[[i, j]])
            });

            (adj_a, adj_b)
        })
    }

    /// Start a new task (consolidate current knowledge)
    pub fn start_new_task(
        &mut self,
        adapters: &HashMap<TargetModule, Arc<RwLock<crate::lora::micro_lora::LoraAdapter>>>,
    ) {
        // Update optimal weights to current
        for (module, adapter) in adapters {
            if let Some(state) = self.states.get_mut(module) {
                let adapter = adapter.read();
                state.update_optimal(&adapter);
            }
        }
        self.task_count += 1;
        self.samples_since_consolidation = 0;
    }

    /// Check if consolidation is needed
    pub fn needs_consolidation(&self) -> bool {
        self.samples_since_consolidation >= self.consolidation_interval
    }

    /// Get current lambda
    pub fn lambda(&self) -> f32 {
        self.lambda
    }

    /// Set lambda
    pub fn set_lambda(&mut self, lambda: f32) {
        self.lambda = lambda;
    }

    /// Get task count
    pub fn task_count(&self) -> usize {
        self.task_count
    }

    /// Get EWC state for a module
    pub fn get_state(&self, module: &TargetModule) -> Option<&EwcState> {
        self.states.get(module)
    }

    /// Export states for serialization
    pub fn export_states(&self) -> HashMap<TargetModule, EwcStateExport> {
        self.states
            .iter()
            .map(|(module, state)| {
                (
                    *module,
                    EwcStateExport {
                        fisher_a: state.fisher_a.iter().copied().collect(),
                        fisher_b: state.fisher_b.iter().copied().collect(),
                        optimal_a: state.optimal_a.iter().copied().collect(),
                        optimal_b: state.optimal_b.iter().copied().collect(),
                        shape_a: (state.fisher_a.nrows(), state.fisher_a.ncols()),
                        shape_b: (state.fisher_b.nrows(), state.fisher_b.ncols()),
                    },
                )
            })
            .collect()
    }
}

/// Serializable EWC state
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EwcStateExport {
    pub fisher_a: Vec<f32>,
    pub fisher_b: Vec<f32>,
    pub optimal_a: Vec<f32>,
    pub optimal_b: Vec<f32>,
    pub shape_a: (usize, usize),
    pub shape_b: (usize, usize),
}

/// Training pipeline for MicroLoRA
pub struct TrainingPipeline {
    /// Configuration
    config: TrainingConfig,
    /// Gradient accumulator
    accumulator: GradientAccumulator,
    /// EWC regularizer
    ewc: EwcRegularizer,
    /// Current learning rate
    current_lr: f32,
    /// Total training steps
    total_steps: AtomicU64,
    /// Async feedback buffer
    feedback_buffer: RwLock<VecDeque<PendingFeedback>>,
    /// Training statistics
    stats: RwLock<TrainingStats>,
}

/// Pending feedback for async processing
struct PendingFeedback {
    input: Vec<f32>,
    feedback: AdaptFeedback,
    timestamp: std::time::Instant,
}

/// Training statistics
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TrainingStats {
    /// Total training steps completed
    pub total_steps: u64,
    /// Total samples processed
    pub total_samples: u64,
    /// Average loss
    pub avg_loss: f32,
    /// Average quality of training samples
    pub avg_quality: f32,
    /// Current learning rate
    pub current_lr: f32,
    /// EWC penalty
    pub ewc_penalty: f32,
    /// Gradient norm
    pub grad_norm: f32,
    /// Samples skipped (below quality threshold)
    pub skipped_samples: u64,
}

impl TrainingPipeline {
    /// Create a new training pipeline
    pub fn new(config: TrainingConfig) -> Self {
        let current_lr = config.learning_rate;
        let ewc = EwcRegularizer::new(config.ewc_lambda, config.fisher_decay);

        Self {
            config,
            accumulator: GradientAccumulator::new(),
            ewc,
            current_lr,
            total_steps: AtomicU64::new(0),
            feedback_buffer: RwLock::new(VecDeque::new()),
            stats: RwLock::new(TrainingStats::default()),
        }
    }

    /// Initialize for a MicroLoRA instance
    pub fn init_for_lora(&mut self, lora: &MicroLoRA) {
        let config = lora.config();
        for module in &config.target_modules {
            self.accumulator.init_module(
                *module,
                config.in_features,
                config.rank,
                config.out_features,
            );

            if let Some(adapter) = lora.get_adapter(module) {
                self.ewc.init_module(*module, &adapter.read());
            }
        }
    }

    /// Process a single training sample
    pub fn train_step(
        &self,
        lora: &MicroLoRA,
        input: &[f32],
        feedback: AdaptFeedback,
    ) -> Result<()> {
        // Skip low-quality samples
        if feedback.quality < self.config.quality_threshold {
            self.stats.write().skipped_samples += 1;
            return Ok(());
        }

        // Accumulate gradients
        lora.adapt(input, feedback.clone())?;

        // Check if we should apply updates
        let step = self.total_steps.fetch_add(1, Ordering::SeqCst);

        if (step + 1) as usize % self.config.batch_size == 0 {
            self.apply_step(lora, step)?;
        }

        Ok(())
    }

    /// Apply accumulated gradients
    fn apply_step(&self, lora: &MicroLoRA, step: u64) -> Result<()> {
        // Update learning rate based on schedule
        let lr = self.compute_lr(step);

        // Apply gradients with EWC
        let ewc_states: HashMap<TargetModule, EwcState> = self
            .ewc
            .states
            .iter()
            .map(|(k, v)| (*k, v.clone()))
            .collect();

        lora.apply_updates_with_ewc(lr, &ewc_states, self.config.ewc_lambda);

        // Update stats
        {
            let mut stats = self.stats.write();
            stats.total_steps = step;
            stats.current_lr = lr;
            stats.total_samples += self.config.batch_size as u64;
        }

        Ok(())
    }

    /// Compute learning rate based on schedule
    fn compute_lr(&self, step: u64) -> f32 {
        let step = step as f32;
        let warmup = self.config.warmup_steps as f32;
        let base_lr = self.config.learning_rate;
        let min_lr = self.config.min_learning_rate;
        let max_lr = self.config.max_learning_rate;

        // Warmup phase
        if step < warmup {
            return min_lr + (base_lr - min_lr) * (step / warmup);
        }

        let adjusted_step = step - warmup;

        match self.config.lr_schedule {
            LearningRateSchedule::Constant => base_lr,

            LearningRateSchedule::Linear => {
                let decay_steps = 10000.0; // Total decay steps
                let factor = 1.0 - (adjusted_step / decay_steps).min(1.0);
                min_lr + (base_lr - min_lr) * factor
            }

            LearningRateSchedule::Cosine => {
                let decay_steps = 10000.0;
                let factor =
                    0.5 * (1.0 + (std::f32::consts::PI * adjusted_step / decay_steps).cos());
                min_lr + (base_lr - min_lr) * factor
            }

            LearningRateSchedule::Exponential => {
                let decay_rate: f32 = 0.99;
                let factor = decay_rate.powf(adjusted_step / 100.0);
                (base_lr * factor).max(min_lr)
            }

            LearningRateSchedule::Step => {
                let milestones = [1000.0, 5000.0, 10000.0];
                let gamma = 0.1;
                let mut lr = base_lr;
                for &milestone in &milestones {
                    if adjusted_step >= milestone {
                        lr *= gamma;
                    }
                }
                lr.max(min_lr)
            }

            LearningRateSchedule::WarmupConstant => base_lr,

            LearningRateSchedule::OneCycle => {
                let cycle_steps = 10000.0;
                let pct = (adjusted_step % cycle_steps) / cycle_steps;
                if pct < 0.5 {
                    // Increase
                    let factor = 2.0 * pct;
                    base_lr + (max_lr - base_lr) * factor
                } else {
                    // Decrease
                    let factor = 2.0 * (1.0 - pct);
                    min_lr + (max_lr - min_lr) * factor
                }
            }
        }
    }

    /// Queue feedback for async processing
    pub fn queue_feedback(&self, input: Vec<f32>, feedback: AdaptFeedback) {
        if !self.config.async_adaptation {
            return;
        }

        let mut buffer = self.feedback_buffer.write();

        if buffer.len() >= self.config.async_buffer_size {
            buffer.pop_front();
        }

        buffer.push_back(PendingFeedback {
            input,
            feedback,
            timestamp: std::time::Instant::now(),
        });
    }

    /// Process queued feedback
    pub fn process_queued(&self, lora: &MicroLoRA) -> Result<usize> {
        let pending: Vec<_> = {
            let mut buffer = self.feedback_buffer.write();
            buffer.drain(..).collect()
        };

        let count = pending.len();
        for pf in pending {
            self.train_step(lora, &pf.input, pf.feedback)?;
        }

        Ok(count)
    }

    /// Start a new task (for EWC)
    pub fn start_new_task(&mut self, lora: &MicroLoRA) {
        let adapters: HashMap<_, _> = lora
            .config()
            .target_modules
            .iter()
            .filter_map(|m| lora.get_adapter(m).map(|a| (*m, a)))
            .collect();
        self.ewc.start_new_task(&adapters);
    }

    /// Get training statistics
    pub fn stats(&self) -> TrainingStats {
        self.stats.read().clone()
    }

    /// Get current learning rate
    pub fn current_lr(&self) -> f32 {
        self.current_lr
    }

    /// Get configuration
    pub fn config(&self) -> &TrainingConfig {
        &self.config
    }

    /// Reset training state
    pub fn reset(&mut self) {
        self.accumulator.clear();
        self.total_steps.store(0, Ordering::SeqCst);
        self.feedback_buffer.write().clear();
        *self.stats.write() = TrainingStats::default();
    }

    /// Export EWC states for serialization
    pub fn export_ewc(&self) -> HashMap<TargetModule, EwcStateExport> {
        self.ewc.export_states()
    }
}

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

    #[test]
    fn test_training_config_default() {
        let config = TrainingConfig::default();
        assert!((config.learning_rate - 0.002).abs() < 1e-6);
        assert_eq!(config.batch_size, 1);
    }

    #[test]
    fn test_gradient_accumulator() {
        let mut acc = GradientAccumulator::new();
        acc.init_module(TargetModule::QProj, 64, 2, 64);

        let grad_a = Array2::from_elem((64, 2), 0.1);
        let grad_b = Array2::from_elem((2, 64), 0.1);

        acc.accumulate(TargetModule::QProj, &grad_a, &grad_b, 0.8);
        assert_eq!(acc.count(), 1);

        let avg = acc.average();
        assert!(avg.contains_key(&TargetModule::QProj));
    }

    #[test]
    fn test_learning_rate_schedule() {
        let config = TrainingConfig {
            learning_rate: 0.01,
            min_learning_rate: 0.001,
            warmup_steps: 10,
            lr_schedule: LearningRateSchedule::Cosine,
            ..Default::default()
        };

        let pipeline = TrainingPipeline::new(config);

        // Warmup phase
        let lr_0 = pipeline.compute_lr(0);
        let lr_5 = pipeline.compute_lr(5);
        let lr_10 = pipeline.compute_lr(10);

        assert!(lr_0 < lr_5);
        assert!(lr_5 < lr_10);

        // After warmup, should start decaying
        let lr_100 = pipeline.compute_lr(100);
        let lr_1000 = pipeline.compute_lr(1000);
        assert!(lr_100 > lr_1000);
    }

    #[test]
    fn test_ewc_regularizer() {
        let mut ewc = EwcRegularizer::new(1000.0, 0.999);

        let adapter = crate::lora::micro_lora::LoraAdapter::new(64, 64, 2, 4.0);
        ewc.init_module(TargetModule::QProj, &adapter);

        let grad_a = Array2::from_elem((64, 2), 0.1);
        let grad_b = Array2::from_elem((2, 64), 0.1);

        ewc.update_fisher(&TargetModule::QProj, &grad_a, &grad_b);

        assert!(ewc.get_state(&TargetModule::QProj).is_some());
    }

    #[test]
    fn test_training_pipeline() {
        let config = TrainingConfig::realtime();
        let mut pipeline = TrainingPipeline::new(config);

        let lora_config = MicroLoraConfig::for_hidden_dim(64);
        let lora = MicroLoRA::new(lora_config);

        pipeline.init_for_lora(&lora);

        let input = vec![0.1; 64];
        let feedback = AdaptFeedback::from_quality(0.8);

        pipeline.train_step(&lora, &input, feedback).unwrap();

        let stats = pipeline.stats();
        assert!(stats.total_steps > 0 || stats.total_samples > 0);
    }

    #[test]
    fn test_async_feedback() {
        let config = TrainingConfig {
            async_adaptation: true,
            async_buffer_size: 4,
            ..Default::default()
        };
        let pipeline = TrainingPipeline::new(config);

        for i in 0..6 {
            let input = vec![i as f32 * 0.1; 64];
            let feedback = AdaptFeedback::from_quality(0.8);
            pipeline.queue_feedback(input, feedback);
        }

        // Buffer should be capped at 4
        let buffer = pipeline.feedback_buffer.read();
        assert_eq!(buffer.len(), 4);
    }
}