torsh-optim 0.1.3

Optimization algorithms for ToRSh with PyTorch-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
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
990
991
992
993
994
//! Enhanced learning rate schedulers with advanced features
//!
//! This module provides sophisticated learning rate scheduling strategies including
//! polynomial decay with warmup, adaptive scheduling, and enhanced versions of
//! standard schedulers with additional features.

use crate::{
    lr_scheduler::{BaseScheduler, LRScheduler, SchedulerState},
    Optimizer, OptimizerError, OptimizerResult,
};
use std::f32::consts::PI;

/// Polynomial decay learning rate scheduler with warmup
///
/// This scheduler combines a warmup phase with polynomial decay, which is commonly
/// used in transformer training and other modern deep learning architectures.
/// During warmup, the learning rate increases linearly or polynomially from 0 to the base LR.
/// After warmup, the learning rate decays polynomially.
pub struct PolynomialDecayWithWarmup<O: Optimizer> {
    base: BaseScheduler<O>,
    /// Number of warmup steps
    warmup_steps: i32,
    /// Total number of training steps
    total_steps: i32,
    /// Power for polynomial decay (1.0 = linear, 2.0 = quadratic, etc.)
    power: f32,
    /// Minimum learning rate multiplier (relative to base_lr)
    end_lr_factor: f32,
    /// Warmup strategy: "linear" or "polynomial"
    warmup_strategy: WarmupStrategy,
    /// Power for warmup (only used if warmup_strategy is Polynomial)
    warmup_power: f32,
}

/// Strategy for warmup phase
#[derive(Debug, Clone)]
pub enum WarmupStrategy {
    /// Linear warmup: lr = base_lr * (step / warmup_steps)
    Linear,
    /// Polynomial warmup: lr = base_lr * (step / warmup_steps)^power
    Polynomial,
}

impl<O: Optimizer> PolynomialDecayWithWarmup<O> {
    /// Create a new polynomial decay with warmup scheduler
    pub fn new(
        optimizer: O,
        warmup_steps: i32,
        total_steps: i32,
        power: Option<f32>,
        end_lr_factor: Option<f32>,
        warmup_strategy: Option<WarmupStrategy>,
        warmup_power: Option<f32>,
    ) -> Self {
        let power = power.unwrap_or(1.0);
        let end_lr_factor = end_lr_factor.unwrap_or(0.0);
        let warmup_strategy = warmup_strategy.unwrap_or(WarmupStrategy::Linear);
        let warmup_power = warmup_power.unwrap_or(1.0);

        Self {
            base: BaseScheduler::new(optimizer),
            warmup_steps,
            total_steps,
            power,
            end_lr_factor,
            warmup_strategy,
            warmup_power,
        }
    }

    /// Create with linear warmup and quadratic decay (common configuration)
    pub fn linear_warmup_quadratic_decay(
        optimizer: O,
        warmup_steps: i32,
        total_steps: i32,
        end_lr_factor: Option<f32>,
    ) -> Self {
        Self::new(
            optimizer,
            warmup_steps,
            total_steps,
            Some(2.0), // Quadratic decay
            end_lr_factor,
            Some(WarmupStrategy::Linear),
            None,
        )
    }

    /// Create with linear warmup and linear decay
    pub fn linear_warmup_linear_decay(
        optimizer: O,
        warmup_steps: i32,
        total_steps: i32,
        end_lr_factor: Option<f32>,
    ) -> Self {
        Self::new(
            optimizer,
            warmup_steps,
            total_steps,
            Some(1.0), // Linear decay
            end_lr_factor,
            Some(WarmupStrategy::Linear),
            None,
        )
    }

