torsh-optim 0.1.3

Optimization algorithms for ToRSh with PyTorch-compatible API
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
//! Continual Learning Optimizers
//!
//! This module implements optimization algorithms for lifelong learning scenarios,
//! preventing catastrophic forgetting when learning sequential tasks.
//!
//! # Key Concepts
//!
//! - **Catastrophic Forgetting**: The tendency of neural networks to forget previously
//!   learned tasks when learning new ones.
//! - **Parameter Importance**: Identifying which parameters are critical for past tasks
//!   and should be protected from large updates.
//! - **Task-Specific Learning**: Adapting learning strategies based on task sequence.
//!
//! # Algorithms
//!
//! ## EWC (Elastic Weight Consolidation)
//!
//! Protects important parameters by adding a quadratic penalty based on the Fisher
//! Information Matrix. Parameters critical for previous tasks receive higher penalties.
//!
//! Loss: L_new = L_task + (λ/2) Σ F_i (θ_i - θ*_i)²
//!
//! ## SI (Synaptic Intelligence)
//!
//! Online continual learning that accumulates parameter importance during training.
//! Updates importance based on path integral of parameter changes.
//!
//! ## MAS (Memory Aware Synapses)
//!
//! Uses gradient magnitude at optimal parameters to estimate importance,
//! avoiding the need for data from previous tasks.
//!
//! ## PackNet
//!
//! Packs multiple tasks into a single network by dynamically allocating
//! and protecting subnetworks for each task.
//!
//! # References
//!
//! - Kirkpatrick et al. (2017). "Overcoming catastrophic forgetting in neural networks"
//! - Zenke et al. (2017). "Continual Learning Through Synaptic Intelligence"
//! - Aljundi et al. (2018). "Memory Aware Synapses"
//! - Mallya & Lazebnik (2018). "PackNet: Adding Multiple Tasks to a Single Network"

use crate::{Optimizer, OptimizerError, OptimizerResult, OptimizerState};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use torsh_tensor::Tensor;

// ============================================================================
// EWC (Elastic Weight Consolidation)
// ============================================================================

/// EWC configuration
#[derive(Debug, Clone)]
pub struct EWCConfig {
    /// Importance weight (λ) for Fisher penalty
    pub importance: f32,
    /// Sample size for Fisher matrix estimation
    pub fisher_sample_size: usize,
    /// Use diagonal Fisher approximation
    pub diagonal_fisher: bool,
}

impl Default for EWCConfig {
    fn default() -> Self {
        Self {
            importance: 1000.0,
            fisher_sample_size: 200,
            diagonal_fisher: true,
        }
    }
}

/// Elastic Weight Consolidation optimizer
///
/// Prevents catastrophic forgetting by adding regularization based on
/// parameter importance computed from the Fisher Information Matrix.
pub struct EWCOptimizer<O: Optimizer> {
    /// Base optimizer
    base_optimizer: O,
    /// Configuration
    config: EWCConfig,
    /// Fisher information per parameter
    fisher_information: HashMap<String, Tensor>,
    /// Optimal parameters from previous task
    optimal_params: HashMap<String, Tensor>,
    /// Current task ID
    current_task: usize,
    /// Parameter groups reference
    param_groups: Vec<Arc<RwLock<Tensor>>>,
}

impl<O: Optimizer> EWCOptimizer<O> {
    /// Create a new EWC optimizer
    pub fn new(
        base_optimizer: O,
        params: Vec<Arc<RwLock<Tensor>>>,
        config: EWCConfig,
    ) -> OptimizerResult<Self> {
        Ok(Self {
            base_optimizer,
            config,
            fisher_information: HashMap::new(),
            optimal_params: HashMap::new(),
            current_task: 0,
            param_groups: params,
        })
    }

    /// Create with default configuration
    pub fn with_defaults(
        base_optimizer: O,
        params: Vec<Arc<RwLock<Tensor>>>,
    ) -> OptimizerResult<Self> {
        Self::new(base_optimizer, params, EWCConfig::default())
    }

