optirs-learned 0.3.1

OptiRS learned optimizers and meta-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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// Meta-learning capabilities for transformer optimization
//
// This module implements meta-learning strategies that allow the transformer
// optimizer to quickly adapt to new tasks and optimization landscapes.

#[allow(dead_code)]
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::Float;
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;

use crate::error::{OptimError, Result};
use crate::transformer::TransformerNetwork;

/// Meta-learning strategies
#[derive(Debug, Clone, Copy)]
pub enum MetaLearningStrategy {
    /// Model-Agnostic Meta-Learning (MAML)
    MAML,
    /// Reptile algorithm
    Reptile,
    /// Gradient-based meta-learning
    GradientBased,
    /// Memory-augmented meta-learning
    MemoryAugmented,
    /// Task-agnostic meta-learning
    TaskAgnostic,
    /// Few-shot meta-learning
    FewShot,
    /// Continual meta-learning
    Continual,
}

/// Meta-learner for transformer optimizer
#[derive(Debug, Clone)]
pub struct TransformerMetaLearner<
    T: Float
        + Debug
        + Default
        + Clone
        + std::iter::Sum
        + scirs2_core::ndarray::ScalarOperand
        + Send
        + Sync
        + 'static,
> {
    /// Meta-learning strategy
    strategy: MetaLearningStrategy,

    /// Meta-transformer for higher-level learning
    meta_transformer: Option<TransformerNetwork<T>>,

    /// Task embeddings
    task_embeddings: HashMap<String, Array1<T>>,

    /// Meta-training history
    meta_history: VecDeque<MetaTrainingEvent<T>>,

    /// Domain adaptation module
    domain_adapter: DomainAdapter<T>,

    /// Few-shot learning capabilities
    few_shot_learner: FewShotLearner<T>,

    /// Continual learning state
    continual_learning: ContinualLearningState<T>,

    /// Meta-learning parameters
    meta_params: MetaLearningParams<T>,
}

/// Meta-training event
#[derive(Debug, Clone)]
pub struct MetaTrainingEvent<T: Float + Debug + Send + Sync + 'static> {
    /// Event type
    event_type: MetaEventType,

    /// Task information
    task_info: TaskInfo<T>,

    /// Performance metrics
    performance: MetaPerformanceMetrics<T>,

    /// Adaptation steps
    adaptation_steps: usize,

    /// Timestamp
    timestamp: usize,
}

/// Meta-event types
#[derive(Debug, Clone, Copy)]
pub enum MetaEventType {
    /// Task adaptation
    TaskAdaptation,
    /// Domain transfer
    DomainTransfer,
    /// Few-shot learning
    FewShotLearning,
    /// Continual learning
    ContinualLearning,
    /// Meta-validation
    MetaValidation,
}

/// Task information
#[derive(Debug, Clone)]
pub struct TaskInfo<T: Float + Debug + Send + Sync + 'static> {
    /// Task identifier
    task_id: String,

    /// Task characteristics
    characteristics: TaskCharacteristics<T>,

    /// Domain information
    domain: DomainInfo,

    /// Difficulty level
    difficulty: T,

    /// Expected performance
    expected_performance: Option<T>,
}

/// Task characteristics
#[derive(Debug, Clone)]
pub struct TaskCharacteristics<T: Float + Debug + Send + Sync + 'static> {
    /// Problem dimensionality
    dimensionality: usize,

    /// Landscape complexity
    landscape_complexity: T,

    /// Noise level
    noise_level: T,

    /// Conditioning number
    conditioning: T,

    /// Sparsity level
    sparsity: T,

    /// Temporal dependencies
    temporal_dependencies: T,

    /// Feature correlations
    feature_correlations: Array2<T>,
}

/// Domain information
#[derive(Debug, Clone)]
pub struct DomainInfo {
    /// Domain name
    name: String,

    /// Domain type
    domain_type: DomainType,

    /// Related domains
    related_domains: Vec<String>,

    /// Domain-specific features
    features: HashMap<String, f64>,
}

/// Domain types
#[derive(Debug, Clone, Copy)]
pub enum DomainType {
    /// Computer vision
    Vision,
    /// Natural language processing
    NLP,
    /// Reinforcement learning
    RL,
    /// Time series
    TimeSeries,
    /// Graph neural networks
    Graph,
    /// Scientific computing
    Scientific,
    /// General optimization
    General,
}

