Skip to main content

tinymind/
optimizer.rs

1//! Weight-update rules for the trainable networks, ported from tinymind (C++)
2//! `cpp/adam.hpp` and `cpp/rmsprop.hpp` (C++ `TransferFunctionOptimizerPolicy`).
3//!
4//! A network's optimizer is a type parameter, as in C++: [`Sgd`] (the default,
5//! zero-sized, so a network without an adaptive optimizer pays nothing for this),
6//! [`Adam`] or [`RmsProp`], or for `f32` and `f64` networks `AdamFloat` and
7//! `RmsPropFloat` (C++ `AdamOptimizerFloat`, `RmsPropOptimizerFloat`; feature
8//! `std` or `libm`). Pass an adaptive optimizer with its hyperparameters to
9//! `with_optimizer` on [`NeuralNetwork`](crate::NeuralNetwork),
10//! [`MultilayerPerceptron`](crate::MultilayerPerceptron) or
11//! [`LstmNetwork`](crate::recurrent::LstmNetwork). Weight decay and a
12//! learning-rate schedule wrap any of them ([`training`](crate::training)).
13//!
14//! Every optimizer updates the bias weights as it updates the other weights,
15//! and the network's gradient clipping applies to both. Adam's step count `t`
16//! advances once per training step, before any weight moves.
17//!
18//! The first and second moments live in the connection's delta-weight slots, as
19//! in tinymind (C++), so an adaptive optimizer needs no extra memory per weight.
20
21// The sealed trait's methods take the crate-private `Connection`. The trait
22// cannot be named outside the crate (it lives in a private module), so nothing
23// private is usable from outside; the lint cannot see that.
24#![allow(private_interfaces)]
25
26use crate::neuralnet::{Connection, clip_gradient, update_connection};
27use crate::qformat::{Scalar, Sqrt};
28
29/// Stochastic gradient descent with momentum and acceleration (the default;
30/// C++ `NullOptimizerPolicy`). The rates are the network's
31/// `set_learning_rate`, `set_momentum_rate` and `set_acceleration_rate`. In
32/// fixed point the step `learning rate * gradient` rounds to nearest
33/// ([`Scalar::mul_round_nearest`]), so steps below one LSB do not drift one
34/// way, and the momentum and acceleration products round toward zero
35/// ([`Scalar::mul_round_toward_zero`]), so a delta weight no gradient
36/// refreshes decays to 0.
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub struct Sgd;
39
40/// Adam (C++ `AdamOptimizer`): per-weight first and second moment estimates
41/// with bias correction by `1 - beta^t`, `beta^t` kept as a running product
42/// (one multiply per training step). Uses the network's learning rate; the
43/// momentum and acceleration rates do not apply.
44///
45/// `Adam::<Q16_16>::default()` and `Adam::<Q8_8>::default()` are the
46/// defaults of tinymind (C++) for those formats: beta1 0.9, beta2 0.99 and epsilon
47/// `sqrt(LSB / (1 - beta2))`, each rounded to the format. Not the textbook
48/// 0.999 and 1e-8: in fixed point `(1 - beta2) * g * g` rounds to zero for
49/// gradients below that epsilon, and a smaller epsilon then lets steps grow
50/// far beyond the learning rate. Q8.8 has too few fractional bits for Adam
51/// (its default epsilon is 0.625).
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub struct Adam<V> {
54    /// Decay of the first moment (C++ `beta1`).
55    pub beta1: V,
56    /// Decay of the second moment (C++ `beta2`).
57    pub beta2: V,
58    /// Added to the root of the second moment.
59    pub epsilon: V,
60    timestep: usize,
61    /// `(beta1^t, beta2^t)`; `None` at step 0, where both are 1.
62    powers: Option<(V, V)>,
63}
64
65impl<V> Adam<V> {
66    /// Adam with these hyperparameters, at step 0.
67    pub const fn new(beta1: V, beta2: V, epsilon: V) -> Self {
68        Self {
69            beta1,
70            beta2,
71            epsilon,
72            timestep: 0,
73            powers: None,
74        }
75    }
76
77    /// The step count bias correction uses: the number of training steps so far.
78    pub fn timestep(&self) -> usize {
79        self.timestep
80    }
81}
82
83impl Default for Adam<crate::Q16_16> {
84    /// tinymind (C++)'s Q16.16 defaults: beta1 58982/65536, beta2
85    /// 64881/65536, epsilon 2560/65536 (0.039).
86    fn default() -> Self {
87        use crate::Q16_16;
88        Self::new(
89            Q16_16::from_raw(58_982),
90            Q16_16::from_raw(64_881),
91            Q16_16::from_raw(2_560),
92        )
93    }
94}
95
96impl Default for Adam<crate::Q8_8> {
97    /// tinymind (C++)'s Q8.8 defaults: beta1 230/256, beta2 253/256,
98    /// epsilon 160/256 (0.625).
99    fn default() -> Self {
100        use crate::Q8_8;
101        Self::new(
102            Q8_8::from_raw(230),
103            Q8_8::from_raw(253),
104            Q8_8::from_raw(160),
105        )
106    }
107}
108
109/// RMSprop (C++ `RmsPropOptimizer`): each weight's step is scaled by a running
110/// root mean square of its gradients. Uses the network's learning rate only.
111/// `RmsProp::<Q16_16>::default()` and `RmsProp::<Q8_8>::default()` are
112/// tinymind (C++)'s defaults: decay 0.9 and epsilon 1e-8, each rounded to the
113/// format and kept above 0 (epsilon is then one LSB).
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub struct RmsProp<V> {
116    /// Decay of the running mean of squared gradients.
117    pub decay: V,
118    /// Added to the root of that mean.
119    pub epsilon: V,
120}
121
122impl<V> RmsProp<V> {
123    /// RMSprop with these hyperparameters.
124    pub const fn new(decay: V, epsilon: V) -> Self {
125        Self { decay, epsilon }
126    }
127}
128
129impl Default for RmsProp<crate::Q16_16> {
130    /// tinymind (C++)'s Q16.16 defaults: decay 58982/65536, epsilon 1/65536.
131    fn default() -> Self {
132        use crate::Q16_16;
133        Self::new(Q16_16::from_raw(58_982), Q16_16::from_raw(1))
134    }
135}
136
137impl Default for RmsProp<crate::Q8_8> {
138    /// tinymind (C++)'s Q8.8 defaults: decay 230/256, epsilon 1/256.
139    fn default() -> Self {
140        use crate::Q8_8;
141        Self::new(Q8_8::from_raw(230), Q8_8::from_raw(1))
142    }
143}
144
145pub(crate) mod sealed {
146    use super::*;
147
148    /// What a network needs from its optimizer. Sealed: the crate implements it
149    /// for [`Sgd`], [`Adam`] and [`RmsProp`], and the floating-point optimizers.
150    pub trait OptimizerImpl<V> {
151        /// C++ `step()`: called once per training step, before any weight
152        /// moves (`beginTrainingStep`).
153        fn begin_step(&mut self);
154        /// Update one weight or bias weight from its gradient (clipped by
155        /// `clip` if set). Since tinymind (C++) #264 every optimizer updates
156        /// bias weights by the same rule as the other weights.
157        fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>);
158        /// L2 weight-decay lambda (C++ `WeightDecayPolicy`), or `None` for
159        /// none (`NullWeightDecayPolicy`, every optimizer but
160        /// [`WeightDecay`](crate::training::WeightDecay)). A constant for
161        /// those, so a network without decay compiles no decay code.
162        fn weight_decay(&self) -> Option<V> {
163            None
164        }
165        /// C++ `stepLearningRate`: called once after each update with the
166        /// rate that update used; returns the rate for the next one. The
167        /// identity (`FixedLearningRatePolicy`) for every optimizer but
168        /// [`Scheduled`](crate::training::Scheduled).
169        fn next_learning_rate(&mut self, rate: V) -> V {
170            rate
171        }
172    }
173}
174
175/// An optimizer a trainable network can use: [`Sgd`], [`Adam`] or [`RmsProp`],
176/// and for floating-point networks `AdamFloat` or `RmsPropFloat`; any of them
177/// wrapped in [`WeightDecay`](crate::training::WeightDecay) or
178/// [`Scheduled`](crate::training::Scheduled).
179pub trait Optimizer<V>: sealed::OptimizerImpl<V> {}
180
181impl<V, T: sealed::OptimizerImpl<V>> Optimizer<V> for T {}
182
183impl<V: Scalar> sealed::OptimizerImpl<V> for Sgd {
184    fn begin_step(&mut self) {}
185
186    fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
187        update_connection(c, rates, clip);
188    }
189}
190
191/// One optimizer step on every connection of `connections` (weights or bias
192/// weights: since tinymind (C++) #264 both follow the same rule). Never
193/// inlined, so a network has one copy of the update code per optimizer
194/// however many layers call it: with the code inlined at every weight and
195/// bias loop the Cortex-M0+ anomaly image no longer fit its 32 KB of flash,
196/// and a single chained-iterator loop instead cost the Cortex-M4 32% more
197/// cycles per training step.
198#[inline(never)]
199pub(crate) fn update_all<V: Copy, Opt: Optimizer<V>>(
200    optimizer: &Opt,
201    connections: &mut [Connection<V>],
202    rates: (V, V, V),
203    clip: Option<(V, V)>,
204) {
205    for c in connections {
206        optimizer.update_weight(c, rates, clip);
207    }
208}
209
210fn clipped<V: Scalar>(gradient: V, clip: Option<(V, V)>) -> V {
211    match clip {
212        Some(range) => clip_gradient(gradient, range),
213        None => gradient,
214    }
215}
216
217impl<V: Scalar + Sqrt> Adam<V> {
218    /// C++ `AdamOptimizer::computeUpdate`, every expression in its order:
219    /// updates the moments in the connection's delta-weight slots and returns
220    /// `lr * m_hat / (sqrt(v_hat) + epsilon)`.
221    fn compute_update(&self, c: &mut Connection<V>, gradient: V, lr: V) -> V {
222        let one = V::ONE;
223        // First moment in the delta-weight slot, second in the previous one.
224        let m = self.beta1 * c.delta_weight + (one - self.beta1) * gradient;
225        let v = self.beta2 * c.previous_delta_weight + (one - self.beta2) * gradient * gradient;
226        c.delta_weight = m;
227        c.previous_delta_weight = v;
228
229        let mut m_hat = m;
230        let mut v_hat = v;
231        // Before the first step both corrections are 1 - 1 = 0 and the moments
232        // are used as they are.
233        let (beta1_power, beta2_power) = self.powers.unwrap_or((one, one));
234        let beta1_correction = one - beta1_power;
235        let beta2_correction = one - beta2_power;
236        if beta1_correction > V::ZERO {
237            m_hat = m / beta1_correction;
238        }
239        if beta2_correction > V::ZERO {
240            v_hat = v / beta2_correction;
241        }
242        lr * m_hat / (v_hat.sqrt() + self.epsilon)
243    }
244}
245
246impl<V: Scalar + Sqrt> sealed::OptimizerImpl<V> for Adam<V> {
247    fn begin_step(&mut self) {
248        self.timestep = self.timestep.wrapping_add(1);
249        let (beta1_power, beta2_power) = self.powers.unwrap_or((V::ONE, V::ONE));
250        self.powers = Some((beta1_power * self.beta1, beta2_power * self.beta2));
251    }
252
253    fn update_weight(&self, c: &mut Connection<V>, (lr, _, _): (V, V, V), clip: Option<(V, V)>) {
254        let update = self.compute_update(c, clipped(c.gradient, clip), lr);
255        c.weight += update;
256    }
257}
258
259impl<V: Scalar + Sqrt> RmsProp<V> {
260    /// C++ `RmsPropOptimizer::computeUpdate`: the running mean of squared
261    /// gradients in the second-moment slot, and `lr * g / (sqrt(v) + epsilon)`.
262    fn compute_update(&self, c: &mut Connection<V>, gradient: V, lr: V) -> V {
263        let v = self.decay * c.previous_delta_weight + (V::ONE - self.decay) * gradient * gradient;
264        c.previous_delta_weight = v;
265        lr * gradient / (v.sqrt() + self.epsilon)
266    }
267}
268
269impl<V: Scalar + Sqrt> sealed::OptimizerImpl<V> for RmsProp<V> {
270    /// C++ counts steps for RMSprop too but never reads the count.
271    fn begin_step(&mut self) {}
272
273    fn update_weight(&self, c: &mut Connection<V>, (lr, _, _): (V, V, V), clip: Option<(V, V)>) {
274        let update = self.compute_update(c, clipped(c.gradient, clip), lr);
275        c.weight += update;
276    }
277}
278
279/// Adam for floating-point networks (C++ `AdamOptimizerFloat`): the
280/// hyperparameters are `f64`, as in the C++, cast to the network's type where
281/// they are used, and from the first training step bias correction divides by
282/// `1 - beta^t`, with `beta^t` a running product in `f64`. The square root is
283/// taken in `f64`.
284///
285/// Implemented for `f32` and `f64` networks; needs the `std` feature (`pow`
286/// and `sqrt` from the platform, bit-identical to the C++ on a glibc host) or
287/// `libm`.
288#[cfg(any(feature = "std", feature = "libm"))]
289#[derive(Clone, Copy, Debug, PartialEq)]
290pub struct AdamFloat {
291    /// Decay of the first moment (C++ default 0.9).
292    pub beta1: f64,
293    /// Decay of the second moment (C++ default 0.999).
294    pub beta2: f64,
295    /// Added to the root of the second moment (C++ default 1e-8).
296    pub epsilon: f64,
297    timestep: usize,
298    beta1_power: f64,
299    beta2_power: f64,
300}
301
302#[cfg(any(feature = "std", feature = "libm"))]
303impl Default for AdamFloat {
304    /// tinymind (C++)'s values: 0.9, 0.999, 1e-8.
305    fn default() -> Self {
306        Self::new(0.9, 0.999, 1e-8)
307    }
308}
309
310#[cfg(any(feature = "std", feature = "libm"))]
311impl AdamFloat {
312    /// Adam with these hyperparameters, at step 0.
313    pub const fn new(beta1: f64, beta2: f64, epsilon: f64) -> Self {
314        Self {
315            beta1,
316            beta2,
317            epsilon,
318            timestep: 0,
319            beta1_power: 1.0,
320            beta2_power: 1.0,
321        }
322    }
323
324    /// The step count bias correction uses: the number of training steps so far.
325    pub fn timestep(&self) -> usize {
326        self.timestep
327    }
328}
329
330/// RMSprop for floating-point networks (C++ `RmsPropOptimizerFloat`): the
331/// hyperparameters are `f64`, cast to the network's type where they are used,
332/// and the square root is taken in `f64`.
333///
334/// Implemented for `f32` and `f64` networks; needs the `std` feature or `libm`.
335#[cfg(any(feature = "std", feature = "libm"))]
336#[derive(Clone, Copy, Debug, PartialEq)]
337pub struct RmsPropFloat {
338    /// Decay of the running mean of squared gradients (C++ default 0.9).
339    pub decay: f64,
340    /// Added to the root of that mean (C++ default 1e-8).
341    pub epsilon: f64,
342}
343
344#[cfg(any(feature = "std", feature = "libm"))]
345impl Default for RmsPropFloat {
346    /// tinymind (C++)'s values: 0.9, 1e-8.
347    fn default() -> Self {
348        Self::new(0.9, 1e-8)
349    }
350}
351
352#[cfg(any(feature = "std", feature = "libm"))]
353impl RmsPropFloat {
354    /// RMSprop with these hyperparameters.
355    pub const fn new(decay: f64, epsilon: f64) -> Self {
356        Self { decay, epsilon }
357    }
358}
359
360/// `sqrt(x)` in `f64`: the platform's with `std`, the `libm` crate's without.
361#[cfg(feature = "std")]
362mod float_math {
363    pub(super) fn sqrt(x: f64) -> f64 {
364        x.sqrt()
365    }
366}
367
368#[cfg(all(feature = "libm", not(feature = "std")))]
369mod float_math {
370    pub(super) fn sqrt(x: f64) -> f64 {
371        libm::sqrt(x)
372    }
373}
374
375/// The shared part of a floating-point optimizer's weight and bias updates,
376/// per float type (a trait so the `f32` and `f64` versions can coexist).
377#[cfg(any(feature = "std", feature = "libm"))]
378trait FloatUpdate<T> {
379    /// Updates the connection's moments and returns the step to add.
380    fn compute_update_float(&self, c: &mut Connection<T>, gradient: T, lr: T) -> T;
381}
382
383/// The floating-point optimizers for one float type, every expression in the
384/// C++ order and with its casts.
385#[cfg(any(feature = "std", feature = "libm"))]
386macro_rules! impl_float_optimizers {
387    ($t:ty) => {
388        impl FloatUpdate<$t> for AdamFloat {
389            /// C++ `AdamOptimizerFloat::computeUpdate`.
390            fn compute_update_float(&self, c: &mut Connection<$t>, gradient: $t, lr: $t) -> $t {
391                let m = (self.beta1 as $t) * c.delta_weight + ((1.0 - self.beta1) as $t) * gradient;
392                let v = (self.beta2 as $t) * c.previous_delta_weight
393                    + ((1.0 - self.beta2) as $t) * gradient * gradient;
394                c.delta_weight = m;
395                c.previous_delta_weight = v;
396                let mut m_hat = m;
397                let mut v_hat = v;
398                if self.timestep > 0 {
399                    m_hat = m / ((1.0 - self.beta1_power) as $t);
400                    v_hat = v / ((1.0 - self.beta2_power) as $t);
401                }
402                let sqrt_v = float_math::sqrt(f64::from(v_hat)) as $t;
403                lr * m_hat / (sqrt_v + self.epsilon as $t)
404            }
405        }
406
407        impl sealed::OptimizerImpl<$t> for AdamFloat {
408            fn begin_step(&mut self) {
409                self.timestep = self.timestep.wrapping_add(1);
410                self.beta1_power *= self.beta1;
411                self.beta2_power *= self.beta2;
412            }
413
414            fn update_weight(
415                &self,
416                c: &mut Connection<$t>,
417                (lr, _, _): ($t, $t, $t),
418                clip: Option<($t, $t)>,
419            ) {
420                let update = self.compute_update_float(c, clipped(c.gradient, clip), lr);
421                c.weight += update;
422            }
423        }
424
425        impl FloatUpdate<$t> for RmsPropFloat {
426            /// C++ `RmsPropOptimizerFloat::computeUpdate`.
427            fn compute_update_float(&self, c: &mut Connection<$t>, gradient: $t, lr: $t) -> $t {
428                let v = (self.decay as $t) * c.previous_delta_weight
429                    + ((1.0 - self.decay) as $t) * gradient * gradient;
430                c.previous_delta_weight = v;
431                let sqrt_v = float_math::sqrt(f64::from(v)) as $t;
432                lr * gradient / (sqrt_v + self.epsilon as $t)
433            }
434        }
435
436        impl sealed::OptimizerImpl<$t> for RmsPropFloat {
437            /// C++ counts steps for RMSprop too but never reads the count.
438            fn begin_step(&mut self) {}
439
440            fn update_weight(
441                &self,
442                c: &mut Connection<$t>,
443                (lr, _, _): ($t, $t, $t),
444                clip: Option<($t, $t)>,
445            ) {
446                let update = self.compute_update_float(c, clipped(c.gradient, clip), lr);
447                c.weight += update;
448            }
449        }
450    };
451}
452
453#[cfg(any(feature = "std", feature = "libm"))]
454impl_float_optimizers!(f32);
455#[cfg(any(feature = "std", feature = "libm"))]
456impl_float_optimizers!(f64);
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use crate::{Q8_8, Q16_16};
462
463    /// The defaults are tinymind (C++)'s `QFractionLsbs<Q, 9, 10>`,
464    /// `QFractionLsbs<Q, 99, 100>`, `QAdamEpsilonLsbs<Q, 100>` and
465    /// `QFractionLsbs<Q, 1, 100000000>`, printed by a C++ program at
466    /// tinymind (C++) a40979f. The Q8.8 ones are also checked by `tests/deep_mlp.rs`, whose
467    /// C++ runs use `AdamOptimizer<Q8>` and `RmsPropOptimizer<Q8>`.
468    #[test]
469    fn defaults_are_tinymind_cpp_constants() {
470        let a = Adam::<Q16_16>::default();
471        assert_eq!(
472            (a.beta1.raw(), a.beta2.raw(), a.epsilon.raw()),
473            (58_982, 64_881, 2_560)
474        );
475        let a = Adam::<Q8_8>::default();
476        assert_eq!(
477            (a.beta1.raw(), a.beta2.raw(), a.epsilon.raw()),
478            (230, 253, 160)
479        );
480        let r = RmsProp::<Q16_16>::default();
481        assert_eq!((r.decay.raw(), r.epsilon.raw()), (58_982, 1));
482        let r = RmsProp::<Q8_8>::default();
483        assert_eq!((r.decay.raw(), r.epsilon.raw()), (230, 1));
484    }
485}