optirs-learned 0.3.2

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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
// Curriculum learning strategies for transformer optimization
//
// This module implements various curriculum learning approaches that progressively
// introduce optimization challenges of increasing difficulty to improve learning.

use scirs2_core::numeric::Float;
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;

use crate::error::Result;

/// Curriculum learning strategies
#[derive(Debug, Clone, Copy)]
pub enum CurriculumStrategy {
    /// No curriculum learning
    None,
    /// Difficulty-based progression
    DifficultyProgression,
    /// Diversity-based curriculum
    DiversityBased,
    /// Self-paced learning
    SelfPaced,
    /// Teacher-student curriculum
    TeacherStudent,
    /// Adversarial curriculum
    Adversarial,
    /// Multi-task curriculum
    MultiTask,
    /// Adaptive curriculum
    Adaptive,
}

/// Curriculum learning manager
#[derive(Debug, Clone)]
pub struct CurriculumLearner<T: Float + Debug + Send + Sync + 'static> {
    /// Curriculum strategy
    strategy: CurriculumStrategy,

    /// Curriculum parameters
    curriculum_params: CurriculumParams<T>,

    /// Learning progress tracker
    progress_tracker: LearningProgressTracker<T>,

    /// Current curriculum state
    curriculum_state: CurriculumState<T>,

    /// Task scheduling policy
    task_scheduler: TaskScheduler<T>,

    /// Performance history
    performance_history: VecDeque<PerformanceRecord<T>>,
}

/// Curriculum parameters
#[derive(Debug, Clone)]
pub struct CurriculumParams<T: Float + Debug + Send + Sync + 'static> {
    /// Initial difficulty threshold
    initial_difficulty: T,

    /// Maximum difficulty threshold
    max_difficulty: T,

    /// Difficulty increment per epoch
    difficulty_increment: T,

    /// Performance threshold for progression
    progression_threshold: T,

    /// Patience for difficulty increases
    patience: usize,

    /// Self-pacing factor
    self_pacing_factor: T,

    /// Diversity weight in curriculum
    diversity_weight: T,

    /// Teacher model confidence threshold
    teacher_confidence: T,
}

/// Learning progress tracker
#[derive(Debug, Clone)]
pub struct LearningProgressTracker<T: Float + Debug + Send + Sync + 'static> {
    /// Performance metrics over time
    performance_timeline: VecDeque<T>,

    /// Learning rate estimates
    learning_rates: VecDeque<T>,

    /// Competency levels for different task types
    competency_levels: HashMap<String, T>,
}

/// Current curriculum state
#[derive(Debug, Clone)]
pub struct CurriculumState<T: Float + Debug + Send + Sync + 'static> {
    /// Current difficulty level
    current_difficulty: T,

    /// Active task types
    active_tasks: Vec<String>,

    /// Recent performance
    recent_performance: T,

    /// Epochs since last difficulty increase
    epochs_since_increase: usize,

    /// Current learning phase
    learning_phase: LearningPhase,
}

/// Task scheduler for curriculum
#[derive(Debug, Clone)]
pub struct TaskScheduler<T: Float + Debug + Send + Sync + 'static> {
    /// Task queue with priorities
    task_queue: VecDeque<ScheduledTask<T>>,

    /// Scheduling policy
    scheduling_policy: SchedulingPolicy,

    /// Task weights for sampling
    task_weights: HashMap<String, T>,

    /// Load balancing factors
    load_balancing: HashMap<String, T>,
}

/// Performance record for curriculum tracking
#[derive(Debug, Clone)]
pub struct PerformanceRecord<T: Float + Debug + Send + Sync + 'static> {
    /// Task identifier
    task_id: String,

    /// Performance score
    performance: T,

    /// Difficulty level when task was attempted
    difficulty_level: T,

    /// Number of training steps
    training_steps: usize,

    /// Timestamp
    timestamp: usize,
}

