use std::collections::HashMap;
use crate::Optimizer;
use crate::common::{l2_norm, zeros_entry};
#[derive(Debug, Clone)]
pub struct Lamb {
pub lr: f32,
pub beta1: f32,
pub beta2: f32,
pub eps: f32,
pub weight_decay: f32,
pub bias_correction: bool,
step: u64,
m: HashMap<String, Vec<f32>>,
v: HashMap<String, Vec<f32>>,
scratch: HashMap<String, Vec<f32>>,
}
impl Lamb {
pub fn new(lr: f32) -> Self {
Self {
lr,
beta1: 0.9,
beta2: 0.999,
eps: 1e-6,
weight_decay: 0.01,
bias_correction: true,
step: 0,
m: HashMap::new(),
v: HashMap::new(),
scratch: HashMap::new(),
}
}
pub fn with_betas(mut self, b1: f32, b2: f32) -> Self {
self.beta1 = b1;
self.beta2 = b2;
self
}
pub fn with_weight_decay(mut self, wd: f32) -> Self {
self.weight_decay = wd;
self
}
}
impl Optimizer for Lamb {
fn step(&mut self, name: &str, _shape: &[usize], param: &mut [f32], grad: &[f32]) {
debug_assert_eq!(param.len(), grad.len());
let t = (self.step + 1) as f64;
let b1 = self.beta1 as f64;
let b2 = self.beta2 as f64;
let (bc1, bc2) = if self.bias_correction {
(1.0 - b1.powf(t), 1.0 - b2.powf(t))
} else {
(1.0, 1.0)
};
let eps = self.eps as f64;
let lr = self.lr;
let wd = self.weight_decay as f64;
let m = zeros_entry(&mut self.m, name, param.len());
let v = zeros_entry(&mut self.v, name, param.len());
let update = zeros_entry(&mut self.scratch, name, param.len());
for i in 0..param.len() {
let g = grad[i] as f64;
let mi = b1 * m[i] as f64 + (1.0 - b1) * g;
let vi = b2 * v[i] as f64 + (1.0 - b2) * g * g;
m[i] = mi as f32;
v[i] = vi as f32;
let m_hat = mi / bc1;
let v_hat = vi / bc2;
update[i] = (m_hat / (v_hat.sqrt() + eps) + wd * param[i] as f64) as f32;
}
let w_norm = l2_norm(param);
let r_norm = l2_norm(update);
let trust = if w_norm > 0.0 && r_norm > 0.0 {
w_norm / r_norm
} else {
1.0
};
let step_size = lr * trust;
for i in 0..param.len() {
param[i] -= step_size * update[i];
}
}
fn end_iteration(&mut self) {
self.step += 1;
}
}