/// Meta-performance metrics
#[derive(Debug, Clone)]
pub struct MetaPerformanceMetrics<T: Float + Debug + Send + Sync + 'static> {
    /// Final performance
    final_performance: T,

    /// Convergence speed
    convergence_speed: T,

    /// Sample efficiency
    sample_efficiency: T,

    /// Generalization score
    generalization: T,

    /// Stability measure
    stability: T,

    /// Resource usage
    resource_usage: T,
}

/// Domain adapter for cross-domain transfer
#[derive(Debug, Clone)]
pub struct DomainAdapter<T: Float + Debug + Send + Sync + 'static> {
    /// Domain-specific adapters
    adapters: HashMap<String, DomainSpecificAdapter<T>>,

    /// Domain similarity estimator
    similarity_estimator: DomainSimilarityEstimator<T>,

    /// Adaptation strategies
    adaptation_strategies: Vec<AdaptationStrategy>,

    /// Transfer efficiency tracker
    transfer_tracker: TransferEfficiencyTracker<T>,
}

/// Domain-specific adapter
#[derive(Debug, Clone)]
pub struct DomainSpecificAdapter<T: Float + Debug + Send + Sync + 'static> {
    /// Adapter parameters
    parameters: HashMap<String, Array1<T>>,

    /// Domain features
    domain_features: Array1<T>,

    /// Adaptation history
    adaptation_history: Vec<AdaptationEvent<T>>,

    /// Performance on domain
    domain_performance: T,
}

/// Few-shot learner component
#[derive(Debug, Clone)]
pub struct FewShotLearner<T: Float + Debug + Send + Sync + 'static> {
    /// Support set memory
    support_memory: HashMap<String, Vec<Array1<T>>>,

    /// Prototype vectors
    prototypes: HashMap<String, Array1<T>>,

    /// Distance metric learner
    distance_learner: DistanceMetricLearner<T>,

    /// Few-shot adaptation parameters
    adaptation_params: FewShotParams<T>,
}

/// Continual learning state
#[derive(Debug, Clone)]
pub struct ContinualLearningState<T: Float + Debug + Send + Sync + 'static> {
    /// Elastic weight consolidation parameters
    ewc_params: HashMap<String, Array1<T>>,

    /// Fisher information matrix
    fisher_information: HashMap<String, Array2<T>>,

    /// Previous task importance scores
    task_importance: HashMap<String, T>,

    /// Memory replay buffer
    replay_buffer: Vec<ContinualLearningEvent<T>>,

    /// Catastrophic forgetting prevention strategy
    forgetting_prevention: ForgettingPreventionStrategy,
}

/// Meta-learning parameters
#[derive(Debug, Clone)]
pub struct MetaLearningParams<T: Float + Debug + Send + Sync + 'static> {
    /// Learning rate for meta-updates
    meta_learning_rate: T,

    /// Number of inner gradient steps
    inner_steps: usize,

    /// Meta-batch size
    meta_batch_size: usize,

    /// Task diversity weight
    diversity_weight: T,

    /// Transfer learning coefficient
    transfer_coefficient: T,

    /// Memory retention factor
    memory_retention: T,
}

// Additional supporting types
#[derive(Debug, Clone, Copy)]
pub enum AdaptationStrategy {
    FineTuning,
    ParameterSharing,
    ModularAdaptation,
    AttentionAdaptation,
}

#[derive(Debug, Clone)]
pub struct DomainSimilarityEstimator<T: Float + Debug + Send + Sync + 'static> {
    similarity_matrix: HashMap<(String, String), T>,
    feature_extractors: HashMap<String, Array2<T>>,
}

#[derive(Debug, Clone)]
pub struct TransferEfficiencyTracker<T: Float + Debug + Send + Sync + 'static> {
    transfer_history: Vec<TransferEvent<T>>,
    efficiency_metrics: HashMap<String, T>,
}

#[derive(Debug, Clone)]
pub struct AdaptationEvent<T: Float + Debug + Send + Sync + 'static> {
    timestamp: usize,
    adaptation_loss: T,
    performance_gain: T,
    adaptation_steps: usize,
}

