use super::{clip_grad_norm, Optimizer};
use crate::tensor::{no_grad, Tensor};
pub struct AdamW {
params: Vec<Tensor>,
lr: f32,
beta1: f32,
beta2: f32,
eps: f32,
weight_decay: f32,
t: usize,
max_grad_norm: Option<f32>,
moments: Vec<Option<(Tensor, Tensor)>>,
}
impl AdamW {
pub fn new(params: Vec<Tensor>, lr: f32) -> Self {
Self::with_params(params, lr, 0.9, 0.999, 1e-8, 0.01)
}
pub fn with_params(
params: Vec<Tensor>,
lr: f32,
beta1: f32,
beta2: f32,
eps: f32,
weight_decay: f32,
) -> Self {
let num_params = params.len();
Self {
params,
lr,
beta1,
beta2,
eps,
weight_decay,
t: 0,
max_grad_norm: None,
moments: vec![None; num_params],
}
}
pub fn weight_decay(mut self, wd: f32) -> Self {
self.weight_decay = wd;
self
}
pub fn beta1(mut self, beta1: f32) -> Self {
self.beta1 = beta1;
self
}
pub fn beta2(mut self, beta2: f32) -> Self {
self.beta2 = beta2;
self
}
pub fn eps(mut self, eps: f32) -> Self {
self.eps = eps;
self
}
pub fn clip_grad_norm(mut self, max_norm: f32) -> Self {
self.max_grad_norm = Some(max_norm);
self
}
pub fn steps(&self) -> usize {
self.t
}
pub fn params(&self) -> &[Tensor] {
&self.params
}
}
impl Optimizer for AdamW {
fn step(&mut self) {
if let Some(max_norm) = self.max_grad_norm {
clip_grad_norm(&self.params, max_norm);
}
self.t += 1;
let t = self.t as i32;
let bias1 = 1.0 - self.beta1.powi(t);
let bias2 = 1.0 - self.beta2.powi(t);
no_grad(|| {
for (param, moments) in self.params.iter().zip(&mut self.moments) {
let Some(g) = param.grad() else { continue };
let (m, v) = moments
.take()
.unwrap_or_else(|| (param.zeros_like(), param.zeros_like()));
let m = m
.mul_scalar(self.beta1)
.add(&g.mul_scalar(1.0 - self.beta1));
let v = v
.mul_scalar(self.beta2)
.add(&g.square().mul_scalar(1.0 - self.beta2));
let denom = v.div_scalar(bias2).sqrt().add_scalar(self.eps);
let update = m.div_scalar(bias1).div(&denom).mul_scalar(self.lr);
let decayed = param.mul_scalar(1.0 - self.lr * self.weight_decay);
param.assign(&decayed.sub(&update));
*moments = Some((m, v));
}
});
}
fn zero_grad(&self) {
for param in &self.params {
param.zero_grad();
}
}
fn lr(&self) -> f32 {
self.lr
}
fn set_lr(&mut self, lr: f32) {
self.lr = lr;
}
}
impl std::fmt::Debug for AdamW {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AdamW")
.field("lr", &self.lr)
.field("beta1", &self.beta1)
.field("beta2", &self.beta2)
.field("eps", &self.eps)
.field("weight_decay", &self.weight_decay)
.field("t", &self.t)
.field("num_params", &self.params.len())
.finish()
}
}