torsh-optim 0.1.3

Optimization algorithms for ToRSh with PyTorch-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! LAMB (Large Batch Optimization for Deep Learning) optimizer implementation
//!
//! LAMB is an optimization algorithm designed for training deep neural networks
//! with large batch sizes. It adapts the learning rate both layer-wise and
//! element-wise, combining the benefits of LARS and Adam.
//!
//! Reference: "Large Batch Optimization for Deep Learning: Training BERT in 76 minutes"
//! <https://arxiv.org/abs/1904.00962>

use crate::{
    Optimizer, OptimizerError, OptimizerResult, OptimizerState, ParamGroup, ParamGroupState,
};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::ops::Add;
use std::sync::Arc;
use torsh_core::error::{Result, TorshError};
use torsh_tensor::Tensor;

/// LAMB optimizer
///
/// Combines layer-wise adaptation (LARS) with element-wise adaptation (Adam)
/// for training with very large batch sizes.
pub struct LAMB {
    param_groups: Vec<ParamGroup>,
    /// First moment estimates (momentum)
    exp_avg: HashMap<String, Tensor>,
    /// Second moment estimates (RMSprop-like)
    exp_avg_sq: HashMap<String, Tensor>,
    /// Step count for bias correction
    step_count: usize,
    /// Learning rate
    lr: f32,
    /// Exponential decay rate for first moment estimates
    beta1: f32,
    /// Exponential decay rate for second moment estimates  
    beta2: f32,
    /// Term added to denominator for numerical stability
    eps: f32,
    /// Weight decay coefficient
    weight_decay: f32,
    /// Whether to apply bias correction
    bias_correction: bool,
    /// Trust ratio threshold
    trust_ratio_threshold: f32,
}

impl LAMB {
    /// Create a new LAMB optimizer
    pub fn new(params: Vec<Arc<RwLock<Tensor>>>, lr: f32) -> Self {
        let param_group = ParamGroup::new(params, lr);
        Self {
            param_groups: vec![param_group],
            exp_avg: HashMap::new(),
            exp_avg_sq: HashMap::new(),
            step_count: 0,
            lr,
            beta1: 0.9,
            beta2: 0.999,
            eps: 1e-6,
            weight_decay: 0.01,
            bias_correction: true,
            trust_ratio_threshold: 1.0,
        }
    }

    /// Create LAMB with custom parameters
    #[allow(clippy::too_many_arguments)]
    pub fn with_params(
        params: Vec<Arc<RwLock<Tensor>>>,
        lr: f32,
        beta1: f32,
        beta2: f32,
        eps: f32,
        weight_decay: f32,
        bias_correction: bool,
    ) -> Self {
        let param_group = ParamGroup::new(params, lr);
        Self {
            param_groups: vec![param_group],
            exp_avg: HashMap::new(),
            exp_avg_sq: HashMap::new(),
            step_count: 0,
            lr,
            beta1,
            beta2,
            eps,
            weight_decay,
            bias_correction,
            trust_ratio_threshold: 1.0,
        }
    }

    /// Set trust ratio threshold
    pub fn set_trust_ratio_threshold(mut self, threshold: f32) -> Self {
        self.trust_ratio_threshold = threshold;
        self
    }

    /// Get parameter key for state storage
    fn get_param_key(param: &Tensor) -> Result<String> {
        // Bind data to a variable to extend lifetime before taking pointer
        let data = param.data()?;
        Ok(format!("param_{:p}", data.as_ptr()))
    }

    /// Compute layer-wise learning rate adaptation
    #[allow(dead_code)]
    fn compute_trust_ratio(&self, param: &Tensor, update: &Tensor) -> Result<f32> {
        Self::compute_trust_ratio_static(param, update, self.eps, self.trust_ratio_threshold)
    }