impl<T: Float + Debug + Send + Sync + 'static> PerformanceRecord<T> {
    /// Task this record was measured on.
    pub fn task_id(&self) -> &str {
        &self.task_id
    }

    /// Performance score reported for the task.
    pub fn performance(&self) -> T {
        self.performance
    }

    /// Curriculum difficulty in force when the task was attempted.
    pub fn difficulty_level(&self) -> T {
        self.difficulty_level
    }

    /// Training steps the task ran for.
    pub fn training_steps(&self) -> usize {
        self.training_steps
    }

    /// Position of this record in the curriculum history.
    pub fn timestamp(&self) -> usize {
        self.timestamp
    }
}

/// Scheduled task with priority
#[derive(Debug, Clone)]
pub struct ScheduledTask<T: Float + Debug + Send + Sync + 'static> {
    /// Task identifier
    task_id: String,

    /// Task priority
    priority: T,

    /// Estimated difficulty
    difficulty: T,

    /// Required competency level
    required_competency: T,
}

/// Learning phases in curriculum
#[derive(Debug, Clone, Copy)]
pub enum LearningPhase {
    /// Initial exploration phase
    Exploration,
    /// Skill building phase
    SkillBuilding,
    /// Mastery phase
    Mastery,
    /// Transfer phase
    Transfer,
    /// Generalization phase
    Generalization,
}

/// Scheduling policies
#[derive(Debug, Clone, Copy)]
pub enum SchedulingPolicy {
    /// First-in-first-out
    FIFO,
    /// Priority-based scheduling
    Priority,
    /// Weighted random sampling
    WeightedRandom,
    /// Balanced sampling
    Balanced,
    /// Adaptive scheduling
    Adaptive,
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> CurriculumLearner<T> {
    /// Create new curriculum learner
    pub fn new(strategy: CurriculumStrategy) -> Result<Self> {
        Ok(Self {
            strategy,
            curriculum_params: CurriculumParams::default(),
            progress_tracker: LearningProgressTracker::new(),
            curriculum_state: CurriculumState::new()?,
            task_scheduler: TaskScheduler::new()?,
            performance_history: VecDeque::new(),
        })
    }

    /// Recorded performance history, oldest first (capped at 1000 entries).
    ///
    /// `difficulty_level`, `training_steps` and `timestamp` are filled in on
    /// every [`Self::update_curriculum`] call but had no accessor, so the
    /// curriculum's own record of what it did was unreadable from outside.
    pub fn performance_history(&self) -> impl ExactSizeIterator<Item = &PerformanceRecord<T>> {
        self.performance_history.iter()
    }

    /// Update curriculum based on performance
    pub fn update_curriculum(
        &mut self,
        task_id: &str,
        performance: T,
        training_steps: usize,
    ) -> Result<()> {
        // Record performance
        let record = PerformanceRecord {
            task_id: task_id.to_string(),
            performance,
            difficulty_level: self.curriculum_state.current_difficulty,
            training_steps,
            timestamp: self.performance_history.len(),
        };

        self.performance_history.push_back(record);
        if self.performance_history.len() > 1000 {
            self.performance_history.pop_front();
        }

        // Update progress tracker
        self.progress_tracker.update_performance(performance);

        // Update curriculum state based on strategy. Every variant has its own
        // progression rule; none of them share an implementation.
        match self.strategy {
            CurriculumStrategy::None => Ok(()),
            CurriculumStrategy::DifficultyProgression => {
                self.update_difficulty_progression(performance)
            }
            CurriculumStrategy::DiversityBased => {
                self.update_diversity_curriculum(task_id, performance)
            }
            CurriculumStrategy::SelfPaced => self.update_self_paced_curriculum(performance),
            CurriculumStrategy::TeacherStudent => {
                self.update_teacher_student_curriculum(performance)
            }
            CurriculumStrategy::Adversarial => self.update_adversarial_curriculum(performance),
            CurriculumStrategy::MultiTask => {
                self.update_multi_task_curriculum(task_id, performance)
            }
            CurriculumStrategy::Adaptive => self.update_adaptive_curriculum(task_id, performance),
        }
    }

    /// Clamp a difficulty proposal into the configured range.
    fn clamp_difficulty(&self, value: T) -> T {
        value
            .max(self.curriculum_params.initial_difficulty)
            .min(self.curriculum_params.max_difficulty)
    }

    /// Diversity-based curriculum: difficulty is driven by how many *distinct*
    /// tasks have been seen relative to the number of attempts, so a learner
    /// grinding a single task progresses more slowly than one covering many.
    fn update_diversity_curriculum(&mut self, task_id: &str, performance: T) -> Result<()> {
        self.curriculum_state.recent_performance = performance;

        if !self
            .curriculum_state
            .active_tasks
            .iter()
            .any(|t| t == task_id)
        {
            self.curriculum_state.active_tasks.push(task_id.to_string());
        }

        let attempts = self.performance_history.len().max(1);
        let distinct = self.curriculum_state.active_tasks.len();
        let diversity: T = scirs2_core::numeric::NumCast::from(distinct as f64 / attempts as f64)
            .unwrap_or_else(|| T::zero());

        let increment = self.curriculum_params.difficulty_increment
            * self.curriculum_params.diversity_weight
            * diversity;
        self.curriculum_state.current_difficulty =
            self.clamp_difficulty(self.curriculum_state.current_difficulty + increment);
        self.update_learning_phase();

        Ok(())
    }

    /// Teacher-student curriculum: the student only advances once its
    /// performance clears the teacher's confidence bar; falling short pulls the
    /// difficulty back down.
    fn update_teacher_student_curriculum(&mut self, performance: T) -> Result<()> {
        self.curriculum_state.recent_performance = performance;

        let increment = self.curriculum_params.difficulty_increment;
        let proposal = if performance >= self.curriculum_params.teacher_confidence {
            self.curriculum_state.epochs_since_increase = 0;
            self.curriculum_state.current_difficulty + increment
        } else {
            self.curriculum_state.epochs_since_increase += 1;
            let half: T = scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::one());
            self.curriculum_state.current_difficulty - increment * half
        };

        self.curriculum_state.current_difficulty = self.clamp_difficulty(proposal);
        self.update_learning_phase();
        Ok(())
    }