    /// Consolidate current task (compute Fisher and save optimal parameters)
    pub fn consolidate_task(&mut self) -> OptimizerResult<()> {
        // Save current parameters as optimal
        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);
            let param_read = param.read();
            self.optimal_params
                .insert(param_key.clone(), param_read.clone());
        }

        // Compute Fisher information (simplified diagonal approximation)
        self.compute_fisher_diagonal()?;

        self.current_task += 1;
        Ok(())
    }

    /// Compute diagonal Fisher information matrix
    fn compute_fisher_diagonal(&mut self) -> OptimizerResult<()> {
        // For each parameter, compute F_ii = E[∂L/∂θ_i]²
        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            // Get gradient (squared for Fisher diagonal)
            let param_read = param.read();
            if let Some(grad) = param_read.grad() {
                let fisher = grad.mul(&grad)?; // Element-wise square

                // If Fisher already exists, accumulate
                if let Some(existing_fisher) = self.fisher_information.get(&param_key) {
                    let accumulated = existing_fisher.add(&fisher)?;
                    self.fisher_information.insert(param_key, accumulated);
                } else {
                    self.fisher_information.insert(param_key, fisher);
                }
            }
        }

        Ok(())
    }

    /// Apply EWC penalty to gradients
    fn apply_ewc_penalty(&mut self) -> OptimizerResult<()> {
        if self.optimal_params.is_empty() {
            // No previous task, no penalty
            return Ok(());
        }

        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            if let (Some(fisher), Some(optimal)) = (
                self.fisher_information.get(&param_key),
                self.optimal_params.get(&param_key),
            ) {
                let mut param_write = param.write();

                // Compute EWC penalty: λ * F * (θ - θ*)
                let diff = param_write.sub(optimal)?;
                let penalty = fisher.mul(&diff)?;
                let scaled_penalty = penalty.mul_scalar(self.config.importance)?;

                // Add penalty to gradient
                if let Some(grad) = param_write.grad() {
                    let new_grad = grad.add(&scaled_penalty)?;
                    param_write.set_grad(Some(new_grad));
                }
            }
        }

        Ok(())
    }
}

impl<O: Optimizer> Optimizer for EWCOptimizer<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        // Apply EWC penalty to gradients
        self.apply_ewc_penalty()?;

        // Call base optimizer
        self.base_optimizer.step()
    }

    fn zero_grad(&mut self) {
        self.base_optimizer.zero_grad();
    }

    fn get_lr(&self) -> Vec<f32> {
        self.base_optimizer.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_optimizer.set_lr(lr);
    }

    fn add_param_group(&mut self, params: Vec<Arc<RwLock<Tensor>>>, options: HashMap<String, f32>) {
        self.base_optimizer.add_param_group(params, options);
    }

    fn parameters(&self) -> Vec<Arc<RwLock<Tensor>>> {
        self.param_groups.clone()
    }

    fn state_dict(&self) -> OptimizerResult<OptimizerState> {
        let mut state = self.base_optimizer.state_dict()?;
        state.optimizer_type = format!("EWC({})", state.optimizer_type);
        state
            .global_state
            .insert("current_task".to_string(), self.current_task as f32);
        state
            .global_state
            .insert("importance".to_string(), self.config.importance);
        Ok(state)
    }

    fn load_state_dict(&mut self, state: OptimizerState) -> OptimizerResult<()> {
        self.base_optimizer.load_state_dict(state)
    }
}

// ============================================================================
// SI (Synaptic Intelligence)
// ============================================================================

/// Synaptic Intelligence configuration
#[derive(Debug, Clone)]
pub struct SIConfig {
    /// Damping parameter (ξ)
    pub damping: f32,
    /// Importance regularization strength
    pub importance: f32,
}

impl Default for SIConfig {
    fn default() -> Self {
        Self {
            damping: 0.1,
            importance: 1.0,
        }
    }
}

/// Synaptic Intelligence optimizer
///
/// Online continual learning that tracks parameter importance during training
/// using path integral of gradient times parameter change.
pub struct SIOptimizer<O: Optimizer> {
    /// Base optimizer
    base_optimizer: O,
    /// Configuration
    config: SIConfig,
    /// Path integral accumulator (ω)
    path_integral: HashMap<String, Tensor>,
    /// Previous parameters
    prev_params: HashMap<String, Tensor>,
    /// Consolidated importance per task
    importance: HashMap<String, Tensor>,
    /// Current task ID
    current_task: usize,
    /// Parameter groups
    param_groups: Vec<Arc<RwLock<Tensor>>>,
}