    /// Compute learning rate for current step
    fn compute_lr(&self, step: i32, base_lr: f32) -> f32 {
        if step < self.warmup_steps {
            // Warmup phase
            let warmup_factor = match self.warmup_strategy {
                WarmupStrategy::Linear => step as f32 / self.warmup_steps as f32,
                WarmupStrategy::Polynomial => {
                    (step as f32 / self.warmup_steps as f32).powf(self.warmup_power)
                }
            };
            base_lr * warmup_factor
        } else if step < self.total_steps {
            // Decay phase
            let decay_steps = self.total_steps - self.warmup_steps;
            let remaining_steps = self.total_steps - step;
            let decay_factor = (remaining_steps as f32 / decay_steps as f32).powf(self.power);

            // Interpolate between end_lr_factor and 1.0
            let lr_factor = self.end_lr_factor + (1.0 - self.end_lr_factor) * decay_factor;
            base_lr * lr_factor
        } else {
            // After total steps, use minimum learning rate
            base_lr * self.end_lr_factor
        }
    }
}

impl<O: Optimizer> LRScheduler for PolynomialDecayWithWarmup<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        self.base.last_epoch += 1;

        let new_lrs: Vec<f32> = self
            .base
            .base_lrs
            .iter()
            .map(|&base_lr| self.compute_lr(self.base.last_epoch, base_lr))
            .collect();

        // Update optimizer with new learning rate
        for (i, &lr) in new_lrs.iter().enumerate() {
            if i == 0 {
                self.base.optimizer.set_lr(lr);
            }
        }

        self.base.last_lr = new_lrs;
        Ok(())
    }

    fn get_last_lr(&self) -> &[f32] {
        &self.base.last_lr
    }

    fn get_base_lrs(&self) -> &[f32] {
        &self.base.base_lrs
    }

    fn get_last_epoch(&self) -> i32 {
        self.base.last_epoch
    }

    fn reset(&mut self) {
        self.base.last_epoch = 0;
        self.base.last_lr = self.base.base_lrs.clone();
    }

    fn state_dict(&self) -> SchedulerState {
        let mut state = SchedulerState::new("PolynomialDecayWithWarmup".to_string());
        state.last_epoch = self.base.last_epoch;
        state.base_lrs = self.base.base_lrs.clone();
        state.last_lr = self.base.last_lr.clone();
        state
            .state
            .insert("warmup_steps".to_string(), self.warmup_steps as f32);
        state
            .state
            .insert("total_steps".to_string(), self.total_steps as f32);
        state.state.insert("power".to_string(), self.power);
        state
            .state
            .insert("end_lr_factor".to_string(), self.end_lr_factor);
        state
    }

    fn load_state_dict(&mut self, state: SchedulerState) -> OptimizerResult<()> {
        self.base.last_epoch = state.last_epoch;
        self.base.base_lrs = state.base_lrs;
        self.base.last_lr = state.last_lr;
        if let Some(&warmup_steps) = state.state.get("warmup_steps") {
            self.warmup_steps = warmup_steps as i32;
        }
        if let Some(&total_steps) = state.state.get("total_steps") {
            self.total_steps = total_steps as i32;
        }
        if let Some(&power) = state.state.get("power") {
            self.power = power;
        }
        if let Some(&end_lr_factor) = state.state.get("end_lr_factor") {
            self.end_lr_factor = end_lr_factor;
        }
        Ok(())
    }
}

/// Adaptive learning rate scheduler that adjusts based on metrics
///
/// This scheduler monitors training metrics and adapts the learning rate dynamically
/// based on performance. It can increase LR when training is progressing well and
/// decrease it when training stagnates.
pub struct AdaptiveLRScheduler<O: Optimizer> {
    base: BaseScheduler<O>,
    /// Current metric value (loss, accuracy, etc.)
    current_metric: Option<f32>,
    /// History of metric values for trend analysis
    metric_history: Vec<f32>,
    /// Maximum history length to keep
    max_history: usize,
    /// Whether higher metric values are better (true for accuracy, false for loss)
    higher_is_better: bool,
    /// Factor to multiply LR when increasing
    increase_factor: f32,
    /// Factor to multiply LR when decreasing
    decrease_factor: f32,
    /// Minimum learning rate
    min_lr: f32,
    /// Maximum learning rate
    max_lr: f32,
    /// Number of steps to look back for trend analysis
    patience: usize,
    /// Threshold for detecting improvement/degradation
    improvement_threshold: f32,
    /// Current strategy being applied
    current_strategy: AdaptiveStrategy,
    /// Steps since last strategy change
    steps_since_change: i32,
    /// Minimum steps between strategy changes
    min_steps_between_changes: i32,
    /// Best metric value seen so far
    best_metric: Option<f32>,
    /// Counter for patience-based adjustments
    patience_counter: usize,
    /// Factor for learning rate adjustments
    factor: f32,
    /// Threshold for metric improvement
    threshold: f32,
    /// Cooldown period between adjustments
    cooldown: usize,
    /// Minimum learning rate factor
    min_lr_factor: f32,
}

