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