use std::collections::HashMap;
use crate::Optimizer;
use crate::common::{zeros_entry, zip4_for_each};
#[derive(Debug, Clone)]
pub struct AdamW {
pub lr: f32,
pub beta1: f32,
pub beta2: f32,
pub eps: f32,
pub weight_decay: f32,
step: u64,
m: HashMap<String, Vec<f32>>,
v: HashMap<String, Vec<f32>>,
}
impl AdamW {
pub fn new(lr: f32) -> Self {
Self {
lr,
beta1: 0.9,
beta2: 0.999,
eps: 1e-8,
weight_decay: 0.01,
step: 0,
m: HashMap::new(),
v: 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
}
pub fn with_eps(mut self, eps: f32) -> Self {
self.eps = eps;
self
}
}
impl Optimizer for AdamW {
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 = 1.0 - b1.powf(t);
let bc2 = 1.0 - b2.powf(t);
let eps = self.eps as f64;
let lr = self.lr as f64;
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());
zip4_for_each(param, m, v, grad, |p, mi, vi, gi| {
let g = gi as f64;
let new_m = b1 * *mi as f64 + (1.0 - b1) * g;
let new_v = b2 * *vi as f64 + (1.0 - b2) * g * g;
*mi = new_m as f32;
*vi = new_v as f32;
let m_hat = new_m / bc1;
let v_hat = new_v / bc2;
let pf = *p as f64;
*p = (pf - lr * (m_hat / (v_hat.sqrt() + eps) + wd * pf)) as f32;
});
}
fn end_iteration(&mut self) {
self.step += 1;
}
}