/// Strategy for adaptive learning rate adjustment
#[derive(Debug, Clone, PartialEq)]
pub enum AdaptiveStrategy {
    /// Maintain current learning rate
    Maintain,
    /// Increase learning rate (training is progressing well)
    Increase,
    /// Decrease learning rate (training is stagnating)
    Decrease,
    /// Oscillate learning rate (explore different ranges)
    Oscillate,
}

impl<O: Optimizer> AdaptiveLRScheduler<O> {
    /// Create a new adaptive learning rate scheduler
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        optimizer: O,
        higher_is_better: bool,
        increase_factor: Option<f32>,
        decrease_factor: Option<f32>,
        min_lr: Option<f32>,
        max_lr: Option<f32>,
        patience: Option<usize>,
        improvement_threshold: Option<f32>,
        min_steps_between_changes: Option<i32>,
    ) -> Self {
        let increase_factor = increase_factor.unwrap_or(1.05);
        let decrease_factor = decrease_factor.unwrap_or(0.9);
        let min_lr = min_lr.unwrap_or(1e-8);
        let max_lr = max_lr.unwrap_or(1.0);
        let patience = patience.unwrap_or(10);
        let improvement_threshold = improvement_threshold.unwrap_or(0.01);
        let min_steps_between_changes = min_steps_between_changes.unwrap_or(5);

        Self {
            base: BaseScheduler::new(optimizer),
            current_metric: None,
            metric_history: Vec::new(),
            max_history: 100,
            higher_is_better,
            increase_factor,
            decrease_factor,
            min_lr,
            max_lr,
            patience,
            improvement_threshold,
            current_strategy: AdaptiveStrategy::Maintain,
            steps_since_change: 0,
            min_steps_between_changes,
            best_metric: None,
            patience_counter: 0,
            factor: decrease_factor, // Default to decrease factor
            threshold: improvement_threshold,
            cooldown: 0,
            min_lr_factor: 0.01,
        }
    }

    /// Update the scheduler with a new metric value
    pub fn step_with_metric(&mut self, metric: f32) {
        self.current_metric = Some(metric);
        self.metric_history.push(metric);

        // Limit history size
        if self.metric_history.len() > self.max_history {
            self.metric_history.remove(0);
        }

        // Analyze trend and adjust strategy
        let new_strategy = self.analyze_trend();

        // Only change strategy if enough steps have passed
        if self.steps_since_change >= self.min_steps_between_changes {
            if new_strategy != self.current_strategy {
                self.current_strategy = new_strategy;
                self.steps_since_change = 0;
            }
        }

        self.steps_since_change += 1;

        // Apply the current strategy
        self.apply_strategy();

        self.base.last_epoch += 1;
    }

    /// Analyze metric trend to determine strategy
    fn analyze_trend(&self) -> AdaptiveStrategy {
        if self.metric_history.len() < self.patience {
            return AdaptiveStrategy::Maintain;
        }

        let recent_metrics = &self.metric_history[self.metric_history.len() - self.patience..];
        let older_metrics = if self.metric_history.len() >= 2 * self.patience {
            &self.metric_history[self.metric_history.len() - 2 * self.patience
                ..self.metric_history.len() - self.patience]
        } else {
            &self.metric_history[0..self.metric_history.len() - self.patience]
        };

        let recent_avg = recent_metrics.iter().sum::<f32>() / recent_metrics.len() as f32;
        let older_avg = older_metrics.iter().sum::<f32>() / older_metrics.len() as f32;

        let improvement = if self.higher_is_better {
            recent_avg - older_avg
        } else {
            older_avg - recent_avg
        };

        let relative_improvement = improvement / older_avg.abs().max(1e-8);

        if relative_improvement > self.improvement_threshold {
            AdaptiveStrategy::Increase
        } else if relative_improvement < -self.improvement_threshold {
            AdaptiveStrategy::Decrease
        } else {
            // Check for stagnation
            let variance = recent_metrics
                .iter()
                .map(|&x| (x - recent_avg).powi(2))
                .sum::<f32>()
                / recent_metrics.len() as f32;

            if variance < 1e-6 {
                AdaptiveStrategy::Oscillate
            } else {
                AdaptiveStrategy::Maintain
            }
        }
    }

    /// Apply the current strategy to adjust learning rate
    fn apply_strategy(&mut self) {
        let current_lrs = self.base.last_lr.clone();
        let mut new_lrs = Vec::new();

        for &current_lr in &current_lrs {
            let new_lr = match self.current_strategy {
                AdaptiveStrategy::Maintain => current_lr,
                AdaptiveStrategy::Increase => (current_lr * self.increase_factor).min(self.max_lr),
                AdaptiveStrategy::Decrease => (current_lr * self.decrease_factor).max(self.min_lr),
                AdaptiveStrategy::Oscillate => {
                    // Oscillate between current LR and slightly higher/lower values
                    let oscillation = (self.base.last_epoch as f32 * 0.1).sin() * 0.1 + 1.0;
                    (current_lr * oscillation).clamp(self.min_lr, self.max_lr)
                }
            };
            new_lrs.push(new_lr);
        }

        // Update optimizer with new learning rate
        for (i, &lr) in new_lrs.iter().enumerate() {
            if i == 0 {
                self.base.optimizer.set_lr(lr);
            }
        }

        self.base.last_lr = new_lrs;
    }

    /// Get current strategy
    pub fn current_strategy(&self) -> &AdaptiveStrategy {
        &self.current_strategy
    }

    /// Get metric history
    pub fn metric_history(&self) -> &[f32] {
        &self.metric_history
    }

    /// Get statistics about the scheduler
    pub fn stats(&self) -> AdaptiveSchedulerStats {
        let avg_metric = if !self.metric_history.is_empty() {
            self.metric_history.iter().sum::<f32>() / self.metric_history.len() as f32
        } else {
            0.0
        };

        let current_lr = if !self.base.last_lr.is_empty() {
            self.base.last_lr[0]
        } else {
            0.0
        };

        AdaptiveSchedulerStats {
            current_lr,
            current_metric: self.current_metric,
            average_metric: avg_metric,
            current_strategy: self.current_strategy.clone(),
            steps_since_change: self.steps_since_change,
            metric_history_length: self.metric_history.len(),
        }
    }
}

