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
//! Learning rate schedulers

use crate::{Optimizer, OptimizerError, OptimizerResult};
use torsh_core::error::{Result, TorshError};

/// Base trait for learning rate schedulers
pub trait LRScheduler {
    /// Update learning rates based on current epoch/step
    fn step(&mut self) -> OptimizerResult<()>;

    /// Update learning rates with optional metrics (for ReduceLROnPlateau)
    fn step_with_metric(&mut self, metric: Option<f32>) -> OptimizerResult<()> {
        // Default implementation ignores the metric
        self.step()
    }

    /// Get current learning rates
    fn get_last_lr(&self) -> &[f32];

    /// Get base learning rates
    fn get_base_lrs(&self) -> &[f32];

    /// Get current epoch/step count
    fn get_last_epoch(&self) -> i32;

    /// Reset the scheduler state
    fn reset(&mut self);

    /// Get scheduler state for serialization
    fn state_dict(&self) -> SchedulerState;

    /// Load scheduler state from serialization
    fn load_state_dict(&mut self, state: SchedulerState) -> OptimizerResult<()>;
}

/// Macro to implement common LRScheduler methods for schedulers with a `base` field
#[macro_export]
macro_rules! impl_base_scheduler_methods {
    ($scheduler_type:ty, $scheduler_name:expr) => {
        impl<O: Optimizer> LRScheduler for $scheduler_type {
            fn step(&mut self) -> OptimizerResult<()> {
                // Default implementation - should be overridden
                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($scheduler_name.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
            }

            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;
                Ok(())
            }
        }
    };
}

/// Macro to implement common LRScheduler methods with custom state handling
#[macro_export]
macro_rules! impl_scheduler_with_state {
    ($scheduler_type:ty, $scheduler_name:expr, $state_fields:expr, $load_state_fields:expr) => {
        impl<O: Optimizer> LRScheduler for $scheduler_type {
            fn step(&mut self) -> OptimizerResult<()> {
                // Default implementation - should be overridden
                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($scheduler_name.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();

                // Add custom state fields
                $state_fields(&self, &mut state);

                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;

                // Load custom state fields
                $load_state_fields(self, &state)?;

                Ok(())
            }
        }
    };
}

/// Scheduler state for serialization
#[derive(Debug, Clone)]
pub struct SchedulerState {
    pub scheduler_type: String,
    pub last_epoch: i32,
    pub base_lrs: Vec<f32>,
    pub last_lr: Vec<f32>,
    pub state: std::collections::HashMap<String, f32>,
}

impl SchedulerState {
    pub fn new(scheduler_type: String) -> Self {
        Self {
            scheduler_type,
            last_epoch: 0,
            base_lrs: Vec::new(),
            last_lr: Vec::new(),
            state: std::collections::HashMap::new(),
        }
    }
}

/// Base scheduler implementation
pub struct BaseScheduler<O: Optimizer> {
    pub optimizer: O,
    pub base_lrs: Vec<f32>,
    pub last_lr: Vec<f32>,
    pub last_epoch: i32,
}

impl<O: Optimizer> BaseScheduler<O> {
    pub fn new(optimizer: O) -> Self {
        let base_lrs = optimizer.get_lr();
        let last_lr = base_lrs.clone();

        Self {
            optimizer,
            base_lrs,
            last_lr,
            last_epoch: 0,
        }
    }

    /// Set the learning rates for all parameter groups
    pub fn set_learning_rates(&mut self, lrs: &[f32]) {
        if !lrs.is_empty() {
            if lrs.len() == 1 {
                // Single learning rate - apply to all groups
                self.optimizer.set_lr(lrs[0]);
            } else {
                // Multiple learning rates - need to implement per-group setting
                // For now, just use the first one
                self.optimizer.set_lr(lrs[0]);
            }
        }
        self.last_lr = lrs.to_vec();
    }

    /// Get a mutable reference to the optimizer
    pub fn optimizer_mut(&mut self) -> &mut O {
        &mut self.optimizer
    }

    /// Get a reference to the optimizer
    pub fn optimizer(&self) -> &O {
        &self.optimizer
    }

    /// Increment the epoch counter
    pub fn increment_epoch(&mut self) {
        self.last_epoch += 1;
    }

    /// Set the epoch counter
    pub fn set_epoch(&mut self, epoch: i32) {
        self.last_epoch = epoch;
    }
}

impl<O: Optimizer> LRScheduler for BaseScheduler<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        self.increment_epoch();
        // Base implementation does nothing - schedulers override this
        Ok(())
    }

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

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

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

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

    fn state_dict(&self) -> SchedulerState {
        let mut state = SchedulerState::new("BaseScheduler".to_string());
        state.last_epoch = self.last_epoch;
        state.base_lrs = self.base_lrs.clone();
        state.last_lr = self.last_lr.clone();
        state
    }

    fn load_state_dict(&mut self, state: SchedulerState) -> OptimizerResult<()> {
        self.last_epoch = state.last_epoch;
        self.base_lrs = state.base_lrs;
        self.last_lr = state.last_lr.clone();
        self.set_learning_rates(&state.last_lr);
        Ok(())
    }
}

