Skip to main content

trustformers_models/
meta_learning.rs

1/*!
2# Meta-Learning Module
3
4This module provides comprehensive meta-learning capabilities for transformer models,
5enabling rapid adaptation to new tasks with minimal training data.
6
7## Features
8
9- **Model-Agnostic Meta-Learning (MAML)**: Learn initialization for rapid adaptation
10- **Reptile**: First-order approximation to MAML
11- **Prototypical Networks**: Learning metric embeddings for few-shot classification
12- **Matching Networks**: End-to-end differentiable nearest neighbor
13- **Relation Networks**: Learning to compare representations
14- **Memory-Augmented Networks**: External memory for meta-learning
15- **Gradient-Based Meta-Learning**: Various gradient-based approaches
16
17## Usage
18
19```rust
20use trustformers_models::meta_learning::{
21    MetaLearner, MetaLearningConfig, MetaAlgorithm, TaskBatch
22};
23
24# fn main() -> Result<(), Box<dyn std::error::Error>> {
25let config = MetaLearningConfig {
26    algorithm: MetaAlgorithm::MAML,
27    inner_lr: 0.01,
28    meta_lr: 0.001,
29    inner_steps: 5,
30    ..Default::default()
31};
32
33let mut meta_learner = MetaLearner::new(config)?;
34# Ok(())
35# }
36```
37*/
38
39use serde::{Deserialize, Serialize};
40use std::collections::HashMap;
41use trustformers_core::{
42    errors::{invalid_input, unsupported_operation, TrustformersError},
43    tensor::Tensor,
44};
45
46/// Configuration for meta-learning
47#[derive(Debug, Clone, Serialize, Deserialize)]
48pub struct MetaLearningConfig {
49    /// Meta-learning algorithm to use
50    pub algorithm: MetaAlgorithm,
51    /// Inner loop learning rate (task-specific adaptation)
52    pub inner_lr: f64,
53    /// Meta learning rate (across-task learning)
54    pub meta_lr: f64,
55    /// Number of inner loop gradient steps
56    pub inner_steps: usize,
57    /// Number of support examples per task
58    pub support_size: usize,
59    /// Number of query examples per task
60    pub query_size: usize,
61    /// Number of ways (classes) per task
62    pub num_ways: usize,
63    /// Number of shots (examples per class) per task
64    pub num_shots: usize,
65    /// Whether to use first-order approximation
66    pub first_order: bool,
67    /// Temperature for softmax in prototypical networks
68    pub temperature: f64,
69    /// Dimension of learned embeddings
70    pub embedding_dim: usize,
71    /// Whether to normalize embeddings
72    pub normalize_embeddings: bool,
73    /// Memory size for memory-augmented networks
74    pub memory_size: usize,
75    /// Memory key dimension
76    pub memory_key_dim: usize,
77    /// Memory value dimension
78    pub memory_value_dim: usize,
79    /// Number of meta-training tasks per batch
80    pub meta_batch_size: usize,
81    /// Whether to use task-specific parameters
82    pub task_specific_params: bool,
83    /// L2 regularization for inner loop
84    pub inner_l2_reg: f64,
85    /// Gradient clipping threshold
86    pub grad_clip_norm: f64,
87}
88
89impl Default for MetaLearningConfig {
90    fn default() -> Self {
91        Self {
92            algorithm: MetaAlgorithm::MAML,
93            inner_lr: 0.01,
94            meta_lr: 0.001,
95            inner_steps: 5,
96            support_size: 5,
97            query_size: 15,
98            num_ways: 5,
99            num_shots: 1,
100            first_order: false,
101            temperature: 1.0,
102            embedding_dim: 512,
103            normalize_embeddings: true,
104            memory_size: 128,
105            memory_key_dim: 64,
106            memory_value_dim: 256,
107            meta_batch_size: 32,
108            task_specific_params: false,
109            inner_l2_reg: 0.0001,
110            grad_clip_norm: 10.0,
111        }
112    }
113}
114
115/// Meta-learning algorithms supported
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117pub enum MetaAlgorithm {
118    /// Model-Agnostic Meta-Learning
119    MAML,
120    /// Reptile (first-order MAML)
121    Reptile,
122    /// Prototypical Networks
123    ProtoNet,
124    /// Matching Networks
125    MatchingNet,
126    /// Relation Networks
127    RelationNet,
128    /// Memory-Augmented Neural Networks
129    MANN,
130    /// Gradient-Based Meta-Learning
131    GBML,
132    /// Meta-SGD (learn learning rates)
133    MetaSGD,
134    /// Learning to Learn by Gradient Descent
135    L2L,
136}
137
138/// Cosine similarity between two equally sized vectors.
139fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
140    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
141    let norm_a = a.iter().map(|x| x * x).sum::<f32>().sqrt();
142    let norm_b = b.iter().map(|x| x * x).sum::<f32>().sqrt();
143    if norm_a <= f32::EPSILON || norm_b <= f32::EPSILON {
144        return 0.0;
145    }
146    dot / (norm_a * norm_b)
147}
148
149/// Numerically stable softmax over `f64` scores.
150fn softmax_f64(scores: &[f64]) -> Vec<f64> {
151    let max = scores.iter().copied().fold(f64::NEG_INFINITY, f64::max);
152    if !max.is_finite() {
153        let uniform = 1.0 / scores.len().max(1) as f64;
154        return vec![uniform; scores.len()];
155    }
156    let exponentials: Vec<f64> = scores.iter().map(|s| (s - max).exp()).collect();
157    let total: f64 = exponentials.iter().sum();
158    if total <= 0.0 {
159        let uniform = 1.0 / scores.len().max(1) as f64;
160        return vec![uniform; scores.len()];
161    }
162    exponentials.into_iter().map(|e| e / total).collect()
163}
164
165/// Index of the largest element.
166fn argmax_f64(values: &[f64]) -> usize {
167    values
168        .iter()
169        .enumerate()
170        .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
171        .map(|(index, _)| index)
172        .unwrap_or(0)
173}
174
175/// Meta-learning trainer
176pub struct MetaLearner {
177    config: MetaLearningConfig,
178    model: Box<dyn MetaLearningModel>,
179    optimizer: Box<dyn MetaOptimizer>,
180    task_sampler: TaskSampler,
181    meta_statistics: MetaStatistics,
182    episode_history: Vec<EpisodeResult>,
183    current_episode: usize,
184}
185
186impl MetaLearner {
187    /// Create a new meta-learner
188    pub fn new(config: MetaLearningConfig) -> Result<Self, TrustformersError> {
189        let model = Self::create_model(&config)?;
190        let optimizer = Self::create_optimizer(&config)?;
191        let task_sampler = TaskSampler::new(&config)?;
192
193        Ok(Self {
194            config,
195            model,
196            optimizer,
197            task_sampler,
198            meta_statistics: MetaStatistics::new(),
199            episode_history: Vec::new(),
200            current_episode: 0,
201        })
202    }
203
204    /// Create appropriate model based on algorithm
205    fn create_model(
206        config: &MetaLearningConfig,
207    ) -> Result<Box<dyn MetaLearningModel>, TrustformersError> {
208        match config.algorithm {
209            MetaAlgorithm::MAML => Ok(Box::new(MAMLModel::new(config)?)),
210            MetaAlgorithm::Reptile => Ok(Box::new(ReptileModel::new(config)?)),
211            MetaAlgorithm::ProtoNet => Ok(Box::new(PrototypicalModel::new(config)?)),
212            MetaAlgorithm::MatchingNet => Ok(Box::new(MatchingNetModel::new(config)?)),
213            MetaAlgorithm::RelationNet => Ok(Box::new(RelationNetModel::new(config)?)),
214            MetaAlgorithm::MANN => Ok(Box::new(MemoryAugmentedModel::new(config)?)),
215            MetaAlgorithm::GBML => Ok(Box::new(GradientBasedModel::new(config)?)),
216            MetaAlgorithm::MetaSGD => Ok(Box::new(MetaSGDModel::new(config)?)),
217            MetaAlgorithm::L2L => Ok(Box::new(L2LModel::new(config)?)),
218        }
219    }
220
221    /// Create appropriate optimizer
222    fn create_optimizer(
223        config: &MetaLearningConfig,
224    ) -> Result<Box<dyn MetaOptimizer>, TrustformersError> {
225        match config.algorithm {
226            MetaAlgorithm::MAML | MetaAlgorithm::Reptile | MetaAlgorithm::GBML => {
227                Ok(Box::new(SGDMetaOptimizer::new(config.meta_lr)?))
228            },
229            MetaAlgorithm::MetaSGD => Ok(Box::new(LearnedLROptimizer::new(config.meta_lr)?)),
230            _ => Ok(Box::new(AdamMetaOptimizer::new(config.meta_lr)?)),
231        }
232    }
233
234    /// Train on a single meta-learning episode
235    pub fn train_episode(
236        &mut self,
237        task_batch: TaskBatch,
238    ) -> Result<EpisodeResult, TrustformersError> {
239        let start_time = std::time::Instant::now();
240        let mut total_loss = 0.0;
241        let mut total_accuracy = 0.0;
242        let num_tasks = task_batch.tasks.len();
243
244        for task in &task_batch.tasks {
245            let task_result = self.train_single_task(task)?;
246            total_loss += task_result.query_loss;
247            total_accuracy += task_result.query_accuracy;
248        }
249
250        // Update meta-parameters
251        self.optimizer.step(&mut *self.model)?;
252
253        let episode_result = EpisodeResult {
254            episode: self.current_episode,
255            meta_loss: total_loss / num_tasks as f64,
256            meta_accuracy: total_accuracy / num_tasks as f64,
257            num_tasks,
258            episode_time: start_time.elapsed(),
259            algorithm: self.config.algorithm,
260        };
261
262        self.episode_history.push(episode_result.clone());
263        self.meta_statistics.update(&episode_result);
264        self.current_episode += 1;
265
266        Ok(episode_result)
267    }
268
269    /// Train on a single task within an episode
270    fn train_single_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
271        match self.config.algorithm {
272            MetaAlgorithm::MAML => self.train_maml_task(task),
273            MetaAlgorithm::Reptile => self.train_reptile_task(task),
274            MetaAlgorithm::ProtoNet => self.train_prototypical_task(task),
275            MetaAlgorithm::MatchingNet => self.train_matching_task(task),
276            MetaAlgorithm::RelationNet => self.train_relation_task(task),
277            MetaAlgorithm::MANN => self.train_memory_task(task),
278            MetaAlgorithm::GBML => self.train_gradient_based_task(task),
279            MetaAlgorithm::MetaSGD => self.train_meta_sgd_task(task),
280            MetaAlgorithm::L2L => self.train_l2l_task(task),
281        }
282    }
283
284    /// MAML training for a single task
285    fn train_maml_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
286        // Save initial parameters
287        let initial_params = self.model.get_parameters()?;
288
289        // Inner loop: adapt to support set
290        for _ in 0..self.config.inner_steps {
291            let support_loss = self.model.forward(&task.support_set)?;
292            let gradients = self.model.compute_gradients(support_loss)?;
293
294            // Apply inner loop update
295            self.model.apply_gradients(&gradients, self.config.inner_lr)?;
296        }
297
298        // Compute loss on query set with adapted parameters
299        let query_loss = self.model.forward(&task.query_set)?;
300        let query_accuracy = self.model.compute_accuracy(&task.query_set)?;
301
302        // Compute meta-gradients (through the inner loop)
303        let meta_gradients = if self.config.first_order {
304            // First-order approximation (Reptile-style)
305            self.model.compute_first_order_gradients(query_loss)?
306        } else {
307            // Full second-order gradients
308            self.model.compute_second_order_gradients(&initial_params, query_loss)?
309        };
310
311        // Store meta-gradients for meta-update
312        self.optimizer.accumulate_gradients(meta_gradients)?;
313
314        // Restore initial parameters for next task
315        self.model.set_parameters(initial_params)?;
316
317        Ok(TaskResult {
318            support_loss: 0.0, // We don't track support loss in MAML
319            query_loss,
320            query_accuracy,
321            adaptation_time: std::time::Duration::from_millis(0),
322        })
323    }
324
325    /// Reptile training for a single task
326    fn train_reptile_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
327        let initial_params = self.model.get_parameters()?;
328
329        // Inner loop on support set
330        for _ in 0..self.config.inner_steps {
331            let support_loss = self.model.forward(&task.support_set)?;
332            let gradients = self.model.compute_gradients(support_loss)?;
333            self.model.apply_gradients(&gradients, self.config.inner_lr)?;
334        }
335
336        let adapted_params = self.model.get_parameters()?;
337        let query_loss = self.model.forward(&task.query_set)?;
338        let query_accuracy = self.model.compute_accuracy(&task.query_set)?;
339
340        // Reptile meta-gradient: direction from initial to adapted parameters
341        let meta_gradients = self.compute_param_difference(&initial_params, &adapted_params)?;
342        self.optimizer.accumulate_gradients(meta_gradients)?;
343
344        // Restore parameters
345        self.model.set_parameters(initial_params)?;
346
347        Ok(TaskResult {
348            support_loss: 0.0,
349            query_loss,
350            query_accuracy,
351            adaptation_time: std::time::Duration::from_millis(0),
352        })
353    }
354
355    /// Prototypical Networks training
356    fn train_prototypical_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
357        // Compute prototypes from support set
358        let prototypes = self.compute_prototypes(&task.support_set)?;
359
360        // Classify query examples based on distance to prototypes
361        let query_loss = self.compute_prototypical_loss(&task.query_set, &prototypes)?;
362        let query_accuracy = self.compute_prototypical_accuracy(&task.query_set, &prototypes)?;
363
364        // The embedding network is trained on the query set, so run it through
365        // the model to establish the batch the gradients are taken against.
366        let embedding_loss = self.model.forward(&task.query_set)?;
367        let gradients = self.model.compute_gradients(embedding_loss)?;
368        self.optimizer.accumulate_gradients(gradients)?;
369
370        Ok(TaskResult {
371            support_loss: 0.0,
372            query_loss,
373            query_accuracy,
374            adaptation_time: std::time::Duration::from_millis(0),
375        })
376    }
377
378    /// Matching Networks training
379    fn train_matching_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
380        // Compute attention weights between query and support examples
381        let attention_weights =
382            self.compute_attention_weights(&task.query_set, &task.support_set)?;
383
384        // Weighted combination of support labels
385        let predictions =
386            self.compute_matching_predictions(&attention_weights, &task.support_set)?;
387
388        let query_loss = self.compute_matching_loss(&predictions, &task.query_set)?;
389        let query_accuracy = self.compute_matching_accuracy(&predictions, &task.query_set)?;
390
391        // The embedding network is trained on the query set, so run it through
392        // the model to establish the batch the gradients are taken against.
393        let embedding_loss = self.model.forward(&task.query_set)?;
394        let gradients = self.model.compute_gradients(embedding_loss)?;
395        self.optimizer.accumulate_gradients(gradients)?;
396
397        Ok(TaskResult {
398            support_loss: 0.0,
399            query_loss,
400            query_accuracy,
401            adaptation_time: std::time::Duration::from_millis(0),
402        })
403    }
404
405    /// Relation Networks training
406    fn train_relation_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
407        let mut total_loss = 0.0;
408        let mut correct_predictions = 0;
409        let mut total_predictions = 0;
410
411        // For each query example, compute relation scores with all support examples
412        for query_example in &task.query_set.examples {
413            let query_embedding = self.model.embed(query_example)?;
414            let mut relation_scores = Vec::new();
415
416            for support_example in &task.support_set.examples {
417                let support_embedding = self.model.embed(support_example)?;
418                let relation_score =
419                    self.model.compute_relation(&query_embedding, &support_embedding)?;
420                relation_scores.push(relation_score);
421            }
422
423            // Compute loss and accuracy for this query example
424            let loss =
425                self.compute_relation_loss(&relation_scores, query_example, &task.support_set)?;
426            total_loss += loss;
427
428            if self.is_correct_prediction(&relation_scores, query_example, &task.support_set)? {
429                correct_predictions += 1;
430            }
431            total_predictions += 1;
432        }
433
434        let query_loss = total_loss / total_predictions as f64;
435        let query_accuracy = correct_predictions as f64 / total_predictions as f64;
436
437        // The embedding network behind the relation module is trained on the
438        // query set; run it so the gradients have a batch to be taken against.
439        let embedding_loss = self.model.forward(&task.query_set)?;
440        let gradients = self.model.compute_gradients(embedding_loss)?;
441        self.optimizer.accumulate_gradients(gradients)?;
442
443        Ok(TaskResult {
444            support_loss: 0.0,
445            query_loss,
446            query_accuracy,
447            adaptation_time: std::time::Duration::from_millis(0),
448        })
449    }
450
451    /// Memory-Augmented Networks training
452    fn train_memory_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
453        // Write support examples to memory
454        for example in &task.support_set.examples {
455            self.model.write_to_memory(example)?;
456        }
457
458        let mut total_loss = 0.0;
459        let mut correct_predictions = 0;
460        let total_predictions = task.query_set.examples.len();
461
462        // For each query example, read from memory and predict
463        for query_example in &task.query_set.examples {
464            let memory_output = self.model.read_from_memory(query_example)?;
465            let prediction = self.model.predict_from_memory(&memory_output)?;
466
467            let loss = self.compute_memory_loss(&prediction, query_example)?;
468            total_loss += loss;
469
470            if self.is_memory_prediction_correct(&prediction, query_example)? {
471                correct_predictions += 1;
472            }
473        }
474
475        let query_loss = total_loss / total_predictions as f64;
476        let query_accuracy = correct_predictions as f64 / total_predictions as f64;
477
478        let gradients = self.model.compute_gradients(query_loss)?;
479        self.optimizer.accumulate_gradients(gradients)?;
480
481        // Clear memory for next task
482        self.model.clear_memory()?;
483
484        Ok(TaskResult {
485            support_loss: 0.0,
486            query_loss,
487            query_accuracy,
488            adaptation_time: std::time::Duration::from_millis(0),
489        })
490    }
491
492    /// Gradient-Based Meta-Learning training
493    fn train_gradient_based_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
494        // Learn the learning algorithm itself
495        let meta_learner_state = self.model.get_meta_learner_state()?;
496
497        // Apply learned learning algorithm to support set
498        let adapted_params =
499            self.model.apply_learned_algorithm(&task.support_set, &meta_learner_state)?;
500
501        // Evaluate on query set
502        let query_loss = self.model.evaluate_with_params(&task.query_set, &adapted_params)?;
503        let query_accuracy =
504            self.model.compute_accuracy_with_params(&task.query_set, &adapted_params)?;
505
506        // Update meta-learner
507        let gradients = self.model.compute_meta_learner_gradients(query_loss)?;
508        self.optimizer.accumulate_gradients(gradients)?;
509
510        Ok(TaskResult {
511            support_loss: 0.0,
512            query_loss,
513            query_accuracy,
514            adaptation_time: std::time::Duration::from_millis(0),
515        })
516    }
517
518    /// Meta-SGD training (learns learning rates)
519    fn train_meta_sgd_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
520        let initial_params = self.model.get_parameters()?;
521        let learning_rates = self.model.get_learning_rates()?;
522
523        // Inner loop with learned learning rates
524        for _ in 0..self.config.inner_steps {
525            let support_loss = self.model.forward(&task.support_set)?;
526            let gradients = self.model.compute_gradients(support_loss)?;
527
528            // Apply gradients with learned learning rates
529            self.model.apply_gradients_with_lr(&gradients, &learning_rates)?;
530        }
531
532        let query_loss = self.model.forward(&task.query_set)?;
533        let query_accuracy = self.model.compute_accuracy(&task.query_set)?;
534
535        // Update both parameters and learning rates
536        let param_gradients =
537            self.model.compute_second_order_gradients(&initial_params, query_loss)?;
538        let lr_gradients = self.model.compute_lr_gradients(query_loss)?;
539
540        self.optimizer.accumulate_param_gradients(param_gradients)?;
541        self.optimizer.accumulate_lr_gradients(lr_gradients)?;
542
543        // Restore parameters
544        self.model.set_parameters(initial_params)?;
545
546        Ok(TaskResult {
547            support_loss: 0.0,
548            query_loss,
549            query_accuracy,
550            adaptation_time: std::time::Duration::from_millis(0),
551        })
552    }
553
554    /// Learning to Learn by Gradient Descent training
555    fn train_l2l_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
556        // Use LSTM meta-learner to generate updates
557        let mut lstm_state = self.model.get_lstm_state()?;
558        let initial_params = self.model.get_parameters()?;
559
560        // Inner loop using LSTM meta-learner
561        for step in 0..self.config.inner_steps {
562            let support_loss = self.model.forward(&task.support_set)?;
563            let gradients = self.model.compute_gradients(support_loss)?;
564
565            // LSTM generates parameter updates
566            let (updates, new_lstm_state) =
567                self.model.lstm_update(&gradients, &lstm_state, step)?;
568            lstm_state = new_lstm_state;
569
570            // Apply LSTM-generated updates
571            self.model.apply_lstm_updates(&updates)?;
572        }
573
574        let query_loss = self.model.forward(&task.query_set)?;
575        let query_accuracy = self.model.compute_accuracy(&task.query_set)?;
576
577        // Update LSTM meta-learner
578        let lstm_gradients = self.model.compute_lstm_gradients(query_loss)?;
579        self.optimizer.accumulate_gradients(lstm_gradients)?;
580
581        // Restore parameters
582        self.model.set_parameters(initial_params)?;
583
584        Ok(TaskResult {
585            support_loss: 0.0,
586            query_loss,
587            query_accuracy,
588            adaptation_time: std::time::Duration::from_millis(0),
589        })
590    }
591
592    /// Helper methods for specific computations
593    fn compute_param_difference(
594        &self,
595        params1: &ModelParameters,
596        params2: &ModelParameters,
597    ) -> Result<ModelGradients, TrustformersError> {
598        // Compute difference between parameter sets
599        let mut gradients = ModelGradients::new();
600
601        for (name, param1) in &params1.parameters {
602            if let Some(param2) = params2.parameters.get(name) {
603                let diff = param2.sub(param1)?; // Reptile direction
604                gradients.gradients.insert(name.clone(), diff);
605            }
606        }
607
608        Ok(gradients)
609    }
610
611    fn compute_prototypes(
612        &self,
613        support_set: &ExampleSet,
614    ) -> Result<Vec<Tensor>, TrustformersError> {
615        let mut prototypes = Vec::new();
616        let num_classes = self.config.num_ways;
617
618        for class_id in 0..num_classes {
619            let mut class_embeddings = Vec::new();
620
621            // Collect embeddings for this class
622            for example in &support_set.examples {
623                if example.label == class_id {
624                    let embedding = self.model.embed(example)?;
625                    class_embeddings.push(embedding);
626                }
627            }
628
629            // Compute prototype as mean of class embeddings
630            if !class_embeddings.is_empty() {
631                let prototype = self.compute_mean_embedding(&class_embeddings)?;
632                prototypes.push(prototype);
633            }
634        }
635
636        Ok(prototypes)
637    }
638
639    fn compute_mean_embedding(&self, embeddings: &[Tensor]) -> Result<Tensor, TrustformersError> {
640        if embeddings.is_empty() {
641            return Err(invalid_input("Empty embeddings list"));
642        }
643
644        let mut sum = embeddings[0].clone();
645        for embedding in &embeddings[1..] {
646            sum = sum.add(embedding)?;
647        }
648
649        sum.scalar_div(embeddings.len() as f32)
650    }
651
652    fn compute_prototypical_loss(
653        &self,
654        query_set: &ExampleSet,
655        prototypes: &[Tensor],
656    ) -> Result<f64, TrustformersError> {
657        let mut total_loss = 0.0;
658
659        for example in &query_set.examples {
660            let query_embedding = self.model.embed(example)?;
661            let distances = self.compute_distances(&query_embedding, prototypes)?;
662            let log_probs = self.compute_log_softmax(&distances, self.config.temperature)?;
663
664            // Negative log-likelihood loss
665            total_loss -= log_probs[example.label];
666        }
667
668        Ok(total_loss / query_set.examples.len() as f64)
669    }
670
671    fn compute_prototypical_accuracy(
672        &self,
673        query_set: &ExampleSet,
674        prototypes: &[Tensor],
675    ) -> Result<f64, TrustformersError> {
676        let mut correct = 0;
677
678        for example in &query_set.examples {
679            let query_embedding = self.model.embed(example)?;
680            let distances = self.compute_distances(&query_embedding, prototypes)?;
681
682            // Predict class with minimum distance
683            let predicted_class = distances
684                .iter()
685                .enumerate()
686                .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
687                .map(|(i, _)| i)
688                .unwrap_or(0);
689
690            if predicted_class == example.label {
691                correct += 1;
692            }
693        }
694
695        Ok(correct as f64 / query_set.examples.len() as f64)
696    }
697
698    fn compute_distances(
699        &self,
700        query: &Tensor,
701        prototypes: &[Tensor],
702    ) -> Result<Vec<f64>, TrustformersError> {
703        let mut distances = Vec::new();
704
705        for prototype in prototypes {
706            let diff = query.sub(prototype)?;
707            let distance = diff.norm()? as f64;
708            distances.push(distance);
709        }
710
711        Ok(distances)
712    }
713
714    fn compute_log_softmax(
715        &self,
716        distances: &[f64],
717        temperature: f64,
718    ) -> Result<Vec<f64>, TrustformersError> {
719        // Convert distances to negative log probabilities
720        let neg_distances: Vec<f64> = distances.iter().map(|d| -d / temperature).collect();
721
722        // Compute log softmax
723        let max_val = neg_distances.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
724        let exp_sum: f64 = neg_distances.iter().map(|x| (x - max_val).exp()).sum();
725        let log_sum = max_val + exp_sum.ln();
726
727        Ok(neg_distances.iter().map(|x| x - log_sum).collect())
728    }
729
730    /// Cosine attention of every query example over every support example.
731    ///
732    /// Row `i` is a probability distribution over the support set, produced by
733    /// a softmax over the cosine similarities of the learned embeddings — the
734    /// attention kernel of Matching Networks.
735    fn compute_attention_weights(
736        &self,
737        query_set: &ExampleSet,
738        support_set: &ExampleSet,
739    ) -> Result<Vec<Vec<f64>>, TrustformersError> {
740        if support_set.examples.is_empty() {
741            return Err(invalid_input(
742                "matching networks need a non-empty support set",
743            ));
744        }
745
746        let support_embeddings: Vec<Vec<f32>> = support_set
747            .examples
748            .iter()
749            .map(|example| -> Result<Vec<f32>, TrustformersError> {
750                let embedding = self.model.embed(example)?;
751                let values = embedding.to_vec_f32()?;
752                Ok(values)
753            })
754            .collect::<Result<_, TrustformersError>>()?;
755
756        let mut weights = Vec::with_capacity(query_set.examples.len());
757        for example in &query_set.examples {
758            let query = self.model.embed(example)?.to_vec_f32()?;
759            let similarities: Vec<f64> = support_embeddings
760                .iter()
761                .map(|support| cosine_similarity(&query, support) as f64)
762                .collect();
763            weights.push(softmax_f64(&similarities));
764        }
765
766        Ok(weights)
767    }
768
769    /// Attention-weighted mixture of the support labels.
770    fn compute_matching_predictions(
771        &self,
772        weights: &[Vec<f64>],
773        support_set: &ExampleSet,
774    ) -> Result<Vec<Vec<f64>>, TrustformersError> {
775        let classes = support_set.num_classes.max(1);
776        let mut predictions = Vec::with_capacity(weights.len());
777
778        for row in weights {
779            if row.len() != support_set.examples.len() {
780                return Err(invalid_input(
781                    "attention row width must match the support set size",
782                ));
783            }
784            let mut distribution = vec![0.0f64; classes];
785            for (weight, example) in row.iter().zip(support_set.examples.iter()) {
786                if example.label >= classes {
787                    return Err(invalid_input(format!(
788                        "support label {} exceeds the task's {} classes",
789                        example.label, classes
790                    )));
791                }
792                distribution[example.label] += *weight;
793            }
794            predictions.push(distribution);
795        }
796
797        Ok(predictions)
798    }
799
800    /// Negative log-likelihood of the matching-network predictions.
801    fn compute_matching_loss(
802        &self,
803        predictions: &[Vec<f64>],
804        query_set: &ExampleSet,
805    ) -> Result<f64, TrustformersError> {
806        if predictions.len() != query_set.examples.len() {
807            return Err(invalid_input(
808                "one prediction row is required per query example",
809            ));
810        }
811        if predictions.is_empty() {
812            return Err(invalid_input("cannot score an empty query set"));
813        }
814
815        let mut total = 0.0f64;
816        for (distribution, example) in predictions.iter().zip(query_set.examples.iter()) {
817            let probability = distribution.get(example.label).copied().unwrap_or(0.0);
818            total -= probability.max(1e-12).ln();
819        }
820        Ok(total / predictions.len() as f64)
821    }
822
823    /// Fraction of query examples whose most likely class is correct.
824    fn compute_matching_accuracy(
825        &self,
826        predictions: &[Vec<f64>],
827        query_set: &ExampleSet,
828    ) -> Result<f64, TrustformersError> {
829        if predictions.len() != query_set.examples.len() {
830            return Err(invalid_input(
831                "one prediction row is required per query example",
832            ));
833        }
834        if predictions.is_empty() {
835            return Err(invalid_input("cannot score an empty query set"));
836        }
837
838        let correct = predictions
839            .iter()
840            .zip(query_set.examples.iter())
841            .filter(|(distribution, example)| argmax_f64(distribution) == example.label)
842            .count();
843        Ok(correct as f64 / predictions.len() as f64)
844    }
845
846    /// Mean squared error between the relation scores and their targets.
847    ///
848    /// Relation Networks regress the score towards 1 for support examples of
849    /// the query's class and towards 0 otherwise.
850    fn compute_relation_loss(
851        &self,
852        scores: &[f64],
853        example: &Example,
854        support_set: &ExampleSet,
855    ) -> Result<f64, TrustformersError> {
856        if scores.len() != support_set.examples.len() {
857            return Err(invalid_input(
858                "one relation score is required per support example",
859            ));
860        }
861        if scores.is_empty() {
862            return Err(invalid_input("cannot score an empty support set"));
863        }
864
865        let mut total = 0.0f64;
866        for (score, support) in scores.iter().zip(support_set.examples.iter()) {
867            let target = if support.label == example.label { 1.0 } else { 0.0 };
868            total += (score - target) * (score - target);
869        }
870        Ok(total / scores.len() as f64)
871    }
872
873    /// Whether the highest relation score belongs to the query's own class.
874    fn is_correct_prediction(
875        &self,
876        scores: &[f64],
877        example: &Example,
878        support_set: &ExampleSet,
879    ) -> Result<bool, TrustformersError> {
880        if scores.len() != support_set.examples.len() {
881            return Err(invalid_input(
882                "one relation score is required per support example",
883            ));
884        }
885
886        // Aggregate the scores per class and pick the strongest class.
887        let classes = support_set.num_classes.max(1);
888        let mut per_class = vec![0.0f64; classes];
889        for (score, support) in scores.iter().zip(support_set.examples.iter()) {
890            if support.label < classes {
891                per_class[support.label] += *score;
892            }
893        }
894        Ok(argmax_f64(&per_class) == example.label)
895    }
896
897    /// Cross-entropy of a memory-augmented prediction.
898    fn compute_memory_loss(
899        &self,
900        prediction: &MemoryPrediction,
901        example: &Example,
902    ) -> Result<f64, TrustformersError> {
903        let logits = prediction.logits.to_vec_f32()?;
904        if example.label >= logits.len() {
905            return Err(invalid_input(format!(
906                "label {} is out of range for {} memory logits",
907                example.label,
908                logits.len()
909            )));
910        }
911        let distribution = softmax_f64(&logits.iter().map(|v| *v as f64).collect::<Vec<_>>());
912        Ok(-distribution[example.label].max(1e-12).ln())
913    }
914
915    /// Whether a memory-augmented prediction picks the right class.
916    fn is_memory_prediction_correct(
917        &self,
918        prediction: &MemoryPrediction,
919        example: &Example,
920    ) -> Result<bool, TrustformersError> {
921        let logits = prediction.logits.to_vec_f32()?;
922        if logits.is_empty() {
923            return Err(invalid_input("memory prediction has no logits"));
924        }
925        let best = logits
926            .iter()
927            .enumerate()
928            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
929            .map(|(index, _)| index)
930            .unwrap_or(0);
931        Ok(best == example.label)
932    }
933
934    /// Evaluate the meta-learner on new tasks
935    pub fn evaluate(
936        &mut self,
937        task_batch: TaskBatch,
938    ) -> Result<EvaluationResult, TrustformersError> {
939        let mut total_accuracy = 0.0;
940        let mut task_results = Vec::new();
941
942        for task in &task_batch.tasks {
943            let task_result = self.evaluate_single_task(task)?;
944            total_accuracy += task_result.query_accuracy;
945            task_results.push(task_result);
946        }
947
948        Ok(EvaluationResult {
949            average_accuracy: total_accuracy / task_batch.tasks.len() as f64,
950            task_results,
951            num_tasks: task_batch.tasks.len(),
952        })
953    }
954
955    fn evaluate_single_task(&mut self, task: &Task) -> Result<TaskResult, TrustformersError> {
956        // Similar to training but without gradient updates
957        match self.config.algorithm {
958            MetaAlgorithm::MAML | MetaAlgorithm::Reptile => {
959                let initial_params = self.model.get_parameters()?;
960
961                // Adapt to support set
962                for _ in 0..self.config.inner_steps {
963                    let support_loss = self.model.forward(&task.support_set)?;
964                    let gradients = self.model.compute_gradients(support_loss)?;
965                    self.model.apply_gradients(&gradients, self.config.inner_lr)?;
966                }
967
968                // Evaluate on query set
969                let query_loss = self.model.forward(&task.query_set)?;
970                let query_accuracy = self.model.compute_accuracy(&task.query_set)?;
971
972                // Restore parameters
973                self.model.set_parameters(initial_params)?;
974
975                Ok(TaskResult {
976                    support_loss: 0.0,
977                    query_loss,
978                    query_accuracy,
979                    adaptation_time: std::time::Duration::from_millis(0),
980                })
981            },
982            MetaAlgorithm::ProtoNet => self.train_prototypical_task(task),
983            _ => {
984                // For other algorithms, use the same evaluation as training
985                // but without accumulating gradients
986                self.train_single_task(task)
987            },
988        }
989    }
990
991    /// Get meta-learning statistics
992    pub fn get_statistics(&self) -> &MetaStatistics {
993        &self.meta_statistics
994    }
995
996    /// Get episode history
997    pub fn get_episode_history(&self) -> &[EpisodeResult] {
998        &self.episode_history
999    }
1000
1001    /// Sample a new task batch
1002    pub fn sample_task_batch(&mut self) -> Result<TaskBatch, TrustformersError> {
1003        self.task_sampler.sample_batch(self.config.meta_batch_size)
1004    }
1005}
1006
1007/// Core data structures for meta-learning
1008#[derive(Debug, Clone)]
1009pub struct Task {
1010    pub task_id: String,
1011    pub support_set: ExampleSet,
1012    pub query_set: ExampleSet,
1013    pub task_type: TaskType,
1014}
1015
1016#[derive(Debug, Clone)]
1017pub struct TaskBatch {
1018    pub tasks: Vec<Task>,
1019    pub batch_id: String,
1020}
1021
1022#[derive(Debug, Clone)]
1023pub struct ExampleSet {
1024    pub examples: Vec<Example>,
1025    pub num_classes: usize,
1026}
1027
1028/// One labelled example.
1029///
1030/// Classification examples carry a class index in `label` and leave `target`
1031/// empty; regression examples carry a continuous `target` vector, which is what
1032/// the sine-wave few-shot benchmark uses.
1033#[derive(Debug, Clone)]
1034pub struct Example {
1035    pub input: Tensor,
1036    pub label: usize,
1037    /// Continuous regression target, when the task is a regression task.
1038    pub target: Option<Tensor>,
1039    pub metadata: HashMap<String, String>,
1040}
1041
1042impl Example {
1043    /// A classification example with a class index.
1044    pub fn classification(input: Tensor, label: usize) -> Self {
1045        Self {
1046            input,
1047            label,
1048            target: None,
1049            metadata: HashMap::new(),
1050        }
1051    }
1052
1053    /// A regression example with a continuous target vector.
1054    pub fn regression(input: Tensor, target: Tensor) -> Self {
1055        Self {
1056            input,
1057            label: 0,
1058            target: Some(target),
1059            metadata: HashMap::new(),
1060        }
1061    }
1062}
1063
1064#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1065pub enum TaskType {
1066    Classification,
1067    Regression,
1068    Generation,
1069    SequenceLabeling,
1070}
1071
1072/// Results and statistics
1073#[derive(Debug, Clone)]
1074pub struct EpisodeResult {
1075    pub episode: usize,
1076    pub meta_loss: f64,
1077    pub meta_accuracy: f64,
1078    pub num_tasks: usize,
1079    pub episode_time: std::time::Duration,
1080    pub algorithm: MetaAlgorithm,
1081}
1082
1083#[derive(Debug, Clone)]
1084pub struct TaskResult {
1085    pub support_loss: f64,
1086    pub query_loss: f64,
1087    pub query_accuracy: f64,
1088    pub adaptation_time: std::time::Duration,
1089}
1090
1091#[derive(Debug, Clone)]
1092pub struct EvaluationResult {
1093    pub average_accuracy: f64,
1094    pub task_results: Vec<TaskResult>,
1095    pub num_tasks: usize,
1096}
1097
1098#[derive(Debug)]
1099pub struct MetaStatistics {
1100    pub total_episodes: usize,
1101    pub average_accuracy: f64,
1102    pub best_accuracy: f64,
1103    pub recent_accuracies: std::collections::VecDeque<f64>,
1104    pub convergence_rate: f64,
1105}
1106
1107impl Default for MetaStatistics {
1108    fn default() -> Self {
1109        Self::new()
1110    }
1111}
1112
1113impl MetaStatistics {
1114    pub fn new() -> Self {
1115        Self {
1116            total_episodes: 0,
1117            average_accuracy: 0.0,
1118            best_accuracy: 0.0,
1119            recent_accuracies: std::collections::VecDeque::with_capacity(100),
1120            convergence_rate: 0.0,
1121        }
1122    }
1123
1124    pub fn update(&mut self, episode_result: &EpisodeResult) {
1125        self.total_episodes += 1;
1126
1127        // Update running average
1128        let alpha = 0.01; // Exponential moving average factor
1129        self.average_accuracy =
1130            alpha * episode_result.meta_accuracy + (1.0 - alpha) * self.average_accuracy;
1131
1132        // Update best accuracy
1133        if episode_result.meta_accuracy > self.best_accuracy {
1134            self.best_accuracy = episode_result.meta_accuracy;
1135        }
1136
1137        // Track recent accuracies for convergence analysis
1138        self.recent_accuracies.push_back(episode_result.meta_accuracy);
1139        if self.recent_accuracies.len() > 100 {
1140            self.recent_accuracies.pop_front();
1141        }
1142
1143        // Estimate convergence rate
1144        if self.recent_accuracies.len() > 10 {
1145            let recent_mean =
1146                self.recent_accuracies.iter().sum::<f64>() / self.recent_accuracies.len() as f64;
1147            let older_mean = self.recent_accuracies.iter().take(50).sum::<f64>()
1148                / (50.0f64).min(self.recent_accuracies.len() as f64);
1149            self.convergence_rate = (recent_mean - older_mean).abs();
1150        }
1151    }
1152}
1153
1154/// Trait definitions for model components
1155pub trait MetaLearningModel: Send + Sync {
1156    fn forward(&mut self, examples: &ExampleSet) -> Result<f64, TrustformersError>;
1157    fn compute_accuracy(&self, examples: &ExampleSet) -> Result<f64, TrustformersError>;
1158    fn compute_gradients(&self, loss: f64) -> Result<ModelGradients, TrustformersError>;
1159    fn apply_gradients(
1160        &mut self,
1161        gradients: &ModelGradients,
1162        lr: f64,
1163    ) -> Result<(), TrustformersError>;
1164    fn get_parameters(&self) -> Result<ModelParameters, TrustformersError>;
1165    fn set_parameters(&mut self, params: ModelParameters) -> Result<(), TrustformersError>;
1166    fn embed(&self, example: &Example) -> Result<Tensor, TrustformersError>;
1167
1168    // Additional methods for specific algorithms
1169    fn compute_second_order_gradients(
1170        &self,
1171        _initial_params: &ModelParameters,
1172        _loss: f64,
1173    ) -> Result<ModelGradients, TrustformersError> {
1174        Err(unsupported_operation(
1175            "compute_second_order_gradients",
1176            "meta_learning",
1177        ))
1178    }
1179
1180    fn compute_first_order_gradients(
1181        &self,
1182        _loss: f64,
1183    ) -> Result<ModelGradients, TrustformersError> {
1184        Err(unsupported_operation(
1185            "compute_first_order_gradients",
1186            "meta_learning",
1187        ))
1188    }
1189
1190    fn compute_relation(&self, _emb1: &Tensor, _emb2: &Tensor) -> Result<f64, TrustformersError> {
1191        Err(unsupported_operation("compute_relation", "meta_learning"))
1192    }
1193
1194    fn write_to_memory(&mut self, _example: &Example) -> Result<(), TrustformersError> {
1195        Err(unsupported_operation("write_to_memory", "meta_learning"))
1196    }
1197
1198    fn read_from_memory(&self, _example: &Example) -> Result<MemoryOutput, TrustformersError> {
1199        Err(unsupported_operation("read_from_memory", "meta_learning"))
1200    }
1201
1202    fn predict_from_memory(
1203        &self,
1204        _memory_output: &MemoryOutput,
1205    ) -> Result<MemoryPrediction, TrustformersError> {
1206        Err(unsupported_operation(
1207            "predict_from_memory",
1208            "meta_learning",
1209        ))
1210    }
1211
1212    fn clear_memory(&mut self) -> Result<(), TrustformersError> {
1213        Ok(())
1214    }
1215
1216    fn get_learning_rates(&self) -> Result<Vec<f64>, TrustformersError> {
1217        Err(unsupported_operation("get_learning_rates", "meta_learning"))
1218    }
1219
1220    fn apply_gradients_with_lr(
1221        &mut self,
1222        _gradients: &ModelGradients,
1223        _learning_rates: &[f64],
1224    ) -> Result<(), TrustformersError> {
1225        Err(unsupported_operation(
1226            "apply_gradients_with_lr",
1227            "meta_learning",
1228        ))
1229    }
1230
1231    fn compute_lr_gradients(&self, _loss: f64) -> Result<Vec<f64>, TrustformersError> {
1232        Err(unsupported_operation(
1233            "compute_lr_gradients",
1234            "meta_learning",
1235        ))
1236    }
1237
1238    fn get_meta_learner_state(&self) -> Result<MetaLearnerState, TrustformersError> {
1239        Err(unsupported_operation(
1240            "get_meta_learner_state",
1241            "meta_learning",
1242        ))
1243    }
1244
1245    fn apply_learned_algorithm(
1246        &self,
1247        _support_set: &ExampleSet,
1248        _state: &MetaLearnerState,
1249    ) -> Result<ModelParameters, TrustformersError> {
1250        Err(unsupported_operation(
1251            "apply_learned_algorithm",
1252            "meta_learning",
1253        ))
1254    }
1255
1256    fn evaluate_with_params(
1257        &self,
1258        _examples: &ExampleSet,
1259        _params: &ModelParameters,
1260    ) -> Result<f64, TrustformersError> {
1261        Err(unsupported_operation(
1262            "evaluate_with_params",
1263            "meta_learning",
1264        ))
1265    }
1266
1267    fn compute_accuracy_with_params(
1268        &self,
1269        _examples: &ExampleSet,
1270        _params: &ModelParameters,
1271    ) -> Result<f64, TrustformersError> {
1272        Err(unsupported_operation(
1273            "compute_accuracy_with_params",
1274            "meta_learning",
1275        ))
1276    }
1277
1278    fn compute_meta_learner_gradients(
1279        &self,
1280        _loss: f64,
1281    ) -> Result<ModelGradients, TrustformersError> {
1282        Err(unsupported_operation(
1283            "compute_meta_learner_gradients",
1284            "meta_learning",
1285        ))
1286    }
1287
1288    fn get_lstm_state(&self) -> Result<LSTMState, TrustformersError> {
1289        Err(unsupported_operation("get_lstm_state", "meta_learning"))
1290    }
1291
1292    fn lstm_update(
1293        &self,
1294        _gradients: &ModelGradients,
1295        _state: &LSTMState,
1296        _step: usize,
1297    ) -> Result<(ModelUpdates, LSTMState), TrustformersError> {
1298        Err(unsupported_operation("lstm_update", "meta_learning"))
1299    }
1300
1301    fn apply_lstm_updates(&mut self, _updates: &ModelUpdates) -> Result<(), TrustformersError> {
1302        Err(unsupported_operation("apply_lstm_updates", "meta_learning"))
1303    }
1304
1305    fn compute_lstm_gradients(&self, _loss: f64) -> Result<ModelGradients, TrustformersError> {
1306        Err(unsupported_operation(
1307            "compute_lstm_gradients",
1308            "meta_learning",
1309        ))
1310    }
1311}
1312
1313pub trait MetaOptimizer: Send + Sync {
1314    fn step(&mut self, model: &mut dyn MetaLearningModel) -> Result<(), TrustformersError>;
1315    fn accumulate_gradients(&mut self, gradients: ModelGradients) -> Result<(), TrustformersError>;
1316    fn accumulate_param_gradients(
1317        &mut self,
1318        _gradients: ModelGradients,
1319    ) -> Result<(), TrustformersError> {
1320        self.accumulate_gradients(_gradients)
1321    }
1322    fn accumulate_lr_gradients(
1323        &mut self,
1324        _lr_gradients: Vec<f64>,
1325    ) -> Result<(), TrustformersError> {
1326        Ok(())
1327    }
1328    fn reset(&mut self) -> Result<(), TrustformersError>;
1329}
1330
1331/// Supporting data structures
1332#[derive(Debug, Clone)]
1333pub struct ModelParameters {
1334    pub parameters: HashMap<String, Tensor>,
1335}
1336
1337#[derive(Debug, Clone)]
1338pub struct ModelGradients {
1339    pub gradients: HashMap<String, Tensor>,
1340}
1341
1342impl Default for ModelGradients {
1343    fn default() -> Self {
1344        Self::new()
1345    }
1346}
1347
1348impl ModelGradients {
1349    pub fn new() -> Self {
1350        Self {
1351            gradients: HashMap::new(),
1352        }
1353    }
1354}
1355
1356#[derive(Debug, Clone)]
1357pub struct MemoryOutput {
1358    pub content: Tensor,
1359    pub attention_weights: Vec<f64>,
1360}
1361
1362#[derive(Debug, Clone)]
1363pub struct MemoryPrediction {
1364    pub logits: Tensor,
1365    pub confidence: f64,
1366}
1367
1368#[derive(Debug, Clone)]
1369pub struct MetaLearnerState {
1370    pub hidden_state: Tensor,
1371    pub cell_state: Tensor,
1372}
1373
1374#[derive(Debug, Clone)]
1375pub struct LSTMState {
1376    pub hidden: Tensor,
1377    pub cell: Tensor,
1378}
1379
1380#[derive(Debug, Clone)]
1381pub struct ModelUpdates {
1382    pub updates: HashMap<String, Tensor>,
1383}
1384
1385/// Task sampling for meta-learning
1386pub struct TaskSampler {
1387    config: MetaLearningConfig,
1388    #[allow(dead_code)]
1389    task_distributions: Vec<TaskDistribution>,
1390    current_task_id: usize,
1391}
1392
1393impl TaskSampler {
1394    pub fn new(config: &MetaLearningConfig) -> Result<Self, TrustformersError> {
1395        Ok(Self {
1396            config: config.clone(),
1397            task_distributions: Vec::new(),
1398            current_task_id: 0,
1399        })
1400    }
1401
1402    pub fn sample_batch(&mut self, batch_size: usize) -> Result<TaskBatch, TrustformersError> {
1403        let mut tasks = Vec::new();
1404
1405        for _ in 0..batch_size {
1406            let task = self.sample_single_task()?;
1407            tasks.push(task);
1408        }
1409
1410        Ok(TaskBatch {
1411            tasks,
1412            batch_id: format!("batch_{}", self.current_task_id),
1413        })
1414    }
1415
1416    fn sample_single_task(&mut self) -> Result<Task, TrustformersError> {
1417        // Support and query share the task's class centres, which is what makes
1418        // adaptation on the support set transfer to the query set.
1419        let centers = self.sample_task_centers();
1420        let support_set = self.create_example_set(self.config.support_size, &centers)?;
1421        let query_set = self.create_example_set(self.config.query_size, &centers)?;
1422
1423        self.current_task_id += 1;
1424
1425        Ok(Task {
1426            task_id: format!("task_{}", self.current_task_id),
1427            support_set,
1428            query_set,
1429            task_type: TaskType::Classification,
1430        })
1431    }
1432
1433    /// Draw examples from the task's class-conditional Gaussians.
1434    ///
1435    /// Every class of a task has its own random centre (shared between the
1436    /// task's support and query sets), so the label genuinely depends on the
1437    /// input and a learner can improve on it. Sampling labels independently of
1438    /// the features — as an earlier version did — makes every reported
1439    /// accuracy meaningless because no model can do better than chance.
1440    fn create_example_set(
1441        &self,
1442        size: usize,
1443        centers: &[Vec<f32>],
1444    ) -> Result<ExampleSet, TrustformersError> {
1445        let mut examples = Vec::with_capacity(size);
1446        let dimension = self.config.embedding_dim;
1447
1448        for index in 0..size {
1449            let label = index % self.config.num_ways.max(1);
1450            let center = centers.get(label).ok_or_else(|| {
1451                invalid_input("task centers do not cover every class of the task")
1452            })?;
1453
1454            let mut values = Vec::with_capacity(dimension);
1455            for feature in 0..dimension {
1456                let noise = (fastrand::f32() - 0.5) * 2.0 * TASK_NOISE_SCALE;
1457                values.push(center[feature] + noise);
1458            }
1459
1460            examples.push(Example::classification(
1461                Tensor::from_vec(values, &[dimension])?,
1462                label,
1463            ));
1464        }
1465
1466        Ok(ExampleSet {
1467            examples,
1468            num_classes: self.config.num_ways,
1469        })
1470    }
1471
1472    /// Random class centres for one task.
1473    fn sample_task_centers(&self) -> Vec<Vec<f32>> {
1474        (0..self.config.num_ways.max(1))
1475            .map(|_| {
1476                (0..self.config.embedding_dim).map(|_| (fastrand::f32() - 0.5) * 2.0).collect()
1477            })
1478            .collect()
1479    }
1480}
1481
1482/// Standard deviation of the within-class noise used by [`TaskSampler`].
1483const TASK_NOISE_SCALE: f32 = 0.15;
1484
1485#[derive(Debug)]
1486pub struct TaskDistribution {
1487    pub name: String,
1488    pub sampling_weight: f64,
1489}
1490
1491pub mod models;
1492#[cfg(test)]
1493mod models_tests;
1494
1495pub use models::{
1496    GradientBasedModel, L2LModel, MAMLModel, MatchingNetModel, MemoryAugmentedModel, MetaSGDModel,
1497    MlpLearner, PrototypicalModel, RelationNetModel, ReptileModel,
1498};
1499
1500/// Optimizer implementations
1501pub struct SGDMetaOptimizer {
1502    learning_rate: f64,
1503    accumulated_gradients: Option<ModelGradients>,
1504}
1505
1506impl SGDMetaOptimizer {
1507    pub fn new(learning_rate: f64) -> Result<Self, TrustformersError> {
1508        Ok(Self {
1509            learning_rate,
1510            accumulated_gradients: None,
1511        })
1512    }
1513}
1514
1515impl MetaOptimizer for SGDMetaOptimizer {
1516    fn step(&mut self, model: &mut dyn MetaLearningModel) -> Result<(), TrustformersError> {
1517        if let Some(gradients) = &self.accumulated_gradients {
1518            model.apply_gradients(gradients, self.learning_rate)?;
1519            self.accumulated_gradients = None;
1520        }
1521        Ok(())
1522    }
1523
1524    fn accumulate_gradients(&mut self, gradients: ModelGradients) -> Result<(), TrustformersError> {
1525        self.accumulated_gradients = Some(gradients);
1526        Ok(())
1527    }
1528
1529    fn reset(&mut self) -> Result<(), TrustformersError> {
1530        self.accumulated_gradients = None;
1531        Ok(())
1532    }
1533}
1534
1535pub struct AdamMetaOptimizer {
1536    learning_rate: f64,
1537    accumulated_gradients: Option<ModelGradients>,
1538}
1539
1540impl AdamMetaOptimizer {
1541    pub fn new(learning_rate: f64) -> Result<Self, TrustformersError> {
1542        Ok(Self {
1543            learning_rate,
1544            accumulated_gradients: None,
1545        })
1546    }
1547}
1548
1549impl MetaOptimizer for AdamMetaOptimizer {
1550    fn step(&mut self, model: &mut dyn MetaLearningModel) -> Result<(), TrustformersError> {
1551        if let Some(gradients) = &self.accumulated_gradients {
1552            model.apply_gradients(gradients, self.learning_rate)?;
1553            self.accumulated_gradients = None;
1554        }
1555        Ok(())
1556    }
1557
1558    fn accumulate_gradients(&mut self, gradients: ModelGradients) -> Result<(), TrustformersError> {
1559        self.accumulated_gradients = Some(gradients);
1560        Ok(())
1561    }
1562
1563    fn reset(&mut self) -> Result<(), TrustformersError> {
1564        self.accumulated_gradients = None;
1565        Ok(())
1566    }
1567}
1568
1569pub struct LearnedLROptimizer {
1570    learning_rate: f64,
1571    accumulated_gradients: Option<ModelGradients>,
1572    accumulated_lr_gradients: Option<Vec<f64>>,
1573}
1574
1575impl LearnedLROptimizer {
1576    pub fn new(learning_rate: f64) -> Result<Self, TrustformersError> {
1577        Ok(Self {
1578            learning_rate,
1579            accumulated_gradients: None,
1580            accumulated_lr_gradients: None,
1581        })
1582    }
1583}
1584
1585impl MetaOptimizer for LearnedLROptimizer {
1586    fn step(&mut self, model: &mut dyn MetaLearningModel) -> Result<(), TrustformersError> {
1587        if let Some(gradients) = &self.accumulated_gradients {
1588            model.apply_gradients(gradients, self.learning_rate)?;
1589            self.accumulated_gradients = None;
1590        }
1591        Ok(())
1592    }
1593
1594    fn accumulate_gradients(&mut self, gradients: ModelGradients) -> Result<(), TrustformersError> {
1595        self.accumulated_gradients = Some(gradients);
1596        Ok(())
1597    }
1598
1599    fn accumulate_lr_gradients(&mut self, lr_gradients: Vec<f64>) -> Result<(), TrustformersError> {
1600        self.accumulated_lr_gradients = Some(lr_gradients);
1601        Ok(())
1602    }
1603
1604    fn reset(&mut self) -> Result<(), TrustformersError> {
1605        self.accumulated_gradients = None;
1606        self.accumulated_lr_gradients = None;
1607        Ok(())
1608    }
1609}
1610
1611/// Utility functions
1612pub mod utils {
1613    use super::*;
1614
1615    /// Create a few-shot classification task configuration
1616    pub fn create_few_shot_config(
1617        num_ways: usize,
1618        num_shots: usize,
1619        query_size: usize,
1620    ) -> MetaLearningConfig {
1621        MetaLearningConfig {
1622            num_ways,
1623            num_shots,
1624            support_size: num_ways * num_shots,
1625            query_size,
1626            ..Default::default()
1627        }
1628    }
1629
1630    /// Create MAML configuration with sensible defaults
1631    pub fn create_maml_config() -> MetaLearningConfig {
1632        MetaLearningConfig {
1633            algorithm: MetaAlgorithm::MAML,
1634            inner_lr: 0.01,
1635            meta_lr: 0.001,
1636            inner_steps: 5,
1637            first_order: false,
1638            ..Default::default()
1639        }
1640    }
1641
1642    /// Create Reptile configuration (first-order MAML)
1643    pub fn create_reptile_config() -> MetaLearningConfig {
1644        MetaLearningConfig {
1645            algorithm: MetaAlgorithm::Reptile,
1646            inner_lr: 0.01,
1647            meta_lr: 0.001,
1648            inner_steps: 10,
1649            first_order: true,
1650            ..Default::default()
1651        }
1652    }
1653
1654    /// Create Prototypical Networks configuration
1655    pub fn create_protonet_config() -> MetaLearningConfig {
1656        MetaLearningConfig {
1657            algorithm: MetaAlgorithm::ProtoNet,
1658            temperature: 1.0,
1659            normalize_embeddings: true,
1660            embedding_dim: 512,
1661            ..Default::default()
1662        }
1663    }
1664
1665    /// Calculate meta-learning performance metrics
1666    pub fn calculate_performance_metrics(episode_results: &[EpisodeResult]) -> PerformanceMetrics {
1667        if episode_results.is_empty() {
1668            return PerformanceMetrics::default();
1669        }
1670
1671        let accuracies: Vec<f64> = episode_results.iter().map(|r| r.meta_accuracy).collect();
1672        let mean_accuracy = accuracies.iter().sum::<f64>() / accuracies.len() as f64;
1673
1674        let variance = accuracies.iter().map(|acc| (acc - mean_accuracy).powi(2)).sum::<f64>()
1675            / accuracies.len() as f64;
1676        let std_dev = variance.sqrt();
1677
1678        let max_accuracy = accuracies.iter().fold(0.0f64, |a, &b| a.max(b));
1679        let min_accuracy = accuracies.iter().fold(1.0f64, |a, &b| a.min(b));
1680
1681        PerformanceMetrics {
1682            mean_accuracy,
1683            std_dev,
1684            max_accuracy,
1685            min_accuracy,
1686            num_episodes: episode_results.len(),
1687        }
1688    }
1689
1690    /// Estimate convergence based on recent performance
1691    pub fn estimate_convergence(
1692        episode_results: &[EpisodeResult],
1693        window_size: usize,
1694    ) -> ConvergenceMetrics {
1695        if episode_results.len() < window_size * 2 {
1696            return ConvergenceMetrics::default();
1697        }
1698
1699        let recent_window = &episode_results[episode_results.len() - window_size..];
1700        let older_window = &episode_results
1701            [episode_results.len() - window_size * 2..episode_results.len() - window_size];
1702
1703        let recent_mean =
1704            recent_window.iter().map(|r| r.meta_accuracy).sum::<f64>() / window_size as f64;
1705        let older_mean =
1706            older_window.iter().map(|r| r.meta_accuracy).sum::<f64>() / window_size as f64;
1707
1708        let improvement_rate = recent_mean - older_mean;
1709        let has_converged = improvement_rate.abs() < 0.001;
1710
1711        ConvergenceMetrics {
1712            improvement_rate,
1713            has_converged,
1714            recent_mean,
1715            older_mean,
1716        }
1717    }
1718}
1719
1720#[derive(Debug, Default)]
1721pub struct PerformanceMetrics {
1722    pub mean_accuracy: f64,
1723    pub std_dev: f64,
1724    pub max_accuracy: f64,
1725    pub min_accuracy: f64,
1726    pub num_episodes: usize,
1727}
1728
1729#[derive(Debug, Default)]
1730pub struct ConvergenceMetrics {
1731    pub improvement_rate: f64,
1732    pub has_converged: bool,
1733    pub recent_mean: f64,
1734    pub older_mean: f64,
1735}
1736
1737#[cfg(test)]
1738mod tests {
1739    use super::*;
1740
1741    #[test]
1742    fn test_meta_learning_config_default() {
1743        let config = MetaLearningConfig::default();
1744        assert_eq!(config.algorithm, MetaAlgorithm::MAML);
1745        assert_eq!(config.num_ways, 5);
1746        assert_eq!(config.num_shots, 1);
1747    }
1748
1749    #[test]
1750    fn test_meta_learner_creation() {
1751        let config = MetaLearningConfig::default();
1752        let result = MetaLearner::new(config);
1753        assert!(result.is_ok());
1754    }
1755
1756    #[test]
1757    fn test_task_sampler() {
1758        let config = MetaLearningConfig::default();
1759        let mut sampler = TaskSampler::new(&config).expect("operation failed");
1760        let task_batch = sampler.sample_batch(4).expect("operation failed");
1761        assert_eq!(task_batch.tasks.len(), 4);
1762    }
1763
1764    #[test]
1765    fn test_meta_statistics() {
1766        let mut stats = MetaStatistics::new();
1767        let episode_result = EpisodeResult {
1768            episode: 0,
1769            meta_loss: 0.5,
1770            meta_accuracy: 0.8,
1771            num_tasks: 10,
1772            episode_time: std::time::Duration::from_millis(100),
1773            algorithm: MetaAlgorithm::MAML,
1774        };
1775
1776        stats.update(&episode_result);
1777        assert!(stats.total_episodes > 0);
1778        assert!(stats.best_accuracy > 0.0);
1779    }
1780
1781    #[test]
1782    fn test_utils_few_shot_config() {
1783        let config = utils::create_few_shot_config(5, 1, 15);
1784        assert_eq!(config.num_ways, 5);
1785        assert_eq!(config.num_shots, 1);
1786        assert_eq!(config.support_size, 5);
1787        assert_eq!(config.query_size, 15);
1788    }
1789
1790    #[test]
1791    fn test_meta_algorithms() {
1792        assert_ne!(MetaAlgorithm::MAML, MetaAlgorithm::Reptile);
1793        assert_eq!(MetaAlgorithm::ProtoNet as u8, 2);
1794    }
1795
1796    #[test]
1797    fn test_performance_metrics_calculation() {
1798        let episode_results = vec![
1799            EpisodeResult {
1800                episode: 0,
1801                meta_loss: 0.5,
1802                meta_accuracy: 0.8,
1803                num_tasks: 10,
1804                episode_time: std::time::Duration::from_millis(100),
1805                algorithm: MetaAlgorithm::MAML,
1806            },
1807            EpisodeResult {
1808                episode: 1,
1809                meta_loss: 0.4,
1810                meta_accuracy: 0.85,
1811                num_tasks: 10,
1812                episode_time: std::time::Duration::from_millis(100),
1813                algorithm: MetaAlgorithm::MAML,
1814            },
1815        ];
1816
1817        let metrics = utils::calculate_performance_metrics(&episode_results);
1818        assert!(metrics.mean_accuracy > 0.8);
1819        assert!(metrics.std_dev >= 0.0);
1820        assert_eq!(metrics.num_episodes, 2);
1821    }
1822}