/// Statistics for the adaptive scheduler
#[derive(Debug, Clone)]
pub struct AdaptiveSchedulerStats {
    pub current_lr: f32,
    pub current_metric: Option<f32>,
    pub average_metric: f32,
    pub current_strategy: AdaptiveStrategy,
    pub steps_since_change: i32,
    pub metric_history_length: usize,
}

impl<O: Optimizer> LRScheduler for AdaptiveLRScheduler<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        // For regular step without metric, just maintain current LR
        self.base.last_epoch += 1;
        self.steps_since_change += 1;
        Ok(())
    }

    fn get_last_lr(&self) -> &[f32] {
        &self.base.last_lr
    }

    fn get_base_lrs(&self) -> &[f32] {
        &self.base.base_lrs
    }

    fn get_last_epoch(&self) -> i32 {
        self.base.last_epoch
    }

    fn reset(&mut self) {
        self.base.last_epoch = 0;
        self.base.last_lr = self.base.base_lrs.clone();
        self.steps_since_change = 0;
        self.best_metric = None;
        self.patience_counter = 0;
    }

    fn state_dict(&self) -> SchedulerState {
        let mut state = SchedulerState::new("AdaptiveLRScheduler".to_string());
        state.last_epoch = self.base.last_epoch;
        state.base_lrs = self.base.base_lrs.clone();
        state.last_lr = self.base.last_lr.clone();
        state.state.insert("factor".to_string(), self.factor);
        state
            .state
            .insert("patience".to_string(), self.patience as f32);
        state.state.insert("threshold".to_string(), self.threshold);
        state
            .state
            .insert("cooldown".to_string(), self.cooldown as f32);
        state
            .state
            .insert("min_lr_factor".to_string(), self.min_lr_factor);
        state.state.insert(
            "steps_since_change".to_string(),
            self.steps_since_change as f32,
        );
        state
            .state
            .insert("patience_counter".to_string(), self.patience_counter as f32);
        if let Some(best_metric) = self.best_metric {
            state.state.insert("best_metric".to_string(), best_metric);
        }
        state
    }

    fn load_state_dict(&mut self, state: SchedulerState) -> OptimizerResult<()> {
        self.base.last_epoch = state.last_epoch;
        self.base.base_lrs = state.base_lrs;
        self.base.last_lr = state.last_lr;
        if let Some(&factor) = state.state.get("factor") {
            self.factor = factor;
        }
        if let Some(&patience) = state.state.get("patience") {
            self.patience = patience as usize;
        }
        if let Some(&threshold) = state.state.get("threshold") {
            self.threshold = threshold;
        }
        if let Some(&cooldown) = state.state.get("cooldown") {
            self.cooldown = cooldown as usize;
        }
        if let Some(&min_lr_factor) = state.state.get("min_lr_factor") {
            self.min_lr_factor = min_lr_factor;
        }
        if let Some(&steps_since_change) = state.state.get("steps_since_change") {
            self.steps_since_change = steps_since_change as i32;
        }
        if let Some(&patience_counter) = state.state.get("patience_counter") {
            self.patience_counter = patience_counter as usize;
        }
        if let Some(&best_metric) = state.state.get("best_metric") {
            self.best_metric = Some(best_metric);
        }
        Ok(())
    }
}