/// Step learning rate scheduler
pub struct StepLR<O: Optimizer> {
    base: BaseScheduler<O>,
    step_size: i32,
    gamma: f32,
}

impl<O: Optimizer> StepLR<O> {
    pub fn new(optimizer: O, step_size: i32, gamma: f32) -> Self {
        Self {
            base: BaseScheduler::new(optimizer),
            step_size,
            gamma,
        }
    }
}

impl<O: Optimizer> LRScheduler for StepLR<O> {
    fn step(&mut self) -> OptimizerResult<()> {
        self.base.increment_epoch();

        let new_lrs: Vec<f32> = self
            .base
            .base_lrs
            .iter()
            .map(|&base_lr| {
                let num_steps = self.base.last_epoch / self.step_size;
                base_lr * self.gamma.powi(num_steps)
            })
            .collect();

        self.base.set_learning_rates(&new_lrs);
        Ok(())
    }

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

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

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

    fn reset(&mut self) {
        self.base.reset()
    }

    fn state_dict(&self) -> SchedulerState {
        let mut state = self.base.state_dict();
        state.scheduler_type = "StepLR".to_string();
        state
            .state
            .insert("step_size".to_string(), self.step_size as f32);
        state.state.insert("gamma".to_string(), self.gamma);
        state
    }

    fn load_state_dict(&mut self, state: SchedulerState) -> OptimizerResult<()> {
        self.base.load_state_dict(state.clone())?;

        if let Some(&step_size) = state.state.get("step_size") {
            self.step_size = step_size as i32;
        }
        if let Some(&gamma) = state.state.get("gamma") {
            self.gamma = gamma;
        }

        Ok(())
    }
}

/// Exponential learning rate scheduler
pub struct ExponentialLR<O: Optimizer> {
    base: BaseScheduler<O>,
    gamma: f32,
}

impl<O: Optimizer> ExponentialLR<O> {
    pub fn new(optimizer: O, gamma: f32) -> Self {
        Self {
            base: BaseScheduler::new(optimizer),
            gamma,
        }
    }
}

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

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

        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("ExponentialLR".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("gamma".to_string(), self.gamma);
        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(&gamma) = state.state.get("gamma") {
            self.gamma = gamma;
        }
        Ok(())
    }
}

/// Cosine annealing learning rate scheduler
pub struct CosineAnnealingLR<O: Optimizer> {
    base: BaseScheduler<O>,
    t_max: i32,
    eta_min: f32,
}

impl<O: Optimizer> CosineAnnealingLR<O> {
    pub fn new(optimizer: O, t_max: i32, eta_min: f32) -> Self {
        Self {
            base: BaseScheduler::new(optimizer),
            t_max,
            eta_min,
        }
    }
}

