Skip to main content

burn_optim/optim/
adan.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::{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/// [`Adan`] Configuration.
16///
17/// See:
18/// - [Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models](https://arxiv.org/abs/2208.06677).
19#[derive(Config, Debug)]
20pub struct AdanConfig {
21    /// Parameter for the first moment.
22    #[config(default = 0.98)]
23    beta_1: f32,
24    /// Parameter for the gradient-difference momentum.
25    #[config(default = 0.92)]
26    beta_2: f32,
27    /// Parameter for the second moment.
28    #[config(default = 0.99)]
29    beta_3: f32,
30    /// A value required for numerical stability.
31    #[config(default = 1e-8)]
32    epsilon: f32,
33    /// Weight decay factor.
34    #[config(default = 0.0)]
35    weight_decay: f32,
36    /// Disable proximal weight decay and use the decoupled update instead.
37    #[config(default = false)]
38    no_prox: bool,
39    /// [Gradient Clipping](GradientClippingConfig) config.
40    grad_clipping: Option<GradientClippingConfig>,
41}
42
43/// Adan optimizer.
44///
45/// See:
46/// - [Adan: Adaptive Nesterov Momentum Algorithm for Faster Optimizing Deep Models](https://arxiv.org/abs/2208.06677).
47///
48/// Configured by [`AdanConfig`].
49#[derive(Clone)]
50pub struct Adan {
51    momentum: AdaptiveNesterovMomentum,
52    weight_decay: f32,
53    no_prox: bool,
54}
55
56/// Adan state.
57#[derive(RecordState, Clone, new)]
58pub struct AdanState<const D: usize> {
59    /// The current adaptive Nesterov momentum state.
60    pub momentum: AdaptiveNesterovMomentumState<D>,
61}
62
63impl Optimizer for Adan {
64    type State<const D: usize> = AdanState<D>;
65
66    fn step<const D: usize>(
67        &self,
68        lr: LearningRate,
69        tensor: Tensor<D>,
70        grad: Tensor<D>,
71        state: Option<Self::State<D>>,
72    ) -> (Tensor<D>, Option<Self::State<D>>) {
73        let (raw_delta, momentum_state) = self.momentum.transform(grad, state.map(|s| s.momentum));
74
75        let decay_rate = lr * (self.weight_decay as f64);
76        let delta = raw_delta.mul_scalar(lr);
77
78        let tensor_updated = if self.no_prox {
79            if decay_rate == 0.0 {
80                tensor - delta
81            } else {
82                tensor.mul_scalar(1.0 - decay_rate) - delta
83            }
84        } else {
85            let updated = tensor - delta;
86            if decay_rate == 0.0 {
87                updated
88            } else {
89                updated.div_scalar(1.0 + decay_rate)
90            }
91        };
92
93        (tensor_updated, Some(AdanState::new(momentum_state)))
94    }
95
96    fn to_device<const D: usize>(mut state: Self::State<D>, device: &Device) -> Self::State<D> {
97        state.momentum = state.momentum.to_device(device);
98        state
99    }
100}
101
102impl AdanConfig {
103    /// Build an [`Adan`] from the config.
104    ///
105    /// The bare optimizer, which
106    /// [`ModuleOptimizer::with_group`](crate::ModuleOptimizer::with_group) takes to
107    /// optimize one parameter group. [`init`](Self::init) is the whole-module
108    /// counterpart, and the only one that applies the configured gradient clipping.
109    pub fn build(&self) -> Adan {
110        Adan {
111            momentum: AdaptiveNesterovMomentum {
112                beta_1: self.beta_1,
113                beta_2: self.beta_2,
114                beta_3: self.beta_3,
115                epsilon: self.epsilon,
116            },
117            weight_decay: self.weight_decay,
118            no_prox: self.no_prox,
119        }
120    }
121
122    /// Initialize Adan optimizer.
123    ///
124    /// # Returns
125    ///
126    /// Returns an optimizer that can be used to optimize a module.
127    pub fn init(&self) -> ModuleOptimizer {
128        let mut optim = ModuleOptimizer::from(self.build());
129        if let Some(config) = &self.grad_clipping {
130            optim = optim.with_grad_clipping(config.init());
131        }
132        optim
133    }
134}
135
136/// Adaptive Nesterov momentum state.
137#[derive(RecordState, Clone, new)]
138pub struct AdaptiveNesterovMomentumState<const D: usize> {
139    /// The number of iterations aggregated.
140    pub time: usize,
141    /// The first order momentum.
142    pub exp_avg: Tensor<D>,
143    /// The gradient-difference weighted second order momentum.
144    pub exp_avg_sq: Tensor<D>,
145    /// The gradient-difference momentum.
146    pub exp_avg_diff: Tensor<D>,
147    /// The negated previous gradient.
148    pub neg_pre_grad: Tensor<D>,
149}
150
151#[derive(Clone)]
152struct AdaptiveNesterovMomentum {
153    beta_1: f32,
154    beta_2: f32,
155    beta_3: f32,
156    epsilon: f32,
157}
158
159impl AdaptiveNesterovMomentum {
160    pub fn transform<const D: usize>(
161        &self,
162        grad: Tensor<D>,
163        state: Option<AdaptiveNesterovMomentumState<D>>,
164    ) -> (Tensor<D>, AdaptiveNesterovMomentumState<D>) {
165        let state = if let Some(mut state) = state {
166            let grad_diff = state.neg_pre_grad.clone().add(grad.clone());
167            let grad_diff_sq = grad_diff
168                .clone()
169                .mul_scalar(self.beta_2)
170                .add(grad.clone())
171                .square();
172
173            state.exp_avg = state
174                .exp_avg
175                .mul_scalar(self.beta_1)
176                .add(grad.clone().mul_scalar(1.0 - self.beta_1));
177            state.exp_avg_diff = state
178                .exp_avg_diff
179                .mul_scalar(self.beta_2)
180                .add(grad_diff.mul_scalar(1.0 - self.beta_2));
181            state.exp_avg_sq = state
182                .exp_avg_sq
183                .mul_scalar(self.beta_3)
184                .add(grad_diff_sq.mul_scalar(1.0 - self.beta_3));
185            state.neg_pre_grad = grad.mul_scalar(-1.0);
186            state.time += 1;
187            state
188        } else {
189            AdaptiveNesterovMomentumState::new(
190                1,
191                grad.clone().mul_scalar(1.0 - self.beta_1),
192                grad.clone().square().mul_scalar(1.0 - self.beta_3),
193                grad.zeros_like(),
194                grad.clone().mul_scalar(-1.0),
195            )
196        };
197
198        let time = state.time as i32;
199        let denom = state
200            .exp_avg_sq
201            .clone()
202            .sqrt()
203            .div_scalar((1.0 - self.beta_3.powi(time)).sqrt())
204            .add_scalar(self.epsilon);
205        let update = state
206            .exp_avg
207            .clone()
208            .div_scalar(1.0 - self.beta_1.powi(time))
209            .div(denom.clone())
210            .add(
211                state
212                    .exp_avg_diff
213                    .clone()
214                    .mul_scalar(self.beta_2)
215                    .div_scalar(1.0 - self.beta_2.powi(time))
216                    .div(denom),
217            );
218
219        (update, state)
220    }
221}
222
223impl<const D: usize> AdaptiveNesterovMomentumState<D> {
224    #[allow(clippy::wrong_self_convention)]
225    fn to_device(mut self, device: &Device) -> Self {
226        self.exp_avg = self.exp_avg.to_device(device);
227        self.exp_avg_sq = self.exp_avg_sq.to_device(device);
228        self.exp_avg_diff = self.exp_avg_diff.to_device(device);
229        self.neg_pre_grad = self.neg_pre_grad.to_device(device);
230        self
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use crate::GradientsParams;
238    use burn::module::Param;
239    use burn::tensor::Tolerance;
240    use burn::tensor::{Distribution, Tensor, TensorData};
241    use burn_nn::{Linear, LinearConfig};
242
243    type FT = f32;
244
245    const LEARNING_RATE: LearningRate = 0.01;
246
247    #[test]
248    fn test_adan_optimizer_save_load_state() {
249        let device = Device::default().autodiff();
250        let linear = LinearConfig::new(6, 6).init(&device);
251        let x = Tensor::<2>::random([2, 6], Distribution::Default, &device);
252        let mut optimizer = create_adan();
253        let grads = linear.forward(x).backward();
254        let grads = GradientsParams::from_grads(grads, &linear);
255        let _linear = optimizer.step(LEARNING_RATE, linear, grads);
256
257        let bytes = optimizer.into_bytes().unwrap();
258        assert!(!bytes.is_empty());
259
260        #[cfg(feature = "std")]
261        optimizer
262            .save(std::env::temp_dir().as_path().join("test_optim_adan"))
263            .unwrap();
264
265        let state_optim_before = optimizer.to_record();
266        let optimizer = create_adan().from_bytes(bytes).unwrap();
267        let state_optim_after = optimizer.to_record();
268
269        assert_eq!(state_optim_before.len(), state_optim_after.len());
270    }
271
272    #[test]
273    fn test_adan_optimizer_with_numbers() {
274        let device = Device::default().autodiff();
275        let linear = given_linear_layer(
276            TensorData::from([
277                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
278                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
279                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
280                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
281                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
282                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
283            ]),
284            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
285            &device,
286        );
287        let x_1 = Tensor::<2>::from_floats(
288            [
289                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
290                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
291            ],
292            &device,
293        )
294        .require_grad();
295        let x_2 = Tensor::<2>::from_floats(
296            [
297                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
298                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
299            ],
300            &device,
301        )
302        .require_grad();
303
304        let mut optimizer = AdanConfig::new()
305            .with_beta_1(0.98)
306            .with_beta_2(0.92)
307            .with_beta_3(0.99)
308            .with_epsilon(1e-8)
309            .with_weight_decay(0.02)
310            .init();
311
312        let grads = linear.forward(x_1).backward();
313        let grads = GradientsParams::from_grads(grads, &linear);
314        let linear = optimizer.step(LEARNING_RATE, linear, grads);
315
316        let grads = linear.forward(x_2).backward();
317        let grads = GradientsParams::from_grads(grads, &linear);
318        let linear = optimizer.step(LEARNING_RATE, linear, grads);
319
320        let state_updated = linear;
321        let weights_expected = TensorData::from([
322            [
323                -0.34034607,
324                0.11747075,
325                0.38426402,
326                0.29999772,
327                0.06599136,
328                0.04719888,
329            ],
330            [
331                0.0644293,
332                -0.031732224,
333                -0.37979296,
334                0.24165839,
335                0.18218218,
336                -0.30532277,
337            ],
338            [
339                -0.038910445,
340                0.01466812,
341                -0.31599957,
342                0.2283826,
343                -0.29780683,
344                0.2929568,
345            ],
346            [
347                -0.3178632,
348                -0.24129382,
349                -0.39133376,
350                -0.31796312,
351                -0.09605193,
352                0.14255258,
353            ],
354            [
355                0.31026322,
356                -0.23771758,
357                0.3519465,
358                -0.19243571,
359                0.35984334,
360                -0.049992695,
361            ],
362            [
363                -0.03577819,
364                -0.031879753,
365                0.10586514,
366                0.17213862,
367                0.009403733,
368                0.36326218,
369            ],
370        ]);
371        let bias_expected = TensorData::from([
372            -0.4103378,
373            0.06837065,
374            -0.116955206,
375            0.097558975,
376            0.11655137,
377            -0.006999196,
378        ]);
379
380        let (weight_updated, bias_updated) = (
381            state_updated.weight.to_data(),
382            state_updated.bias.unwrap().to_data(),
383        );
384
385        let tolerance = Tolerance::absolute(1e-5);
386        bias_updated.assert_approx_eq::<FT>(&bias_expected, tolerance);
387        weight_updated.assert_approx_eq::<FT>(&weights_expected, tolerance);
388    }
389
390    #[test]
391    fn test_adan_optimizer_no_nan() {
392        let device = Device::default().autodiff();
393        let linear = given_linear_layer(
394            TensorData::from([
395                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
396                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
397                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
398                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
399                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
400                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
401            ]),
402            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
403            &device,
404        );
405
406        let x = Tensor::<2>::from_floats(
407            [
408                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
409                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
410            ],
411            &device,
412        )
413        .require_grad();
414
415        let mut optimizer = AdanConfig::new()
416            .with_epsilon(1e-8)
417            .with_weight_decay(0.02)
418            .init();
419
420        let grads = linear.forward(x.clone()).backward();
421        let grads = GradientsParams::from_grads(grads, &linear);
422        let linear = optimizer.step(LEARNING_RATE, linear, grads);
423
424        let grads = linear.forward(x).backward();
425        let grads = GradientsParams::from_grads(grads, &linear);
426        let linear = optimizer.step(LEARNING_RATE, linear, grads);
427
428        let state_updated = linear;
429        assert!(!state_updated.weight.to_data().as_slice::<f32>().unwrap()[0].is_nan());
430    }
431
432    fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
433        Linear {
434            weight: Param::from_data(weight, device),
435            bias: Some(Param::from_data(bias, device)),
436        }
437    }
438
439    fn create_adan() -> ModuleOptimizer {
440        let config = AdanConfig::new();
441        Adan {
442            momentum: AdaptiveNesterovMomentum {
443                beta_1: config.beta_1,
444                beta_2: config.beta_2,
445                beta_3: config.beta_3,
446                epsilon: config.epsilon,
447            },
448            weight_decay: config.weight_decay,
449            no_prox: config.no_prox,
450        }
451        .into()
452    }
453}