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    ///
118    /// The bare optimizer, which
119    /// [`ModuleOptimizer::with_group`](crate::ModuleOptimizer::with_group) takes to
120    /// optimize one parameter group. [`init`](Self::init) is the whole-module
121    /// counterpart, and the only one that applies the configured gradient clipping.
122    pub fn build(&self) -> AdamW {
123        AdamW {
124            momentum: AdaptiveMomentumW {
125                beta_1: self.beta_1,
126                beta_2: self.beta_2,
127                epsilon: self.epsilon,
128                amsgrad: self.amsgrad,
129            },
130            weight_decay: self.weight_decay,
131            cautious_weight_decay: self.cautious_weight_decay,
132        }
133    }
134
135    /// Initialize AdamW optimizer.
136    ///
137    /// # Returns
138    ///
139    /// Returns an optimizer that can be used to optimize a module.
140    pub fn init(&self) -> ModuleOptimizer {
141        let mut optim = ModuleOptimizer::from(self.build());
142        if let Some(config) = &self.grad_clipping {
143            optim = optim.with_grad_clipping(config.init());
144        }
145        optim
146    }
147}
148
149#[derive(Clone)]
150struct AdaptiveMomentumW {
151    beta_1: f32,
152    beta_2: f32,
153    epsilon: f32,
154    amsgrad: bool,
155}
156
157impl AdaptiveMomentumW {
158    pub fn transform<const D: usize>(
159        &self,
160        grad: Tensor<D>,
161        state: Option<AdaptiveMomentumState<D>>,
162    ) -> (Tensor<D>, AdaptiveMomentumState<D>) {
163        let factor_1 = 1.0 - self.beta_1;
164        let factor_2 = 1.0 - self.beta_2;
165
166        let state = if let Some(mut state) = state {
167            // Update first moment estimate.
168            state.moment_1 = state
169                .moment_1
170                .mul_scalar(self.beta_1)
171                .add(grad.clone().mul_scalar(factor_1));
172
173            // Update second moment estimate.
174            state.moment_2 = state
175                .moment_2
176                .mul_scalar(self.beta_2)
177                .add(grad.square().mul_scalar(factor_2));
178
179            if self.amsgrad {
180                let max_v = state
181                    .max_moment_2
182                    .take()
183                    .unwrap_or_else(|| state.moment_2.clone());
184                state.max_moment_2 = Some(max_v.max_pair(state.moment_2.clone()));
185            }
186
187            // Update time.
188            state.time += 1;
189
190            state
191        } else {
192            // Initialize first moment estimate.
193            let moment_1 = grad.clone().mul_scalar(factor_1);
194
195            // Initialize second moment estimate.
196            let moment_2 = grad.square().mul_scalar(factor_2);
197            let max_moment_2 = self.amsgrad.then(|| moment_2.clone());
198            AdaptiveMomentumState {
199                time: 1,
200                moment_1,
201                moment_2,
202                max_moment_2,
203            }
204        };
205
206        let time: i32 = state.time as i32;
207
208        // Compute bias-corrected first and second moment estimates.
209        let moment_1_corrected = state
210            .moment_1
211            .clone()
212            .div_scalar(1f32 - self.beta_1.powi(time));
213
214        let v_to_use = if self.amsgrad {
215            state.max_moment_2.as_ref().unwrap_or(&state.moment_2)
216        } else {
217            &state.moment_2
218        };
219
220        let moment_2_corrected = v_to_use.clone().div_scalar(1f32 - self.beta_2.powi(time));
221
222        let update_delta =
223            moment_1_corrected.div(moment_2_corrected.sqrt().add_scalar(self.epsilon));
224
225        (update_delta, state)
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::GradientsParams;
233    use crate::optim::test_utils::assert_optimizer_resume;
234    use burn::module::Param;
235    use burn::tensor::Tolerance;
236    use burn::tensor::{Tensor, TensorData};
237    use burn_nn::{Linear, LinearConfig};
238
239    type FT = f32;
240
241    const LEARNING_RATE: LearningRate = 0.01;
242
243    #[test]
244    fn test_adamw_optimizer_save_load_state() {
245        let device = Device::default().autodiff();
246        let linear = LinearConfig::new(6, 6).init(&device);
247        for amsgrad in [false, true] {
248            assert_optimizer_resume(
249                || AdamWConfig::new().with_amsgrad(amsgrad).init(),
250                linear.clone(),
251                LEARNING_RATE,
252            );
253        }
254    }
255    #[test]
256    fn test_adamw_optimizer_with_amsgrad_50_steps() {
257        let device = Device::default().autodiff();
258        let mut linear = given_linear_layer(
259            TensorData::from([
260                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
261                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
262                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
263                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
264                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
265                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
266            ]),
267            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
268            &device,
269        );
270
271        let mut optimizer = AdamWConfig::new()
272            .with_epsilon(1e-8)
273            .with_beta_1(0.9)
274            .with_beta_2(0.999)
275            .with_amsgrad(true)
276            .with_weight_decay(0.5)
277            .init();
278
279        for i in 1..=50 {
280            let x = Tensor::<2>::ones([2, 6], &device)
281                .mul_scalar(i as f32 * 0.1)
282                .require_grad();
283
284            let grads = linear.forward(x).backward();
285            let grads = GradientsParams::from_grads(grads, &linear);
286            linear = optimizer.step(LEARNING_RATE, linear, grads);
287        }
288
289        let state_updated = linear;
290        let weight_updated = state_updated.weight.to_data();
291        let bias_updated = state_updated.bias.unwrap().to_data();
292
293        let weights_expected = TensorData::from([
294            [
295                -0.7822558283805847,
296                -0.42578864097595215,
297                -0.21805696189403534,
298                -0.28366872668266296,
299                -0.46587175130844116,
300                -0.4805040955543518,
301            ],
302            [
303                -0.4722539782524109,
304                -0.5471276640892029,
305                -0.8181359767913818,
306                -0.33425918221473694,
307                -0.3805687427520752,
308                -0.7601516842842102,
309            ],
310            [
311                -0.5475167632102966,
312                -0.5057991743087769,
313                -0.763265073299408,
314                -0.3393959403038025,
315                -0.7490996718406677,
316                -0.28911691904067993,
317            ],
318            [
319                -0.7646660208702087,
320                -0.7050473093986511,
321                -0.8218720555305481,
322                -0.7647438049316406,
323                -0.5919585227966309,
324                -0.40617525577545166,
325            ],
326            [
327                -0.27588561177253723,
328                -0.7025567889213562,
329                -0.24343004822731018,
330                -0.6672990918159485,
331                -0.23728127777576447,
332                -0.556389570236206,
333            ],
334            [
335                -0.5451040267944336,
336                -0.5420684814453125,
337                -0.4348171353340149,
338                -0.3832150399684906,
339                -0.5099242925643921,
340                -0.23440153896808624,
341            ],
342        ]);
343        let bias_expected = TensorData::from([
344            -0.7473056316375732,
345            -0.3745720386505127,
346            -0.5188710689544678,
347            -0.35184532403945923,
348            -0.33705732226371765,
349            -0.4332566559314728,
350        ]);
351
352        let tolerance = Tolerance::absolute(1e-5);
353        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
354        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
355    }
356    #[test]
357    fn test_adamw_optimizer_with_numbers() {
358        let device = Device::default().autodiff();
359        let linear = given_linear_layer(
360            TensorData::from([
361                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
362                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
363                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
364                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
365                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
366                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
367            ]),
368            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
369            &device,
370        );
371        let x_1 = Tensor::<2>::from_floats(
372            [
373                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
374                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
375            ],
376            &device,
377        )
378        .require_grad();
379        let x_2 = Tensor::<2>::from_floats(
380            [
381                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
382                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
383            ],
384            &device,
385        )
386        .require_grad();
387
388        let mut optimizer = AdamWConfig::new()
389            .with_epsilon(1e-8)
390            .with_beta_1(0.9)
391            .with_beta_2(0.999)
392            .with_weight_decay(0.5)
393            .init();
394
395        let grads = linear.forward(x_1).backward();
396        let grads = GradientsParams::from_grads(grads, &linear);
397        let linear = optimizer.step(LEARNING_RATE, linear, grads);
398
399        let grads = linear.forward(x_2).backward();
400        let grads = GradientsParams::from_grads(grads, &linear);
401        let linear = optimizer.step(LEARNING_RATE, linear, grads);
402
403        let state_updated = linear;
404        let weights_expected = TensorData::from([
405            [-0.337295, 0.117827, 0.380358, 0.296868, 0.065232, 0.046534],
406            [
407                0.057032, -0.036518, -0.382951, 0.232516, 0.173738, -0.309182,
408            ],
409            [
410                -0.038703, 0.016052, -0.313155, 0.225982, -0.295039, 0.289981,
411            ],
412            [
413                -0.314920, -0.237394, -0.387704, -0.315067, -0.095153, 0.141081,
414            ],
415            [
416                0.306815, -0.234226, 0.348083, -0.191115, 0.356002, -0.049993,
417            ],
418            [-0.035634, -0.030083, 0.104636, 0.170244, 0.009196, 0.359580],
419        ]);
420        let bias_expected = TensorData::from([
421            -0.406555, 0.067568, -0.115982, 0.096477, 0.115287, -0.007080,
422        ]);
423
424        let (weight_updated, bias_updated) = (
425            state_updated.weight.to_data(),
426            state_updated.bias.unwrap().to_data(),
427        );
428
429        let tolerance = Tolerance::absolute(1e-2);
430        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
431        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
432    }
433
434    #[test]
435    fn test_adamw_optimizer_with_numbers_cautious() {
436        let device = Device::default().autodiff();
437        let linear = given_linear_layer(
438            TensorData::from([
439                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
440                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
441                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
442                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
443                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
444                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
445            ]),
446            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
447            &device,
448        );
449        let x_1 = Tensor::<2>::from_floats(
450            [
451                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
452                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
453            ],
454            &device,
455        )
456        .require_grad();
457        let x_2 = Tensor::<2>::from_floats(
458            [
459                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
460                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, -0.9085],
461            ],
462            &device,
463        )
464        .require_grad();
465
466        let mut optimizer = AdamWConfig::new()
467            .with_cautious_weight_decay(true)
468            .with_epsilon(1e-8)
469            .with_beta_1(0.9)
470            .with_beta_2(0.999)
471            .with_weight_decay(0.5)
472            .init();
473
474        let grads = linear.forward(x_1).backward();
475        let grads = GradientsParams::from_grads(grads, &linear);
476        let linear = optimizer.step(LEARNING_RATE, linear, grads);
477
478        let grads = linear.forward(x_2).backward();
479        let grads = GradientsParams::from_grads(grads, &linear);
480        let linear = optimizer.step(LEARNING_RATE, linear, grads);
481
482        let state_updated = linear;
483        let weights_expected = TensorData::from([
484            [-0.337295, 0.117827, 0.380358, 0.296868, 0.065232, 0.046534],
485            [
486                0.057032, -0.036518, -0.382951, 0.232516, 0.173738, -0.309182,
487            ],
488            [
489                -0.038703, 0.016052, -0.313155, 0.225982, -0.295039, 0.289981,
490            ],
491            [
492                -0.314920, -0.237394, -0.387704, -0.315067, -0.095153, 0.141081,
493            ],
494            [
495                0.306815, -0.234226, 0.348083, -0.191115, 0.356002, -0.049993,
496            ],
497            [
498                -0.035634, -0.030083, 0.104636, 0.170244, 0.009196, 0.37061332,
499            ],
500        ]);
501        let bias_expected = TensorData::from([
502            -0.406555, 0.067568, -0.115982, 0.096477, 0.115287, -0.007080,
503        ]);
504
505        let (weight_updated, bias_updated) = (
506            state_updated.weight.to_data(),
507            state_updated.bias.unwrap().to_data(),
508        );
509
510        let tolerance = Tolerance::absolute(1e-2);
511        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
512        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
513    }
514
515    #[test]
516    fn test_adam_optimizer_no_nan() {
517        let device = Device::default().autodiff();
518        let linear = given_linear_layer(
519            TensorData::from([
520                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
521                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
522                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
523                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
524                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
525                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
526            ]),
527            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
528            &device,
529        );
530
531        let x = Tensor::<2>::from_floats(
532            [
533                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
534                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
535            ],
536            &device,
537        )
538        .require_grad();
539
540        let mut optimizer = AdamWConfig::new()
541            .with_epsilon(1e-8)
542            .with_beta_1(0.9)
543            .with_beta_2(0.999)
544            .with_weight_decay(0.5)
545            .init();
546
547        let grads = linear.forward(x.clone()).backward();
548        let grads = GradientsParams::from_grads(grads, &linear);
549        let linear = optimizer.step(LEARNING_RATE, linear, grads);
550
551        let grads = linear.forward(x).backward();
552        let grads = GradientsParams::from_grads(grads, &linear);
553        let linear = optimizer.step(LEARNING_RATE, linear, grads);
554
555        let state_updated = linear;
556        assert!(!state_updated.weight.to_data().as_slice::<f32>().unwrap()[0].is_nan());
557    }
558
559    fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
560        Linear {
561            weight: Param::from_data(weight, device),
562            bias: Some(Param::from_data(bias, device)),
563        }
564    }
565}