Skip to main content

burn_optim/optim/
adamw.rs

1use burn_core as burn;
2
3use crate::RecordState;
4use burn::config::Config;
5use burn::tensor::Device;
6use burn::tensor::Tensor;
7
8use super::{AdaptiveMomentumState, Optimizer, module_optimizer::ModuleOptimizer};
9use crate::{LearningRate, grad_clipping::GradientClippingConfig};
10
11#[cfg(not(feature = "std"))]
12#[allow(unused_imports)]
13use num_traits::Float as _;
14
15/// [`AdamW`] Configuration.
16#[derive(Config, Debug)]
17pub struct AdamWConfig {
18    /// Parameter for AdamW.
19    #[config(default = 0.9)]
20    beta_1: f32,
21    /// Parameter for AdamW.
22    #[config(default = 0.999)]
23    beta_2: f32,
24    /// A value required for numerical stability.
25    #[config(default = 1e-5)]
26    epsilon: f32,
27    /// Weight decay config.
28    #[config(default = 1e-4)]
29    weight_decay: f32,
30
31    /// Cautious weight decay config.
32    ///
33    /// See: <https://arxiv.org/abs/2510.12402>
34    #[config(default = false)]
35    cautious_weight_decay: bool,
36
37    /// Whether to use AMSGrad algorithm
38    #[config(default = false)]
39    amsgrad: bool,
40    /// [Gradient Clipping](GradientClippingConfig) config.
41    grad_clipping: Option<GradientClippingConfig>,
42}
43
44/// AdamW optimizer.
45///
46/// See:
47/// - [Decoupled Weight Decay Regularization, Loshchilov and Hutter, 2019](https://arxiv.org/abs/1711.05101).
48/// - [Cautious Weight Decay, 2025](https://arxiv.org/abs/2510.12402)
49/// - [On the Convergence of Adam and Beyond](https://openreview.net/forum?id=ryQu7f-RZ)
50///
51/// Configured by [`AdamWConfig`].
52#[derive(Clone)]
53pub struct AdamW {
54    momentum: AdaptiveMomentumW,
55    weight_decay: f32,
56    cautious_weight_decay: bool,
57}
58
59/// AdamW state.
60#[derive(RecordState, Clone, new)]
61pub struct AdamWState<const D: usize> {
62    /// Th current adaptive momentum state.
63    pub momentum: AdaptiveMomentumState<D>,
64}
65
66impl Optimizer for AdamW {
67    type State<const D: usize> = AdamWState<D>;
68
69    /// A single optimization step for any tensor that represents the parameters of a model.
70    fn step<const D: usize>(
71        &self,
72        // Learning rate.
73        lr: LearningRate,
74        // Any tensor that represents the parameters of a model.
75        tensor: Tensor<D>,
76        // Gradient of the loss w.r.t. the parameters.
77        grad: Tensor<D>,
78        // State of the optimizer.
79        state: Option<Self::State<D>>,
80    ) -> (Tensor<D>, Option<Self::State<D>>) {
81        let (raw_delta, momentum_state) = self.momentum.transform(grad, state.map(|s| s.momentum));
82
83        let decay_rate = lr * (self.weight_decay as f64);
84
85        let decayed_tensor = if decay_rate == 0.0 {
86            tensor.clone()
87        } else if self.cautious_weight_decay {
88            // Cautious weight decay.
89            // See: https://arxiv.org/abs/2510.12402
90            let tensor_pos = tensor.clone().greater_equal_scalar(0.0);
91            let grad_pos = momentum_state.moment_1.clone().greater_equal_scalar(0.0);
92            let differ = tensor_pos.not_equal(grad_pos);
93
94            // Zero out the decay where the decay is counter to the update direction.
95            tensor.clone() - tensor.mul_scalar(decay_rate).mask_fill(differ, 0.0)
96        } else {
97            tensor.clone().mul_scalar(1.0 - decay_rate)
98        };
99
100        let tensor_updated = decayed_tensor - raw_delta.mul_scalar(lr);
101
102        let state = AdamWState {
103            momentum: momentum_state,
104        };
105
106        (tensor_updated, Some(state))
107    }
108
109    fn to_device<const D: usize>(mut state: Self::State<D>, device: &Device) -> Self::State<D> {
110        state.momentum = state.momentum.to_device(device);
111        state
112    }
113}
114
115impl AdamWConfig {
116    /// Build an [`AdamW`] from the config.
117    pub(crate) fn build(&self) -> AdamW {
118        AdamW {
119            momentum: AdaptiveMomentumW {
120                beta_1: self.beta_1,
121                beta_2: self.beta_2,
122                epsilon: self.epsilon,
123                amsgrad: self.amsgrad,
124            },
125            weight_decay: self.weight_decay,
126            cautious_weight_decay: self.cautious_weight_decay,
127        }
128    }
129
130    /// Initialize AdamW optimizer.
131    ///
132    /// # Returns
133    ///
134    /// Returns an optimizer that can be used to optimize a module.
135    pub fn init(&self) -> ModuleOptimizer {
136        let mut optim = ModuleOptimizer::from(self.build());
137        if let Some(config) = &self.grad_clipping {
138            optim = optim.with_grad_clipping(config.init());
139        }
140        optim
141    }
142}
143
144#[derive(Clone)]
145struct AdaptiveMomentumW {
146    beta_1: f32,
147    beta_2: f32,
148    epsilon: f32,
149    amsgrad: bool,
150}
151
152impl AdaptiveMomentumW {
153    pub fn transform<const D: usize>(
154        &self,
155        grad: Tensor<D>,
156        state: Option<AdaptiveMomentumState<D>>,
157    ) -> (Tensor<D>, AdaptiveMomentumState<D>) {
158        let factor_1 = 1.0 - self.beta_1;
159        let factor_2 = 1.0 - self.beta_2;
160
161        let state = if let Some(mut state) = state {
162            // Update first moment estimate.
163            state.moment_1 = state
164                .moment_1
165                .mul_scalar(self.beta_1)
166                .add(grad.clone().mul_scalar(factor_1));
167
168            // Update second moment estimate.
169            state.moment_2 = state
170                .moment_2
171                .mul_scalar(self.beta_2)
172                .add(grad.square().mul_scalar(factor_2));
173
174            if self.amsgrad {
175                let max_v = state
176                    .max_moment_2
177                    .take()
178                    .unwrap_or_else(|| state.moment_2.clone());
179                state.max_moment_2 = Some(max_v.max_pair(state.moment_2.clone()));
180            }
181
182            // Update time.
183            state.time += 1;
184
185            state
186        } else {
187            // Initialize first moment estimate.
188            let moment_1 = grad.clone().mul_scalar(factor_1);
189
190            // Initialize second moment estimate.
191            let moment_2 = grad.square().mul_scalar(factor_2);
192            let max_moment_2 = self.amsgrad.then(|| moment_2.clone());
193            AdaptiveMomentumState {
194                time: 1,
195                moment_1,
196                moment_2,
197                max_moment_2,
198            }
199        };
200
201        let time: i32 = state.time as i32;
202
203        // Compute bias-corrected first and second moment estimates.
204        let moment_1_corrected = state
205            .moment_1
206            .clone()
207            .div_scalar(1f32 - self.beta_1.powi(time));
208
209        let v_to_use = if self.amsgrad {
210            state.max_moment_2.as_ref().unwrap_or(&state.moment_2)
211        } else {
212            &state.moment_2
213        };
214
215        let moment_2_corrected = v_to_use.clone().div_scalar(1f32 - self.beta_2.powi(time));
216
217        let update_delta =
218            moment_1_corrected.div(moment_2_corrected.sqrt().add_scalar(self.epsilon));
219
220        (update_delta, state)
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use crate::GradientsParams;
228    use burn::module::Param;
229    use burn::tensor::Tolerance;
230    use burn::tensor::{Distribution, Tensor, TensorData};
231    use burn_nn::{Linear, LinearConfig};
232
233    type FT = f32;
234
235    const LEARNING_RATE: LearningRate = 0.01;
236
237    #[test]
238    fn test_adamw_optimizer_save_load_state() {
239        let device = Device::default().autodiff();
240        let linear = LinearConfig::new(6, 6).init(&device);
241        let x = Tensor::<2>::random([2, 6], Distribution::Default, &device);
242        let mut optimizer = create_adamw();
243        let grads = linear.forward(x).backward();
244        let grads = GradientsParams::from_grads(grads, &linear);
245        let _linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
246
247        let bytes = optimizer.into_bytes().unwrap();
248        assert!(!bytes.is_empty());
249
250        #[cfg(feature = "std")]
251        optimizer
252            .save(std::env::temp_dir().as_path().join("test_optim_adamw"))
253            .unwrap();
254
255        let state_optim_before = optimizer.to_record();
256        let optimizer = create_adamw().from_bytes(bytes).unwrap();
257        let state_optim_after = optimizer.to_record();
258
259        assert_eq!(state_optim_before.len(), state_optim_after.len());
260    }
261    #[test]
262    fn test_adamw_optimizer_with_amsgrad_50_steps() {
263        let device = Device::default().autodiff();
264        let mut linear = given_linear_layer(
265            TensorData::from([
266                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
267                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
268                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
269                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
270                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
271                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
272            ]),
273            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
274            &device,
275        );
276
277        let mut optimizer = AdamWConfig::new()
278            .with_epsilon(1e-8)
279            .with_beta_1(0.9)
280            .with_beta_2(0.999)
281            .with_amsgrad(true)
282            .with_weight_decay(0.5)
283            .init();
284
285        for i in 1..=50 {
286            let x = Tensor::<2>::ones([2, 6], &device)
287                .mul_scalar(i as f32 * 0.1)
288                .require_grad();
289
290            let grads = linear.forward(x).backward();
291            let grads = GradientsParams::from_grads(grads, &linear);
292            linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
293        }
294
295        let state_updated = linear;
296        let weight_updated = state_updated.weight.to_data();
297        let bias_updated = state_updated.bias.unwrap().to_data();
298
299        let weights_expected = TensorData::from([
300            [
301                -0.7822558283805847,
302                -0.42578864097595215,
303                -0.21805696189403534,
304                -0.28366872668266296,
305                -0.46587175130844116,
306                -0.4805040955543518,
307            ],
308            [
309                -0.4722539782524109,
310                -0.5471276640892029,
311                -0.8181359767913818,
312                -0.33425918221473694,
313                -0.3805687427520752,
314                -0.7601516842842102,
315            ],
316            [
317                -0.5475167632102966,
318                -0.5057991743087769,
319                -0.763265073299408,
320                -0.3393959403038025,
321                -0.7490996718406677,
322                -0.28911691904067993,
323            ],
324            [
325                -0.7646660208702087,
326                -0.7050473093986511,
327                -0.8218720555305481,
328                -0.7647438049316406,
329                -0.5919585227966309,
330                -0.40617525577545166,
331            ],
332            [
333                -0.27588561177253723,
334                -0.7025567889213562,
335                -0.24343004822731018,
336                -0.6672990918159485,
337                -0.23728127777576447,
338                -0.556389570236206,
339            ],
340            [
341                -0.5451040267944336,
342                -0.5420684814453125,
343                -0.4348171353340149,
344                -0.3832150399684906,
345                -0.5099242925643921,
346                -0.23440153896808624,
347            ],
348        ]);
349        let bias_expected = TensorData::from([
350            -0.7473056316375732,
351            -0.3745720386505127,
352            -0.5188710689544678,
353            -0.35184532403945923,
354            -0.33705732226371765,
355            -0.4332566559314728,
356        ]);
357
358        let tolerance = Tolerance::absolute(1e-5);
359        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
360        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
361    }
362    #[test]
363    fn test_adamw_optimizer_with_numbers() {
364        let device = Device::default().autodiff();
365        let linear = given_linear_layer(
366            TensorData::from([
367                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
368                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
369                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
370                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
371                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
372                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
373            ]),
374            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
375            &device,
376        );
377        let x_1 = Tensor::<2>::from_floats(
378            [
379                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
380                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
381            ],
382            &device,
383        )
384        .require_grad();
385        let x_2 = Tensor::<2>::from_floats(
386            [
387                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
388                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
389            ],
390            &device,
391        )
392        .require_grad();
393
394        let mut optimizer = AdamWConfig::new()
395            .with_epsilon(1e-8)
396            .with_beta_1(0.9)
397            .with_beta_2(0.999)
398            .with_weight_decay(0.5)
399            .init();
400
401        let grads = linear.forward(x_1).backward();
402        let grads = GradientsParams::from_grads(grads, &linear);
403        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
404
405        let grads = linear.forward(x_2).backward();
406        let grads = GradientsParams::from_grads(grads, &linear);
407        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
408
409        let state_updated = linear;
410        let weights_expected = TensorData::from([
411            [-0.337295, 0.117827, 0.380358, 0.296868, 0.065232, 0.046534],
412            [
413                0.057032, -0.036518, -0.382951, 0.232516, 0.173738, -0.309182,
414            ],
415            [
416                -0.038703, 0.016052, -0.313155, 0.225982, -0.295039, 0.289981,
417            ],
418            [
419                -0.314920, -0.237394, -0.387704, -0.315067, -0.095153, 0.141081,
420            ],
421            [
422                0.306815, -0.234226, 0.348083, -0.191115, 0.356002, -0.049993,
423            ],
424            [-0.035634, -0.030083, 0.104636, 0.170244, 0.009196, 0.359580],
425        ]);
426        let bias_expected = TensorData::from([
427            -0.406555, 0.067568, -0.115982, 0.096477, 0.115287, -0.007080,
428        ]);
429
430        let (weight_updated, bias_updated) = (
431            state_updated.weight.to_data(),
432            state_updated.bias.unwrap().to_data(),
433        );
434
435        let tolerance = Tolerance::absolute(1e-2);
436        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
437        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
438    }
439
440    #[test]
441    fn test_adamw_optimizer_with_numbers_cautious() {
442        let device = Device::default().autodiff();
443        let linear = given_linear_layer(
444            TensorData::from([
445                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
446                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
447                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
448                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
449                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
450                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
451            ]),
452            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
453            &device,
454        );
455        let x_1 = Tensor::<2>::from_floats(
456            [
457                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
458                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
459            ],
460            &device,
461        )
462        .require_grad();
463        let x_2 = Tensor::<2>::from_floats(
464            [
465                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
466                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, -0.9085],
467            ],
468            &device,
469        )
470        .require_grad();
471
472        let mut optimizer = AdamWConfig::new()
473            .with_cautious_weight_decay(true)
474            .with_epsilon(1e-8)
475            .with_beta_1(0.9)
476            .with_beta_2(0.999)
477            .with_weight_decay(0.5)
478            .init();
479
480        let grads = linear.forward(x_1).backward();
481        let grads = GradientsParams::from_grads(grads, &linear);
482        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
483
484        let grads = linear.forward(x_2).backward();
485        let grads = GradientsParams::from_grads(grads, &linear);
486        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
487
488        let state_updated = linear;
489        let weights_expected = TensorData::from([
490            [-0.337295, 0.117827, 0.380358, 0.296868, 0.065232, 0.046534],
491            [
492                0.057032, -0.036518, -0.382951, 0.232516, 0.173738, -0.309182,
493            ],
494            [
495                -0.038703, 0.016052, -0.313155, 0.225982, -0.295039, 0.289981,
496            ],
497            [
498                -0.314920, -0.237394, -0.387704, -0.315067, -0.095153, 0.141081,
499            ],
500            [
501                0.306815, -0.234226, 0.348083, -0.191115, 0.356002, -0.049993,
502            ],
503            [
504                -0.035634, -0.030083, 0.104636, 0.170244, 0.009196, 0.37061332,
505            ],
506        ]);
507        let bias_expected = TensorData::from([
508            -0.406555, 0.067568, -0.115982, 0.096477, 0.115287, -0.007080,
509        ]);
510
511        let (weight_updated, bias_updated) = (
512            state_updated.weight.to_data(),
513            state_updated.bias.unwrap().to_data(),
514        );
515
516        let tolerance = Tolerance::absolute(1e-2);
517        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
518        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
519    }
520
521    #[test]
522    fn test_adam_optimizer_no_nan() {
523        let device = Device::default().autodiff();
524        let linear = given_linear_layer(
525            TensorData::from([
526                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
527                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
528                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
529                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
530                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
531                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
532            ]),
533            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
534            &device,
535        );
536
537        let x = Tensor::<2>::from_floats(
538            [
539                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
540                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
541            ],
542            &device,
543        )
544        .require_grad();
545
546        let mut optimizer = AdamWConfig::new()
547            .with_epsilon(1e-8)
548            .with_beta_1(0.9)
549            .with_beta_2(0.999)
550            .with_weight_decay(0.5)
551            .init();
552
553        let grads = linear.forward(x.clone()).backward();
554        let grads = GradientsParams::from_grads(grads, &linear);
555        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
556
557        let grads = linear.forward(x).backward();
558        let grads = GradientsParams::from_grads(grads, &linear);
559        let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
560
561        let state_updated = linear;
562        assert!(!state_updated.weight.to_data().as_slice::<f32>().unwrap()[0].is_nan());
563    }
564
565    fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
566        Linear {
567            weight: Param::from_data(weight, device),
568            bias: Some(Param::from_data(bias, device)),
569        }
570    }
571
572    fn create_adamw() -> ModuleOptimizer {
573        let config = AdamWConfig::new();
574        AdamW {
575            momentum: AdaptiveMomentumW {
576                beta_1: config.beta_1,
577                beta_2: config.beta_2,
578                epsilon: config.epsilon,
579                amsgrad: config.amsgrad,
580            },
581            weight_decay: config.weight_decay,
582            cautious_weight_decay: false,
583        }
584        .into()
585    }
586}