    /// Static version of compute_trust_ratio to avoid borrow checker issues
    fn compute_trust_ratio_static(
        param: &Tensor,
        update: &Tensor,
        eps: f32,
        trust_ratio_threshold: f32,
    ) -> Result<f32> {
        // Compute parameter norm
        let param_data = param.to_vec()?;
        let param_norm: f32 = param_data.iter().map(|&x| x * x).sum::<f32>().sqrt();

        // Compute update norm
        let update_data = update.to_vec()?;
        let update_norm: f32 = update_data.iter().map(|&x| x * x).sum::<f32>().sqrt();

        // Compute trust ratio
        let trust_ratio = if update_norm > eps && param_norm > eps {
            param_norm / update_norm
        } else {
            1.0
        };

        // Apply threshold
        Ok(trust_ratio.min(trust_ratio_threshold))
    }
}

impl Optimizer for LAMB {
    fn step(&mut self) -> OptimizerResult<()> {
        if self.param_groups.is_empty() {
            return Ok(());
        }

        self.step_count += 1;

        for group in &mut self.param_groups {
            let lr = group.lr;
            let weight_decay = group
                .options
                .get("weight_decay")
                .copied()
                .unwrap_or(self.weight_decay);

            for param_ref in &group.params {
                let param = param_ref.read();

                // Skip parameters without gradients
                let grad = match param.grad() {
                    Some(g) => g,
                    None => continue,
                };

                let param_key = Self::get_param_key(&param)?;

                // Initialize state if needed
                if !self.exp_avg.contains_key(&param_key) {
                    self.exp_avg.insert(
                        param_key.clone(),
                        torsh_tensor::creation::zeros_like(&param)?,
                    );
                    self.exp_avg_sq.insert(
                        param_key.clone(),
                        torsh_tensor::creation::zeros_like(&param)?,
                    );
                }

                // Get momentum states
                let exp_avg = self
                    .exp_avg
                    .get_mut(&param_key)
                    .expect("exp_avg state should exist");
                let exp_avg_sq = self
                    .exp_avg_sq
                    .get_mut(&param_key)
                    .expect("exp_avg_sq state should exist");

                // Add weight decay to gradient
                let grad_with_decay = if weight_decay != 0.0 {
                    grad.add(&param.mul_scalar(weight_decay)?)?
                } else {
                    grad.clone()
                };

                // Update first moment estimate (exponential moving average of gradient)
                *exp_avg = exp_avg
                    .mul_scalar(self.beta1)?
                    .add(&grad_with_decay.mul_scalar(1.0 - self.beta1)?)?;

                // Update second moment estimate (exponential moving average of squared gradient)
                let grad_sq = grad_with_decay.mul_op(&grad_with_decay)?;
                *exp_avg_sq = exp_avg_sq
                    .mul_scalar(self.beta2)?
                    .add(&grad_sq.mul_scalar(1.0 - self.beta2)?)?;

                // Bias correction
                let (corrected_exp_avg, corrected_exp_avg_sq) = if self.bias_correction {
                    let bias_correction1 = 1.0 - self.beta1.powi(self.step_count as i32);
                    let bias_correction2 = 1.0 - self.beta2.powi(self.step_count as i32);
                    (
                        exp_avg.div_scalar(bias_correction1)?,
                        exp_avg_sq.div_scalar(bias_correction2)?,
                    )
                } else {
                    (exp_avg.clone(), exp_avg_sq.clone())
                };

                // Compute Adam-like update
                let sqrt_v = corrected_exp_avg_sq.sqrt()?;
                let adam_update = corrected_exp_avg.div(&sqrt_v.add_scalar(self.eps)?)?;

                // Compute trust ratio (layer-wise adaptation)
                let trust_ratio = Self::compute_trust_ratio_static(
                    &param,
                    &adam_update,
                    self.eps,
                    self.trust_ratio_threshold,
                )?;

                // Apply LAMB update with trust ratio
                let lamb_lr = lr * trust_ratio;
                let update = adam_update.mul_scalar(lamb_lr)?;

                // Update parameters (in-place)
                drop(param); // Release read lock
                let mut param_mut = param_ref.write();
                *param_mut = param_mut.sub(&update)?;
            }
        }

        Ok(())
    }

