#![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,
powers: Option<(V, V)>,
}
impl<V> Adam<V> {
pub const fn new(beta1: V, beta2: V, epsilon: V) -> Self {
Self {
beta1,
beta2,
epsilon,
timestep: 0,
powers: None,
}
}
pub fn timestep(&self) -> usize {
self.timestep
}
}
impl Default for Adam<crate::Q16_16> {
fn default() -> Self {
use crate::Q16_16;
Self::new(
Q16_16::from_raw(58_982),
Q16_16::from_raw(64_881),
Q16_16::from_raw(2_560),
)
}
}
impl Default for Adam<crate::Q8_8> {
fn default() -> Self {
use crate::Q8_8;
Self::new(
Q8_8::from_raw(230),
Q8_8::from_raw(253),
Q8_8::from_raw(160),
)
}
}
#[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 }
}
}
impl Default for RmsProp<crate::Q16_16> {
fn default() -> Self {
use crate::Q16_16;
Self::new(Q16_16::from_raw(58_982), Q16_16::from_raw(1))
}
}
impl Default for RmsProp<crate::Q8_8> {
fn default() -> Self {
use crate::Q8_8;
Self::new(Q8_8::from_raw(230), Q8_8::from_raw(1))
}
}
pub(crate) mod sealed {
use super::*;
pub trait OptimizerImpl<V> {
fn begin_step(&mut self);
fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>);
fn weight_decay(&self) -> Option<V> {
None
}
fn next_learning_rate(&mut self, rate: V) -> V {
rate
}
}
}
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_step(&mut self) {}
fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
update_connection(c, rates, clip);
}
}
#[inline(never)]
pub(crate) fn update_all<V: Copy, Opt: Optimizer<V>>(
optimizer: &Opt,
connections: &mut [Connection<V>],
rates: (V, V, V),
clip: Option<(V, V)>,
) {
for c in connections {
optimizer.update_weight(c, rates, clip);
}
}
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> Adam<V> {
fn compute_update(&self, c: &mut Connection<V>, gradient: V, lr: V) -> V {
let one = V::ONE;
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;
let (beta1_power, beta2_power) = self.powers.unwrap_or((one, one));
let beta1_correction = one - beta1_power;
let beta2_correction = one - beta2_power;
if beta1_correction > V::ZERO {
m_hat = m / beta1_correction;
}
if beta2_correction > V::ZERO {
v_hat = v / beta2_correction;
}
lr * m_hat / (v_hat.sqrt() + self.epsilon)
}
}
impl<V: Scalar + Sqrt> sealed::OptimizerImpl<V> for Adam<V> {
fn begin_step(&mut self) {
self.timestep = self.timestep.wrapping_add(1);
let (beta1_power, beta2_power) = self.powers.unwrap_or((V::ONE, V::ONE));
self.powers = Some((beta1_power * self.beta1, beta2_power * self.beta2));
}
fn update_weight(&self, c: &mut Connection<V>, (lr, _, _): (V, V, V), clip: Option<(V, V)>) {
let update = self.compute_update(c, clipped(c.gradient, clip), lr);
c.weight += update;
}
}
impl<V: Scalar + Sqrt> RmsProp<V> {
fn compute_update(&self, c: &mut Connection<V>, gradient: V, lr: V) -> V {
let v = self.decay * c.previous_delta_weight + (V::ONE - self.decay) * gradient * gradient;
c.previous_delta_weight = v;
lr * gradient / (v.sqrt() + self.epsilon)
}
}
impl<V: Scalar + Sqrt> sealed::OptimizerImpl<V> for RmsProp<V> {
fn begin_step(&mut self) {}
fn update_weight(&self, c: &mut Connection<V>, (lr, _, _): (V, V, V), clip: Option<(V, V)>) {
let update = self.compute_update(c, clipped(c.gradient, clip), lr);
c.weight += update;
}
}
#[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,
beta1_power: f64,
beta2_power: f64,
}
#[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,
beta1_power: 1.0,
beta2_power: 1.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 sqrt(x: f64) -> f64 {
x.sqrt()
}
}
#[cfg(all(feature = "libm", not(feature = "std")))]
mod float_math {
pub(super) fn sqrt(x: f64) -> f64 {
libm::sqrt(x)
}
}
#[cfg(any(feature = "std", feature = "libm"))]
trait FloatUpdate<T> {
fn compute_update_float(&self, c: &mut Connection<T>, gradient: T, lr: T) -> T;
}
#[cfg(any(feature = "std", feature = "libm"))]
macro_rules! impl_float_optimizers {
($t:ty) => {
impl FloatUpdate<$t> for AdamFloat {
fn compute_update_float(&self, c: &mut Connection<$t>, gradient: $t, lr: $t) -> $t {
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 mut m_hat = m;
let mut v_hat = v;
if self.timestep > 0 {
m_hat = m / ((1.0 - self.beta1_power) as $t);
v_hat = v / ((1.0 - self.beta2_power) as $t);
}
let sqrt_v = float_math::sqrt(f64::from(v_hat)) as $t;
lr * m_hat / (sqrt_v + self.epsilon as $t)
}
}
impl sealed::OptimizerImpl<$t> for AdamFloat {
fn begin_step(&mut self) {
self.timestep = self.timestep.wrapping_add(1);
self.beta1_power *= self.beta1;
self.beta2_power *= self.beta2;
}
fn update_weight(
&self,
c: &mut Connection<$t>,
(lr, _, _): ($t, $t, $t),
clip: Option<($t, $t)>,
) {
let update = self.compute_update_float(c, clipped(c.gradient, clip), lr);
c.weight += update;
}
}
impl FloatUpdate<$t> for RmsPropFloat {
fn compute_update_float(&self, c: &mut Connection<$t>, gradient: $t, lr: $t) -> $t {
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;
lr * gradient / (sqrt_v + self.epsilon as $t)
}
}
impl sealed::OptimizerImpl<$t> for RmsPropFloat {
fn begin_step(&mut self) {}
fn update_weight(
&self,
c: &mut Connection<$t>,
(lr, _, _): ($t, $t, $t),
clip: Option<($t, $t)>,
) {
let update = self.compute_update_float(c, clipped(c.gradient, clip), lr);
c.weight += update;
}
}
};
}
#[cfg(any(feature = "std", feature = "libm"))]
impl_float_optimizers!(f32);
#[cfg(any(feature = "std", feature = "libm"))]
impl_float_optimizers!(f64);
#[cfg(test)]
mod tests {
use super::*;
use crate::{Q8_8, Q16_16};
#[test]
fn defaults_are_tinymind_cpp_constants() {
let a = Adam::<Q16_16>::default();
assert_eq!(
(a.beta1.raw(), a.beta2.raw(), a.epsilon.raw()),
(58_982, 64_881, 2_560)
);
let a = Adam::<Q8_8>::default();
assert_eq!(
(a.beta1.raw(), a.beta2.raw(), a.epsilon.raw()),
(230, 253, 160)
);
let r = RmsProp::<Q16_16>::default();
assert_eq!((r.decay.raw(), r.epsilon.raw()), (58_982, 1));
let r = RmsProp::<Q8_8>::default();
assert_eq!((r.decay.raw(), r.epsilon.raw()), (230, 1));
}
}