#[derive(Debug, Clone)]
pub struct DistanceMetricLearner<T: Float + Debug + Send + Sync + 'static> {
    metric_parameters: Array2<T>,
    learned_similarities: HashMap<String, T>,
}

#[derive(Debug, Clone)]
pub struct FewShotParams<T: Float + Debug + Send + Sync + 'static> {
    support_size: usize,
    query_size: usize,
    adaptation_lr: T,
    temperature: T,
}

#[derive(Debug, Clone)]
pub struct ContinualLearningEvent<T: Float + Debug + Send + Sync + 'static> {
    task_id: String,
    gradients: Array1<T>,
    performance: T,
    timestamp: usize,
}

#[derive(Debug, Clone, Copy)]
pub enum ForgettingPreventionStrategy {
    EWC,
    PackNet,
    ProgressiveNetworks,
    GEM,
}

#[derive(Debug, Clone)]
pub struct TransferEvent<T: Float + Debug + Send + Sync + 'static> {
    source_domain: String,
    target_domain: String,
    transfer_performance: T,
    adaptation_time: usize,
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > TransformerMetaLearner<T>
{
    /// Create new meta-learner
    pub fn new(strategy: MetaLearningStrategy) -> Result<Self> {
        Ok(Self {
            strategy,
            meta_transformer: None,
            task_embeddings: HashMap::new(),
            meta_history: VecDeque::new(),
            domain_adapter: DomainAdapter::new()?,
            few_shot_learner: FewShotLearner::new()?,
            continual_learning: ContinualLearningState::new()?,
            meta_params: MetaLearningParams::default(),
        })
    }

    /// Adapt to a new task
    pub fn adapt_to_task(
        &mut self,
        task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        query_data: &[Array1<T>],
    ) -> Result<T> {
        match self.strategy {
            MetaLearningStrategy::MAML => self.maml_adaptation(task_info, support_data, query_data),
            MetaLearningStrategy::Reptile => {
                self.reptile_adaptation(task_info, support_data, query_data)
            }
            MetaLearningStrategy::FewShot => {
                self.few_shot_adaptation(task_info, support_data, query_data)
            }
            MetaLearningStrategy::Continual => {
                self.continual_adaptation(task_info, support_data, query_data)
            }
            _ => self.generic_adaptation(task_info, support_data, query_data),
        }
    }

    /// MAML adaptation
    fn maml_adaptation(
        &mut self,
        task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        query_data: &[Array1<T>],
    ) -> Result<T> {
        // Simplified MAML implementation
        let mut adaptation_loss = T::zero();

        // Perform inner loop updates
        for _ in 0..self.meta_params.inner_steps {
            // Compute gradients on support set
            let support_loss = self.compute_support_loss(support_data)?;

            // Update parameters (simplified)
            adaptation_loss = adaptation_loss + support_loss;
        }

        // Evaluate on query set
        let query_loss = self.compute_query_loss(query_data)?;

        // Record adaptation event
        let event = MetaTrainingEvent {
            event_type: MetaEventType::TaskAdaptation,
            task_info: task_info.clone(),
            performance: MetaPerformanceMetrics {
                final_performance: query_loss,
                convergence_speed: scirs2_core::numeric::NumCast::from(
                    1.0 / self.meta_params.inner_steps as f64,
                )
                .unwrap_or_else(|| T::zero()),
                sample_efficiency: T::from(support_data.len() as f64).expect("unwrap failed"),
                generalization: T::one() / (T::one() + query_loss),
                stability: scirs2_core::numeric::NumCast::from(0.9).unwrap_or_else(|| T::zero()),
                resource_usage: scirs2_core::numeric::NumCast::from(
                    self.meta_params.inner_steps as f64,
                )
                .unwrap_or_else(|| T::zero()),
            },
            adaptation_steps: self.meta_params.inner_steps,
            timestamp: self.meta_history.len(),
        };

        self.meta_history.push_back(event);

        Ok(query_loss)
    }

    /// Reptile adaptation
    fn reptile_adaptation(
        &mut self,
        task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        _query_data: &[Array1<T>],
    ) -> Result<T> {
        // Simplified Reptile implementation
        let initial_loss = self.compute_support_loss(support_data)?;

        // Perform multiple gradient steps
        let mut final_loss = initial_loss;
        for _ in 0..self.meta_params.inner_steps {
            final_loss =
                final_loss * scirs2_core::numeric::NumCast::from(0.95).unwrap_or_else(|| T::zero());
            // Simplified decay
        }

        Ok(final_loss)
    }

    /// Few-shot adaptation
    fn few_shot_adaptation(
        &mut self,
        task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        query_data: &[Array1<T>],
    ) -> Result<T> {
        self.few_shot_learner
            .adapt(task_info, support_data, query_data)
    }

    /// Continual learning adaptation
    fn continual_adaptation(
        &mut self,
        task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        query_data: &[Array1<T>],
    ) -> Result<T> {
        // Update continual learning state
        self.continual_learning
            .update_for_task(task_info, support_data)?;

        // Compute adaptation loss with forgetting prevention
        let base_loss = self.compute_support_loss(support_data)?;
        let forgetting_penalty = self.continual_learning.compute_forgetting_penalty()?;

        Ok(base_loss + forgetting_penalty)
    }

    /// Generic adaptation fallback
    fn generic_adaptation(
        &mut self,
        _task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        query_data: &[Array1<T>],
    ) -> Result<T> {
        let support_loss = self.compute_support_loss(support_data)?;
        let query_loss = self.compute_query_loss(query_data)?;
        Ok((support_loss + query_loss)
            / scirs2_core::numeric::NumCast::from(2.0).unwrap_or_else(|| T::zero()))
    }

    /// Compute loss on support set
    fn compute_support_loss(&self, support_data: &[Array1<T>]) -> Result<T> {
        if support_data.is_empty() {
            return Ok(T::zero());
        }

        let mut total_loss = T::zero();
        for data in support_data {
            // Simplified loss computation
            let loss = data.iter().map(|&x| x * x).fold(T::zero(), |a, b| a + b);
            total_loss = total_loss + loss;
        }

        Ok(total_loss / T::from(support_data.len() as f64).expect("unwrap failed"))
    }

    /// Compute loss on query set
    fn compute_query_loss(&self, query_data: &[Array1<T>]) -> Result<T> {
        if query_data.is_empty() {
            return Ok(T::zero());
        }

        let mut total_loss = T::zero();
        for data in query_data {
            // Simplified loss computation
            let loss = data.iter().map(|&x| x * x).fold(T::zero(), |a, b| a + b);
            total_loss = total_loss + loss;
        }

        Ok(total_loss / T::from(query_data.len() as f64).expect("unwrap failed"))
    }

    /// Get meta-learning statistics
    pub fn get_meta_statistics(&self) -> HashMap<String, T> {
        let mut stats = HashMap::new();

        stats.insert(
            "meta_events_count".to_string(),
            T::from(self.meta_history.len() as f64).expect("unwrap failed"),
        );
        stats.insert(
            "task_embeddings_count".to_string(),
            T::from(self.task_embeddings.len() as f64).expect("unwrap failed"),
        );

        // Compute average performance
        if !self.meta_history.is_empty() {
            let avg_performance = self
                .meta_history
                .iter()
                .map(|event| event.performance.final_performance)
                .fold(T::zero(), |a, b| a + b)
                / T::from(self.meta_history.len() as f64).expect("unwrap failed");
            stats.insert("average_performance".to_string(), avg_performance);
        }

        stats
    }

    /// Update meta-parameters
    pub fn update_meta_parameters(&mut self, params: MetaLearningParams<T>) {
        self.meta_params = params;
    }

    /// Get domain adapter
    pub fn domain_adapter(&self) -> &DomainAdapter<T> {
        &self.domain_adapter
    }

    /// Reset meta-learner state
    pub fn reset(&mut self) {
        self.task_embeddings.clear();
        self.meta_history.clear();
        self.domain_adapter.reset();
        self.few_shot_learner.reset();
        self.continual_learning.reset();
    }
}

