tinymind/training.rs
1//! Training controls for the trainable networks, ported from tinymind (C++)
2//! `cpp/weightDecay.hpp`, `cpp/learningRateSchedule.hpp`,
3//! `cpp/earlyStopping.hpp` and `cpp/teacherForcing.hpp`.
4//!
5//! - **[`WeightDecay`]** (L2) shrinks every connection weight, but no bias
6//! weight, by `learning rate * lambda * weight` before each update. With
7//! plain SGD (no momentum) this is the gradient step of an L2 penalty
8//! `(lambda / 2) * w^2`; the shrink does not enter the momentum terms, so
9//! with momentum, and under Adam and RMSprop, it is decoupled weight decay
10//! (AdamW). In fixed point it keeps weights from growing until they
11//! overflow.
12//! - **[`Scheduled`]** with a [`StepDecay`] multiplies the learning rate by a
13//! factor every `interval` training steps. Read the current rate with the
14//! network's `learning_rate()`. Any other schedule is a call to
15//! `set_learning_rate` between steps.
16//! - **[`EarlyStopping`]** watches an error (training or validation) and says
17//! when it has not improved for `patience` checks in a row. It is not tied
18//! to a network; the training loop asks it.
19//! - **[`ScheduledSampling`]** picks, for each step of a sequence, whether a
20//! recurrent network's next input is the true value or its own previous
21//! prediction, moving from always-true to always-prediction over a number
22//! of training steps (teacher forcing with a decaying ratio). Like
23//! [`EarlyStopping`], the training loop asks it.
24//!
25//! [`WeightDecay`] and [`Scheduled`] wrap an optimizer ([`Sgd`](crate::Sgd),
26//! [`Adam`](crate::Adam), ...) and are passed to `with_optimizer` on
27//! [`MultilayerPerceptron`](crate::MultilayerPerceptron),
28//! [`NeuralNetwork`](crate::NeuralNetwork) or
29//! [`LstmNetwork`](crate::recurrent::LstmNetwork), as tinymind (C++) takes
30//! `L2WeightDecay` and `StepDecaySchedule` as policies. A network built
31//! without them compiles no decay or schedule code and stores nothing for
32//! them. With them, fixed-point results are bit-identical to the C++ network
33//! built with the same policies. tinymind (C++)'s policies are fixed-point
34//! only, so for `f32` and `f64` there is no C++ counterpart to compare with.
35//!
36//! The wrappers are part of the network's optimizer, which is fixed when the
37//! network is built: to change `lambda` or the schedule, build the wrapper
38//! with the values wanted, or adjust the rate between steps with
39//! `set_learning_rate`.
40//!
41//! ```
42//! use tinymind::training::{Scheduled, StepDecay, WeightDecay};
43//! use tinymind::{MultilayerPerceptron, Q16_16, Sgd, Sigmoid, Tanh};
44//!
45//! // tinymind (C++)'s defaults for Q16.16: lambda 66/65536 (0.001), and the
46//! // rate times 0.9 every 1000 steps.
47//! let optimizer = Scheduled::new(
48//! WeightDecay::new(Sgd, Q16_16::from_raw(66)),
49//! StepDecay::<Q16_16>::default(),
50//! );
51//! let mut seed = 1u32;
52//! let mut nn = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1, _>::with_optimizer(
53//! || {
54//! seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
55//! Q16_16::from_raw((seed >> 16) as i32 % 32_769 - 16_384)
56//! },
57//! optimizer,
58//! );
59//!
60//! let samples = [([0, 0], 0), ([0, 1], 1), ([1, 0], 1), ([1, 1], 0)];
61//! for step in 0..2_500 {
62//! let (x, t) = samples[step % 4];
63//! nn.feed_forward(&x.map(Q16_16::from_int));
64//! nn.train(&[Q16_16::from_int(t)]);
65//! }
66//! // Two decays so far: 1/4 * 0.9 * 0.9, each product floored.
67//! let factor = Q16_16::from_raw(58_982);
68//! assert_eq!(nn.learning_rate(), Q16_16::from_raw(16_384) * factor * factor);
69//! assert_eq!(nn.optimizer().schedule.steps_since_decay(), 500);
70//! ```
71
72// The sealed optimizer trait's methods take the crate-private `Connection`;
73// see `crate::optimizer`.
74#![allow(private_interfaces)]
75
76use crate::neuralnet::Connection;
77use crate::optimizer::sealed::OptimizerImpl;
78use crate::qformat::Scalar;
79
80/// L2 weight decay around an optimizer (C++ `L2WeightDecay`): before each
81/// update every connection weight, but no bias weight, becomes
82/// `w - (learning rate * lambda) * w`, then `optimizer` takes its step.
83///
84/// tinymind (C++)'s default lambda is 0.001 rounded to the format and kept at
85/// one LSB or more: `Q16_16::from_raw(66)` and `Q8_8::from_raw(1)` (0.001 is
86/// below one Q8.8 LSB). A lambda of 0 gives the same results as `optimizer`
87/// alone.
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89pub struct WeightDecay<Opt, V> {
90 /// The optimizer that takes each step after the decay.
91 pub optimizer: Opt,
92 /// The decay rate.
93 pub lambda: V,
94}
95
96impl<Opt, V> WeightDecay<Opt, V> {
97 /// `optimizer` with L2 weight decay `lambda`.
98 pub const fn new(optimizer: Opt, lambda: V) -> Self {
99 Self { optimizer, lambda }
100 }
101}
102
103impl<V: Scalar, Opt: OptimizerImpl<V>> OptimizerImpl<V> for WeightDecay<Opt, V> {
104 fn begin_step(&mut self) {
105 self.optimizer.begin_step();
106 }
107
108 fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
109 self.optimizer.update_weight(c, rates, clip);
110 }
111
112 fn weight_decay(&self) -> Option<V> {
113 Some(self.lambda)
114 }
115
116 fn next_learning_rate(&mut self, rate: V) -> V {
117 self.optimizer.next_learning_rate(rate)
118 }
119}
120
121/// A learning-rate schedule around an optimizer (C++ `StepDecaySchedule` as
122/// the `LearningRateSchedulePolicy`): after each update the network's
123/// learning rate becomes `schedule.step(rate)`.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub struct Scheduled<Opt, V> {
126 /// The optimizer that takes each step.
127 pub optimizer: Opt,
128 /// The schedule, with its step count.
129 pub schedule: StepDecay<V>,
130}
131
132impl<Opt, V> Scheduled<Opt, V> {
133 /// `optimizer` with the learning rate following `schedule`.
134 pub const fn new(optimizer: Opt, schedule: StepDecay<V>) -> Self {
135 Self {
136 optimizer,
137 schedule,
138 }
139 }
140}
141
142impl<V: Scalar, Opt: OptimizerImpl<V>> OptimizerImpl<V> for Scheduled<Opt, V> {
143 fn begin_step(&mut self) {
144 self.optimizer.begin_step();
145 }
146
147 fn update_weight(&self, c: &mut Connection<V>, rates: (V, V, V), clip: Option<(V, V)>) {
148 self.optimizer.update_weight(c, rates, clip);
149 }
150
151 fn weight_decay(&self) -> Option<V> {
152 self.optimizer.weight_decay()
153 }
154
155 fn next_learning_rate(&mut self, rate: V) -> V {
156 let rate = self.optimizer.next_learning_rate(rate);
157 self.schedule.step(rate)
158 }
159}
160
161/// Step-decay learning-rate schedule (C++ `StepDecaySchedule`): every
162/// `interval` training steps the learning rate is multiplied by `factor`.
163///
164/// A network trained with [`Scheduled`] calls [`step`](Self::step) after each
165/// weight update, so the rate used by update `n` (counting from 1) is the initial
166/// rate times `factor^((n - 1) / interval)`, each product rounded as the
167/// value type rounds. An interval of 0 decays after every step, as 1 does.
168///
169/// `StepDecay::<Q16_16>::default()` and `StepDecay::<Q8_8>::default()` are
170/// tinymind (C++)'s defaults: interval 1000 and factor 0.9 rounded to the format
171/// (58982/65536 and 230/256). The counts are `u32` (C++ `size_t`), so the
172/// schedule is the same size on a microcontroller and a 64-bit host.
173#[derive(Clone, Copy, Debug, PartialEq, Eq)]
174pub struct StepDecay<V> {
175 /// Training steps between two decays.
176 pub interval: u32,
177 /// What the learning rate is multiplied by at each decay.
178 pub factor: V,
179 pub(crate) count: u32,
180}
181
182impl<V> StepDecay<V> {
183 /// A schedule that multiplies the rate by `factor` every `interval` steps,
184 /// starting its count at 0.
185 pub const fn new(interval: u32, factor: V) -> Self {
186 Self {
187 interval,
188 factor,
189 count: 0,
190 }
191 }
192
193 /// Steps counted since the last decay (or since the start).
194 pub fn steps_since_decay(&self) -> u32 {
195 self.count
196 }
197}
198
199impl<V: Scalar> StepDecay<V> {
200 /// Count one training step and return the learning rate for the next one:
201 /// `rate * factor` when this step completes an interval, else `rate`.
202 pub fn step(&mut self, rate: V) -> V {
203 self.count = self.count.saturating_add(1);
204 if self.count >= self.interval {
205 self.count = 0;
206 return rate * self.factor;
207 }
208 rate
209 }
210}
211
212impl Default for StepDecay<crate::Q16_16> {
213 /// tinymind (C++)'s Q16.16 default: interval 1000, factor 58982/65536.
214 fn default() -> Self {
215 Self::new(1000, crate::Q16_16::from_raw(58_982))
216 }
217}
218
219impl Default for StepDecay<crate::Q8_8> {
220 /// tinymind (C++)'s Q8.8 default: interval 1000, factor 230/256.
221 fn default() -> Self {
222 Self::new(1000, crate::Q8_8::from_raw(230))
223 }
224}
225
226/// Early stopping (C++ `EarlyStopping`): reports when the error has not
227/// improved for `patience` checks in a row.
228///
229/// The first error checked becomes the best. After that, an error below the
230/// best replaces it and resets the count; any other error (equal, larger, or
231/// a floating-point NaN) adds one to the count, and
232/// [`should_stop`](Self::should_stop) returns `true` once the count reaches
233/// `patience`, and keeps returning `true` until an error improves on the best.
234/// A NaN as the first error becomes the best, and no error is below it, so
235/// check floating-point errors for NaN before passing them in.
236///
237/// The default patience is 100, tinymind (C++)'s default.
238///
239/// ```
240/// use tinymind::training::EarlyStopping;
241///
242/// let mut stopper = EarlyStopping::new(2);
243/// let errors = [0.9, 0.5, 0.6, 0.4, 0.4, 0.7, 0.3];
244/// let stop = errors.iter().position(|&e| stopper.should_stop(e));
245/// assert_eq!(stop, Some(5)); // 0.4 and then 0.7 did not improve on 0.4
246/// assert_eq!(stopper.best_error(), Some(0.4));
247/// ```
248#[derive(Clone, Copy, Debug, PartialEq, Eq)]
249pub struct EarlyStopping<V> {
250 /// Checks without improvement after which training should stop.
251 pub patience: u32,
252 pub(crate) best: Option<V>,
253 pub(crate) counter: u32,
254}
255
256impl<V> EarlyStopping<V> {
257 /// Early stopping after `patience` checks without improvement.
258 pub const fn new(patience: u32) -> Self {
259 Self {
260 patience,
261 best: None,
262 counter: 0,
263 }
264 }
265
266 /// Forget the best error and the count, as before the first check.
267 pub fn reset(&mut self) {
268 self.best = None;
269 self.counter = 0;
270 }
271
272 /// Checks since the error last improved.
273 pub fn patience_counter(&self) -> u32 {
274 self.counter
275 }
276}
277
278impl<V: Copy> EarlyStopping<V> {
279 /// The lowest error seen so far, or `None` before the first check.
280 pub fn best_error(&self) -> Option<V> {
281 self.best
282 }
283}
284
285impl<V: Copy + PartialOrd> EarlyStopping<V> {
286 /// Report `error` (training or validation) and return whether training
287 /// should stop: `true` when `patience` checks in a row, this one included,
288 /// have not improved on the best error.
289 pub fn should_stop(&mut self, error: V) -> bool {
290 match self.best {
291 None => {
292 self.best = Some(error);
293 self.counter = 0;
294 false
295 }
296 Some(best) if error < best => {
297 self.best = Some(error);
298 self.counter = 0;
299 false
300 }
301 Some(_) => {
302 // Saturating: past u32::MAX checks the answer stays `true`.
303 self.counter = self.counter.saturating_add(1);
304 self.counter >= self.patience
305 }
306 }
307 }
308}
309
310impl<V> Default for EarlyStopping<V> {
311 /// Patience 100, tinymind (C++)'s default.
312 fn default() -> Self {
313 Self::new(100)
314 }
315}
316
317/// Scheduled sampling for training a recurrent network on its own outputs
318/// (C++ `ScheduledSampling`, `cpp/teacherForcing.hpp`).
319///
320/// When a network is trained to predict a sequence one step ahead, each
321/// step's input can be the true value (teacher forcing) or the network's own
322/// previous prediction. Training only on true values leaves the network
323/// unprepared for its own errors when it later runs free; scheduled sampling
324/// starts with the true value every time and, over `total_decay_steps`
325/// training steps, moves linearly to the prediction every time.
326///
327/// [`select_input`](Self::select_input) picks one of the two. Inside the
328/// decay window it rolls `draw() % 1000` and returns the true value when the
329/// roll is below `(total - step) * 1000 / total`; from step `total` on it
330/// returns the prediction without calling `draw`. tinymind (C++) rolls with
331/// `rand()`; pass the same generator, for example
332/// `|| rng.next_i32() as u32` with [`GlibcRand`](crate::rand::GlibcRand), to
333/// reproduce a C++ run. Call [`step`](Self::step) once per training step.
334///
335/// ```
336/// use tinymind::rand::GlibcRand;
337/// use tinymind::training::ScheduledSampling;
338///
339/// let mut rng = GlibcRand::new(7);
340/// let mut sampler = ScheduledSampling::new(1000);
341/// let (truth, prediction) = (1.0, 0.5);
342/// // Step 0: the ratio is 1, so the true value always wins.
343/// assert_eq!(sampler.select_input(truth, prediction, || rng.next_i32() as u32), truth);
344/// for _ in 0..1000 {
345/// sampler.step();
346/// }
347/// // After the decay window, always the prediction.
348/// assert_eq!(sampler.teacher_forcing_ratio(), 0.0);
349/// assert_eq!(sampler.select_input(truth, prediction, || unreachable!()), prediction);
350/// ```
351#[derive(Clone, Copy, Debug, PartialEq, Eq)]
352pub struct ScheduledSampling {
353 pub(crate) total_decay_steps: usize,
354 pub(crate) current_step: usize,
355}
356
357impl ScheduledSampling {
358 /// A schedule that decays from always-true to always-prediction over
359 /// `total_decay_steps` training steps. With 0 it returns the prediction
360 /// from the start.
361 pub const fn new(total_decay_steps: usize) -> Self {
362 Self {
363 total_decay_steps,
364 current_step: 0,
365 }
366 }
367
368 /// Return `ground_truth` or `prediction` for the next input, as described
369 /// on the type. `draw` is called once inside the decay window and never
370 /// after it.
371 pub fn select_input<V>(&self, ground_truth: V, prediction: V, draw: impl FnOnce() -> u32) -> V {
372 let remaining = match self.total_decay_steps.checked_sub(self.current_step) {
373 Some(r) if r > 0 => r,
374 _ => return prediction,
375 };
376 // C++: ((total - step) * 1000U) / total in size_t, then unsigned.
377 let threshold = remaining
378 .wrapping_mul(1000)
379 .checked_div(self.total_decay_steps)
380 .unwrap_or(0) as u32;
381 if draw() % 1000 < threshold {
382 ground_truth
383 } else {
384 prediction
385 }
386 }
387
388 /// Advance one training step (no further than `total_decay_steps`).
389 pub fn step(&mut self) {
390 if self.current_step < self.total_decay_steps {
391 self.current_step += 1;
392 }
393 }
394
395 /// Back to step 0: the true value every time.
396 pub fn reset(&mut self) {
397 self.current_step = 0;
398 }
399
400 /// The share of inputs that are true values: 1 at step 0, falling
401 /// linearly to 0 at `total_decay_steps`.
402 pub fn teacher_forcing_ratio(&self) -> f64 {
403 if self.current_step >= self.total_decay_steps {
404 return 0.0;
405 }
406 (self.total_decay_steps - self.current_step) as f64 / self.total_decay_steps as f64
407 }
408
409 /// Training steps taken so far, at most `total_decay_steps`.
410 pub fn current_step(&self) -> usize {
411 self.current_step
412 }
413
414 /// The length of the decay window.
415 pub fn total_decay_steps(&self) -> usize {
416 self.total_decay_steps
417 }
418}
419
420/// C++ `L2WeightDecay::applyDecay` on every connection of `connections`:
421/// `w - (learning rate * lambda) * w`, where `factor` is the product
422/// `learning rate * lambda` (the C++ evaluates it left to right, so it is the
423/// same value for every weight). Never inlined, so a network has one copy
424/// however many layers call it.
425#[inline(never)]
426pub(crate) fn decay_weights<V: Scalar>(connections: &mut [Connection<V>], factor: V) {
427 for c in connections {
428 c.weight = c.weight - factor * c.weight;
429 }
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435 use crate::{Q8_8, Q16_16};
436
437 /// The defaults are tinymind (C++)'s `QFractionLsbs<Q, 9, 10>` with
438 /// `StepInterval = 1000`.
439 #[test]
440 fn step_decay_defaults_are_tinymind_cpp_constants() {
441 let s = StepDecay::<Q16_16>::default();
442 assert_eq!((s.interval, s.factor.raw()), (1000, 58_982));
443 let s = StepDecay::<Q8_8>::default();
444 assert_eq!((s.interval, s.factor.raw()), (1000, 230));
445 }
446
447 #[test]
448 fn step_decay_multiplies_every_interval() {
449 let half = Q16_16::from_raw(1 << 15);
450 let mut s = StepDecay::new(3, half);
451 let mut rate = Q16_16::ONE;
452 let mut rates = [0; 7];
453 for r in &mut rates {
454 rate = s.step(rate);
455 *r = rate.raw();
456 }
457 assert_eq!(
458 rates,
459 [65_536, 65_536, 32_768, 32_768, 32_768, 16_384, 16_384]
460 );
461 assert_eq!(s.steps_since_decay(), 1);
462 }
463
464 /// tinymind (C++)'s `test_case_teacher_forcing`: the ratio falls
465 /// linearly, the prediction wins after the window, `reset` starts over.
466 #[test]
467 fn scheduled_sampling_decays_linearly() {
468 let mut s = ScheduledSampling::new(100);
469 assert_eq!(s.teacher_forcing_ratio(), 1.0);
470 for _ in 0..50 {
471 s.step();
472 }
473 assert_eq!(s.teacher_forcing_ratio(), 0.5);
474 // Halfway: the threshold is 500, so a roll of 499 keeps the truth
475 // and 500 takes the prediction.
476 assert_eq!(s.select_input(1.0, 0.5, || 1499), 1.0);
477 assert_eq!(s.select_input(1.0, 0.5, || 500), 0.5);
478 for _ in 0..60 {
479 s.step();
480 }
481 assert_eq!((s.current_step(), s.teacher_forcing_ratio()), (100, 0.0));
482 assert_eq!(s.select_input(1.0, 0.5, || 0), 0.5);
483 s.reset();
484 assert_eq!((s.current_step(), s.teacher_forcing_ratio()), (0, 1.0));
485 assert_eq!(ScheduledSampling::new(0).select_input(1, 2, || 0), 2);
486 }
487
488 #[test]
489 fn step_decay_interval_zero_decays_every_step() {
490 let mut s = StepDecay::new(0, 0.5f64);
491 assert_eq!(s.step(1.0), 0.5);
492 assert_eq!(s.step(0.5), 0.25);
493 assert_eq!(s.steps_since_decay(), 0);
494 }
495
496 #[test]
497 fn early_stopping_counts_non_improving_checks() {
498 let mut e = EarlyStopping::new(2);
499 assert_eq!(e.best_error(), None);
500 assert!(!e.should_stop(5));
501 assert!(!e.should_stop(5)); // equal: count 1
502 assert!(e.should_stop(6)); // count 2
503 assert!(e.should_stop(7)); // still true
504 assert!(!e.should_stop(4)); // improved
505 assert_eq!((e.best_error(), e.patience_counter()), (Some(4), 0));
506 e.reset();
507 assert_eq!((e.best_error(), e.patience_counter()), (None, 0));
508 assert!(!e.should_stop(9));
509 }
510
511 #[test]
512 fn early_stopping_counts_nan_as_no_improvement() {
513 let mut e = EarlyStopping::new(1);
514 assert!(!e.should_stop(1.0f32));
515 assert!(e.should_stop(f32::NAN));
516 assert_eq!(e.best_error(), Some(1.0));
517 }
518
519 /// Lambda 0 and a factor of 1 change nothing: the wrapped optimizer
520 /// trains every network type exactly as the plain one does, in fixed
521 /// and floating point.
522 #[test]
523 fn neutral_wrappers_train_like_the_plain_optimizer() {
524 use crate::recurrent::LstmNetwork;
525 use crate::{Dense, Linear, MultilayerPerceptron, NeuralNetwork, Relu, Sgd, Sigmoid, Tanh};
526
527 fn weights(seed: &mut u32) -> i32 {
528 *seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
529 (*seed >> 16) as i32 % 32_769 - 16_384
530 }
531 let neutral =
532 |l: Q16_16| Scheduled::new(WeightDecay::new(Sgd, l), StepDecay::new(1, Q16_16::ONE));
533
534 let (mut s1, mut s2) = (1u32, 1u32);
535 let mut plain = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1>::new(|| {
536 Q16_16::from_raw(weights(&mut s1))
537 });
538 let mut wrapped = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1, _>::with_optimizer(
539 || Q16_16::from_raw(weights(&mut s2)),
540 neutral(Q16_16::ZERO),
541 );
542 let (mut s3, mut s4) = (2u32, 2u32);
543 let mut deep_plain =
544 NeuralNetwork::<(Dense<f64, Relu, 2, 3>, Dense<f64, Linear, 3, 1>)>::new(|| {
545 f64::from(weights(&mut s3)) / 65_536.0
546 });
547 let mut deep_wrapped =
548 NeuralNetwork::<(Dense<f64, Relu, 2, 3>, Dense<f64, Linear, 3, 1>), _>::with_optimizer(
549 || f64::from(weights(&mut s4)) / 65_536.0,
550 Scheduled::new(WeightDecay::new(Sgd, 0.0), StepDecay::new(1, 1.0)),
551 );
552 let (mut s5, mut s6) = (3u32, 3u32);
553 let mut lstm_plain = LstmNetwork::<Q16_16, Tanh, Sigmoid, 2, 3, 1>::new(|| {
554 Q16_16::from_raw(weights(&mut s5))
555 });
556 let mut lstm_wrapped = LstmNetwork::<Q16_16, Tanh, Sigmoid, 2, 3, 1, _>::with_optimizer(
557 || Q16_16::from_raw(weights(&mut s6)),
558 neutral(Q16_16::ZERO),
559 );
560 for step in 0..200 {
561 let (a, b) = (step % 2, (step / 2) % 2);
562 let x = [Q16_16::from_int(a), Q16_16::from_int(b)];
563 let t = [Q16_16::from_int(a ^ b)];
564 plain.feed_forward(&x);
565 plain.train(&t);
566 wrapped.feed_forward(&x);
567 wrapped.train(&t);
568 lstm_plain.feed_forward(&x);
569 lstm_plain.train(&t);
570 lstm_wrapped.feed_forward(&x);
571 lstm_wrapped.train(&t);
572 let xf = [f64::from(a), f64::from(b)];
573 let tf = [f64::from(a - b)];
574 deep_plain.feed_forward(&xf);
575 deep_plain.train(&tf);
576 deep_wrapped.feed_forward(&xf);
577 deep_wrapped.train(&tf);
578 }
579 assert_eq!(plain.input_weights(), wrapped.input_weights());
580 assert_eq!(plain.hidden_weights(), wrapped.hidden_weights());
581 assert_eq!(plain.learning_rate(), wrapped.learning_rate());
582 assert_eq!(lstm_plain.input_weights(), lstm_wrapped.input_weights());
583 assert_eq!(
584 lstm_plain.recurrent_weights(),
585 lstm_wrapped.recurrent_weights()
586 );
587 assert_eq!(lstm_plain.hidden_weights(), lstm_wrapped.hidden_weights());
588 assert_eq!(
589 deep_plain.layers().0.weights(),
590 deep_wrapped.layers().0.weights()
591 );
592 assert_eq!(
593 deep_plain.layers().1.weights(),
594 deep_wrapped.layers().1.weights()
595 );
596
597 // And a nonzero lambda does change the weights (bias weights alone
598 // are left to the optimizer).
599 let mut s7 = 1u32;
600 let mut decayed = MultilayerPerceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1, _>::with_optimizer(
601 || Q16_16::from_raw(weights(&mut s7)),
602 neutral(Q16_16::from_raw(655)),
603 );
604 for step in 0..200 {
605 let (a, b) = (step % 2, (step / 2) % 2);
606 decayed.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
607 decayed.train(&[Q16_16::from_int(a ^ b)]);
608 }
609 assert_ne!(plain.input_weights(), decayed.input_weights());
610 }
611
612 /// Wrappers pass the inner optimizer's decay and schedule through, so
613 /// nested schedules both apply (inner first) and the outer `WeightDecay`
614 /// wins.
615 #[test]
616 fn wrappers_compose() {
617 use crate::Sgd;
618 let half = Q16_16::from_raw(1 << 15);
619 let quarter = Q16_16::from_raw(1 << 14);
620 let mut opt = Scheduled::new(
621 WeightDecay::new(Scheduled::new(Sgd, StepDecay::new(1, half)), Q16_16::ONE),
622 StepDecay::new(2, quarter),
623 );
624 let one = Q16_16::ONE;
625 assert_eq!(opt.next_learning_rate(one), half); // inner only
626 assert_eq!(opt.next_learning_rate(one), Q16_16::from_raw(1 << 13)); // both
627 assert_eq!(opt.weight_decay(), Some(Q16_16::ONE));
628 let opt = WeightDecay::new(WeightDecay::new(Sgd, half), quarter);
629 assert_eq!(opt.weight_decay(), Some(quarter));
630 assert_eq!(OptimizerImpl::<Q16_16>::weight_decay(&Sgd), None);
631 }
632
633 #[test]
634 fn weight_decay_matches_the_cpp_expression() {
635 // lr 1/4, lambda 0.01 (655 raw): factor (1/4 * 655/65536) = 163 raw,
636 // floored; w = 2: 2 - 163/65536 * 2 = 131072 - 326.
637 let factor = Q16_16::from_raw(1 << 14) * Q16_16::from_raw(655);
638 assert_eq!(factor.raw(), 163);
639 let mut c = [Connection {
640 weight: Q16_16::from_int(2),
641 ..Connection::default()
642 }];
643 decay_weights(&mut c, factor);
644 assert_eq!(c[0].weight.raw(), 131_072 - 326);
645 }
646}