/// Cosine annealing with warm restarts and polynomial warmup
///
/// This scheduler combines polynomial warmup with cosine annealing and supports
/// warm restarts for improved convergence in long training runs.
pub struct CosineAnnealingWarmRestartsWithWarmup<O: Optimizer> {
    base: BaseScheduler<O>,
    /// Initial restart period
    t_0: i32,
    /// Factor to multiply restart period after each restart
    t_mult: i32,
    /// Number of warmup steps at the beginning
    warmup_steps: i32,
    /// Minimum learning rate multiplier
    eta_min_factor: f32,
    /// Current restart period
    current_t: i32,
    /// Steps since last restart
    steps_since_restart: i32,
    /// Number of completed restarts
    restart_count: i32,
    /// Warmup strategy
    warmup_strategy: WarmupStrategy,
    /// Power for polynomial warmup
    warmup_power: f32,
}

impl<O: Optimizer> CosineAnnealingWarmRestartsWithWarmup<O> {
    /// Create a new cosine annealing with warm restarts and warmup scheduler
    pub fn new(
        optimizer: O,
        t_0: i32,
        t_mult: Option<i32>,
        warmup_steps: Option<i32>,
        eta_min_factor: Option<f32>,
        warmup_strategy: Option<WarmupStrategy>,
        warmup_power: Option<f32>,
    ) -> Self {
        let t_mult = t_mult.unwrap_or(1);
        let warmup_steps = warmup_steps.unwrap_or(0);
        let eta_min_factor = eta_min_factor.unwrap_or(0.0);
        let warmup_strategy = warmup_strategy.unwrap_or(WarmupStrategy::Linear);
        let warmup_power = warmup_power.unwrap_or(1.0);

        Self {
            base: BaseScheduler::new(optimizer),
            t_0,
            t_mult,
            warmup_steps,
            eta_min_factor,
            current_t: t_0,
            steps_since_restart: 0,
            restart_count: 0,
            warmup_strategy,
            warmup_power,
        }
    }