// Implementation for supporting types
impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > DomainAdapter<T>
{
    fn new() -> Result<Self> {
        Ok(Self {
            adapters: HashMap::new(),
            similarity_estimator: DomainSimilarityEstimator::new()?,
            adaptation_strategies: vec![AdaptationStrategy::FineTuning],
            transfer_tracker: TransferEfficiencyTracker::new()?,
        })
    }

    fn reset(&mut self) {
        self.adapters.clear();
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > FewShotLearner<T>
{
    fn new() -> Result<Self> {
        Ok(Self {
            support_memory: HashMap::new(),
            prototypes: HashMap::new(),
            distance_learner: DistanceMetricLearner::new()?,
            adaptation_params: FewShotParams::default(),
        })
    }

    fn adapt(
        &mut self,
        _task_info: &TaskInfo<T>,
        support_data: &[Array1<T>],
        query_data: &[Array1<T>],
    ) -> Result<T> {
        // Simplified few-shot adaptation
        let support_loss = support_data
            .iter()
            .map(|x| x.iter().map(|&v| v * v).fold(T::zero(), |a, b| a + b))
            .fold(T::zero(), |a, b| a + b);
        let query_loss = query_data
            .iter()
            .map(|x| x.iter().map(|&v| v * v).fold(T::zero(), |a, b| a + b))
            .fold(T::zero(), |a, b| a + b);

        Ok((support_loss + query_loss)
            / T::from((support_data.len() + query_data.len()) as f64).expect("unwrap failed"))
    }

    fn reset(&mut self) {
        self.support_memory.clear();
        self.prototypes.clear();
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > ContinualLearningState<T>
{
    fn new() -> Result<Self> {
        Ok(Self {
            ewc_params: HashMap::new(),
            fisher_information: HashMap::new(),
            task_importance: HashMap::new(),
            replay_buffer: Vec::new(),
            forgetting_prevention: ForgettingPreventionStrategy::EWC,
        })
    }

    fn update_for_task(
        &mut self,
        task_info: &TaskInfo<T>,
        _support_data: &[Array1<T>],
    ) -> Result<()> {
        self.task_importance
            .insert(task_info.task_id.clone(), task_info.difficulty);
        Ok(())
    }

    fn compute_forgetting_penalty(&self) -> Result<T> {
        // Simplified forgetting penalty
        Ok(scirs2_core::numeric::NumCast::from(0.01).unwrap_or_else(|| T::zero()))
    }

    fn reset(&mut self) {
        self.ewc_params.clear();
        self.fisher_information.clear();
        self.task_importance.clear();
        self.replay_buffer.clear();
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > DomainSimilarityEstimator<T>
{
    fn new() -> Result<Self> {
        Ok(Self {
            similarity_matrix: HashMap::new(),
            feature_extractors: HashMap::new(),
        })
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > TransferEfficiencyTracker<T>
{
    fn new() -> Result<Self> {
        Ok(Self {
            transfer_history: Vec::new(),
            efficiency_metrics: HashMap::new(),
        })
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > DistanceMetricLearner<T>
{
    fn new() -> Result<Self> {
        Ok(Self {
            metric_parameters: Array2::eye(10), // Default 10x10 identity matrix
            learned_similarities: HashMap::new(),
        })
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > Default for MetaLearningParams<T>
{
    fn default() -> Self {
        Self {
            meta_learning_rate: scirs2_core::numeric::NumCast::from(0.001)
                .unwrap_or_else(|| T::zero()),
            inner_steps: 5,
            meta_batch_size: 32,
            diversity_weight: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),
            transfer_coefficient: scirs2_core::numeric::NumCast::from(0.5)
                .unwrap_or_else(|| T::zero()),
            memory_retention: scirs2_core::numeric::NumCast::from(0.95)
                .unwrap_or_else(|| T::zero()),
        }
    }
}

impl<
        T: Float
            + Debug
            + Send
            + Sync
            + 'static
            + Default
            + Clone
            + std::iter::Sum
            + scirs2_core::ndarray::ScalarOperand,
    > Default for FewShotParams<T>
{
    fn default() -> Self {
        Self {
            support_size: 5,
            query_size: 15,
            adaptation_lr: scirs2_core::numeric::NumCast::from(0.01).unwrap_or_else(|| T::zero()),
            temperature: scirs2_core::numeric::NumCast::from(1.0).unwrap_or_else(|| T::zero()),
        }
    }
}