impl<O: Optimizer> LRScheduler for CosineAnnealingLR<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.eta_min
                    + (base_lr - self.eta_min)
                        * (1.0
                            + (std::f32::consts::PI * self.base.last_epoch as f32
                                / self.t_max as f32)
                                .cos())
                        / 2.0
            })
            .collect();

        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("CosineAnnealingLR".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_max".to_string(), self.t_max as f32);
        state.state.insert("eta_min".to_string(), self.eta_min);
        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_max) = state.state.get("t_max") {
            self.t_max = t_max as i32;
        }
        if let Some(&eta_min) = state.state.get("eta_min") {
            self.eta_min = eta_min;
        }
        Ok(())
    }
}

/// Reduce learning rate on plateau
pub struct ReduceLROnPlateau<O: Optimizer> {
    optimizer: O,
    mode: String,
    factor: f32,
    patience: i32,
    threshold: f32,
    threshold_mode: String,
    cooldown: i32,
    min_lr: f32,
    eps: f32,
    best: Option<f32>,
    num_bad_epochs: i32,
    cooldown_counter: i32,
}

impl<O: Optimizer> ReduceLROnPlateau<O> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        optimizer: O,
        mode: &str,
        factor: f32,
        patience: i32,
        threshold: f32,
        threshold_mode: &str,
        cooldown: i32,
        min_lr: f32,
        eps: f32,
    ) -> Result<Self> {
        if factor >= 1.0 {
            return Err(TorshError::Other("Factor should be < 1.0".to_string()));
        }

        Ok(Self {
            optimizer,
            mode: mode.to_string(),
            factor,
            patience,
            threshold,
            threshold_mode: threshold_mode.to_string(),
            cooldown,
            min_lr,
            eps,
            best: None,
            num_bad_epochs: 0,
            cooldown_counter: 0,
        })
    }

    pub fn step(&mut self, metrics: f32) {
        let current = metrics;

        if self.best.is_none() {
            self.best = Some(current);
        } else {
            let best_value = self.best.expect("best should exist after is_none check");
            let is_better = match self.mode.as_str() {
                "min" => match self.threshold_mode.as_str() {
                    "rel" => current < best_value * (1.0 - self.threshold),
                    "abs" => current < best_value - self.threshold,
                    _ => false,
                },
                "max" => match self.threshold_mode.as_str() {
                    "rel" => current > best_value * (1.0 + self.threshold),
                    "abs" => current > best_value + self.threshold,
                    _ => false,
                },
                _ => false,
            };

            if is_better {
                self.best = Some(current);
                self.num_bad_epochs = 0;
            } else {
                self.num_bad_epochs += 1;
            }

            if self.cooldown_counter > 0 {
                self.cooldown_counter -= 1;
                self.num_bad_epochs = 0;
            }

            if self.num_bad_epochs > self.patience {
                self.reduce_lr();
                self.cooldown_counter = self.cooldown;
                self.num_bad_epochs = 0;
            }
        }
    }

    fn reduce_lr(&mut self) {
        let old_lrs = self.optimizer.get_lr();
        let new_lrs: Vec<f32> = old_lrs
            .iter()
            .map(|&lr| (lr * self.factor).max(self.min_lr))
            .collect();

        // Only reduce if the change is significant
        for (old_lr, new_lr) in old_lrs.iter().zip(new_lrs.iter()) {
            if old_lr - new_lr > self.eps {
                self.optimizer.set_lr(*new_lr);
                println!("Reducing learning rate from {} to {}", old_lr, new_lr);
            }
        }
    }
}

/// One cycle learning rate scheduler
pub struct OneCycleLR<O: Optimizer> {
    base: BaseScheduler<O>,
    max_lr: Vec<f32>,
    total_steps: i32,
    pct_start: f32,
    anneal_strategy: String,
    #[allow(dead_code)]
    cycle_momentum: bool,
    #[allow(dead_code)]
    base_momentum: f32,
    #[allow(dead_code)]
    max_momentum: f32,
    #[allow(dead_code)]
    div_factor: f32,
    final_div_factor: f32,
    step_count: i32,
}