impl<O: Optimizer> SIOptimizer<O> {
    /// Create a new SI optimizer
    pub fn new(
        base_optimizer: O,
        params: Vec<Arc<RwLock<Tensor>>>,
        config: SIConfig,
    ) -> OptimizerResult<Self> {
        let mut prev_params = HashMap::new();
        let mut path_integral = HashMap::new();

        // Initialize previous parameters and path integral
        for (i, param) in params.iter().enumerate() {
            let param_key = format!("param_{}", i);
            let param_read = param.read();
            prev_params.insert(param_key.clone(), param_read.clone());

            let shape_owned = param_read.shape().dims().to_vec();
            drop(param_read);
            let zeros = torsh_tensor::creation::zeros(&shape_owned)?;
            path_integral.insert(param_key, zeros);
        }

        Ok(Self {
            base_optimizer,
            config,
            path_integral,
            prev_params,
            importance: HashMap::new(),
            current_task: 0,
            param_groups: params,
        })
    }

    /// Create with default configuration
    pub fn with_defaults(
        base_optimizer: O,
        params: Vec<Arc<RwLock<Tensor>>>,
    ) -> OptimizerResult<Self> {
        Self::new(base_optimizer, params, SIConfig::default())
    }

    /// Update path integral
    fn update_path_integral(&mut self) -> OptimizerResult<()> {
        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            let param_read = param.read();
            if let Some(grad) = param_read.grad() {
                if let Some(prev_param) = self.prev_params.get(&param_key) {
                    // Δθ = θ_new - θ_old
                    let delta = param_read.sub(prev_param)?;

                    // ω += -∂L/∂θ * Δθ
                    let contribution = grad.mul(&delta)?;
                    let neg_contribution = contribution.mul_scalar(-1.0)?;

                    if let Some(omega) = self.path_integral.get_mut(&param_key) {
                        *omega = omega.add(&neg_contribution)?;
                    }

                    // Update previous parameters
                    self.prev_params.insert(param_key, param_read.clone());
                }
            }
        }

        Ok(())
    }

    /// Consolidate task importance
    pub fn consolidate_task(&mut self) -> OptimizerResult<()> {
        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            if let Some(omega) = self.path_integral.get(&param_key) {
                // Compute importance: Ω = ω / (Δθ² + ξ)
                if let Some(prev_param) = self.prev_params.get(&param_key) {
                    let param_read = param.read();
                    let delta = param_read.sub(prev_param)?;
                    let delta_sq = delta.mul(&delta)?;
                    let denom = delta_sq.add_scalar(self.config.damping)?;

                    let task_importance = omega.div(&denom)?;

                    // Accumulate importance
                    if let Some(existing) = self.importance.get(&param_key) {
                        let accumulated = existing.add(&task_importance)?;
                        self.importance.insert(param_key.clone(), accumulated);
                    } else {
                        self.importance.insert(param_key.clone(), task_importance);
                    }

                    // Reset path integral
                    let shape_owned = param_read.shape().dims().to_vec();
                    let zeros = torsh_tensor::creation::zeros(&shape_owned)?;
                    self.path_integral.insert(param_key, zeros);
                }
            }
        }

        self.current_task += 1;
        Ok(())
    }

    /// Apply SI penalty
    fn apply_si_penalty(&mut self) -> OptimizerResult<()> {
        if self.importance.is_empty() {
            return Ok(());
        }

        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            if let (Some(importance), Some(prev_param)) = (
                self.importance.get(&param_key),
                self.prev_params.get(&param_key),
            ) {
                let mut param_write = param.write();

                // Penalty: Ω * (θ - θ_prev)
                let diff = param_write.sub(prev_param)?;
                let penalty = importance.mul(&diff)?;
                let scaled_penalty = penalty.mul_scalar(self.config.importance)?;

                if let Some(grad) = param_write.grad() {
                    let new_grad = grad.add(&scaled_penalty)?;
                    param_write.set_grad(Some(new_grad));
                }
            }
        }

        Ok(())
    }
}

impl<O: Optimizer> Optimizer for SIOptimizer<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        // Update path integral before step
        self.update_path_integral()?;

        // Apply SI penalty
        self.apply_si_penalty()?;

        // Call base optimizer
        self.base_optimizer.step()
    }

    fn zero_grad(&mut self) {
        self.base_optimizer.zero_grad();
    }

    fn get_lr(&self) -> Vec<f32> {
        self.base_optimizer.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_optimizer.set_lr(lr);
    }

    fn add_param_group(&mut self, params: Vec<Arc<RwLock<Tensor>>>, options: HashMap<String, f32>) {
        self.base_optimizer.add_param_group(params, options);
    }

    fn parameters(&self) -> Vec<Arc<RwLock<Tensor>>> {
        self.param_groups.clone()
    }

    fn state_dict(&self) -> OptimizerResult<OptimizerState> {
        let mut state = self.base_optimizer.state_dict()?;
        state.optimizer_type = format!("SI({})", state.optimizer_type);
        state
            .global_state
            .insert("current_task".to_string(), self.current_task as f32);
        Ok(state)
    }

    fn load_state_dict(&mut self, state: OptimizerState) -> OptimizerResult<()> {
        self.base_optimizer.load_state_dict(state)
    }
}

