Skip to main content

burn_optim/optim/
adam.rs

1use burn_core as burn;
2
3use crate::RecordState;
4
5use burn::config::Config;
6use burn::tensor::Device;
7use burn::tensor::Tensor;
8
9use super::{
10    Optimizer,
11    decay::{WeightDecay, WeightDecayConfig},
12    module_optimizer::ModuleOptimizer,
13};
14use crate::{LearningRate, grad_clipping::GradientClippingConfig};
15
16#[cfg(not(feature = "std"))]
17#[allow(unused_imports)]
18use num_traits::Float as _;
19
20/// Adam configuration.
21#[derive(Config, Debug)]
22pub struct AdamConfig {
23    /// Parameter for Adam.
24    #[config(default = 0.9)]
25    beta_1: f32,
26    /// Parameter for Adam.
27    #[config(default = 0.999)]
28    beta_2: f32,
29    /// A value required for numerical stability.
30    #[config(default = 1e-5)]
31    epsilon: f32,
32    /// Whether to use AMSGrad algorithm
33    #[config(default = false)]
34    amsgrad: bool,
35    /// [Weight decay](WeightDecayConfig) config.
36    weight_decay: Option<WeightDecayConfig>,
37    /// [Gradient Clipping](GradientClippingConfig) config.
38    grad_clipping: Option<GradientClippingConfig>,
39}
40
41/// Adam optimizer.
42///
43/// See:
44/// - [Adam: A Method for Stochastic Optimization](https://arxiv.org/pdf/1412.6980.pdf).
45/// - [On the Convergence of Adam and Beyond](https://openreview.net/forum?id=ryQu7f-RZ)
46#[derive(Clone)]
47pub struct Adam {
48    momentum: AdaptiveMomentum,
49    weight_decay: Option<WeightDecay>,
50}
51
52/// Adam state.
53#[derive(RecordState, Clone, new)]
54pub struct AdamState<const D: usize> {
55    /// The current adaptive momentum.
56    pub momentum: AdaptiveMomentumState<D>,
57}
58
59impl Optimizer for Adam {
60    type State<const D: usize> = AdamState<D>;
61
62    fn step<const D: usize>(
63        &self,
64        lr: LearningRate,
65        tensor: Tensor<D>,
66        mut grad: Tensor<D>,
67        state: Option<Self::State<D>>,
68    ) -> (Tensor<D>, Option<Self::State<D>>) {
69        let mut state_momentum = None;
70
71        if let Some(state) = state {
72            state_momentum = Some(state.momentum);
73        }
74
75        if let Some(weight_decay) = &self.weight_decay {
76            grad = weight_decay.transform(grad, tensor.clone());
77        }
78
79        let (grad, state_momentum) = self.momentum.transform(grad, state_momentum);
80
81        let state = AdamState::new(state_momentum);
82        let delta = grad.mul_scalar(lr);
83
84        (tensor - delta, Some(state))
85    }
86
87    fn to_device<const D: usize>(mut state: Self::State<D>, device: &Device) -> Self::State<D> {
88        state.momentum = state.momentum.to_device(device);
89        state
90    }
91}
92
93impl AdamConfig {
94    /// Build an [`Adam`] from the config.
95    pub(crate) fn build(&self) -> Adam {
96        Adam {
97            momentum: AdaptiveMomentum {
98                beta_1: self.beta_1,
99                beta_2: self.beta_2,
100                epsilon: self.epsilon,
101                amsgrad: self.amsgrad,
102            },
103            weight_decay: self.weight_decay.as_ref().map(WeightDecay::new),
104        }
105    }
106
107    /// Initialize Adam optimizer.
108    ///
109    /// # Returns
110    ///
111    /// Returns an optimizer that can be used to optimize a module.
112    pub fn init(&self) -> ModuleOptimizer {
113        let mut optim = ModuleOptimizer::from(self.build());
114        if let Some(config) = &self.grad_clipping {
115            optim = optim.with_grad_clipping(config.init());
116        }
117        optim
118    }
119}
120
121/// Adaptive momentum state.
122#[derive(RecordState, new, Clone)]
123pub struct AdaptiveMomentumState<const D: usize> {
124    /// The number of iterations aggregated.
125    pub time: usize,
126    /// The first order momentum.
127    pub moment_1: Tensor<D>,
128    /// The second order momentum.
129    pub moment_2: Tensor<D>,
130    /// Max of second  order momentum (for AMSGrad)
131    #[new(default)]
132    pub max_moment_2: Option<Tensor<D>>,
133}
134
135#[derive(Clone)]
136struct AdaptiveMomentum {
137    beta_1: f32,
138    beta_2: f32,
139    epsilon: f32,
140    amsgrad: bool,
141}
142
143impl AdaptiveMomentum {
144    pub fn transform<const D: usize>(
145        &self,
146        grad: Tensor<D>,
147        momentum_state: Option<AdaptiveMomentumState<D>>,
148    ) -> (Tensor<D>, AdaptiveMomentumState<D>) {
149        let state = if let Some(mut state) = momentum_state {
150            let factor = 1.0 - self.beta_1;
151            state.moment_1 = state
152                .moment_1
153                .mul_scalar(self.beta_1)
154                .add(grad.clone().mul_scalar(factor));
155
156            let factor = 1.0 - self.beta_2;
157            state.moment_2 = state
158                .moment_2
159                .mul_scalar(self.beta_2)
160                .add(grad.square().mul_scalar(factor));
161            if self.amsgrad {
162                let max_v = state
163                    .max_moment_2
164                    .take()
165                    .unwrap_or_else(|| state.moment_2.clone());
166
167                let new_max = max_v.max_pair(state.moment_2.clone());
168                state.max_moment_2 = Some(new_max);
169            }
170
171            state.time += 1;
172
173            state
174        } else {
175            let factor = 1.0 - self.beta_1;
176            let moment_1 = grad.clone().mul_scalar(factor);
177
178            let factor = 1.0 - self.beta_2;
179            let moment_2 = grad.square().mul_scalar(factor);
180            let max_moment_2 = self.amsgrad.then(|| moment_2.clone());
181            AdaptiveMomentumState {
182                time: 1,
183                moment_1,
184                moment_2,
185                max_moment_2,
186            }
187        };
188
189        let time = state.time as i32;
190        let bias_correction2_sqrt = (1.0 - self.beta_2.powi(time)).sqrt();
191        let combined_factor = bias_correction2_sqrt / (1.0 - self.beta_1.powi(time));
192
193        let v_to_use = if self.amsgrad {
194            state.max_moment_2.as_ref().unwrap_or(&state.moment_2)
195        } else {
196            &state.moment_2
197        };
198
199        let grad = state.moment_1.clone().mul_scalar(combined_factor).div(
200            v_to_use
201                .clone()
202                .sqrt()
203                .add_scalar(self.epsilon * bias_correction2_sqrt),
204        );
205        (grad, state)
206    }
207}
208
209impl<const D: usize> AdaptiveMomentumState<D> {
210    /// Move state to device.
211    ///
212    /// # Arguments
213    ///
214    /// * `device` - Device to move state to.
215    ///
216    /// # Returns
217    ///
218    /// Returns state moved to device.
219    pub fn to_device(mut self, device: &Device) -> Self {
220        self.moment_1 = self.moment_1.to_device(device);
221        self.moment_2 = self.moment_2.to_device(device);
222        self.max_moment_2 = self.max_moment_2.map(|tensor| tensor.to_device(device));
223        self
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use burn::tensor::Tolerance;
230
231    use super::*;
232    use crate::GradientsParams;
233    use burn::module::Param;
234    use burn::tensor::{Distribution, Tensor, TensorData};
235    use burn_nn::{Linear, LinearConfig};
236
237    const LEARNING_RATE: LearningRate = 0.01;
238
239    #[test]
240    fn test_adam_optimizer_save_load_state() {
241        let device = Device::default().autodiff();
242        let linear = LinearConfig::new(6, 6).init(&device);
243        let x = Tensor::<2>::random([2, 6], Distribution::Default, &device);
244        let mut optimizer = create_adam();
245        let grads = linear.forward(x).backward();
246        let grads = GradientsParams::from_grads(grads, &linear);
247        let _linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
248
249        let bytes = optimizer.into_bytes().unwrap();
250        assert!(!bytes.is_empty());
251
252        #[cfg(feature = "std")]
253        optimizer
254            .save(std::env::temp_dir().as_path().join("test_optim_adam"))
255            .unwrap();
256
257        let state_optim_before = optimizer.to_record();
258        let optimizer = create_adam().from_bytes(bytes).unwrap();
259        let state_optim_after = optimizer.to_record();
260
261        assert_eq!(state_optim_before.len(), state_optim_after.len());
262    }
263
264    /// A burnpack round-trip must restore the full state — the moment tensors, amsgrad's optional
265    /// `max_moment_2`, and the `time` step counter — so that a subsequent step produces identical
266    /// parameters whether taken on the original or the reloaded optimizer.
267    #[test]
268    fn test_adam_state_survives_burnpack_round_trip() {
269        let device = Device::default().autodiff();
270        let mut linear = LinearConfig::new(6, 6).init(&device);
271        let mut optimizer = AdamConfig::new().with_amsgrad(true).init();
272
273        // Warm up the optimizer state over a few steps.
274        for i in 1..=3 {
275            let x = Tensor::<2>::ones([2, 6], &device)
276                .mul_scalar(i as f32 * 0.1)
277                .require_grad();
278            let grads = linear.forward(x).backward();
279            let grads = GradientsParams::from_grads(grads, &linear);
280            linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
281        }
282
283        // Round-trip the optimizer state through the burnpack format. No device is needed on load:
284        // each parameter's state is migrated to that parameter's device on the next step.
285        let bytes = optimizer.into_bytes().unwrap();
286        let mut reloaded = AdamConfig::new()
287            .with_amsgrad(true)
288            .init()
289            .from_bytes(bytes)
290            .unwrap();
291
292        // One more identical step on each optimizer must yield identical parameters.
293        let x = Tensor::<2>::ones([2, 6], &device)
294            .mul_scalar(0.4)
295            .require_grad();
296        let grads_original =
297            GradientsParams::from_grads(linear.forward(x.clone()).backward(), &linear);
298        let grads_reloaded = GradientsParams::from_grads(linear.forward(x).backward(), &linear);
299
300        let from_original = optimizer.step(LEARNING_RATE.into(), linear.clone(), grads_original);
301        let from_reloaded = reloaded.step(LEARNING_RATE.into(), linear, grads_reloaded);
302
303        let weight_original = from_original.weight.to_data();
304        let weight_reloaded = from_reloaded.weight.to_data();
305        weight_original.assert_approx_eq::<f32>(&weight_reloaded, Tolerance::absolute(1e-6));
306    }
307
308    #[test]
309    fn test_adam_optimizer_with_amsgrad_50_steps() {
310        let device = Device::default().autodiff();
311        let mut linear = given_linear_layer(
312            TensorData::from([
313                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
314                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
315                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
316                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
317                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
318                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
319            ]),
320            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
321            &device,
322        );
323
324        let mut optimizer = AdamConfig::new()
325            .with_epsilon(1e-8)
326            .with_beta_1(0.9)
327            .with_beta_2(0.999)
328            .with_amsgrad(true)
329            .with_weight_decay(Some(WeightDecayConfig::new(0.5)))
330            .init();
331
332        for i in 1..=50 {
333            let x = Tensor::<2>::ones([2, 6], &device)
334                .mul_scalar(i as f32 * 0.1)
335                .require_grad();
336
337            let grads = linear.forward(x).backward();
338            let grads = GradientsParams::from_grads(grads, &linear);
339            linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
340        }
341
342        let state_updated = linear;
343        let weight_updated = state_updated.weight.to_data();
344        let bias_updated = state_updated.bias.unwrap().to_data();
345
346        let weights_expected = TensorData::from([
347            [
348                -0.9125810265541077,
349                -0.45855265855789185,
350                -0.1915993094444275,
351                -0.2759990692138672,
352                -0.5099529027938843,
353                -0.5287043452262878,
354            ],
355            [
356                -0.5181325674057007,
357                -0.6139854788780212,
358                -0.9574727416038513,
359                -0.34102925658226013,
360                -0.400514155626297,
361                -0.8847861886024475,
362            ],
363            [
364                -0.614483118057251,
365                -0.5611032247543335,
366                -0.8887064456939697,
367                -0.34762972593307495,
368                -0.8708556890487671,
369                -0.2830044627189636,
370            ],
371            [
372                -0.8904699683189392,
373                -0.8151527643203735,
374                -0.9621278643608093,
375                -0.8905676603317261,
376                -0.671261191368103,
377                -0.4333854615688324,
378            ],
379            [
380                -0.26599061489105225,
381                -0.8119961023330688,
382                -0.22424538433551788,
383                -0.7672406435012817,
384                -0.2163349837064743,
385                -0.6258266568183899,
386            ],
387            [
388                -0.611397922039032,
389                -0.6075160503387451,
390                -0.4701341986656189,
391                -0.4039117991924286,
392                -0.5663845539093018,
393                -0.21262989938259125,
394            ],
395        ]);
396        let bias_expected = TensorData::from([
397            -0.8817203044891357,
398            -0.4038999378681183,
399            -0.5889149308204651,
400            -0.37475723028182983,
401            -0.3557940721511841,
402            -0.47914788126945496,
403        ]);
404
405        let tolerance = Tolerance::absolute(1e-5);
406        weight_updated.assert_approx_eq::<f32>(&weights_expected, tolerance);
407        bias_updated.assert_approx_eq::<f32>(&bias_expected, tolerance);
408    }
409    #[test]
410    fn test_adam_optimizer_with_numbers() {
411        let device = Device::default().autodiff();
412        let linear = given_linear_layer(
413            TensorData::from([
414                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
415                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
416                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
417                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
418                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
419                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
420            ]),
421            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
422            &device,
423        );
424        let x_1 = Tensor::<2>::from_floats(
425            [
426                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
427                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
428            ],
429            &device,
430        )
431        .require_grad();
432        let x_2 = Tensor::<2>::from_floats(
433            [
434                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
435                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
436            ],
437            &device,
438        )
439        .require_grad();
440
441        let mut optimizer = AdamConfig::new()
442            .with_epsilon(1e-8)
443            .with_beta_1(0.9)
444            .with_beta_2(0.999)
445            .with_weight_decay(Some(WeightDecayConfig::new(0.5)))
446            .init();
447
448        let grads = linear.forward(x_1).backward();
449        let grads = GradientsParams::from_grads(grads, &linear);
450        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
451
452        let grads = linear.forward(x_2).backward();
453        let grads = GradientsParams::from_grads(grads, &linear);
454        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
455
456        let state_updated = linear;
457        let weights_expected = TensorData::from([
458            [-0.340528, 0.118929, 0.384336, 0.300010, 0.066034, 0.047154],
459            [
460                0.057757, -0.036690, -0.386649, 0.235010, 0.175624, -0.312133,
461            ],
462            [
463                -0.038940, 0.016306, -0.316151, 0.228410, -0.297819, 0.293047,
464            ],
465            [
466                -0.317929, -0.239100, -0.391449, -0.318087, -0.095948, 0.142651,
467            ],
468            [
469                0.310050, -0.235909, 0.351736, -0.192888, 0.359710, -0.050343,
470            ],
471            [-0.035840, -0.030203, 0.105840, 0.172110, 0.009440, 0.363346],
472        ]);
473        let bias_expected = TensorData::from([
474            -0.410499, 0.068401, -0.116999, 0.097601, 0.116601, -0.006999,
475        ]);
476
477        let (weight_updated, bias_updated) = (
478            state_updated.weight.to_data(),
479            state_updated.bias.unwrap().to_data(),
480        );
481
482        let tolerance = Tolerance::absolute(1e-2);
483        bias_updated.assert_approx_eq::<f32>(&bias_expected, tolerance);
484        weight_updated.assert_approx_eq::<f32>(&weights_expected, tolerance);
485    }
486
487    #[test]
488    fn test_adam_optimizer_no_nan() {
489        let device = Device::default().autodiff();
490        let linear = given_linear_layer(
491            TensorData::from([
492                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
493                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
494                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
495                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
496                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
497                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
498            ]),
499            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
500            &device,
501        );
502
503        let x = Tensor::<2>::from_floats(
504            [
505                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
506                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
507            ],
508            &device,
509        )
510        .require_grad();
511
512        let mut optimizer = AdamConfig::new()
513            .with_epsilon(1e-8)
514            .with_beta_1(0.9)
515            .with_beta_2(0.999)
516            .with_weight_decay(Some(WeightDecayConfig::new(0.5)))
517            .init();
518
519        let grads = linear.forward(x.clone()).backward();
520        let grads = GradientsParams::from_grads(grads, &linear);
521        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
522
523        let grads = linear.forward(x).backward();
524        let grads = GradientsParams::from_grads(grads, &linear);
525        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
526
527        let state_updated = linear;
528        assert!(!state_updated.weight.to_data().as_slice::<f32>().unwrap()[0].is_nan());
529    }
530
531    fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
532        Linear {
533            weight: Param::from_data(weight, device),
534            bias: Some(Param::from_data(bias, device)),
535        }
536    }
537
538    fn create_adam() -> ModuleOptimizer {
539        let config = AdamConfig::new();
540        Adam {
541            momentum: AdaptiveMomentum {
542                beta_1: config.beta_1,
543                beta_2: config.beta_2,
544                epsilon: config.epsilon,
545                amsgrad: config.amsgrad,
546            },
547            weight_decay: config.weight_decay.as_ref().map(WeightDecay::new),
548        }
549        .into()
550    }
551}