Skip to main content

tinymind/
network.rs

1//! A trainable feed-forward network with up to seven hidden layers, ported
2//! from tinymind (C++)'s `NeuralNetwork<ValueType, Inputs, HiddenLayers<...>,
3//! Outputs, ...>` (`cpp/neuralnet.hpp`, the chain-based path).
4//!
5//! The C++ network takes its hidden-layer sizes as a variadic template
6//! (`HiddenLayers<8, 6>`). Rust has no variadic generics, so here a network is
7//! a tuple of [`Dense`] layers, each sized by const generics:
8//!
9//! ```
10//! use tinymind::{Dense, NeuralNetwork, Q16_16, Relu, Sigmoid};
11//!
12//! // 4 inputs -> 8 ReLU -> 6 ReLU -> 3 sigmoid outputs.
13//! type Net = NeuralNetwork<(
14//!     Dense<Q16_16, Relu, 4, 8>,
15//!     Dense<Q16_16, Relu, 8, 6>,
16//!     Dense<Q16_16, Sigmoid, 6, 3>,
17//! )>;
18//!
19//! let mut seed = 1u32;
20//! let mut nn = Net::new(|| {
21//!     // Any source of small initial weights; here a tiny LCG in [-0.5, 0.5].
22//!     seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
23//!     Q16_16::from_raw((seed >> 16) as i32 % 32_769 - 16_384)
24//! });
25//! let x = [Q16_16::ONE, Q16_16::ZERO, Q16_16::ONE, Q16_16::ZERO];
26//! let target = [Q16_16::ONE, Q16_16::ZERO, Q16_16::ZERO];
27//! for _ in 0..100 {
28//!     nn.feed_forward(&x);
29//!     nn.train(&target);
30//! }
31//! nn.feed_forward(&x);
32//! let [a, b, c] = nn.learned_values();
33//! assert!(a > b && a > c);
34//! assert_eq!(nn.predicted_class(), 0);
35//! ```
36//!
37//! To pick a class, rank the output logits with `predicted_class()`
38//! (`output_pre_activations()` returns them) rather than `learned_values()`:
39//! the fixed-point sigmoid table is flat beyond ±6, so confident outputs tie.
40//!
41//! Adjacent layers must agree (`Dense<_, _, 4, 8>` then `Dense<_, _, 8, _>`),
42//! which the compiler checks. Each layer has its own activation; tinymind (C++)'s
43//! network uses one activation for every hidden layer, which is the special
44//! case where they are all the same. Tuples of 1 to 8 layers are supported.
45//!
46//! Training is SGD with momentum by default, or Adam or RMSprop ([`crate::optimizer`],
47//! through [`NeuralNetwork::with_optimizer`]), with optional gradient clipping
48//! ([`NeuralNetwork::set_gradient_clip`]) and optional L2 weight decay and a
49//! step-decay learning-rate schedule ([`crate::training`], wrapping the
50//! optimizer; fixed point only on the C++ side), and every result is bit-identical to the C++
51//! network with the same layer sizes, activations and initial weights (and to
52//! [`MultilayerPerceptron`](crate::MultilayerPerceptron) for one hidden layer).
53//!
54//! A trained network becomes an [`InferenceNetwork`] of [`InferenceDense`]
55//! layers, its weights only, with [`NeuralNetwork::to_inference`] (and back with
56//! [`NeuralNetwork::set_weights`]); that form can be a `static` in flash.
57//!
58//! The value type is any [`Scalar`]: a Q format, `f32` or `f64`.
59//! ReLU and linear layers need nothing more; [`Tanh`](crate::Tanh) and
60//! [`Sigmoid`](crate::Sigmoid) on floats need the `std` or `libm` feature.
61//!
62//! ```
63//! use tinymind::{Dense, Linear, NeuralNetwork, Relu};
64//!
65//! // A floating-point regression: 2 inputs -> 8 ReLU -> 1 linear output, y = a - b.
66//! let mut seed = 7u32;
67//! let mut nn = NeuralNetwork::<(Dense<f64, Relu, 2, 8>, Dense<f64, Linear, 8, 1>)>::new(|| {
68//!     seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
69//!     f64::from(seed >> 16) / 65_536.0 - 0.5
70//! });
71//! nn.set_learning_rate(0.05);
72//! for step in 0..4000 {
73//!     let (a, b) = (f64::from(step % 7) / 7.0, f64::from(step % 5) / 5.0);
74//!     nn.feed_forward(&[a, b]);
75//!     nn.train(&[a - b]);
76//! }
77//! nn.feed_forward(&[0.8, 0.2]);
78//! assert!((nn.learned_values()[0] - 0.6).abs() < 0.1);
79//! ```
80
81use core::marker::PhantomData;
82
83use crate::activation::Activation;
84use crate::neuralnet::{Connection, argmax};
85use crate::optimizer::{Optimizer, Sgd};
86use crate::qformat::Scalar;
87use crate::training::decay_weights;
88
89/// A fully connected layer: `IN` inputs (plus a bias) to `OUT` neurons with
90/// activation `A`, and the training state of every connection.
91///
92/// A layer is a building block for [`NeuralNetwork`]; on its own it only
93/// exposes its weights.
94pub struct Dense<V, A, const IN: usize, const OUT: usize> {
95    /// `weights[i][o]`: from input `i` to neuron `o`, stored by source as the
96    /// C++ stores a neuron's outgoing connections.
97    weights: [[Connection<V>; OUT]; IN],
98    /// From the bias input (always 1) to neuron `o`.
99    bias: [Connection<V>; OUT],
100    outputs: [V; OUT],
101    deltas: [V; OUT],
102    activation: PhantomData<fn() -> A>,
103}
104
105impl<V: Scalar, A, const IN: usize, const OUT: usize> Default for Dense<V, A, IN, OUT> {
106    fn default() -> Self {
107        Self {
108            weights: [[Connection::default(); OUT]; IN],
109            bias: [Connection::default(); OUT],
110            outputs: [V::ZERO; OUT],
111            deltas: [V::ZERO; OUT],
112            activation: PhantomData,
113        }
114    }
115}
116
117impl<V: Copy, A, const IN: usize, const OUT: usize> Dense<V, A, IN, OUT> {
118    /// The weights: `weights()[input][neuron]`.
119    pub fn weights(&self) -> [[V; OUT]; IN] {
120        self.weights.map(|row| row.map(|c| c.weight))
121    }
122
123    /// The bias weights: `bias_weights()[neuron]`.
124    pub fn bias_weights(&self) -> [V; OUT] {
125        self.bias.map(|c| c.weight)
126    }
127
128    /// Replace the weights, laid out as [`weights`](Self::weights) returns
129    /// them. The training state (delta weights, gradients) is kept.
130    pub fn set_weights(&mut self, weights: &[[V; OUT]; IN]) {
131        for (row, new) in self.weights.iter_mut().zip(weights) {
132            for (c, &w) in row.iter_mut().zip(new) {
133                c.weight = w;
134            }
135        }
136    }
137
138    /// Replace the bias weights.
139    pub fn set_bias_weights(&mut self, weights: &[V; OUT]) {
140        for (c, &w) in self.bias.iter_mut().zip(weights) {
141            c.weight = w;
142        }
143    }
144
145    /// The neurons' activations from the latest forward pass.
146    pub fn outputs(&self) -> [V; OUT] {
147        self.outputs
148    }
149}
150
151impl<V: Scalar, A: Activation<V>, const IN: usize, const OUT: usize> Dense<V, A, IN, OUT> {
152    /// C++ `initializeWeights` for this layer's sources: each input's outgoing
153    /// connections in order (one random draw each, then the delta weights
154    /// zeroed), then the bias neuron's.
155    fn initialize(&mut self, random_weight: &mut dyn FnMut() -> V) {
156        for row in self
157            .weights
158            .iter_mut()
159            .chain(core::iter::once(&mut self.bias))
160        {
161            for c in row.iter_mut() {
162                c.weight = random_weight();
163            }
164            for c in row.iter_mut() {
165                c.set_delta_weight(V::ZERO);
166            }
167        }
168    }
169
170    /// `out[o] = A(1 * bias[o] + (0 + in[0] * w[0][o] + in[1] * w[1][o] + ...))`,
171    /// the C++ sum order.
172    fn forward(&mut self, input: &[V; IN]) {
173        for o in 0..OUT {
174            let sum = self.pre_activation(input, o);
175            if let Some(out) = self.outputs.get_mut(o) {
176                *out = A::activate(sum);
177            }
178        }
179    }
180
181    /// Neuron `o`'s sum before the activation, `1 * bias[o] + (0 + in[0] *
182    /// w[0][o] + ...)`. Shared by [`forward`](Self::forward) and
183    /// [`NeuralNetwork::output_pre_activations`], so the two agree bit for bit.
184    fn pre_activation(&self, input: &[V; IN], o: usize) -> V {
185        // Callers pass o < OUT; the lookups are total anyway so that no
186        // bounds-check panic survives when this is not inlined.
187        let weight = |c: Option<&Connection<V>>| c.map_or(V::ZERO, |c| c.weight);
188        let mut sum = V::ONE * weight(self.bias.get(o));
189        let mut layer_sum = V::ZERO;
190        for (&x, row) in input.iter().zip(&self.weights) {
191            layer_sum += x * weight(row.get(o));
192        }
193        sum += layer_sum;
194        sum
195    }
196
197    /// Output-layer deltas: `(target - out) * A'(out)`.
198    fn output_deltas(&mut self, targets: &[V; OUT]) {
199        for ((delta, &out), &target) in self.deltas.iter_mut().zip(&self.outputs).zip(targets) {
200            *delta = (target - out) * A::derivative(out);
201        }
202    }
203
204    /// Hidden-layer deltas from the error the next layer sends back:
205    /// `signal * A'(out)`.
206    fn hidden_deltas(&mut self, signal: &[V; OUT]) {
207        for ((delta, &out), &s) in self.deltas.iter_mut().zip(&self.outputs).zip(signal) {
208            *delta = s * A::derivative(out);
209        }
210    }
211
212    /// The error this layer sends back to each input: `sum_o w[i][o] *
213    /// delta[o]`, summed from zero in neuron order (C++ `calculateAndSetNodeDeltas`).
214    fn back_signal(&self) -> [V; IN] {
215        self.weights.map(|row| {
216            let mut sum = V::ZERO;
217            for (c, &delta) in row.iter().zip(&self.deltas) {
218                sum += c.weight * delta;
219            }
220            sum
221        })
222    }
223
224    /// `gradient = source output * delta`; the bias input is 1.
225    fn gradients(&mut self, input: &[V; IN]) {
226        for (row, &x) in self.weights.iter_mut().zip(input) {
227            for (c, &delta) in row.iter_mut().zip(&self.deltas) {
228                c.gradient = x * delta;
229            }
230        }
231        for (c, &delta) in self.bias.iter_mut().zip(&self.deltas) {
232            c.gradient = V::ONE * delta;
233        }
234    }
235
236    /// One optimizer step on every connection (C++ `updateConnectionWeights`
237    /// for this layer). Each update reads only its own connection, so the
238    /// order does not matter. `clip` applies to the weights and the bias
239    /// weights alike, as in the C++.
240    fn update<Opt: Optimizer<V>>(
241        &mut self,
242        rates: (V, V, V),
243        clip: Option<(V, V)>,
244        decay: Option<V>,
245        optimizer: &mut Opt,
246    ) {
247        // Weight decay (`decay` = learning rate * lambda) on the weights, not
248        // the bias weights, before the step: the C++ decays each weight just
249        // before adding its step, and no update reads the weight.
250        if let Some(factor) = decay {
251            decay_weights(self.weights.as_flattened_mut(), factor);
252        }
253        crate::optimizer::update_all(optimizer, self.weights.as_flattened_mut(), rates, clip);
254        crate::optimizer::update_all(optimizer, &mut self.bias, rates, clip);
255    }
256}
257
258/// A fully connected layer holding only its weights: the inference-only form
259/// of [`Dense`] (C++ `IsTrainable = false`), for [`InferenceNetwork`].
260///
261/// One value per connection, no training state, and [`new`](Self::new) is a
262/// `const fn`, so trained weights can be a `static` in flash.
263pub struct InferenceDense<V, A, const IN: usize, const OUT: usize> {
264    /// `weights[i][o]`: from input `i` to neuron `o`, as [`Dense::weights`]
265    /// returns them.
266    pub weights: [[V; OUT]; IN],
267    /// `bias_weights[o]`: the bias input's weight to neuron `o`.
268    pub bias_weights: [V; OUT],
269    activation: PhantomData<fn() -> A>,
270}
271
272impl<V: Copy, A, const IN: usize, const OUT: usize> Clone for InferenceDense<V, A, IN, OUT> {
273    fn clone(&self) -> Self {
274        *self
275    }
276}
277
278impl<V: Copy, A, const IN: usize, const OUT: usize> Copy for InferenceDense<V, A, IN, OUT> {}
279
280impl<V, A, const IN: usize, const OUT: usize> InferenceDense<V, A, IN, OUT> {
281    /// A layer with these weights, laid out as [`Dense::weights`] and
282    /// [`Dense::bias_weights`] return them.
283    pub const fn new(weights: [[V; OUT]; IN], bias_weights: [V; OUT]) -> Self {
284        Self {
285            weights,
286            bias_weights,
287            activation: PhantomData,
288        }
289    }
290}
291
292impl<V: Scalar, A: Activation<V>, const IN: usize, const OUT: usize> InferenceDense<V, A, IN, OUT> {
293    /// `out[o] = A(1 * bias[o] + (0 + in[0] * w[0][o] + in[1] * w[1][o] + ...))`,
294    /// the C++ sum order, as [`Dense`] computes it.
295    pub fn forward(&self, input: &[V; IN]) -> [V; OUT] {
296        let mut out = [V::ZERO; OUT];
297        for (o, y) in out.iter_mut().enumerate() {
298            let mut sum = V::ONE * self.bias_weights[o];
299            let mut layer_sum = V::ZERO;
300            for (&x, row) in input.iter().zip(&self.weights) {
301                layer_sum += x * row[o];
302            }
303            sum += layer_sum;
304            *y = A::activate(sum);
305        }
306        out
307    }
308}
309
310impl<V: Copy, A, const IN: usize, const OUT: usize> Dense<V, A, IN, OUT> {
311    /// This layer's weights as an [`InferenceDense`].
312    pub fn to_inference(&self) -> InferenceDense<V, A, IN, OUT> {
313        InferenceDense::new(self.weights(), self.bias_weights())
314    }
315
316    /// Load the weights of an [`InferenceDense`] of the same shape (the
317    /// training state is left as it is).
318    pub fn set_from(&mut self, from: &InferenceDense<V, A, IN, OUT>) {
319        self.set_weights(&from.weights);
320        self.set_bias_weights(&from.bias_weights);
321    }
322}
323
324mod sealed {
325    /// The per-network operations, implemented for tuples of [`Dense`] layers
326    /// whose sizes chain. Sealed: the set of layer types is the crate's to grow.
327    ///
328    /// [`Dense`]: super::Dense
329    pub trait LayersImpl {
330        type Value: Copy;
331        type Inputs: Copy;
332        type Outputs: Copy + AsRef<[Self::Value]>;
333
334        fn zero_inputs() -> Self::Inputs;
335        fn initialize(&mut self, random_weight: &mut dyn FnMut() -> Self::Value);
336        fn feed_forward(&mut self, inputs: &Self::Inputs);
337        fn outputs(&self) -> Self::Outputs;
338        /// The last layer's sums before its activation, for the latest
339        /// `feed_forward` of `inputs`.
340        fn output_pre_activations(&self, inputs: &Self::Inputs) -> Self::Outputs;
341        fn calculate_error(&self, targets: &Self::Outputs) -> Self::Value;
342        fn train<Opt: crate::optimizer::Optimizer<Self::Value>>(
343            &mut self,
344            inputs: &Self::Inputs,
345            targets: &Self::Outputs,
346            rates: (Self::Value, Self::Value, Self::Value),
347            clip: Option<(Self::Value, Self::Value)>,
348            decay: Option<Self::Value>,
349            optimizer: &mut Opt,
350        );
351        /// Number of output neurons: each owns one unused C++ connection whose
352        /// initialisation consumes a random draw.
353        const OUTPUTS: usize;
354        /// The same stack as [`InferenceDense`](super::InferenceDense) layers.
355        type Inference: InferenceLayersImpl<Inputs = Self::Inputs, Outputs = Self::Outputs>;
356        fn to_inference(&self) -> Self::Inference;
357        fn set_from(&mut self, from: &Self::Inference);
358    }
359
360    /// The forward pass over a tuple of
361    /// [`InferenceDense`](super::InferenceDense) layers whose sizes chain.
362    pub trait InferenceLayersImpl {
363        type Inputs: Copy;
364        type Outputs: Copy;
365        fn feed_forward(&self, inputs: &Self::Inputs) -> Self::Outputs;
366    }
367}
368
369/// A stack of layers [`NeuralNetwork`] can run: a tuple of 1 to 8 [`Dense`]
370/// layers in which each layer's `OUT` is the next layer's `IN`. Implemented
371/// by the crate only.
372pub trait Layers: sealed::LayersImpl {}
373
374impl<T: sealed::LayersImpl> Layers for T {}
375
376/// A stack of layers [`InferenceNetwork`] can run: a tuple of 1 to 8
377/// [`InferenceDense`] layers in which each layer's `OUT` is the next layer's
378/// `IN`. Implemented by the crate only.
379pub trait InferenceLayers: sealed::InferenceLayersImpl {}
380
381impl<T: sealed::InferenceLayersImpl> InferenceLayers for T {}
382
383/// Mean-squared error against `targets` (C++ `MeanSquaredErrorCalculator`):
384/// the sum of squared differences, divided by the output count when it is more
385/// than one.
386fn mean_squared_error<V: Scalar, const OUT: usize>(outputs: &[V; OUT], targets: &[V; OUT]) -> V {
387    let mut error = V::ZERO;
388    for (&target, &out) in targets.iter().zip(outputs) {
389        let delta = target - out;
390        error += delta * delta;
391    }
392    if OUT > 1 {
393        error = error.div_int(OUT as i32);
394    }
395    error
396}
397
398/// Implements the layer-stack operations for one tuple arity. `fwd` lists the
399/// adjacent pairs `prev > next` from the input side, `back` the same pairs from
400/// the output side.
401macro_rules! impl_layers {
402    (
403        [$($idx:tt: $act:ident, $din:ident, $dout:ident);+]
404        first $first:tt, $d0:ident; last $last:tt, $dn:ident;
405        fwd [$($prev:tt > $next:tt),*]; back [$($hi:tt > $lo:tt),*];
406        consts [$($d:ident),+]
407    ) => {
408        impl<V: Scalar, $($act: Activation<V>,)+ $(const $d: usize,)+> sealed::LayersImpl
409            for ($(Dense<V, $act, $din, $dout>,)+)
410        {
411            type Value = V;
412            type Inputs = [V; $d0];
413            type Outputs = [V; $dn];
414            const OUTPUTS: usize = $dn;
415
416            fn zero_inputs() -> [V; $d0] {
417                [V::ZERO; $d0]
418            }
419
420            fn initialize(&mut self, random_weight: &mut dyn FnMut() -> V) {
421                $(self.$idx.initialize(random_weight);)+
422            }
423
424            fn feed_forward(&mut self, inputs: &[V; $d0]) {
425                self.$first.forward(inputs);
426                $(self.$next.forward(&self.$prev.outputs);)*
427            }
428
429            fn outputs(&self) -> [V; $dn] {
430                self.$last.outputs
431            }
432
433            fn output_pre_activations(&self, inputs: &[V; $d0]) -> [V; $dn] {
434                // The last layer's input: the network inputs, shadowed by each
435                // layer's outputs in turn, so the last binding is the layer
436                // before the output layer (or the inputs for one layer).
437                let _input = inputs;
438                $(let _input = &self.$prev.outputs;)*
439                core::array::from_fn(|o| self.$last.pre_activation(_input, o))
440            }
441
442            fn calculate_error(&self, targets: &[V; $dn]) -> V {
443                mean_squared_error(&self.$last.outputs, targets)
444            }
445
446            fn train<Opt: Optimizer<V>>(
447                &mut self,
448                inputs: &[V; $d0],
449                targets: &[V; $dn],
450                rates: (V, V, V),
451                clip: Option<(V, V)>,
452                decay: Option<V>,
453                optimizer: &mut Opt,
454            ) {
455                // Deltas from the output back (C++ ChainNetworkDeltasCalculator),
456                // all computed before any weight changes.
457                self.$last.output_deltas(targets);
458                $(
459                    let signal = self.$hi.back_signal();
460                    self.$lo.hidden_deltas(&signal);
461                )*
462                // Gradients (ChainNetworkGradientsCalculator), then one
463                // optimizer step (beginTrainingStep) and the updates from the
464                // output layer back (ChainBackPropConnectionWeightUpdater).
465                self.$first.gradients(inputs);
466                $(self.$next.gradients(&self.$prev.outputs);)*
467                optimizer.begin_step();
468                self.$last.update(rates, clip, decay, optimizer);
469                $(self.$lo.update(rates, clip, decay, optimizer);)*
470            }
471
472            type Inference = ($(InferenceDense<V, $act, $din, $dout>,)+);
473
474            fn to_inference(&self) -> Self::Inference {
475                ($(self.$idx.to_inference(),)+)
476            }
477
478            fn set_from(&mut self, from: &Self::Inference) {
479                $(self.$idx.set_from(&from.$idx);)+
480            }
481        }
482
483        impl<V: Scalar, $($act: Activation<V>,)+ $(const $d: usize,)+> sealed::InferenceLayersImpl
484            for ($(InferenceDense<V, $act, $din, $dout>,)+)
485        {
486            type Inputs = [V; $d0];
487            type Outputs = [V; $dn];
488
489            fn feed_forward(&self, inputs: &[V; $d0]) -> [V; $dn] {
490                let x = self.$first.forward(inputs);
491                $(let x = self.$next.forward(&x);)*
492                x
493            }
494        }
495    };
496}
497
498impl_layers!([0: A0, D0, D1] first 0, D0; last 0, D1; fwd []; back []; consts [D0, D1]);
499impl_layers!([0: A0, D0, D1; 1: A1, D1, D2] first 0, D0; last 1, D2;
500    fwd [0 > 1]; back [1 > 0]; consts [D0, D1, D2]);
501impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3] first 0, D0; last 2, D3;
502    fwd [0 > 1, 1 > 2]; back [2 > 1, 1 > 0]; consts [D0, D1, D2, D3]);
503impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4] first 0, D0; last 3, D4;
504    fwd [0 > 1, 1 > 2, 2 > 3]; back [3 > 2, 2 > 1, 1 > 0]; consts [D0, D1, D2, D3, D4]);
505impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4; 4: A4, D4, D5]
506    first 0, D0; last 4, D5;
507    fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4]; back [4 > 3, 3 > 2, 2 > 1, 1 > 0];
508    consts [D0, D1, D2, D3, D4, D5]);
509impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4; 4: A4, D4, D5; 5: A5, D5, D6]
510    first 0, D0; last 5, D6;
511    fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4, 4 > 5]; back [5 > 4, 4 > 3, 3 > 2, 2 > 1, 1 > 0];
512    consts [D0, D1, D2, D3, D4, D5, D6]);
513impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4; 4: A4, D4, D5; 5: A5, D5, D6;
514    6: A6, D6, D7]
515    first 0, D0; last 6, D7;
516    fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4, 4 > 5, 5 > 6]; back [6 > 5, 5 > 4, 4 > 3, 3 > 2, 2 > 1, 1 > 0];
517    consts [D0, D1, D2, D3, D4, D5, D6, D7]);
518impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4; 4: A4, D4, D5; 5: A5, D5, D6;
519    6: A6, D6, D7; 7: A7, D7, D8]
520    first 0, D0; last 7, D8;
521    fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4, 4 > 5, 5 > 6, 6 > 7];
522    back [7 > 6, 6 > 5, 5 > 4, 4 > 3, 3 > 2, 2 > 1, 1 > 0];
523    consts [D0, D1, D2, D3, D4, D5, D6, D7, D8]);
524
525/// A trainable feed-forward network over a tuple of [`Dense`] layers (C++
526/// `NeuralNetwork<..., HiddenLayers<...>, ...>`). See the [module
527/// documentation](self) for an example.
528///
529/// `Opt` is the optimizer: [`Sgd`] (the default) or an adaptive one from
530/// [`optimizer`](crate::optimizer), passed to [`with_optimizer`](Self::with_optimizer).
531pub struct NeuralNetwork<L: Layers, Opt = Sgd> {
532    layers: L,
533    inputs: L::Inputs,
534    learning_rate: L::Value,
535    momentum_rate: L::Value,
536    acceleration_rate: L::Value,
537    gradient_clip: Option<(L::Value, L::Value)>,
538    optimizer: Opt,
539}
540
541impl<V: Scalar, L: Layers<Value = V> + Default> NeuralNetwork<L, Sgd> {
542    /// Build the network, trained with [`Sgd`], and initialise its weights from
543    /// `random_weight`, in the C++ order: each layer's inputs and then its bias,
544    /// from the input side, then one draw per output neuron (the C++ output
545    /// neurons own an unused connection whose initialisation consumes a draw).
546    pub fn new(random_weight: impl FnMut() -> V) -> Self {
547        Self::with_optimizer(random_weight, Sgd)
548    }
549}
550
551impl<V: Scalar, L: Layers<Value = V> + Default, Opt: Optimizer<V>> NeuralNetwork<L, Opt> {
552    /// As [`new`](NeuralNetwork::new), trained with `optimizer`, for example
553    /// [`Adam`](crate::Adam).
554    pub fn with_optimizer(mut random_weight: impl FnMut() -> V, optimizer: Opt) -> Self {
555        let mut layers = L::default();
556        layers.initialize(&mut random_weight);
557        for _ in 0..L::OUTPUTS {
558            random_weight();
559        }
560        Self {
561            layers,
562            inputs: L::zero_inputs(),
563            // DefaultNetworkInitializer: 1/4, 1/2, 1/16.
564            learning_rate: V::pow2_neg(2),
565            momentum_rate: V::pow2_neg(1),
566            acceleration_rate: V::pow2_neg(4),
567            gradient_clip: None,
568            optimizer,
569        }
570    }
571}
572
573impl<V: Scalar, L: Layers<Value = V>, Opt: Optimizer<V>> NeuralNetwork<L, Opt> {
574    /// The optimizer, for example to read [`Adam::timestep`](crate::Adam::timestep).
575    pub fn optimizer(&self) -> &Opt {
576        &self.optimizer
577    }
578
579    /// Replace the learning rate (default `2^-2`).
580    pub fn set_learning_rate(&mut self, rate: V) {
581        self.learning_rate = rate;
582    }
583
584    /// Replace the momentum rate (default `2^-1`).
585    pub fn set_momentum_rate(&mut self, rate: V) {
586        self.momentum_rate = rate;
587    }
588
589    /// Replace the acceleration rate, the weight on the delta weight from two
590    /// steps back (default `2^-4`).
591    pub fn set_acceleration_rate(&mut self, rate: V) {
592        self.acceleration_rate = rate;
593    }
594
595    /// Clip each weight's and bias weight's gradient to `[min, max]` before
596    /// the update, or `None` (the default). C++ `GradientClipByValue<ValueType,
597    /// I, F>` is `Some((-b, b))` with `b = QValue(I, F)`; the default
598    /// `GradientClipByValue<ValueType>` is `Some((-1.0, 1.0))`.
599    pub fn set_gradient_clip(&mut self, range: Option<(V, V)>) {
600        self.gradient_clip = range;
601    }
602
603    /// The learning rate the next training step will use: the one set with
604    /// [`set_learning_rate`](Self::set_learning_rate), as a
605    /// [`Scheduled`](crate::training::Scheduled) optimizer has decayed it so far.
606    pub fn learning_rate(&self) -> V {
607        self.learning_rate
608    }
609
610    /// Run one forward pass. Read the result with
611    /// [`learned_values`](Self::learned_values).
612    pub fn feed_forward(&mut self, inputs: &L::Inputs) {
613        self.inputs = *inputs;
614        self.layers.feed_forward(inputs);
615    }
616
617    /// The output layer's activations from the latest forward pass.
618    pub fn learned_values(&self) -> L::Outputs {
619        self.layers.outputs()
620    }
621
622    /// The output layer's pre-activations (the logits) for the latest
623    /// [`feed_forward`](Self::feed_forward) (C++ `getOutputPreActivations`).
624    ///
625    /// Recomputed from the layer before the output layer with the sum
626    /// `feed_forward` forms, so they match it bit for bit and cost no memory.
627    ///
628    /// Call it before [`train`](Self::train): training changes the weights it
629    /// is recomputed from.
630    pub fn output_pre_activations(&self) -> L::Outputs {
631        self.layers.output_pre_activations(&self.inputs)
632    }
633
634    /// The index of the largest [output pre-activation](Self::output_pre_activations)
635    /// for the latest [`feed_forward`](Self::feed_forward), ties to the lower
636    /// index (C++ `getPredictedClass`).
637    ///
638    /// Use it, not an argmax of [`learned_values`](Self::learned_values), to
639    /// pick a class: the fixed-point sigmoid table is flat beyond ±6, so
640    /// confident outputs tie there and an argmax can only take the first.
641    ///
642    /// Call it before [`train`](Self::train): training changes the weights it
643    /// is recomputed from.
644    pub fn predicted_class(&self) -> usize {
645        argmax(self.layers.output_pre_activations(&self.inputs).as_ref())
646    }
647
648    /// Mean-squared error of the latest forward pass against `targets` (C++
649    /// `MeanSquaredErrorCalculator`).
650    pub fn calculate_error(&self, targets: &L::Outputs) -> V {
651        self.layers.calculate_error(targets)
652    }
653
654    /// One back-propagation step towards `targets` for the latest forward pass
655    /// (C++ `ChainBackPropagationPolicy`).
656    pub fn train(&mut self, targets: &L::Outputs) {
657        let rates = (
658            self.learning_rate,
659            self.momentum_rate,
660            self.acceleration_rate,
661        );
662        self.layers.train(
663            &self.inputs,
664            targets,
665            rates,
666            self.gradient_clip,
667            self.optimizer
668                .weight_decay()
669                .map(|lambda| self.learning_rate * lambda),
670            &mut self.optimizer,
671        );
672        // C++ stepLearningRate, after the update.
673        self.learning_rate = self.optimizer.next_learning_rate(self.learning_rate);
674    }
675
676    /// The layers, to read their weights (`nn.layers().0.weights()`).
677    pub fn layers(&self) -> &L {
678        &self.layers
679    }
680
681    /// The layers, to load weights (`nn.layers_mut().0.set_weights(..)`).
682    pub fn layers_mut(&mut self) -> &mut L {
683        &mut self.layers
684    }
685
686    /// The trained network as an [`InferenceNetwork`]: the same weights and the
687    /// same outputs, bit for bit, without the training state.
688    pub fn to_inference(&self) -> InferenceNetwork<L::Inference> {
689        InferenceNetwork::new(self.layers.to_inference())
690    }
691
692    /// Load every weight from an inference network of the same shape, for
693    /// example to keep training shipped weights on the device. The optimizer
694    /// state and delta weights are left as they are.
695    pub fn set_weights(&mut self, from: &InferenceNetwork<L::Inference>) {
696        self.layers.set_from(&from.layers);
697    }
698}
699
700/// An inference-only feed-forward network over a tuple of [`InferenceDense`]
701/// layers: tinymind (C++)'s `NeuralNetwork<..., HiddenLayers<...>, ...>` with
702/// `IsTrainable = false`, and the any-depth form of
703/// [`InferencePerceptron`](crate::InferencePerceptron).
704///
705/// Train with [`NeuralNetwork`] (on a host or on the device), then ship this:
706/// one value per connection, no per-neuron state and no training code. Its
707/// outputs are bit-identical to the trainable network's with the same
708/// weights. [`feed_forward`](Self::feed_forward) takes `&self`, and
709/// [`new`](Self::new) and [`InferenceDense::new`] are `const fn`, so a trained
710/// network can be a `static`:
711///
712/// ```
713/// use tinymind::{InferenceDense, InferenceNetwork, Q16_16, Relu, Sigmoid};
714///
715/// const fn q(x: i32) -> Q16_16 {
716///     Q16_16::from_int(x)
717/// }
718///
719/// // 2 inputs -> 2 ReLU -> 2 ReLU -> 1 sigmoid output: XOR by hand (OR minus
720/// // twice AND, then a margin). Weights from `NeuralNetwork::to_inference`
721/// // go here the same way.
722/// static XOR: InferenceNetwork<(
723///     InferenceDense<Q16_16, Relu, 2, 2>,
724///     InferenceDense<Q16_16, Relu, 2, 2>,
725///     InferenceDense<Q16_16, Sigmoid, 2, 1>,
726/// )> = InferenceNetwork::new((
727///     InferenceDense::new([[q(1), q(1)], [q(1), q(1)]], [q(0), q(-1)]), // [OR-ish, AND]
728///     InferenceDense::new([[q(1), q(0)], [q(-2), q(0)]], [q(0), q(0)]), // OR - 2 AND
729///     InferenceDense::new([[q(8)], [q(0)]], [q(-4)]),
730/// ));
731///
732/// let half = Q16_16::from_raw(1 << 15);
733/// for (a, b, want) in [(0, 0, false), (0, 1, true), (1, 0, true), (1, 1, false)] {
734///     let [y] = XOR.feed_forward(&[q(a), q(b)]);
735///     assert_eq!(y > half, want);
736/// }
737/// ```
738pub struct InferenceNetwork<L> {
739    /// The layers, first to last.
740    pub layers: L,
741}
742
743impl<L> InferenceNetwork<L> {
744    /// A network over these layers.
745    pub const fn new(layers: L) -> Self {
746        Self { layers }
747    }
748}
749
750impl<L: InferenceLayers> InferenceNetwork<L> {
751    /// One forward pass: the output layer's activations. Nothing is kept
752    /// between calls.
753    pub fn feed_forward(&self, inputs: &L::Inputs) -> L::Outputs {
754        self.layers.feed_forward(inputs)
755    }
756}
757
758#[cfg(test)]
759mod tests {
760    use super::*;
761    use crate::activation::{Linear, Relu, Sigmoid, Tanh};
762    use crate::rand::GlibcRand;
763    use crate::{MultilayerPerceptron, Q8_8, Q16_16};
764
765    /// A two-layer network is the one-hidden-layer MultilayerPerceptron (which
766    /// is bit-exact with the C++): the same random draws, outputs, errors and
767    /// weights after every training step.
768    fn same_as_perceptron<V, H, O, const IN: usize, const HID: usize, const OUT: usize>(
769        raw: impl Fn(i32) -> V,
770        seed: u32,
771    ) where
772        V: Scalar + PartialEq + core::fmt::Debug,
773        H: Activation<V>,
774        O: Activation<V>,
775    {
776        let mut a = GlibcRand::new(seed);
777        let mut b = GlibcRand::new(seed);
778        let mut mlp = MultilayerPerceptron::<V, H, O, IN, HID, OUT>::new(|| raw(a.next_i32()));
779        let mut net = NeuralNetwork::<(Dense<V, H, IN, HID>, Dense<V, O, HID, OUT>)>::new(|| {
780            raw(b.next_i32())
781        });
782        assert_eq!(a.next_i32(), b.next_i32(), "same number of draws");
783
784        let mut data = GlibcRand::new(seed + 1000);
785        for step in 0..500 {
786            let input: [V; IN] = core::array::from_fn(|_| raw(data.next_i32()));
787            let target: [V; OUT] = core::array::from_fn(|_| raw(data.next_i32()));
788            mlp.feed_forward(&input);
789            net.feed_forward(&input);
790            assert_eq!(net.learned_values(), mlp.learned_values(), "step {step}");
791            assert_eq!(net.calculate_error(&target), mlp.calculate_error(&target));
792            assert_eq!(net.output_pre_activations(), mlp.output_pre_activations());
793            assert_eq!(net.predicted_class(), mlp.predicted_class());
794            mlp.train(&target);
795            net.train(&target);
796            let (l0, l1) = net.layers();
797            assert_eq!(l0.weights(), mlp.input_weights(), "step {step}");
798            assert_eq!(l0.bias_weights(), mlp.input_bias_weights());
799            assert_eq!(l1.weights(), mlp.hidden_weights());
800            assert_eq!(l1.bias_weights(), mlp.hidden_bias_weights());
801        }
802    }
803
804    /// Within +-1.0 (`one` is the format's 1.0 in raw units).
805    fn unit(r: i32, one: i32) -> i32 {
806        r % (2 * one + 1) - one
807    }
808
809    #[test]
810    fn two_layers_match_multilayer_perceptron() {
811        let q16 = |r: i32| Q16_16::from_raw(unit(r, 1 << 16));
812        let q8 = |r: i32| Q8_8::from_raw(unit(r, 1 << 8) as i16);
813        same_as_perceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1>(q16, 1);
814        same_as_perceptron::<Q16_16, Relu, Sigmoid, 4, 8, 3>(q16, 2);
815        same_as_perceptron::<Q8_8, Tanh, Sigmoid, 2, 4, 1>(q8, 3);
816        same_as_perceptron::<Q8_8, Relu, Sigmoid, 4, 8, 3>(q8, 4);
817    }
818
819    /// The same with a linear output, gradient clipping and every rate set:
820    /// the settings tinymind (C++)'s energy_efficiency example uses, on random data
821    /// large enough that the clip and the unclipped biases both matter.
822    #[test]
823    fn two_layers_match_perceptron_with_clipping() {
824        let mut a = GlibcRand::new(11);
825        let mut b = GlibcRand::new(11);
826        let w = |r: i32| Q16_16::from_raw(unit(r, 1 << 15));
827        let mut mlp =
828            MultilayerPerceptron::<Q16_16, Relu, Linear, 3, 5, 2>::new(|| w(a.next_i32()));
829        let mut net =
830            NeuralNetwork::<(Dense<Q16_16, Relu, 3, 5>, Dense<Q16_16, Linear, 5, 2>)>::new(|| {
831                w(b.next_i32())
832            });
833        let range = (Q16_16::from_raw(-(1 << 15)), Q16_16::ONE);
834        let lr = Q16_16::from_raw(1 << 10);
835        mlp.set_learning_rate(lr);
836        net.set_learning_rate(lr);
837        mlp.set_acceleration_rate(Q16_16::from_raw(1 << 12));
838        net.set_acceleration_rate(Q16_16::from_raw(1 << 12));
839        mlp.set_gradient_clip(Some(range));
840        net.set_gradient_clip(Some(range));
841        let mut data = GlibcRand::new(12);
842        for step in 0..1000 {
843            let input: [Q16_16; 3] =
844                core::array::from_fn(|_| Q16_16::from_raw(unit(data.next_i32(), 1 << 16)));
845            let target: [Q16_16; 2] =
846                core::array::from_fn(|_| Q16_16::from_raw(unit(data.next_i32(), 8 << 16)));
847            mlp.feed_forward(&input);
848            net.feed_forward(&input);
849            assert_eq!(net.learned_values(), mlp.learned_values(), "step {step}");
850            mlp.train(&target);
851            net.train(&target);
852            assert_eq!(net.layers().0.weights(), mlp.input_weights(), "step {step}");
853            assert_eq!(
854                net.layers().1.bias_weights(),
855                mlp.hidden_bias_weights(),
856                "step {step}"
857            );
858        }
859    }
860
861    /// The output layer's activation `O` applied to the pre-activations gives
862    /// `learned_values` bit for bit, and the predicted class is their argmax.
863    fn pre_activations_reproduce_outputs<V, O, L, const N: usize>(
864        mut net: NeuralNetwork<L>,
865        mut input: impl FnMut() -> L::Inputs,
866    ) where
867        V: Scalar + PartialEq + core::fmt::Debug,
868        O: Activation<V>,
869        L: Layers<Value = V, Outputs = [V; N]>,
870    {
871        for sample in 0..200 {
872            net.feed_forward(&input());
873            let pre = net.output_pre_activations();
874            assert_eq!(
875                pre.map(O::activate),
876                net.learned_values(),
877                "sample {sample}"
878            );
879            assert_eq!(net.predicted_class(), argmax(&pre), "sample {sample}");
880        }
881    }
882
883    #[test]
884    fn pre_activations_reproduce_outputs_for_every_depth() {
885        // Weights over the whole storage range, so the sums wrap.
886        let wide = |r: i32| Q16_16::from_raw(r.wrapping_mul(2_654_435_761u32 as i32));
887        let q8 = |r: i32| Q8_8::from_raw(unit(r, 4 << 8) as i16);
888        let mut w = GlibcRand::new(21);
889        let mut x = GlibcRand::new(22);
890
891        let one = NeuralNetwork::<(Dense<Q16_16, Sigmoid, 3, 4>,)>::new(|| wide(w.next_i32()));
892        pre_activations_reproduce_outputs::<_, Sigmoid, _, 4>(one, || {
893            core::array::from_fn(|_| wide(x.next_i32()))
894        });
895
896        let three = NeuralNetwork::<(
897            Dense<Q8_8, Relu, 2, 5>,
898            Dense<Q8_8, Tanh, 5, 4>,
899            Dense<Q8_8, Sigmoid, 4, 3>,
900        )>::new(|| q8(w.next_i32()));
901        pre_activations_reproduce_outputs::<_, Sigmoid, _, 3>(three, || {
902            core::array::from_fn(|_| q8(x.next_i32()))
903        });
904
905        let linear =
906            NeuralNetwork::<(Dense<Q16_16, Relu, 2, 6>, Dense<Q16_16, Linear, 6, 2>)>::new(|| {
907                wide(w.next_i32())
908            });
909        pre_activations_reproduce_outputs::<_, Linear, _, 2>(linear, || {
910            core::array::from_fn(|_| wide(x.next_i32()))
911        });
912    }
913
914    #[test]
915    fn linear_and_clip() {
916        use crate::activation::Linear;
917        let x = Q8_8::from_raw(-300);
918        assert_eq!(<Linear as Activation<Q8_8>>::activate(x), x);
919        assert_eq!(<Linear as Activation<Q8_8>>::derivative(x), Q8_8::ONE);
920        let range = (Q16_16::from_int(-1), Q16_16::ONE);
921        let clip = |g: i32| crate::neuralnet::clip_gradient(Q16_16::from_int(g), range);
922        assert_eq!(clip(5), Q16_16::ONE);
923        assert_eq!(clip(-5), Q16_16::from_int(-1));
924        assert_eq!(clip(0), Q16_16::ZERO);
925        // An inverted range does not panic: max wins above it, min below.
926        let inverted = (Q16_16::ONE, Q16_16::ZERO);
927        assert_eq!(
928            crate::neuralnet::clip_gradient(Q16_16::from_int(3), inverted),
929            Q16_16::ZERO
930        );
931    }
932
933    /// Setters and getters round-trip; the training state is untouched.
934    #[test]
935    fn weights_round_trip() {
936        let mut net =
937            NeuralNetwork::<(Dense<Q16_16, Relu, 2, 3>, Dense<Q16_16, Sigmoid, 3, 1>)>::new(|| {
938                Q16_16::ZERO
939            });
940        let w = [[Q16_16::ONE; 3], [Q16_16::from_int(-2); 3]];
941        net.layers_mut().0.set_weights(&w);
942        net.layers_mut().1.set_bias_weights(&[Q16_16::from_int(3)]);
943        assert_eq!(net.layers().0.weights(), w);
944        assert_eq!(net.layers().1.bias_weights(), [Q16_16::from_int(3)]);
945    }
946}