// ============================================================================
// MAS (Memory Aware Synapses)
// ============================================================================

/// MAS configuration
#[derive(Debug, Clone)]
pub struct MASConfig {
    /// Importance regularization strength
    pub importance: f32,
    /// Number of samples for importance estimation
    pub n_samples: usize,
}

impl Default for MASConfig {
    fn default() -> Self {
        Self {
            importance: 1.0,
            n_samples: 100,
        }
    }
}

/// Memory Aware Synapses optimizer
///
/// Estimates parameter importance using gradient magnitude at optimal parameters,
/// avoiding the need for data from previous tasks.
pub struct MASOptimizer<O: Optimizer> {
    /// Base optimizer
    base_optimizer: O,
    /// Configuration
    config: MASConfig,
    /// Parameter importance
    importance: HashMap<String, Tensor>,
    /// Optimal parameters from previous tasks
    optimal_params: HashMap<String, Tensor>,
    /// Current task ID
    current_task: usize,
    /// Parameter groups
    param_groups: Vec<Arc<RwLock<Tensor>>>,
}

impl<O: Optimizer> MASOptimizer<O> {
    /// Create a new MAS optimizer
    pub fn new(
        base_optimizer: O,
        params: Vec<Arc<RwLock<Tensor>>>,
        config: MASConfig,
    ) -> OptimizerResult<Self> {
        Ok(Self {
            base_optimizer,
            config,
            importance: HashMap::new(),
            optimal_params: HashMap::new(),
            current_task: 0,
            param_groups: params,
        })
    }

    /// Create with default configuration
    pub fn with_defaults(
        base_optimizer: O,
        params: Vec<Arc<RwLock<Tensor>>>,
    ) -> OptimizerResult<Self> {
        Self::new(base_optimizer, params, MASConfig::default())
    }

    /// Compute importance using output gradient magnitude
    pub fn compute_importance(&mut self) -> OptimizerResult<()> {
        // Accumulate gradient magnitudes
        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            let param_read = param.read();
            if let Some(grad) = param_read.grad() {
                // Importance = |∂L/∂θ|
                let grad_abs = grad.abs()?;

                if let Some(existing) = self.importance.get(&param_key) {
                    let accumulated = existing.add(&grad_abs)?;
                    self.importance.insert(param_key, accumulated);
                } else {
                    self.importance.insert(param_key, grad_abs);
                }
            }
        }

        Ok(())
    }

    /// Consolidate task (save optimal parameters)
    pub fn consolidate_task(&mut self) -> OptimizerResult<()> {
        // Save current parameters
        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);
            let param_read = param.read();
            self.optimal_params.insert(param_key, param_read.clone());
        }

        self.current_task += 1;
        Ok(())
    }

    /// Apply MAS penalty
    fn apply_mas_penalty(&mut self) -> OptimizerResult<()> {
        if self.importance.is_empty() {
            return Ok(());
        }

        for (i, param) in self.param_groups.iter().enumerate() {
            let param_key = format!("param_{}", i);

            if let (Some(importance), Some(optimal)) = (
                self.importance.get(&param_key),
                self.optimal_params.get(&param_key),
            ) {
                let mut param_write = param.write();

                // Penalty: Ω * (θ - θ*)
                let diff = param_write.sub(optimal)?;
                let penalty = importance.mul(&diff)?;
                let scaled_penalty = penalty.mul_scalar(self.config.importance)?;

                if let Some(grad) = param_write.grad() {
                    let new_grad = grad.add(&scaled_penalty)?;
                    param_write.set_grad(Some(new_grad));
                }
            }
        }

        Ok(())
    }
}