    fn zero_grad(&mut self) {
        for group in &mut self.param_groups {
            for param_ref in &group.params {
                let mut param = param_ref.write();
                param.zero_grad();
            }
        }
    }

    fn get_lr(&self) -> Vec<f32> {
        self.param_groups.iter().map(|group| group.lr).collect()
    }

    fn set_lr(&mut self, lr: f32) {
        self.lr = lr;
        for group in &mut self.param_groups {
            group.lr = lr;
        }
    }

    fn add_param_group(&mut self, params: Vec<Arc<RwLock<Tensor>>>, options: HashMap<String, f32>) {
        let lr = options.get("lr").copied().unwrap_or(self.lr);
        let param_group = ParamGroup::new(params, lr).with_options(options);
        self.param_groups.push(param_group);
    }

    fn parameters(&self) -> Vec<Arc<RwLock<Tensor>>> {
        crate::optimizer::collect_parameters(&self.param_groups)
    }

    fn state_dict(&self) -> OptimizerResult<OptimizerState> {
        let param_groups: Vec<ParamGroupState> = self
            .param_groups
            .iter()
            .map(|group| ParamGroupState {
                lr: group.lr,
                options: group.options.clone(),
                param_count: group.params.len(),
            })
            .collect();

        let mut state = HashMap::new();

        // Save momentum states
        for (key, tensor) in &self.exp_avg {
            let mut param_state = HashMap::new();
            param_state.insert("exp_avg".to_string(), tensor.clone());
            state.insert(format!("{}_exp_avg", key), param_state);
        }

        for (key, tensor) in &self.exp_avg_sq {
            let mut param_state = HashMap::new();
            param_state.insert("exp_avg_sq".to_string(), tensor.clone());
            state.insert(format!("{}_exp_avg_sq", key), param_state);
        }

        let mut global_state = HashMap::new();
        global_state.insert("beta1".to_string(), self.beta1);
        global_state.insert("beta2".to_string(), self.beta2);
        global_state.insert("eps".to_string(), self.eps);
        global_state.insert("weight_decay".to_string(), self.weight_decay);
        global_state.insert("step_count".to_string(), self.step_count as f32);

        Ok(OptimizerState {
            optimizer_type: "LAMB".to_string(),
            version: "1.0".to_string(),
            param_groups,
            state,
            global_state,
        })
    }

