#![allow(private_interfaces)]
use crate::neuralnet::Connection;
use crate::optimizer::sealed::OptimizerImpl;
use crate::qformat::Scalar;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WeightDecay<Opt, V> {
pub optimizer: Opt,
pub lambda: V,
}
impl<Opt, V> WeightDecay<Opt, V> {
pub const fn new(optimizer: Opt, lambda: V) -> Self {
Self { optimizer, lambda }
}
}
impl<V: Scalar, Opt: OptimizerImpl<V>> OptimizerImpl<V> for WeightDecay<Opt, V> {
fn begin_step(&mut self) {
self.optimizer.begin_step();
}
fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
self.optimizer.update_weight(c, rates, clip);
}
fn weight_decay(&self) -> Option<V> {
Some(self.lambda)
}
fn next_learning_rate(&mut self, rate: V) -> V {
self.optimizer.next_learning_rate(rate)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scheduled<Opt, V> {
pub optimizer: Opt,
pub schedule: StepDecay<V>,
}
impl<Opt, V> Scheduled<Opt, V> {
pub const fn new(optimizer: Opt, schedule: StepDecay<V>) -> Self {
Self {
optimizer,
schedule,
}
}
}
impl<V: Scalar, Opt: OptimizerImpl<V>> OptimizerImpl<V> for Scheduled<Opt, V> {
fn begin_step(&mut self) {
self.optimizer.begin_step();
}
fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
self.optimizer.update_weight(c, rates, clip);
}
fn weight_decay(&self) -> Option<V> {
self.optimizer.weight_decay()
}
fn next_learning_rate(&mut self, rate: V) -> V {
let rate = self.optimizer.next_learning_rate(rate);
self.schedule.step(rate)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StepDecay<V> {
pub interval: u32,
pub factor: V,
pub(crate) count: u32,
}
impl<V> StepDecay<V> {
pub const fn new(interval: u32, factor: V) -> Self {
Self {
interval,
factor,
count: 0,
}
}
pub fn steps_since_decay(&self) -> u32 {
self.count
}
}
impl<V: Scalar> StepDecay<V> {
pub fn step(&mut self, rate: V) -> V {
self.count = self.count.saturating_add(1);
if self.count >= self.interval {
self.count = 0;
return rate * self.factor;
}
rate
}
}
impl Default for StepDecay<crate::Q16_16> {
fn default() -> Self {
Self::new(1000, crate::Q16_16::from_raw(58_982))
}
}
impl Default for StepDecay<crate::Q8_8> {
fn default() -> Self {
Self::new(1000, crate::Q8_8::from_raw(230))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EarlyStopping<V> {
pub patience: u32,
pub(crate) best: Option<V>,
pub(crate) counter: u32,
}
impl<V> EarlyStopping<V> {
pub const fn new(patience: u32) -> Self {
Self {
patience,
best: None,
counter: 0,
}
}
pub fn reset(&mut self) {
self.best = None;
self.counter = 0;
}
pub fn patience_counter(&self) -> u32 {
self.counter
}
}
impl<V: Copy> EarlyStopping<V> {
pub fn best_error(&self) -> Option<V> {
self.best
}
}
impl<V: Copy + PartialOrd> EarlyStopping<V> {
pub fn should_stop(&mut self, error: V) -> bool {
match self.best {
None => {
self.best = Some(error);
self.counter = 0;
false
}
Some(best) if error < best => {
self.best = Some(error);
self.counter = 0;
false
}
Some(_) => {
self.counter = self.counter.saturating_add(1);
self.counter >= self.patience
}
}
}
}
impl<V> Default for EarlyStopping<V> {
fn default() -> Self {
Self::new(100)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ScheduledSampling {
pub(crate) total_decay_steps: usize,
pub(crate) current_step: usize,
}
impl ScheduledSampling {
pub const fn new(total_decay_steps: usize) -> Self {
Self {
total_decay_steps,
current_step: 0,
}
}
pub fn select_input<V>(&self, ground_truth: V, prediction: V, draw: impl FnOnce() -> u32) -> V {
let remaining = match self.total_decay_steps.checked_sub(self.current_step) {
Some(r) if r > 0 => r,
_ => return prediction,
};
let threshold = remaining
.wrapping_mul(1000)
.checked_div(self.total_decay_steps)
.unwrap_or(0) as u32;
if draw() % 1000 < threshold {
ground_truth
} else {
prediction
}
}
pub fn step(&mut self) {
if self.current_step < self.total_decay_steps {
self.current_step += 1;
}
}
pub fn reset(&mut self) {
self.current_step = 0;
}
pub fn teacher_forcing_ratio(&self) -> f64 {
if self.current_step >= self.total_decay_steps {
return 0.0;
}
(self.total_decay_steps - self.current_step) as f64 / self.total_decay_steps as f64
}
pub fn current_step(&self) -> usize {
self.current_step
}
pub fn total_decay_steps(&self) -> usize {
self.total_decay_steps
}
}
#[inline(never)]
pub(crate) fn decay_weights<V: Scalar>(connections: &mut [Connection<V>], factor: V) {
for c in connections {
c.weight = c.weight - factor * c.weight;
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Q8_8, Q16_16};
#[test]
fn step_decay_defaults_are_tinymind_cpp_constants() {
let s = StepDecay::<Q16_16>::default();
assert_eq!((s.interval, s.factor.raw()), (1000, 58_982));
let s = StepDecay::<Q8_8>::default();
assert_eq!((s.interval, s.factor.raw()), (1000, 230));
}
#[test]
fn step_decay_multiplies_every_interval() {
let half = Q16_16::from_raw(1 << 15);
let mut s = StepDecay::new(3, half);
let mut rate = Q16_16::ONE;
let mut rates = [0; 7];
for r in &mut rates {
rate = s.step(rate);
*r = rate.raw();
}
assert_eq!(
rates,
[65_536, 65_536, 32_768, 32_768, 32_768, 16_384, 16_384]
);
assert_eq!(s.steps_since_decay(), 1);
}
#[test]
fn scheduled_sampling_decays_linearly() {
let mut s = ScheduledSampling::new(100);
assert_eq!(s.teacher_forcing_ratio(), 1.0);
for _ in 0..50 {
s.step();
}
assert_eq!(s.teacher_forcing_ratio(), 0.5);
assert_eq!(s.select_input(1.0, 0.5, || 1499), 1.0);
assert_eq!(s.select_input(1.0, 0.5, || 500), 0.5);
for _ in 0..60 {
s.step();
}
assert_eq!((s.current_step(), s.teacher_forcing_ratio()), (100, 0.0));
assert_eq!(s.select_input(1.0, 0.5, || 0), 0.5);
s.reset();
assert_eq!((s.current_step(), s.teacher_forcing_ratio()), (0, 1.0));
assert_eq!(ScheduledSampling::new(0).select_input(1, 2, || 0), 2);
}
#[test]
fn step_decay_interval_zero_decays_every_step() {
let mut s = StepDecay::new(0, 0.5f64);
assert_eq!(s.step(1.0), 0.5);
assert_eq!(s.step(0.5), 0.25);
assert_eq!(s.steps_since_decay(), 0);
}
#[test]
fn early_stopping_counts_non_improving_checks() {
let mut e = EarlyStopping::new(2);
assert_eq!(e.best_error(), None);
assert!(!e.should_stop(5));
assert!(!e.should_stop(5)); assert!(e.should_stop(6)); assert!(e.should_stop(7)); assert!(!e.should_stop(4)); assert_eq!((e.best_error(), e.patience_counter()), (Some(4), 0));
e.reset();
assert_eq!((e.best_error(), e.patience_counter()), (None, 0));
assert!(!e.should_stop(9));
}
#[test]
fn early_stopping_counts_nan_as_no_improvement() {
let mut e = EarlyStopping::new(1);
assert!(!e.should_stop(1.0f32));
assert!(e.should_stop(f32::NAN));
assert_eq!(e.best_error(), Some(1.0));
}
#[test]
fn neutral_wrappers_train_like_the_plain_optimizer() {
use crate::recurrent::LstmNetwork;
use crate::{Dense, Linear, MultilayerPerceptron, NeuralNetwork, Relu, Sgd, Sigmoid, Tanh};
fn weights(seed: &mut u32) -> i32 {
*seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(*seed >> 16) as i32 % 32_769 - 16_384
}
let neutral =
|l: Q16_16| Scheduled::new(WeightDecay::new(Sgd, l), StepDecay::new(1, Q16_16::ONE));
let (mut s1, mut s2) = (1u32, 1u32);
let mut plain = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1>::new(|| {
Q16_16::from_raw(weights(&mut s1))
});
let mut wrapped = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1, _>::with_optimizer(
|| Q16_16::from_raw(weights(&mut s2)),
neutral(Q16_16::ZERO),
);
let (mut s3, mut s4) = (2u32, 2u32);
let mut deep_plain =
NeuralNetwork::<(Dense<f64, Relu, 2, 3>, Dense<f64, Linear, 3, 1>)>::new(|| {
f64::from(weights(&mut s3)) / 65_536.0
});
let mut deep_wrapped =
NeuralNetwork::<(Dense<f64, Relu, 2, 3>, Dense<f64, Linear, 3, 1>), _>::with_optimizer(
|| f64::from(weights(&mut s4)) / 65_536.0,
Scheduled::new(WeightDecay::new(Sgd, 0.0), StepDecay::new(1, 1.0)),
);
let (mut s5, mut s6) = (3u32, 3u32);
let mut lstm_plain = LstmNetwork::<Q16_16, Tanh, Sigmoid, 2, 3, 1>::new(|| {
Q16_16::from_raw(weights(&mut s5))
});
let mut lstm_wrapped = LstmNetwork::<Q16_16, Tanh, Sigmoid, 2, 3, 1, _>::with_optimizer(
|| Q16_16::from_raw(weights(&mut s6)),
neutral(Q16_16::ZERO),
);
for step in 0..200 {
let (a, b) = (step % 2, (step / 2) % 2);
let x = [Q16_16::from_int(a), Q16_16::from_int(b)];
let t = [Q16_16::from_int(a ^ b)];
plain.feed_forward(&x);
plain.train(&t);
wrapped.feed_forward(&x);
wrapped.train(&t);
lstm_plain.feed_forward(&x);
lstm_plain.train(&t);
lstm_wrapped.feed_forward(&x);
lstm_wrapped.train(&t);
let xf = [f64::from(a), f64::from(b)];
let tf = [f64::from(a - b)];
deep_plain.feed_forward(&xf);
deep_plain.train(&tf);
deep_wrapped.feed_forward(&xf);
deep_wrapped.train(&tf);
}
assert_eq!(plain.input_weights(), wrapped.input_weights());
assert_eq!(plain.hidden_weights(), wrapped.hidden_weights());
assert_eq!(plain.learning_rate(), wrapped.learning_rate());
assert_eq!(lstm_plain.input_weights(), lstm_wrapped.input_weights());
assert_eq!(
lstm_plain.recurrent_weights(),
lstm_wrapped.recurrent_weights()
);
assert_eq!(lstm_plain.hidden_weights(), lstm_wrapped.hidden_weights());
assert_eq!(
deep_plain.layers().0.weights(),
deep_wrapped.layers().0.weights()
);
assert_eq!(
deep_plain.layers().1.weights(),
deep_wrapped.layers().1.weights()
);
let mut s7 = 1u32;
let mut decayed = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1, _>::with_optimizer(
|| Q16_16::from_raw(weights(&mut s7)),
neutral(Q16_16::from_raw(655)),
);
for step in 0..200 {
let (a, b) = (step % 2, (step / 2) % 2);
decayed.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
decayed.train(&[Q16_16::from_int(a ^ b)]);
}
assert_ne!(plain.input_weights(), decayed.input_weights());
}
#[test]
fn wrappers_compose() {
use crate::Sgd;
let half = Q16_16::from_raw(1 << 15);
let quarter = Q16_16::from_raw(1 << 14);
let mut opt = Scheduled::new(
WeightDecay::new(Scheduled::new(Sgd, StepDecay::new(1, half)), Q16_16::ONE),
StepDecay::new(2, quarter),
);
let one = Q16_16::ONE;
assert_eq!(opt.next_learning_rate(one), half); assert_eq!(opt.next_learning_rate(one), Q16_16::from_raw(1 << 13)); assert_eq!(opt.weight_decay(), Some(Q16_16::ONE));
let opt = WeightDecay::new(WeightDecay::new(Sgd, half), quarter);
assert_eq!(opt.weight_decay(), Some(quarter));
assert_eq!(OptimizerImpl::<Q16_16>::weight_decay(&Sgd), None);
}
#[test]
fn weight_decay_matches_the_cpp_expression() {
let factor = Q16_16::from_raw(1 << 14) * Q16_16::from_raw(655);
assert_eq!(factor.raw(), 163);
let mut c = [Connection {
weight: Q16_16::from_int(2),
..Connection::default()
}];
decay_weights(&mut c, factor);
assert_eq!(c[0].weight.raw(), 131_072 - 326);
}
}