impl<O: Optimizer> OneCycleLR<O> {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        optimizer: O,
        max_lr: Vec<f32>,
        total_steps: i32,
        pct_start: Option<f32>,
        anneal_strategy: Option<&str>,
        cycle_momentum: Option<bool>,
        base_momentum: Option<f32>,
        max_momentum: Option<f32>,
        div_factor: Option<f32>,
        final_div_factor: Option<f32>,
    ) -> Self {
        let pct_start = pct_start.unwrap_or(0.3);
        let anneal_strategy = anneal_strategy.unwrap_or("cos").to_string();
        let cycle_momentum = cycle_momentum.unwrap_or(true);
        let base_momentum = base_momentum.unwrap_or(0.85);
        let max_momentum = max_momentum.unwrap_or(0.95);
        let div_factor = div_factor.unwrap_or(25.0);
        let final_div_factor = final_div_factor.unwrap_or(10000.0);

        let mut base = BaseScheduler::new(optimizer);

        // Initialize base learning rates
        base.base_lrs = max_lr.iter().map(|&lr| lr / div_factor).collect();

        Self {
            base,
            max_lr,
            total_steps,
            pct_start,
            anneal_strategy,
            cycle_momentum,
            base_momentum,
            max_momentum,
            div_factor,
            final_div_factor,
            step_count: 0,
        }
    }
}

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

        let step_num = self.step_count as f32;
        let step_size_up = (self.pct_start * self.total_steps as f32).floor();
        let step_size_down = self.total_steps as f32 - step_size_up;

        let new_lrs: Vec<f32> = if step_num <= step_size_up {
            // Increase phase
            let computed_lr =
                |base_lr: f32, max_lr: f32| base_lr + (max_lr - base_lr) * step_num / step_size_up;

            self.base
                .base_lrs
                .iter()
                .zip(self.max_lr.iter())
                .map(|(&base, &max)| computed_lr(base, max))
                .collect()
        } else {
            // Decrease phase
            let down_step_num = step_num - step_size_up;
            match self.anneal_strategy.as_str() {
                "cos" => {
                    let computed_lr = |max_lr: f32, base_lr: f32| {
                        let min_lr = base_lr / self.final_div_factor;
                        min_lr
                            + (max_lr - min_lr)
                                * (1.0
                                    + (std::f32::consts::PI * down_step_num / step_size_down).cos())
                                / 2.0
                    };

                    self.max_lr
                        .iter()
                        .zip(self.base.base_lrs.iter())
                        .map(|(&max, &base)| computed_lr(max, base))
                        .collect()
                }
                "linear" => {
                    let computed_lr = |max_lr: f32, base_lr: f32| {
                        let min_lr = base_lr / self.final_div_factor;
                        max_lr - (max_lr - min_lr) * down_step_num / step_size_down
                    };

                    self.max_lr
                        .iter()
                        .zip(self.base.base_lrs.iter())
                        .map(|(&max, &base)| computed_lr(max, base))
                        .collect()
                }
                _ => {
                    return Err(OptimizerError::InvalidParameter(format!(
                        "Unknown anneal strategy: {}",
                        self.anneal_strategy
                    )))
                }
            }
        };

        // Update learning rates
        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.step_count
    }

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

    fn state_dict(&self) -> SchedulerState {
        let mut state = SchedulerState::new("OneCycleLR".to_string());
        state.last_epoch = self.step_count;
        state.base_lrs = self.base.base_lrs.clone();
        state.last_lr = self.base.last_lr.clone();
        state
            .state
            .insert("total_steps".to_string(), self.total_steps as f32);
        state.state.insert("pct_start".to_string(), self.pct_start);
        state
            .state
            .insert("final_div_factor".to_string(), self.final_div_factor);
        state
    }

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