    /// Compute learning rate for current step
    fn compute_lr(&self, step: i32, base_lr: f32) -> f32 {
        if step < self.warmup_steps {
            // Warmup phase
            let warmup_factor = match self.warmup_strategy {
                WarmupStrategy::Linear => step as f32 / self.warmup_steps as f32,
                WarmupStrategy::Polynomial => {
                    (step as f32 / self.warmup_steps as f32).powf(self.warmup_power)
                }
            };
            base_lr * warmup_factor
        } else {
            // Cosine annealing phase
            let adjusted_step = step - self.warmup_steps;
            let cycle_progress = (adjusted_step % self.current_t) as f32 / self.current_t as f32;
            let cosine_factor = 0.5 * (1.0 + (PI * cycle_progress).cos());

            base_lr * (self.eta_min_factor + (1.0 - self.eta_min_factor) * cosine_factor)
        }
    }
}

impl<O: Optimizer> LRScheduler for CosineAnnealingWarmRestartsWithWarmup<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        self.base.last_epoch += 1;

        // Check for restart (only after warmup)
        if self.base.last_epoch >= self.warmup_steps {
            let adjusted_step = self.base.last_epoch - self.warmup_steps;
            if adjusted_step > 0 && adjusted_step % self.current_t == 0 {
                // Restart
                self.restart_count += 1;
                self.current_t *= self.t_mult;
                self.steps_since_restart = 0;
            } else {
                self.steps_since_restart += 1;
            }
        }

        let new_lrs: Vec<f32> = self
            .base
            .base_lrs
            .iter()
            .map(|&base_lr| self.compute_lr(self.base.last_epoch, base_lr))
            .collect();

        // Update optimizer with new learning rate
        for (i, &lr) in new_lrs.iter().enumerate() {
            if i == 0 {
                self.base.optimizer.set_lr(lr);
            }
        }

        self.base.last_lr = new_lrs;
        Ok(())
    }

    fn get_last_lr(&self) -> &[f32] {
        &self.base.last_lr
    }

    fn get_base_lrs(&self) -> &[f32] {
        &self.base.base_lrs
    }

    fn get_last_epoch(&self) -> i32 {
        self.base.last_epoch
    }

    fn reset(&mut self) {
        self.base.last_epoch = 0;
        self.base.last_lr = self.base.base_lrs.clone();
        self.current_t = self.t_0;
        self.steps_since_restart = 0;
        self.restart_count = 0;
    }

    fn state_dict(&self) -> SchedulerState {
        let mut state = SchedulerState::new("CosineAnnealingWarmRestartsWithWarmup".to_string());
        state.last_epoch = self.base.last_epoch;
        state.base_lrs = self.base.base_lrs.clone();
        state.last_lr = self.base.last_lr.clone();
        state.state.insert("t_0".to_string(), self.t_0 as f32);
        state.state.insert("t_mult".to_string(), self.t_mult as f32);
        state
            .state
            .insert("warmup_steps".to_string(), self.warmup_steps as f32);
        state
            .state
            .insert("eta_min_factor".to_string(), self.eta_min_factor);
        state
            .state
            .insert("current_t".to_string(), self.current_t as f32);
        state.state.insert(
            "steps_since_restart".to_string(),
            self.steps_since_restart as f32,
        );
        state
            .state
            .insert("restart_count".to_string(), self.restart_count as f32);
        state
            .state
            .insert("warmup_power".to_string(), self.warmup_power);
        state
    }

    fn load_state_dict(&mut self, state: SchedulerState) -> OptimizerResult<()> {
        self.base.last_epoch = state.last_epoch;
        self.base.base_lrs = state.base_lrs;
        self.base.last_lr = state.last_lr;
        if let Some(&t_0) = state.state.get("t_0") {
            self.t_0 = t_0 as i32;
        }
        if let Some(&t_mult) = state.state.get("t_mult") {
            self.t_mult = t_mult as i32;
        }
        if let Some(&warmup_steps) = state.state.get("warmup_steps") {
            self.warmup_steps = warmup_steps as i32;
        }
        if let Some(&eta_min_factor) = state.state.get("eta_min_factor") {
            self.eta_min_factor = eta_min_factor;
        }
        if let Some(&current_t) = state.state.get("current_t") {
            self.current_t = current_t as i32;
        }
        if let Some(&steps_since_restart) = state.state.get("steps_since_restart") {
            self.steps_since_restart = steps_since_restart as i32;
        }
        if let Some(&restart_count) = state.state.get("restart_count") {
            self.restart_count = restart_count as i32;
        }
        if let Some(&warmup_power) = state.state.get("warmup_power") {
            self.warmup_power = warmup_power;
        }
        Ok(())
    }
}