    fn load_state_dict(&mut self, state: OptimizerState) -> OptimizerResult<()> {
        // Restore parameter groups
        if state.param_groups.len() != self.param_groups.len() {
            return Err(OptimizerError::TensorError(TorshError::InvalidArgument(
                "Mismatch in number of parameter groups".to_string(),
            )));
        }

        for (i, group_state) in state.param_groups.iter().enumerate() {
            self.param_groups[i].lr = group_state.lr;
            self.param_groups[i].options = group_state.options.clone();
        }

        // Restore optimizer state
        self.exp_avg.clear();
        self.exp_avg_sq.clear();

        for (key, param_state) in state.state {
            if key.ends_with("_exp_avg") {
                if let Some(tensor) = param_state.get("exp_avg") {
                    let param_key = key
                        .strip_suffix("_exp_avg")
                        .expect("suffix should exist after ends_with check")
                        .to_string();
                    self.exp_avg.insert(param_key, tensor.clone());
                }
            } else if key.ends_with("_exp_avg_sq") {
                if let Some(tensor) = param_state.get("exp_avg_sq") {
                    let param_key = key
                        .strip_suffix("_exp_avg_sq")
                        .expect("suffix should exist after ends_with check")
                        .to_string();
                    self.exp_avg_sq.insert(param_key, tensor.clone());
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use parking_lot::RwLock;
    use std::sync::Arc;
    use torsh_tensor::creation::{ones, zeros};

    #[test]
    fn test_lamb_creation() {
        let param = Arc::new(RwLock::new(ones(&[2, 3]).unwrap()));
        let optimizer = LAMB::new(vec![param], 0.001);

        assert_eq!(optimizer.lr, 0.001);
        assert_eq!(optimizer.beta1, 0.9);
        assert_eq!(optimizer.beta2, 0.999);
        assert_eq!(optimizer.eps, 1e-6);
        assert_eq!(optimizer.weight_decay, 0.01);
    }

    #[test]
    fn test_lamb_with_params() {
        let param = Arc::new(RwLock::new(ones(&[2, 3]).unwrap()));
        let optimizer = LAMB::with_params(vec![param], 0.002, 0.95, 0.9999, 1e-7, 0.02, false);

        assert_eq!(optimizer.lr, 0.002);
        assert_eq!(optimizer.beta1, 0.95);
        assert_eq!(optimizer.beta2, 0.9999);
        assert_eq!(optimizer.eps, 1e-7);
        assert_eq!(optimizer.weight_decay, 0.02);
        assert!(!optimizer.bias_correction);
    }

    #[test]
    fn test_lamb_step() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(ones(&[2, 2]).unwrap()));

        // Set a gradient
        {
            let mut p = param.write();
            let grad = ones(&[2, 2]).unwrap().mul_scalar(0.1).unwrap();
            p.set_grad(Some(grad));
        }

        let mut optimizer = LAMB::new(vec![param.clone()], 0.01);

        optimizer.step()?;
        assert_eq!(optimizer.step_count, 1);

        Ok(())
    }

    #[test]
    fn test_lamb_zero_grad() {
        let param = Arc::new(RwLock::new(ones(&[2, 2]).unwrap()));

        // Set a gradient
        {
            let mut p = param.write();
            let grad = ones(&[2, 2]).unwrap();
            p.set_grad(Some(grad));
            assert!(p.grad().is_some());
        }

        let mut optimizer = LAMB::new(vec![param.clone()], 0.01);
        optimizer.zero_grad();

        // Check gradient is cleared
        let p = param.read();
        assert!(p.grad().is_none());
    }

    #[test]
    fn test_lamb_lr_operations() {
        let param = Arc::new(RwLock::new(ones(&[2, 2]).unwrap()));
        let mut optimizer = LAMB::new(vec![param], 0.01);

        assert_eq!(optimizer.get_lr(), vec![0.01]);

        optimizer.set_lr(0.02);
        assert_eq!(optimizer.get_lr(), vec![0.02]);
        assert_eq!(optimizer.lr, 0.02);
    }

    #[test]
    fn test_lamb_trust_ratio() {
        let param = Arc::new(RwLock::new(ones(&[2, 2]).unwrap()));
        let optimizer = LAMB::new(vec![param.clone()], 0.01);

        let param_tensor = param.read();
        let update = zeros(&[2, 2]).unwrap();

        let trust_ratio = optimizer
            .compute_trust_ratio(&param_tensor, &update)
            .unwrap();
        assert!(trust_ratio >= 0.0);

        // When update norm is 0, trust ratio should be 1.0
        assert_eq!(trust_ratio, 1.0);
    }

    #[test]
    fn test_lamb_param_group() {
        let param1 = Arc::new(RwLock::new(ones(&[2, 2]).unwrap()));
        let param2 = Arc::new(RwLock::new(ones(&[3, 3]).unwrap()));

        let mut optimizer = LAMB::new(vec![param1], 0.01);

        let mut options = HashMap::new();
        options.insert("lr".to_string(), 0.02);
        options.insert("weight_decay".to_string(), 0.05);

        optimizer.add_param_group(vec![param2], options);

        assert_eq!(optimizer.param_groups.len(), 2);
        assert_eq!(optimizer.param_groups[1].lr, 0.02);
        assert_eq!(
            optimizer.param_groups[1].options.get("weight_decay"),
            Some(&0.05)
        );
    }

    #[test]
    fn test_lamb_state_dict() -> OptimizerResult<()> {
        let param = Arc::new(RwLock::new(ones(&[2, 2]).unwrap()));
        let optimizer = LAMB::new(vec![param], 0.01);

        let state = optimizer.state_dict()?;
        assert_eq!(state.param_groups.len(), 1);
        assert_eq!(state.param_groups[0].lr, 0.01);

        Ok(())
    }
}