Skip to main content

burn_optim/optim/
adagrad.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/// AdaGrad configuration.
17#[derive(Config, Debug)]
18pub struct AdaGradConfig {
19    #[config(default = 0.)]
20    lr_decay: f64,
21    #[config(default = 1e-5)]
22    epsilon: f32,
23    /// [Weight decay](WeightDecayConfig) config.
24    weight_decay: Option<WeightDecayConfig>,
25    /// [Gradient Clipping](GradientClippingConfig) config.
26    grad_clipping: Option<GradientClippingConfig>,
27}
28
29/// AdaGrad optimizer
30#[derive(Clone)]
31pub struct AdaGrad {
32    lr_decay: LrDecay,
33    weight_decay: Option<WeightDecay>,
34}
35
36/// AdaGrad state.
37#[derive(RecordState, Clone, new)]
38pub struct AdaGradState<const D: usize> {
39    lr_decay: LrDecayState<D>,
40}
41
42impl Optimizer for AdaGrad {
43    type State<const D: usize> = AdaGradState<D>;
44
45    fn step<const D: usize>(
46        &self,
47        lr: LearningRate,
48        tensor: Tensor<D>,
49        mut grad: Tensor<D>,
50        state: Option<Self::State<D>>,
51    ) -> (Tensor<D>, Option<Self::State<D>>) {
52        let mut state_lr_decay = None;
53
54        if let Some(state) = state {
55            state_lr_decay = Some(state.lr_decay);
56        }
57
58        if let Some(weight_decay) = &self.weight_decay {
59            grad = weight_decay.transform(grad, tensor.clone());
60        }
61
62        let (grad, state_lr_decay) = self.lr_decay.transform(grad, lr, state_lr_decay);
63
64        let state = AdaGradState::new(state_lr_decay);
65
66        (tensor - grad, Some(state))
67    }
68
69    fn to_device<const D: usize>(mut state: Self::State<D>, device: &Device) -> Self::State<D> {
70        state.lr_decay = state.lr_decay.to_device(device);
71        state
72    }
73}
74
75impl AdaGradConfig {
76    /// Build an [`AdaGrad`] from the config.
77    ///
78    /// The bare optimizer, which
79    /// [`ModuleOptimizer::with_group`](crate::ModuleOptimizer::with_group) takes to
80    /// optimize one parameter group. [`init`](Self::init) is the whole-module
81    /// counterpart, and the only one that applies the configured gradient clipping.
82    pub fn build(&self) -> AdaGrad {
83        AdaGrad {
84            lr_decay: LrDecay {
85                lr_decay: self.lr_decay,
86                epsilon: self.epsilon,
87            },
88            weight_decay: self.weight_decay.as_ref().map(WeightDecay::new),
89        }
90    }
91
92    /// Initialize AdaGrad optimizer.
93    ///
94    /// # Returns
95    ///
96    /// Returns an optimizer that can be used to optimize a module.
97    pub fn init(&self) -> ModuleOptimizer {
98        let mut optim = ModuleOptimizer::from(self.build());
99        if let Some(config) = &self.grad_clipping {
100            optim = optim.with_grad_clipping(config.init());
101        }
102        optim
103    }
104}
105
106/// Learning rate decay state (also includes sum state).
107#[derive(RecordState, new, Clone)]
108pub struct LrDecayState<const D: usize> {
109    time: usize,
110    sum: Tensor<D>,
111}
112
113#[derive(Clone)]
114struct LrDecay {
115    lr_decay: f64,
116    epsilon: f32,
117}
118
119impl LrDecay {
120    pub fn transform<const D: usize>(
121        &self,
122        grad: Tensor<D>,
123        lr: LearningRate,
124        lr_decay_state: Option<LrDecayState<D>>,
125    ) -> (Tensor<D>, LrDecayState<D>) {
126        let state = if let Some(mut state) = lr_decay_state {
127            state.sum = state.sum.add(grad.clone().square());
128            state.time += 1;
129            state
130        } else {
131            LrDecayState::new(1, grad.clone().square())
132        };
133
134        let new_lr = lr / (1. + (state.time as f64 - 1.) * self.lr_decay);
135
136        let grad = grad
137            .div(state.sum.clone().sqrt().add_scalar(self.epsilon))
138            .mul_scalar(new_lr);
139
140        (grad, state)
141    }
142}
143
144impl<const D: usize> LrDecayState<D> {
145    /// Move state to device.
146    ///
147    /// # Arguments
148    ///
149    /// * `device` - Device to move state to.
150    ///
151    /// # Returns
152    ///
153    /// Returns state moved to device.
154    pub fn to_device(mut self, device: &Device) -> Self {
155        self.sum = self.sum.to_device(device);
156        self
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use burn::tensor::Tolerance;
163
164    use super::*;
165    use crate::GradientsParams;
166    use burn::module::Param;
167    use burn::tensor::{Distribution, Tensor, TensorData};
168    use burn_nn::{Linear, LinearConfig};
169
170    const LEARNING_RATE: LearningRate = 0.01;
171
172    #[test]
173    fn test_adagrad_optimizer_save_load_state() {
174        let device = Device::default().autodiff();
175        let linear = LinearConfig::new(6, 6).init(&device);
176        let x = Tensor::<2>::random([2, 6], Distribution::Default, &device);
177        let mut optimizer = create_adagrad();
178        let grads = linear.forward(x).backward();
179        let grads = GradientsParams::from_grads(grads, &linear);
180        let _linear = optimizer.step(LEARNING_RATE, linear, grads);
181
182        let bytes = optimizer.into_bytes().unwrap();
183        assert!(!bytes.is_empty());
184
185        #[cfg(feature = "std")]
186        optimizer
187            .save(std::env::temp_dir().as_path().join("test_optim_adagrad"))
188            .unwrap();
189
190        let state_optim_before = optimizer.to_record();
191        let optimizer = create_adagrad().from_bytes(bytes).unwrap();
192        let state_optim_after = optimizer.to_record();
193
194        assert_eq!(state_optim_before.len(), state_optim_after.len());
195    }
196
197    #[test]
198    fn test_adagrad_optimizer_with_numbers() {
199        let device = Device::default().autodiff();
200        let linear = given_linear_layer(
201            TensorData::from([
202                [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
203                [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
204                [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
205                [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
206                [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
207                [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
208            ]),
209            TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
210            &device,
211        );
212        let x_1 = Tensor::<2>::from_floats(
213            [
214                [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
215                [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
216            ],
217            &device,
218        )
219        .require_grad();
220        let x_2 = Tensor::<2>::from_floats(
221            [
222                [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
223                [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
224            ],
225            &device,
226        )
227        .require_grad();
228
229        let mut optimizer = AdaGradConfig::new()
230            .with_epsilon(1e-8)
231            .with_lr_decay(0.5)
232            .init();
233
234        let grads = linear.forward(x_1).backward();
235        let grads = GradientsParams::from_grads(grads, &linear);
236        let linear = optimizer.step(LEARNING_RATE, linear, grads);
237
238        let grads = linear.forward(x_2).backward();
239        let grads = GradientsParams::from_grads(grads, &linear);
240        let linear = optimizer.step(LEARNING_RATE, linear, grads);
241
242        let state_updated = linear;
243        let weights_expected = TensorData::from([
244            [-0.334989, 0.123011, 0.389911, 0.305611, 0.071511, 0.052711],
245            [
246                0.066144, -0.030056, -0.378256, 0.243444, 0.183944, -0.303756,
247            ],
248            [
249                -0.033462, 0.020138, -0.310662, 0.233938, -0.292462, 0.298538,
250            ],
251            [
252                -0.312636, -0.236036, -0.386136, -0.312736, -0.090736, 0.147964,
253            ],
254            [
255                0.315896, -0.232304, 0.357596, -0.187004, 0.365496, -0.044504,
256            ],
257            [-0.030305, -0.026405, 0.111395, 0.177695, 0.014895, 0.368895],
258        ]);
259        let bias_expected = TensorData::from([
260            -0.405214, 0.073686, -0.111714, 0.102886, 0.121886, -0.001714,
261        ]);
262
263        let (weight_updated, bias_updated) = (
264            state_updated.weight.val().into_data(),
265            state_updated.bias.unwrap().val().into_data(),
266        );
267
268        let tolerance = Tolerance::absolute(1e-6);
269        bias_updated.assert_approx_eq::<f32>(&bias_expected, tolerance);
270        weight_updated.assert_approx_eq::<f32>(&weights_expected, tolerance);
271    }
272
273    fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
274        Linear {
275            weight: Param::from_data(weight, device),
276            bias: Some(Param::from_data(bias, device)),
277        }
278    }
279
280    fn create_adagrad() -> ModuleOptimizer {
281        let config = AdaGradConfig::new();
282        AdaGrad {
283            lr_decay: LrDecay {
284                lr_decay: config.lr_decay,
285                epsilon: config.epsilon,
286            },
287            weight_decay: config.weight_decay.as_ref().map(WeightDecay::new),
288        }
289        .into()
290    }
291}