/// Utility functions for creating common scheduler configurations
pub mod utils {
    use super::*;

    /// Create a polynomial decay with linear warmup (common transformer configuration)
    pub fn transformer_scheduler<O: Optimizer>(
        optimizer: O,
        warmup_steps: i32,
        total_steps: i32,
    ) -> PolynomialDecayWithWarmup<O> {
        PolynomialDecayWithWarmup::linear_warmup_linear_decay(
            optimizer,
            warmup_steps,
            total_steps,
            Some(0.0),
        )
    }

    /// Create an adaptive scheduler for loss monitoring
    pub fn adaptive_loss_scheduler<O: Optimizer>(
        optimizer: O,
        patience: Option<usize>,
    ) -> AdaptiveLRScheduler<O> {
        AdaptiveLRScheduler::new(
            optimizer,
            false,      // Lower loss is better
            Some(1.02), // Conservative increase
            Some(0.8),  // More aggressive decrease
            Some(1e-7),
            Some(0.1),
            patience,
            Some(0.005), // 0.5% improvement threshold
            Some(10),
        )
    }

    /// Create an adaptive scheduler for accuracy monitoring
    pub fn adaptive_accuracy_scheduler<O: Optimizer>(
        optimizer: O,
        patience: Option<usize>,
    ) -> AdaptiveLRScheduler<O> {
        AdaptiveLRScheduler::new(
            optimizer,
            true,       // Higher accuracy is better
            Some(1.05), // Moderate increase
            Some(0.9),  // Conservative decrease
            Some(1e-7),
            Some(0.1),
            patience,
            Some(0.01), // 1% improvement threshold
            Some(8),
        )
    }