    /// Adversarial curriculum: the environment pushes back hardest exactly when
    /// the learner is doing well, and relents when it collapses.
    fn update_adversarial_curriculum(&mut self, performance: T) -> Result<()> {
        self.curriculum_state.recent_performance = performance;

        let two: T = scirs2_core::numeric::NumCast::from(2.0).unwrap_or_else(|| T::one());
        let half: T = scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::one());
        let threshold = self.curriculum_params.progression_threshold;

        let proposal = if performance > threshold {
            self.curriculum_state.current_difficulty
                + self.curriculum_params.difficulty_increment * two
        } else if performance < threshold * half {
            self.curriculum_state.current_difficulty - self.curriculum_params.difficulty_increment
        } else {
            self.curriculum_state.current_difficulty
        };

        self.curriculum_state.current_difficulty = self.clamp_difficulty(proposal);
        self.update_learning_phase();
        Ok(())
    }

    /// Multi-task curriculum: the difficulty follows the *weakest* task, so a
    /// single lagging task holds the whole curriculum back.
    fn update_multi_task_curriculum(&mut self, task_id: &str, performance: T) -> Result<()> {
        self.curriculum_state.recent_performance = performance;

        let alpha: T = scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero());
        let competency = self
            .progress_tracker
            .competency_levels
            .get(task_id)
            .copied()
            .unwrap_or(T::zero());
        let updated = competency * (T::one() - alpha) + performance * alpha;
        self.progress_tracker
            .competency_levels
            .insert(task_id.to_string(), updated);

        let weakest = self
            .progress_tracker
            .competency_levels
            .values()
            .cloned()
            .fold(T::infinity(), |a, b| a.min(b));

        let proposal = if weakest.is_finite()
            && weakest > self.curriculum_params.progression_threshold
        {
            self.curriculum_state.current_difficulty + self.curriculum_params.difficulty_increment
        } else {
            self.curriculum_state.current_difficulty
        };

        self.curriculum_state.current_difficulty = self.clamp_difficulty(proposal);
        self.update_learning_phase();
        Ok(())
    }

    /// Get next task according to curriculum
    pub fn get_next_task(&mut self) -> Result<Option<String>> {
        match self.strategy {
            CurriculumStrategy::None => Ok(None),
            _ => Ok(self.task_scheduler.schedule_next_task()),
        }
    }

    /// Update difficulty progression curriculum
    fn update_difficulty_progression(&mut self, performance: T) -> Result<()> {
        self.curriculum_state.recent_performance = performance;

        if performance > self.curriculum_params.progression_threshold {
            self.curriculum_state.epochs_since_increase += 1;

            if self.curriculum_state.epochs_since_increase >= self.curriculum_params.patience {
                // Increase difficulty
                let new_difficulty = (self.curriculum_state.current_difficulty
                    + self.curriculum_params.difficulty_increment)
                    .min(self.curriculum_params.max_difficulty);

                self.curriculum_state.current_difficulty = new_difficulty;
                self.curriculum_state.epochs_since_increase = 0;

                // Update learning phase
                self.update_learning_phase();
            }
        } else {
            self.curriculum_state.epochs_since_increase = 0;
        }

        Ok(())
    }

    /// Update self-paced curriculum
    fn update_self_paced_curriculum(&mut self, performance: T) -> Result<()> {
        let pacing_factor = self.curriculum_params.self_pacing_factor;

        // Adjust difficulty based on performance
        let performance_ratio = performance / self.get_expected_performance();
        let difficulty_adjustment = (performance_ratio - T::one()) * pacing_factor;

        let new_difficulty = (self.curriculum_state.current_difficulty + difficulty_adjustment)
            .max(self.curriculum_params.initial_difficulty)
            .min(self.curriculum_params.max_difficulty);

        self.curriculum_state.current_difficulty = new_difficulty;

        Ok(())
    }

    /// Update adaptive curriculum
    fn update_adaptive_curriculum(&mut self, task_id: &str, performance: T) -> Result<()> {
        // Update task-specific competency
        let competency = self
            .progress_tracker
            .competency_levels
            .get(task_id)
            .copied()
            .unwrap_or(T::zero());

        let alpha = scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero());
        let new_competency = competency * (T::one() - alpha) + performance * alpha;

        self.progress_tracker
            .competency_levels
            .insert(task_id.to_string(), new_competency);

        // Adapt curriculum parameters
        self.adapt_curriculum_parameters(task_id)?;

        Ok(())
    }

    /// Update learning phase
    fn update_learning_phase(&mut self) {
        let difficulty_ratio =
            self.curriculum_state.current_difficulty / self.curriculum_params.max_difficulty;

        self.curriculum_state.learning_phase = match difficulty_ratio {
            x if x < scirs2_core::numeric::NumCast::from(0.2).unwrap_or_else(|| T::zero()) => {
                LearningPhase::Exploration
            }
            x if x < scirs2_core::numeric::NumCast::from(0.4).unwrap_or_else(|| T::zero()) => {
                LearningPhase::SkillBuilding
            }
            x if x < scirs2_core::numeric::NumCast::from(0.7).unwrap_or_else(|| T::zero()) => {
                LearningPhase::Mastery
            }
            x if x < scirs2_core::numeric::NumCast::from(0.9).unwrap_or_else(|| T::zero()) => {
                LearningPhase::Transfer
            }
            _ => LearningPhase::Generalization,
        };
    }

    /// Adapt curriculum parameters from the recorded performance history.
    ///
    /// This takes no separate `performance` argument: `update_curriculum` pushes
    /// the fresh observation onto `performance_history` *before* dispatching to
    /// the per-strategy update, so both
    /// [`Self::calculate_performance_variance`] and
    /// [`Self::calculate_performance_trend`] already include it. Passing it again
    /// would let the two views of "current performance" drift apart.
    fn adapt_curriculum_parameters(&mut self, task_id: &str) -> Result<()> {
        // Adapt patience based on task performance variance
        let performance_variance = self.calculate_performance_variance(task_id);
        if performance_variance
            > scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero())
        {
            self.curriculum_params.patience = self.curriculum_params.patience.max(5);
        } else {
            self.curriculum_params.patience =
                (self.curriculum_params.patience.saturating_sub(1)).max(1);
        }

        // Adapt progression threshold based on recent performance trend
        let trend = self.calculate_performance_trend();
        if trend > T::zero() {
            // Performance is improving, can be more aggressive
            self.curriculum_params.progression_threshold =
                (self.curriculum_params.progression_threshold
                    * scirs2_core::numeric::NumCast::from(0.95).unwrap_or_else(|| T::zero()))
                .max(scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero()));
        } else {
            // Performance declining, be more conservative
            self.curriculum_params.progression_threshold =
                (self.curriculum_params.progression_threshold
                    * scirs2_core::numeric::NumCast::from(1.05).unwrap_or_else(|| T::zero()))
                .min(scirs2_core::numeric::NumCast::from(0.95).unwrap_or_else(|| T::zero()));
        }

        Ok(())
    }

    /// Calculate performance variance for a task
    fn calculate_performance_variance(&self, task_id: &str) -> T {
        let task_performances: Vec<T> = self
            .performance_history
            .iter()
            .filter(|record| record.task_id == task_id)
            .map(|record| record.performance)
            .collect();

        if task_performances.len() < 2 {
            return T::zero();
        }

        let mean = task_performances
            .iter()
            .cloned()
            .fold(T::zero(), |a, b| a + b)
            / scirs2_core::numeric::NumCast::from(task_performances.len() as f64)
                .unwrap_or_else(|| T::one());

        let variance = task_performances
            .iter()
            .map(|&x| (x - mean) * (x - mean))
            .fold(T::zero(), |a, b| a + b)
            / scirs2_core::numeric::NumCast::from((task_performances.len() - 1) as f64)
                .unwrap_or_else(|| T::one());

        variance
    }

    /// Calculate recent performance trend
    fn calculate_performance_trend(&self) -> T {
        if self.performance_history.len() < 10 {
            return T::zero();
        }

        let recent: Vec<T> = self
            .performance_history
            .iter()
            .rev()
            .take(10)
            .map(|record| record.performance)
            .collect();

        let first_half_avg = recent[5..].iter().cloned().fold(T::zero(), |a, b| a + b)
            / scirs2_core::numeric::NumCast::from(5.0).unwrap_or_else(|| T::zero());
        let second_half_avg = recent[..5].iter().cloned().fold(T::zero(), |a, b| a + b)
            / scirs2_core::numeric::NumCast::from(5.0).unwrap_or_else(|| T::zero());

        second_half_avg - first_half_avg
    }

    /// Get expected performance for current difficulty
    fn get_expected_performance(&self) -> T {
        // Simple model: expected performance decreases with difficulty
        let difficulty_factor =
            self.curriculum_state.current_difficulty / self.curriculum_params.max_difficulty;
        T::one()
            - difficulty_factor
                * scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero())
    }

    /// Add task to curriculum
    pub fn add_task(
        &mut self,
        task_id: String,
        estimated_difficulty: T,
        required_competency: T,
    ) -> Result<()> {
        let scheduled_task = ScheduledTask {
            task_id: task_id.clone(),
            priority: T::one() / estimated_difficulty, // Higher priority for easier tasks initially
            difficulty: estimated_difficulty,
            required_competency,
        };

        self.task_scheduler.add_task(scheduled_task);

        // Initialize competency tracking
        self.progress_tracker
            .competency_levels
            .insert(task_id, T::zero());

        Ok(())
    }

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

        stats.insert(
            "current_difficulty".to_string(),
            self.curriculum_state.current_difficulty,
        );
        stats.insert(
            "recent_performance".to_string(),
            self.curriculum_state.recent_performance,
        );
        stats.insert(
            "epochs_since_increase".to_string(),
            scirs2_core::numeric::NumCast::from(self.curriculum_state.epochs_since_increase as f64)
                .unwrap_or_else(|| T::zero()),
        );
        stats.insert(
            "active_tasks_count".to_string(),
            scirs2_core::numeric::NumCast::from(self.curriculum_state.active_tasks.len() as f64)
                .unwrap_or_else(|| T::zero()),
        );

        // Average competency across all tasks
        if !self.progress_tracker.competency_levels.is_empty() {
            let avg_competency = self
                .progress_tracker
                .competency_levels
                .values()
                .cloned()
                .fold(T::zero(), |a, b| a + b)
                / scirs2_core::numeric::NumCast::from(
                    self.progress_tracker.competency_levels.len() as f64,
                )
                .unwrap_or_else(|| T::one());
            stats.insert("average_competency".to_string(), avg_competency);
        }

        stats
    }

    /// Get the active curriculum strategy
    pub fn strategy(&self) -> CurriculumStrategy {
        self.strategy
    }

    /// Current difficulty level
    pub fn current_difficulty(&self) -> T {
        self.curriculum_state.current_difficulty
    }

    /// Current learning phase
    pub fn learning_phase(&self) -> LearningPhase {
        self.curriculum_state.learning_phase
    }

    /// Change the task scheduling policy
    pub fn set_scheduling_policy(&mut self, policy: SchedulingPolicy) {
        self.task_scheduler.set_policy(policy);
    }

    /// Reset curriculum state
    pub fn reset(&mut self) {
        self.curriculum_state = CurriculumState::new_state();
        self.progress_tracker.reset();
        self.performance_history.clear();
        self.task_scheduler.reset();
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> LearningProgressTracker<T> {
    fn new() -> Self {
        Self {
            performance_timeline: VecDeque::new(),
            learning_rates: VecDeque::new(),
            competency_levels: HashMap::new(),
        }
    }

    fn update_performance(&mut self, performance: T) {
        self.performance_timeline.push_back(performance);
        if self.performance_timeline.len() > 1000 {
            self.performance_timeline.pop_front();
        }
    }

    fn reset(&mut self) {
        self.performance_timeline.clear();
        self.learning_rates.clear();
        self.competency_levels.clear();
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> CurriculumState<T> {
    fn new() -> Result<Self> {
        Ok(Self::new_state())
    }

    fn new_state() -> Self {
        Self {
            current_difficulty: scirs2_core::numeric::NumCast::from(0.1)
                .unwrap_or_else(|| T::zero()),
            active_tasks: Vec::new(),
            recent_performance: T::zero(),
            epochs_since_increase: 0,
            learning_phase: LearningPhase::Exploration,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> TaskScheduler<T> {
    fn new() -> Result<Self> {
        Ok(Self {
            task_queue: VecDeque::new(),
            scheduling_policy: SchedulingPolicy::Priority,
            task_weights: HashMap::new(),
            load_balancing: HashMap::new(),
        })
    }

    fn add_task(&mut self, task: ScheduledTask<T>) {
        self.task_queue.push_back(task);
    }

    /// Pick the next task according to the configured scheduling policy.
    fn schedule_next_task(&mut self) -> Option<String> {
        if self.task_queue.is_empty() {
            return None;
        }

        let index = match self.scheduling_policy {
            SchedulingPolicy::FIFO => 0,
            SchedulingPolicy::Priority => Self::arg_extreme(&self.task_queue, true),
            SchedulingPolicy::Balanced => Self::arg_extreme(&self.task_queue, false),
            SchedulingPolicy::WeightedRandom => {
                // Deterministic weighted choice driven by the queue state so the
                // scheduler stays reproducible without an external generator.
                let total: f64 = self
                    .task_queue
                    .iter()
                    .map(|t| t.priority.to_f64().unwrap_or(0.0).max(0.0))
                    .sum();
                if total <= 0.0 {
                    0
                } else {
                    let mut target =
                        (self.task_weights.len() as f64 * 0.618_033_988_75).fract() * total;
                    let mut chosen = self.task_queue.len() - 1;
                    for (i, task) in self.task_queue.iter().enumerate() {
                        target -= task.priority.to_f64().unwrap_or(0.0).max(0.0);
                        if target <= 0.0 {
                            chosen = i;
                            break;
                        }
                    }
                    chosen
                }
            }
            SchedulingPolicy::Adaptive => {
                // Prefer the task whose difficulty is closest to the required
                // competency, i.e. the best-matched challenge.
                let mut best = 0;
                let mut best_gap = T::infinity();
                for (i, task) in self.task_queue.iter().enumerate() {
                    let gap = (task.difficulty - task.required_competency).abs();
                    if gap < best_gap {
                        best_gap = gap;
                        best = i;
                    }
                }
                best
            }
        };

        let task = self.task_queue.remove(index)?;
        let counter = self
            .load_balancing
            .entry(task.task_id.clone())
            .or_insert(T::zero());
        *counter = *counter + T::one();
        self.task_weights
            .insert(task.task_id.clone(), task.priority);
        Some(task.task_id)
    }

    /// Index of the highest (or lowest) priority task.
    fn arg_extreme(queue: &VecDeque<ScheduledTask<T>>, highest: bool) -> usize {
        let mut best = 0;
        let mut best_priority = match queue.front() {
            Some(task) => task.priority,
            None => return 0,
        };
        for (i, task) in queue.iter().enumerate() {
            let better = if highest {
                task.priority > best_priority
            } else {
                task.priority < best_priority
            };
            if better {
                best_priority = task.priority;
                best = i;
            }
        }
        best
    }

    /// Change the scheduling policy.
    fn set_policy(&mut self, policy: SchedulingPolicy) {
        self.scheduling_policy = policy;
    }

    fn reset(&mut self) {
        self.task_queue.clear();
        self.task_weights.clear();
        self.load_balancing.clear();
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> Default for CurriculumParams<T> {
    fn default() -> Self {
        Self {
            initial_difficulty: scirs2_core::numeric::NumCast::from(0.1)
                .unwrap_or_else(|| T::zero()),
            max_difficulty: scirs2_core::numeric::NumCast::from(1.0).unwrap_or_else(|| T::zero()),
            difficulty_increment: scirs2_core::numeric::NumCast::from(0.05)
                .unwrap_or_else(|| T::zero()),
            progression_threshold: scirs2_core::numeric::NumCast::from(0.8)
                .unwrap_or_else(|| T::zero()),
            patience: 5,
            self_pacing_factor: scirs2_core::numeric::NumCast::from(0.1)
                .unwrap_or_else(|| T::zero()),
            diversity_weight: scirs2_core::numeric::NumCast::from(0.2).unwrap_or_else(|| T::zero()),
            teacher_confidence: scirs2_core::numeric::NumCast::from(0.9)
                .unwrap_or_else(|| T::zero()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn all_strategies() -> [CurriculumStrategy; 8] {
        [
            CurriculumStrategy::None,
            CurriculumStrategy::DifficultyProgression,
            CurriculumStrategy::DiversityBased,
            CurriculumStrategy::SelfPaced,
            CurriculumStrategy::TeacherStudent,
            CurriculumStrategy::Adversarial,
            CurriculumStrategy::MultiTask,
            CurriculumStrategy::Adaptive,
        ]
    }

    #[test]
    fn every_strategy_runs_and_stays_in_range() {
        for strategy in all_strategies() {
            let mut learner = CurriculumLearner::<f64>::new(strategy).expect("curriculum creation");
            for step in 0..50 {
                let task = if step % 3 == 0 { "a" } else { "b" };
                learner
                    .update_curriculum(task, 0.9, step)
                    .unwrap_or_else(|e| panic!("{strategy:?} failed: {e}"));
            }
            let difficulty = learner.current_difficulty();
            assert!(
                (0.1..=1.0).contains(&difficulty),
                "{strategy:?} produced difficulty {difficulty}"
            );
        }
    }

    #[test]
    fn strategies_do_not_all_behave_identically() {
        let run = |strategy| {
            let mut learner = CurriculumLearner::<f64>::new(strategy).expect("curriculum creation");
            for step in 0..30 {
                learner
                    .update_curriculum("task", 0.95, step)
                    .expect("update");
            }
            learner.current_difficulty()
        };

        let teacher = run(CurriculumStrategy::TeacherStudent);
        let adversarial = run(CurriculumStrategy::Adversarial);
        let diversity = run(CurriculumStrategy::DiversityBased);
        let multi_task = run(CurriculumStrategy::MultiTask);

        let mut distinct = vec![teacher, adversarial, diversity, multi_task];
        distinct.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        distinct.dedup_by(|a, b| (*a - *b).abs() < 1e-12);
        assert!(
            distinct.len() >= 3,
            "strategies collapsed to the same behaviour: {distinct:?}"
        );
    }

    #[test]
    fn zero_performance_keeps_difficulty_finite() {
        for strategy in all_strategies() {
            let mut learner = CurriculumLearner::<f64>::new(strategy).expect("curriculum creation");
            for step in 0..20 {
                learner.update_curriculum("t", 0.0, step).expect("update");
            }
            assert!(
                learner.current_difficulty().is_finite(),
                "{strategy:?} produced a non-finite difficulty"
            );
        }
    }

    #[test]
    fn scheduling_policies_pick_different_tasks() {
        let mut learner =
            CurriculumLearner::<f64>::new(CurriculumStrategy::Adaptive).expect("creation");
        learner.add_task("hard".to_string(), 4.0, 0.9).expect("add");
        learner.add_task("easy".to_string(), 1.0, 0.9).expect("add");

        learner.set_scheduling_policy(SchedulingPolicy::FIFO);
        assert_eq!(
            learner.get_next_task().expect("schedule"),
            Some("hard".to_string())
        );

        let mut learner =
            CurriculumLearner::<f64>::new(CurriculumStrategy::Adaptive).expect("creation");
        learner.add_task("hard".to_string(), 4.0, 0.9).expect("add");
        learner.add_task("easy".to_string(), 1.0, 0.9).expect("add");
        learner.set_scheduling_policy(SchedulingPolicy::Priority);
        // Priority is 1 / difficulty, so the easy task wins.
        assert_eq!(
            learner.get_next_task().expect("schedule"),
            Some("easy".to_string())
        );
    }

    #[test]
    fn statistics_are_reported() {
        let mut learner =
            CurriculumLearner::<f64>::new(CurriculumStrategy::Adaptive).expect("creation");
        learner.update_curriculum("t", 0.7, 1).expect("update");
        let stats = learner.get_curriculum_statistics();
        assert!(stats.contains_key("current_difficulty"));
        assert!(stats.contains_key("recent_performance"));
    }

    #[test]
    fn reset_restores_the_initial_state() {
        let mut learner =
            CurriculumLearner::<f64>::new(CurriculumStrategy::Adversarial).expect("creation");
        for step in 0..20 {
            learner.update_curriculum("t", 0.99, step).expect("update");
        }
        assert!(learner.current_difficulty() > 0.1);
        learner.reset();
        assert!((learner.current_difficulty() - 0.1).abs() < 1e-12);
    }
}