#![allow(private_interfaces)]
use crate::neuralnet::{Connection, clip_gradient, update_connection};
use crate::qformat::{Scalar, Sqrt};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Sgd;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Adam<V> {
pub beta1: V,
pub beta2: V,
pub epsilon: V,
timestep: usize,
}
impl<V> Adam<V> {
pub const fn new(beta1: V, beta2: V, epsilon: V) -> Self {
Self {
beta1,
beta2,
epsilon,
timestep: 0,
}
}
pub fn timestep(&self) -> usize {
self.timestep
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RmsProp<V> {
pub decay: V,
pub epsilon: V,
}
impl<V> RmsProp<V> {
pub const fn new(decay: V, epsilon: V) -> Self {
Self { decay, epsilon }
}
}
mod sealed {
use super::*;
pub trait OptimizerImpl<V> {
fn begin_layer(&mut self);
fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>);
fn update_bias(&self, c: &mut Connection<V>, rates: (V, V, V));
}
}
pub trait Optimizer<V>: sealed::OptimizerImpl<V> {}
impl<V, T: sealed::OptimizerImpl<V>> Optimizer<V> for T {}
impl<V: Scalar> sealed::OptimizerImpl<V> for Sgd {
fn begin_layer(&mut self) {}
fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
update_connection(c, rates, clip);
}
fn update_bias(&self, c: &mut Connection<V>, rates: (V, V, V)) {
update_connection(c, rates, None);
}
}
fn clipped<V: Scalar>(gradient: V, clip: Option<(V, V)>) -> V {
match clip {
Some(range) => clip_gradient(gradient, range),
None => gradient,
}
}
impl<V: Scalar + Sqrt> sealed::OptimizerImpl<V> for Adam<V> {
fn begin_layer(&mut self) {
self.timestep = self.timestep.wrapping_add(1);
}
fn update_weight(&self, c: &mut Connection<V>, (lr, _, _): (V, V, V), clip: Option<(V, V)>) {
let one = V::ONE;
let gradient = clipped(c.gradient, clip);
let m = self.beta1 * c.delta_weight + (one - self.beta1) * gradient;
let v = self.beta2 * c.previous_delta_weight + (one - self.beta2) * gradient * gradient;
c.delta_weight = m;
c.previous_delta_weight = v;
let mut m_hat = m;
let mut v_hat = v;
if self.timestep < 100 {
let mut beta1_power = one;
let mut beta2_power = one;
for _ in 0..self.timestep {
beta1_power = beta1_power * self.beta1;
beta2_power = beta2_power * self.beta2;
}
let beta1_correction = one - beta1_power;
let beta2_correction = one - beta2_power;
if beta1_correction > self.epsilon {
m_hat = m / beta1_correction;
}
if beta2_correction > self.epsilon {
v_hat = v / beta2_correction;
}
}
let update = lr * m_hat / (v_hat.sqrt() + self.epsilon);
c.weight += update;
}
fn update_bias(&self, _c: &mut Connection<V>, _rates: (V, V, V)) {}
}
impl<V: Scalar + Sqrt> sealed::OptimizerImpl<V> for RmsProp<V> {
fn begin_layer(&mut self) {}
fn update_weight(&self, c: &mut Connection<V>, (lr, _, _): (V, V, V), clip: Option<(V, V)>) {
let gradient = clipped(c.gradient, clip);
let v = self.decay * c.previous_delta_weight + (V::ONE - self.decay) * gradient * gradient;
c.previous_delta_weight = v;
let update = lr * gradient / (v.sqrt() + self.epsilon);
c.weight += update;
}
fn update_bias(&self, _c: &mut Connection<V>, _rates: (V, V, V)) {}
}
#[cfg(any(feature = "std", feature = "libm"))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AdamFloat {
pub beta1: f64,
pub beta2: f64,
pub epsilon: f64,
timestep: usize,
}
#[cfg(any(feature = "std", feature = "libm"))]
impl Default for AdamFloat {
fn default() -> Self {
Self::new(0.9, 0.999, 1e-8)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl AdamFloat {
pub const fn new(beta1: f64, beta2: f64, epsilon: f64) -> Self {
Self {
beta1,
beta2,
epsilon,
timestep: 0,
}
}
pub fn timestep(&self) -> usize {
self.timestep
}
}
#[cfg(any(feature = "std", feature = "libm"))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RmsPropFloat {
pub decay: f64,
pub epsilon: f64,
}
#[cfg(any(feature = "std", feature = "libm"))]
impl Default for RmsPropFloat {
fn default() -> Self {
Self::new(0.9, 1e-8)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
impl RmsPropFloat {
pub const fn new(decay: f64, epsilon: f64) -> Self {
Self { decay, epsilon }
}
}
#[cfg(feature = "std")]
mod float_math {
pub(super) fn pow(x: f64, y: f64) -> f64 {
x.powf(y)
}
pub(super) fn sqrt(x: f64) -> f64 {
x.sqrt()
}
}
#[cfg(all(feature = "libm", not(feature = "std")))]
mod float_math {
pub(super) fn pow(x: f64, y: f64) -> f64 {
libm::pow(x, y)
}
pub(super) fn sqrt(x: f64) -> f64 {
libm::sqrt(x)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
macro_rules! impl_float_optimizers {
($t:ty) => {
impl sealed::OptimizerImpl<$t> for AdamFloat {
fn begin_layer(&mut self) {
self.timestep = self.timestep.wrapping_add(1);
}
fn update_weight(
&self,
c: &mut Connection<$t>,
(lr, _, _): ($t, $t, $t),
clip: Option<($t, $t)>,
) {
let gradient = clipped(c.gradient, clip);
let m = (self.beta1 as $t) * c.delta_weight + ((1.0 - self.beta1) as $t) * gradient;
let v = (self.beta2 as $t) * c.previous_delta_weight
+ ((1.0 - self.beta2) as $t) * gradient * gradient;
c.delta_weight = m;
c.previous_delta_weight = v;
let t = self.timestep as f64;
let beta1_power = float_math::pow(self.beta1, t);
let beta2_power = float_math::pow(self.beta2, t);
let m_hat = m / ((1.0 - beta1_power) as $t);
let v_hat = v / ((1.0 - beta2_power) as $t);
let sqrt_v = float_math::sqrt(f64::from(v_hat)) as $t;
let update = lr * m_hat / (sqrt_v + self.epsilon as $t);
c.weight += update;
}
fn update_bias(&self, _c: &mut Connection<$t>, _rates: ($t, $t, $t)) {}
}
impl sealed::OptimizerImpl<$t> for RmsPropFloat {
fn begin_layer(&mut self) {}
fn update_weight(
&self,
c: &mut Connection<$t>,
(lr, _, _): ($t, $t, $t),
clip: Option<($t, $t)>,
) {
let gradient = clipped(c.gradient, clip);
let v = (self.decay as $t) * c.previous_delta_weight
+ ((1.0 - self.decay) as $t) * gradient * gradient;
c.previous_delta_weight = v;
let sqrt_v = float_math::sqrt(f64::from(v)) as $t;
let update = lr * gradient / (sqrt_v + self.epsilon as $t);
c.weight += update;
}
fn update_bias(&self, _c: &mut Connection<$t>, _rates: ($t, $t, $t)) {}
}
};
}
#[cfg(any(feature = "std", feature = "libm"))]
impl_float_optimizers!(f32);
#[cfg(any(feature = "std", feature = "libm"))]
impl_float_optimizers!(f64);