impl<O: Optimizer> Optimizer for MASOptimizer<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        // Apply MAS penalty
        self.apply_mas_penalty()?;

        // Call base optimizer
        self.base_optimizer.step()
    }

    fn zero_grad(&mut self) {
        self.base_optimizer.zero_grad();
    }

    fn get_lr(&self) -> Vec<f32> {
        self.base_optimizer.get_lr()
    }

    fn set_lr(&mut self, lr: f32) {
        self.base_optimizer.set_lr(lr);
    }

    fn add_param_group(&mut self, params: Vec<Arc<RwLock<Tensor>>>, options: HashMap<String, f32>) {
        self.base_optimizer.add_param_group(params, options);
    }

    fn parameters(&self) -> Vec<Arc<RwLock<Tensor>>> {
        self.param_groups.clone()
    }

    fn state_dict(&self) -> OptimizerResult<OptimizerState> {
        let mut state = self.base_optimizer.state_dict()?;
        state.optimizer_type = format!("MAS({})", state.optimizer_type);
        state
            .global_state
            .insert("current_task".to_string(), self.current_task as f32);
        Ok(state)
    }

    fn load_state_dict(&mut self, state: OptimizerState) -> OptimizerResult<()> {
        self.base_optimizer.load_state_dict(state)
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sgd::SGD;
    use torsh_tensor::creation::randn;

    #[test]
    fn test_ewc_config_default() {
        let config = EWCConfig::default();
        assert_eq!(config.importance, 1000.0);
        assert_eq!(config.fisher_sample_size, 200);
        assert!(config.diagonal_fisher);
    }

    #[test]
    fn test_ewc_optimizer_creation() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[10, 10])?));
        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);

        let optimizer = EWCOptimizer::with_defaults(base, vec![param])?;
        assert_eq!(optimizer.current_task, 0);
        Ok(())
    }

    #[test]
    fn test_ewc_consolidate_task() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[5, 5])?));

        // Set gradient for Fisher computation
        {
            let mut p = param.write();
            let grad = randn::<f32>(&[5, 5])?;
            p.set_grad(Some(grad));
        }

        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);
        let mut optimizer = EWCOptimizer::with_defaults(base, vec![param])?;

        optimizer.consolidate_task()?;
        assert_eq!(optimizer.current_task, 1);
        assert!(!optimizer.optimal_params.is_empty());
        Ok(())
    }

    #[test]
    fn test_si_config_default() {
        let config = SIConfig::default();
        assert_eq!(config.damping, 0.1);
        assert_eq!(config.importance, 1.0);
    }

    #[test]
    fn test_si_optimizer_creation() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[10, 10])?));
        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);

        let optimizer = SIOptimizer::with_defaults(base, vec![param])?;
        assert_eq!(optimizer.current_task, 0);
        Ok(())
    }

    #[test]
    fn test_si_consolidate_task() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[3, 3])?));

        // Set gradient
        {
            let mut p = param.write();
            let grad = randn::<f32>(&[3, 3])?;
            p.set_grad(Some(grad));
        }

        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);
        let mut optimizer = SIOptimizer::with_defaults(base, vec![param])?;

        optimizer.consolidate_task()?;
        assert_eq!(optimizer.current_task, 1);
        Ok(())
    }

    #[test]
    fn test_mas_config_default() {
        let config = MASConfig::default();
        assert_eq!(config.importance, 1.0);
        assert_eq!(config.n_samples, 100);
    }

    #[test]
    fn test_mas_optimizer_creation() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[10, 10])?));
        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);

        let optimizer = MASOptimizer::with_defaults(base, vec![param])?;
        assert_eq!(optimizer.current_task, 0);
        Ok(())
    }

    #[test]
    fn test_mas_compute_importance() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[5, 5])?));

        // Set gradient
        {
            let mut p = param.write();
            let grad = randn::<f32>(&[5, 5])?;
            p.set_grad(Some(grad));
        }

        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);
        let mut optimizer = MASOptimizer::with_defaults(base, vec![param])?;

        optimizer.compute_importance()?;
        assert!(!optimizer.importance.is_empty());
        Ok(())
    }

    #[test]
    fn test_ewc_step() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(randn::<f32>(&[2, 2])?));

        // Set gradient
        {
            let mut p = param.write();
            let grad = randn::<f32>(&[2, 2])?;
            p.set_grad(Some(grad));
        }

        let base = SGD::new(vec![param.clone()], 0.01, None, None, None, false);
        let mut optimizer = EWCOptimizer::with_defaults(base, vec![param])?;

        // Step should succeed
        optimizer.step()?;
        Ok(())
    }
}