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(crate) fn build(&self) -> AdaGrad {
78 AdaGrad {
79 lr_decay: LrDecay {
80 lr_decay: self.lr_decay,
81 epsilon: self.epsilon,
82 },
83 weight_decay: self.weight_decay.as_ref().map(WeightDecay::new),
84 }
85 }
86
87 pub fn init(&self) -> ModuleOptimizer {
93 let mut optim = ModuleOptimizer::from(self.build());
94 if let Some(config) = &self.grad_clipping {
95 optim = optim.with_grad_clipping(config.init());
96 }
97 optim
98 }
99}
100
101#[derive(RecordState, new, Clone)]
103pub struct LrDecayState<const D: usize> {
104 time: usize,
105 sum: Tensor<D>,
106}
107
108#[derive(Clone)]
109struct LrDecay {
110 lr_decay: f64,
111 epsilon: f32,
112}
113
114impl LrDecay {
115 pub fn transform<const D: usize>(
116 &self,
117 grad: Tensor<D>,
118 lr: LearningRate,
119 lr_decay_state: Option<LrDecayState<D>>,
120 ) -> (Tensor<D>, LrDecayState<D>) {
121 let state = if let Some(mut state) = lr_decay_state {
122 state.sum = state.sum.add(grad.clone().square());
123 state.time += 1;
124 state
125 } else {
126 LrDecayState::new(1, grad.clone().square())
127 };
128
129 let new_lr = lr / (1. + (state.time as f64 - 1.) * self.lr_decay);
130
131 let grad = grad
132 .div(state.sum.clone().sqrt().add_scalar(self.epsilon))
133 .mul_scalar(new_lr);
134
135 (grad, state)
136 }
137}
138
139impl<const D: usize> LrDecayState<D> {
140 pub fn to_device(mut self, device: &Device) -> Self {
150 self.sum = self.sum.to_device(device);
151 self
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use burn::tensor::Tolerance;
158
159 use super::*;
160 use crate::GradientsParams;
161 use burn::module::Param;
162 use burn::tensor::{Distribution, Tensor, TensorData};
163 use burn_nn::{Linear, LinearConfig};
164
165 const LEARNING_RATE: LearningRate = 0.01;
166
167 #[test]
168 fn test_adagrad_optimizer_save_load_state() {
169 let device = Device::default().autodiff();
170 let linear = LinearConfig::new(6, 6).init(&device);
171 let x = Tensor::<2>::random([2, 6], Distribution::Default, &device);
172 let mut optimizer = create_adagrad();
173 let grads = linear.forward(x).backward();
174 let grads = GradientsParams::from_grads(grads, &linear);
175 let _linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
176
177 let bytes = optimizer.into_bytes().unwrap();
178 assert!(!bytes.is_empty());
179
180 #[cfg(feature = "std")]
181 optimizer
182 .save(std::env::temp_dir().as_path().join("test_optim_adagrad"))
183 .unwrap();
184
185 let state_optim_before = optimizer.to_record();
186 let optimizer = create_adagrad().from_bytes(bytes).unwrap();
187 let state_optim_after = optimizer.to_record();
188
189 assert_eq!(state_optim_before.len(), state_optim_after.len());
190 }
191
192 #[test]
193 fn test_adagrad_optimizer_with_numbers() {
194 let device = Device::default().autodiff();
195 let linear = given_linear_layer(
196 TensorData::from([
197 [-0.3206, 0.1374, 0.4043, 0.3200, 0.0859, 0.0671],
198 [0.0777, -0.0185, -0.3667, 0.2550, 0.1955, -0.2922],
199 [-0.0190, 0.0346, -0.2962, 0.2484, -0.2780, 0.3130],
200 [-0.2980, -0.2214, -0.3715, -0.2981, -0.0761, 0.1626],
201 [0.3300, -0.2182, 0.3717, -0.1729, 0.3796, -0.0304],
202 [-0.0159, -0.0120, 0.1258, 0.1921, 0.0293, 0.3833],
203 ]),
204 TensorData::from([-0.3905, 0.0884, -0.0970, 0.1176, 0.1366, 0.0130]),
205 &device,
206 );
207 let x_1 = Tensor::<2>::from_floats(
208 [
209 [0.6294, 0.0940, 0.8176, 0.8824, 0.5228, 0.4310],
210 [0.7152, 0.9559, 0.7893, 0.5684, 0.5939, 0.8883],
211 ],
212 &device,
213 )
214 .require_grad();
215 let x_2 = Tensor::<2>::from_floats(
216 [
217 [0.8491, 0.2108, 0.8939, 0.4433, 0.5527, 0.2528],
218 [0.3270, 0.0412, 0.5538, 0.9605, 0.3195, 0.9085],
219 ],
220 &device,
221 )
222 .require_grad();
223
224 let mut optimizer = AdaGradConfig::new()
225 .with_epsilon(1e-8)
226 .with_lr_decay(0.5)
227 .init();
228
229 let grads = linear.forward(x_1).backward();
230 let grads = GradientsParams::from_grads(grads, &linear);
231 let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
232
233 let grads = linear.forward(x_2).backward();
234 let grads = GradientsParams::from_grads(grads, &linear);
235 let linear = optimizer.step(LEARNING_RATE.into(), linear, grads);
236
237 let state_updated = linear;
238 let weights_expected = TensorData::from([
239 [-0.334989, 0.123011, 0.389911, 0.305611, 0.071511, 0.052711],
240 [
241 0.066144, -0.030056, -0.378256, 0.243444, 0.183944, -0.303756,
242 ],
243 [
244 -0.033462, 0.020138, -0.310662, 0.233938, -0.292462, 0.298538,
245 ],
246 [
247 -0.312636, -0.236036, -0.386136, -0.312736, -0.090736, 0.147964,
248 ],
249 [
250 0.315896, -0.232304, 0.357596, -0.187004, 0.365496, -0.044504,
251 ],
252 [-0.030305, -0.026405, 0.111395, 0.177695, 0.014895, 0.368895],
253 ]);
254 let bias_expected = TensorData::from([
255 -0.405214, 0.073686, -0.111714, 0.102886, 0.121886, -0.001714,
256 ]);
257
258 let (weight_updated, bias_updated) = (
259 state_updated.weight.val().into_data(),
260 state_updated.bias.unwrap().val().into_data(),
261 );
262
263 let tolerance = Tolerance::absolute(1e-6);
264 bias_updated.assert_approx_eq::<f32>(&bias_expected, tolerance);
265 weight_updated.assert_approx_eq::<f32>(&weights_expected, tolerance);
266 }
267
268 fn given_linear_layer(weight: TensorData, bias: TensorData, device: &Device) -> Linear {
269 Linear {
270 weight: Param::from_data(weight, device),
271 bias: Some(Param::from_data(bias, device)),
272 }
273 }
274
275 fn create_adagrad() -> ModuleOptimizer {
276 let config = AdaGradConfig::new();
277 AdaGrad {
278 lr_decay: LrDecay {
279 lr_decay: config.lr_decay,
280 epsilon: config.epsilon,
281 },
282 weight_decay: config.weight_decay.as_ref().map(WeightDecay::new),
283 }
284 .into()
285 }
286}