    /// Create cosine annealing with warm restarts and linear warmup
    pub fn cosine_restart_with_warmup<O: Optimizer>(
        optimizer: O,
        restart_period: i32,
        warmup_steps: Option<i32>,
        t_mult: Option<i32>,
    ) -> CosineAnnealingWarmRestartsWithWarmup<O> {
        CosineAnnealingWarmRestartsWithWarmup::new(
            optimizer,
            restart_period,
            t_mult,
            warmup_steps,
            Some(0.0),
            Some(WarmupStrategy::Linear),
            None,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::SGD;
    use parking_lot::RwLock;
    use std::sync::Arc;
    use torsh_tensor::creation::randn;

    #[test]
    fn test_polynomial_decay_with_warmup() {
        let params = vec![Arc::new(RwLock::new(randn::<f32>(&[10, 10]).unwrap()))];
        let sgd = SGD::new(params, 0.1, None, None, None, false);
        let mut scheduler =
            PolynomialDecayWithWarmup::linear_warmup_quadratic_decay(sgd, 5, 20, Some(0.0));

        // Test warmup phase
        for step in 0..5 {
            let _ = scheduler.step();
            let lr = scheduler.get_last_lr()[0];
            let expected_lr = 0.1 * (step + 1) as f32 / 5.0;
            assert!(
                (lr - expected_lr).abs() < 1e-6,
                "Step {}: expected {}, got {}",
                step,
                expected_lr,
                lr
            );
        }

        // Test decay phase
        let _ = scheduler.step(); // Step 5
        let lr_step_5 = scheduler.get_last_lr()[0];
        assert!(lr_step_5 <= 0.1, "LR should start decaying after warmup");
    }

    #[test]
    fn test_adaptive_scheduler_with_improving_metric() {
        let params = vec![Arc::new(RwLock::new(randn::<f32>(&[10, 10]).unwrap()))];
        let sgd = SGD::new(params, 0.1, None, None, None, false);
        let mut scheduler = AdaptiveLRScheduler::new(
            sgd,
            false,
            Some(1.1),
            Some(0.9),
            Some(1e-4),
            Some(1.0),
            Some(3),
            Some(0.1),
            Some(2),
        );

        // Simulate improving loss (decreasing)
        let losses = vec![1.0, 0.9, 0.8, 0.7, 0.6, 0.5];
        for loss in losses {
            scheduler.step_with_metric(loss);
        }

        // Should increase learning rate due to improvement
        let final_lr = scheduler.get_last_lr()[0];
        assert!(final_lr >= 0.1, "LR should increase with improving metrics");
    }

    #[test]
    fn test_cosine_annealing_with_warmup() {
        let params = vec![Arc::new(RwLock::new(randn::<f32>(&[10, 10]).unwrap()))];
        let sgd = SGD::new(params, 0.1, None, None, None, false);
        let mut scheduler = CosineAnnealingWarmRestartsWithWarmup::new(
            sgd,
            10,
            Some(2),
            Some(5),
            Some(0.0),
            Some(WarmupStrategy::Linear),
            None,
        );

        // Test warmup phase
        for _ in 0..5 {
            let _ = scheduler.step();
        }
        let warmup_lr = scheduler.get_last_lr()[0];
        assert!(
            (warmup_lr - 0.1).abs() < 1e-6,
            "Should reach base LR at end of warmup"
        );

        // Test cosine annealing
        for _ in 5..15 {
            let _ = scheduler.step();
        }
        let final_lr = scheduler.get_last_lr()[0];
        assert!(
            final_lr >= 0.0 && final_lr <= 0.1,
            "LR should be within expected range"
        );
    }

    #[test]
    fn test_warmup_strategies() {
        let params = vec![Arc::new(RwLock::new(randn::<f32>(&[10, 10]).unwrap()))];

        // Test linear warmup
        let sgd_linear = SGD::new(params.clone(), 0.1, None, None, None, false);
        let mut scheduler_linear = PolynomialDecayWithWarmup::new(
            sgd_linear,
            4,
            10,
            None,
            None,
            Some(WarmupStrategy::Linear),
            None,
        );

        // Test polynomial warmup
        let sgd_poly = SGD::new(params, 0.1, None, None, None, false);
        let mut scheduler_poly = PolynomialDecayWithWarmup::new(
            sgd_poly,
            4,
            10,
            None,
            None,
            Some(WarmupStrategy::Polynomial),
            Some(2.0),
        );

        // Compare warmup curves
        for step in 0..4 {
            let _ = scheduler_linear.step();
            let _ = scheduler_poly.step();

            let lr_linear = scheduler_linear.get_last_lr()[0];
            let lr_poly = scheduler_poly.get_last_lr()[0];

            if step < 3 {
                assert!(
                    lr_poly < lr_linear,
                    "Polynomial warmup should be slower initially"
                );
            }
        }
    }

    #[test]
    fn test_adaptive_strategy_detection() -> Result<(), Box<dyn std::error::Error>> {
        let params = vec![Arc::new(RwLock::new(randn::<f32>(&[10, 10]).unwrap()))];
        let sgd = SGD::new(params, 0.1, None, None, None, false);
        let mut scheduler = AdaptiveLRScheduler::new(
            sgd,
            false,
            Some(1.1),
            Some(0.9),
            Some(1e-4),
            Some(1.0),
            Some(3),
            Some(0.05),
            Some(1),
        );

        // Simulate stagnating loss
        for _ in 0..10 {
            scheduler.step_with_metric(1.0);
        }

        let stats = scheduler.stats();
        // Should detect stagnation and potentially oscillate
        assert!(matches!(
            stats.current_strategy,
            AdaptiveStrategy::Oscillate | AdaptiveStrategy::Decrease
        ));
        Ok(())
    }
}