use std::collections::HashMap;
use crate::Optimizer;
use crate::common::zeros_entry;
#[derive(Debug, Clone)]
pub struct QHAdamW {
pub lr: f32,
pub beta1: f32,
pub beta2: f32,
pub nu1: f32,
pub nu2: f32,
pub eps: f32,
pub weight_decay: f32,
step: u64,
m: HashMap<String, Vec<f32>>,
v: HashMap<String, Vec<f32>>,
}
impl QHAdamW {
pub fn new(lr: f32) -> Self {
Self {
lr,
beta1: 0.995,
beta2: 0.999,
nu1: 0.7,
nu2: 1.0,
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_nus(mut self, n1: f32, n2: f32) -> Self {
self.nu1 = n1;
self.nu2 = n2;
self
}
pub fn with_weight_decay(mut self, wd: f32) -> Self {
self.weight_decay = wd;
self
}
}
impl Optimizer for QHAdamW {
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 n1 = self.nu1 as f64;
let n2 = self.nu2 as f64;
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());
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;
let num = (1.0 - n1) * g + n1 * m_hat;
let den = ((1.0 - n2) * g * g + n2 * v_hat).sqrt() + eps;
let p = param[i] as f64;
param[i] = (p - lr * (num / den + wd * p)) as f32;
}
}
fn end_iteration(&mut self) {
self.step += 1;
}
}