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 burn::module::Param;
234    use burn::tensor::Tolerance;
235    use burn::tensor::{Distribution, Tensor, TensorData};
236    use burn_nn::{Linear, LinearConfig};
237
238    type FT = f32;
239
240    const LEARNING_RATE: LearningRate = 0.01;
241
242    #[test]
243    fn test_adamw_optimizer_save_load_state() {
244        let device = Device::default().autodiff();
245        let linear = LinearConfig::new(6, 6).init(&device);
246        let x = Tensor::<2>::random([2, 6], Distribution::Default, &device);
247        let mut optimizer = create_adamw();
248        let grads = linear.forward(x).backward();
249        let grads = GradientsParams::from_grads(grads, &linear);
250        let _linear = optimizer.step(LEARNING_RATE, linear, grads);
251
252        let bytes = optimizer.into_bytes().unwrap();
253        assert!(!bytes.is_empty());
254
255        #[cfg(feature = "std")]
256        optimizer
257            .save(std::env::temp_dir().as_path().join("test_optim_adamw"))
258            .unwrap();
259
260        let state_optim_before = optimizer.to_record();
261        let optimizer = create_adamw().from_bytes(bytes).unwrap();
262        let state_optim_after = optimizer.to_record();
263
264        assert_eq!(state_optim_before.len(), state_optim_after.len());
265    }
266    #[test]
267    fn test_adamw_optimizer_with_amsgrad_50_steps() {
268        let device = Device::default().autodiff();
269        let mut linear = given_linear_layer(
270            TensorData::from([
271                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
272                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
273                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
274                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
275                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
276                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
277            ]),
278            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
279            &device,
280        );
281
282        let mut optimizer = AdamWConfig::new()
283            .with_epsilon(1e-8)
284            .with_beta_1(0.9)
285            .with_beta_2(0.999)
286            .with_amsgrad(true)
287            .with_weight_decay(0.5)
288            .init();
289
290        for i in 1..=50 {
291            let x = Tensor::<2>::ones([2, 6], &device)
292                .mul_scalar(i as f32 * 0.1)
293                .require_grad();
294
295            let grads = linear.forward(x).backward();
296            let grads = GradientsParams::from_grads(grads, &linear);
297            linear = optimizer.step(LEARNING_RATE, linear, grads);
298        }
299
300        let state_updated = linear;
301        let weight_updated = state_updated.weight.to_data();
302        let bias_updated = state_updated.bias.unwrap().to_data();
303
304        let weights_expected = TensorData::from([
305            [
306                -0.7822558283805847,
307                -0.42578864097595215,
308                -0.21805696189403534,
309                -0.28366872668266296,
310                -0.46587175130844116,
311                -0.4805040955543518,
312            ],
313            [
314                -0.4722539782524109,
315                -0.5471276640892029,
316                -0.8181359767913818,
317                -0.33425918221473694,
318                -0.3805687427520752,
319                -0.7601516842842102,
320            ],
321            [
322                -0.5475167632102966,
323                -0.5057991743087769,
324                -0.763265073299408,
325                -0.3393959403038025,
326                -0.7490996718406677,
327                -0.28911691904067993,
328            ],
329            [
330                -0.7646660208702087,
331                -0.7050473093986511,
332                -0.8218720555305481,
333                -0.7647438049316406,
334                -0.5919585227966309,
335                -0.40617525577545166,
336            ],
337            [
338                -0.27588561177253723,
339                -0.7025567889213562,
340                -0.24343004822731018,
341                -0.6672990918159485,
342                -0.23728127777576447,
343                -0.556389570236206,
344            ],
345            [
346                -0.5451040267944336,
347                -0.5420684814453125,
348                -0.4348171353340149,
349                -0.3832150399684906,
350                -0.5099242925643921,
351                -0.23440153896808624,
352            ],
353        ]);
354        let bias_expected = TensorData::from([
355            -0.7473056316375732,
356            -0.3745720386505127,
357            -0.5188710689544678,
358            -0.35184532403945923,
359            -0.33705732226371765,
360            -0.4332566559314728,
361        ]);
362
363        let tolerance = Tolerance::absolute(1e-5);
364        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
365        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
366    }
367    #[test]
368    fn test_adamw_optimizer_with_numbers() {
369        let device = Device::default().autodiff();
370        let linear = given_linear_layer(
371            TensorData::from([
372                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
373                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
374                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
375                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
376                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
377                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
378            ]),
379            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
380            &device,
381        );
382        let x_1 = Tensor::<2>::from_floats(
383            [
384                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
385                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
386            ],
387            &device,
388        )
389        .require_grad();
390        let x_2 = Tensor::<2>::from_floats(
391            [
392                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
393                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
394            ],
395            &device,
396        )
397        .require_grad();
398
399        let mut optimizer = AdamWConfig::new()
400            .with_epsilon(1e-8)
401            .with_beta_1(0.9)
402            .with_beta_2(0.999)
403            .with_weight_decay(0.5)
404            .init();
405
406        let grads = linear.forward(x_1).backward();
407        let grads = GradientsParams::from_grads(grads, &linear);
408        let linear = optimizer.step(LEARNING_RATE, linear, grads);
409
410        let grads = linear.forward(x_2).backward();
411        let grads = GradientsParams::from_grads(grads, &linear);
412        let linear = optimizer.step(LEARNING_RATE, linear, grads);
413
414        let state_updated = linear;
415        let weights_expected = TensorData::from([
416            [-0.337295, 0.117827, 0.380358, 0.296868, 0.065232, 0.046534],
417            [
418                0.057032, -0.036518, -0.382951, 0.232516, 0.173738, -0.309182,
419            ],
420            [
421                -0.038703, 0.016052, -0.313155, 0.225982, -0.295039, 0.289981,
422            ],
423            [
424                -0.314920, -0.237394, -0.387704, -0.315067, -0.095153, 0.141081,
425            ],
426            [
427                0.306815, -0.234226, 0.348083, -0.191115, 0.356002, -0.049993,
428            ],
429            [-0.035634, -0.030083, 0.104636, 0.170244, 0.009196, 0.359580],
430        ]);
431        let bias_expected = TensorData::from([
432            -0.406555, 0.067568, -0.115982, 0.096477, 0.115287, -0.007080,
433        ]);
434
435        let (weight_updated, bias_updated) = (
436            state_updated.weight.to_data(),
437            state_updated.bias.unwrap().to_data(),
438        );
439
440        let tolerance = Tolerance::absolute(1e-2);
441        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
442        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
443    }
444
445    #[test]
446    fn test_adamw_optimizer_with_numbers_cautious() {
447        let device = Device::default().autodiff();
448        let linear = given_linear_layer(
449            TensorData::from([
450                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
451                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
452                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
453                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
454                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
455                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
456            ]),
457            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
458            &device,
459        );
460        let x_1 = Tensor::<2>::from_floats(
461            [
462                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
463                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
464            ],
465            &device,
466        )
467        .require_grad();
468        let x_2 = Tensor::<2>::from_floats(
469            [
470                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
471                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, -0.9085],
472            ],
473            &device,
474        )
475        .require_grad();
476
477        let mut optimizer = AdamWConfig::new()
478            .with_cautious_weight_decay(true)
479            .with_epsilon(1e-8)
480            .with_beta_1(0.9)
481            .with_beta_2(0.999)
482            .with_weight_decay(0.5)
483            .init();
484
485        let grads = linear.forward(x_1).backward();
486        let grads = GradientsParams::from_grads(grads, &linear);
487        let linear = optimizer.step(LEARNING_RATE, linear, grads);
488
489        let grads = linear.forward(x_2).backward();
490        let grads = GradientsParams::from_grads(grads, &linear);
491        let linear = optimizer.step(LEARNING_RATE, linear, grads);
492
493        let state_updated = linear;
494        let weights_expected = TensorData::from([
495            [-0.337295, 0.117827, 0.380358, 0.296868, 0.065232, 0.046534],
496            [
497                0.057032, -0.036518, -0.382951, 0.232516, 0.173738, -0.309182,
498            ],
499            [
500                -0.038703, 0.016052, -0.313155, 0.225982, -0.295039, 0.289981,
501            ],
502            [
503                -0.314920, -0.237394, -0.387704, -0.315067, -0.095153, 0.141081,
504            ],
505            [
506                0.306815, -0.234226, 0.348083, -0.191115, 0.356002, -0.049993,
507            ],
508            [
509                -0.035634, -0.030083, 0.104636, 0.170244, 0.009196, 0.37061332,
510            ],
511        ]);
512        let bias_expected = TensorData::from([
513            -0.406555, 0.067568, -0.115982, 0.096477, 0.115287, -0.007080,
514        ]);
515
516        let (weight_updated, bias_updated) = (
517            state_updated.weight.to_data(),
518            state_updated.bias.unwrap().to_data(),
519        );
520
521        let tolerance = Tolerance::absolute(1e-2);
522        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
523        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
524    }
525
526    #[test]
527    fn test_adam_optimizer_no_nan() {
528        let device = Device::default().autodiff();
529        let linear = given_linear_layer(
530            TensorData::from([
531                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
532                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
533                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
534                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
535                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
536                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
537            ]),
538            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
539            &device,
540        );
541
542        let x = Tensor::<2>::from_floats(
543            [
544                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
545                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
546            ],
547            &device,
548        )
549        .require_grad();
550
551        let mut optimizer = AdamWConfig::new()
552            .with_epsilon(1e-8)
553            .with_beta_1(0.9)
554            .with_beta_2(0.999)
555            .with_weight_decay(0.5)
556            .init();
557
558        let grads = linear.forward(x.clone()).backward();
559        let grads = GradientsParams::from_grads(grads, &linear);
560        let linear = optimizer.step(LEARNING_RATE, linear, grads);
561
562        let grads = linear.forward(x).backward();
563        let grads = GradientsParams::from_grads(grads, &linear);
564        let linear = optimizer.step(LEARNING_RATE, linear, grads);
565
566        let state_updated = linear;
567        assert!(!state_updated.weight.to_data().as_slice::<f32>().unwrap()[0].is_nan());
568    }
569
570    fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
571        Linear {
572            weight: Param::from_data(weight, device),
573            bias: Some(Param::from_data(bias, device)),
574        }
575    }
576
577    fn create_adamw() -> ModuleOptimizer {
578        let config = AdamWConfig::new();
579        AdamW {
580            momentum: AdaptiveMomentumW {
581                beta_1: config.beta_1,
582                beta_2: config.beta_2,
583                epsilon: config.epsilon,
584                amsgrad: config.amsgrad,
585            },
586            weight_decay: config.weight_decay,
587            cautious_weight_decay: false,
588        }
589        .into()
590    }
591}