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#[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: Option<WeightDecayConfig>,
25 grad_clipping: Option<GradientClippingConfig>,
27}
28
29#[derive(Clone)]
31pub struct AdaGrad {
32 lr_decay: LrDecay,
33 weight_decay: Option<WeightDecay>,
34}
35
36#[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 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 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#[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 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 crate::optim::test_utils::assert_optimizer_resume;
163 use burn::tensor::Tolerance;
164
165 use super::*;
166 use crate::GradientsParams;
167 use burn::module::Param;
168 use burn::tensor::{Tensor, TensorData};
169 use burn_nn::{Linear, LinearConfig};
170
171 const LEARNING_RATE: LearningRate = 0.01;
172
173 #[test]
174 fn test_adagrad_optimizer_save_load_state() {
175 let device = Device::default().autodiff();
176 let linear = LinearConfig::new(6, 6).init(&device);
177 assert_optimizer_resume(
178 || AdaGradConfig::new().with_lr_decay(0.1).init(),
179 linear,
180 LEARNING_RATE,
181 );
182 }
183
184 #[test]
185 fn test_adagrad_optimizer_with_numbers() {
186 let device = Device::default().autodiff();
187 let linear = given_linear_layer(
188 TensorData::from([
189 [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
190 [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
191 [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
192 [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
193 [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
194 [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
195 ]),
196 TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
197 &device,
198 );
199 let x_1 = Tensor::<2>::from_floats(
200 [
201 [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
202 [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
203 ],
204 &device,
205 )
206 .require_grad();
207 let x_2 = Tensor::<2>::from_floats(
208 [
209 [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
210 [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
211 ],
212 &device,
213 )
214 .require_grad();
215
216 let mut optimizer = AdaGradConfig::new()
217 .with_epsilon(1e-8)
218 .with_lr_decay(0.5)
219 .init();
220
221 let grads = linear.forward(x_1).backward();
222 let grads = GradientsParams::from_grads(grads, &linear);
223 let linear = optimizer.step(LEARNING_RATE, linear, grads);
224
225 let grads = linear.forward(x_2).backward();
226 let grads = GradientsParams::from_grads(grads, &linear);
227 let linear = optimizer.step(LEARNING_RATE, linear, grads);
228
229 let state_updated = linear;
230 let weights_expected = TensorData::from([
231 [-0.334989, 0.123011, 0.389911, 0.305611, 0.071511, 0.052711],
232 [
233 0.066144, -0.030056, -0.378256, 0.243444, 0.183944, -0.303756,
234 ],
235 [
236 -0.033462, 0.020138, -0.310662, 0.233938, -0.292462, 0.298538,
237 ],
238 [
239 -0.312636, -0.236036, -0.386136, -0.312736, -0.090736, 0.147964,
240 ],
241 [
242 0.315896, -0.232304, 0.357596, -0.187004, 0.365496, -0.044504,
243 ],
244 [-0.030305, -0.026405, 0.111395, 0.177695, 0.014895, 0.368895],
245 ]);
246 let bias_expected = TensorData::from([
247 -0.405214, 0.073686, -0.111714, 0.102886, 0.121886, -0.001714,
248 ]);
249
250 let (weight_updated, bias_updated) = (
251 state_updated.weight.val().into_data(),
252 state_updated.bias.unwrap().val().into_data(),
253 );
254
255 let tolerance = Tolerance::absolute(1e-6);
256 bias_updated.assert_approx_eq::<f32>(&bias_expected, tolerance);
257 weight_updated.assert_approx_eq::<f32>(&weights_expected, tolerance);
258 }
259
260 fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
261 Linear {
262 weight: Param::from_data(weight, device),
263 bias: Some(Param::from_data(bias, device)),
264 }
265 }
266}