Skip to main content

tinymind/
neuralnet.rs

1//! A multilayer perceptron with one hidden layer, ported from the
2//! `NeuralNetwork` / `MultilayerPerceptron` path of tinymind (C++) `cpp/neuralnet.hpp`,
3//! in two forms: [`MultilayerPerceptron`] trains on the device, and
4//! [`InferencePerceptron`] only runs a trained network (C++ `IsTrainable = false`).
5//!
6//! The C++ network is assembled from layer, neuron, connection, gradient-manager
7//! and training-policy templates, stored in placement-new byte buffers. This port
8//! keeps only what the default MLP configuration actually executes
9//! (`FixedPointTransferFunctions` with default policies, or tinymind (C++)'s
10//! floating-point bundle for `f32`/`f64`, plus optional
11//! `GradientClipByValue`, an optional Adam or RMSprop optimizer, and optional L2
12//! weight decay and a step-decay learning-rate schedule ([`crate::training`],
13//! wrapping the optimizer); batch size 1, no recurrence, one hidden layer; for more
14//! hidden layers see [`NeuralNetwork`](crate::NeuralNetwork)) and stores everything
15//! in plain fixed-size arrays:
16//! no heap, so the crate stays `#![no_std]`.
17//!
18//! Every arithmetic step keeps the C++ operation order, because fixed-point
19//! multiplication truncates and a reordered expression gives different bits.
20//!
21//! To pick a class, rank the output logits with `predicted_class()`
22//! (`output_pre_activations()` returns them) rather than `learned_values()`:
23//! the fixed-point sigmoid table is flat beyond ±6, so confident outputs tie.
24
25use core::marker::PhantomData;
26
27use crate::activation::Activation;
28use crate::optimizer::{Optimizer, Sgd};
29use crate::qformat::Scalar;
30use crate::training::decay_weights;
31
32/// One weighted edge to a neuron in the next layer (C++ `TrainableConnection`).
33#[derive(Clone, Copy, Debug, Default)]
34pub(crate) struct Connection<V> {
35    pub weight: V,
36    pub delta_weight: V,
37    pub previous_delta_weight: V,
38    pub gradient: V,
39}
40
41impl<V: Copy> Connection<V> {
42    /// C++ `setDeltaWeight`: the old delta becomes the previous delta.
43    pub(crate) fn set_delta_weight(&mut self, value: V) {
44        self.previous_delta_weight = self.delta_weight;
45        self.delta_weight = value;
46    }
47}
48
49/// A neuron and its outgoing connections (C++ `TrainableNeuron`).
50#[derive(Clone, Copy, Debug)]
51pub(crate) struct Neuron<V, const N: usize> {
52    pub output: V,
53    pub node_delta: V,
54    pub connections: [Connection<V>; N],
55}
56
57impl<V: Scalar, const N: usize> Default for Neuron<V, N> {
58    fn default() -> Self {
59        Self {
60            output: V::ZERO,
61            node_delta: V::ZERO,
62            connections: [Connection::default(); N],
63        }
64    }
65}
66
67impl<V: Scalar, const N: usize> Neuron<V, N> {
68    /// C++ `TrainableNeuron::initializeWeights`: one random weight per connection,
69    /// in connection order, then zero the delta weights.
70    pub(crate) fn initialize_weights(&mut self, random_weight: &mut impl FnMut() -> V) {
71        for c in &mut self.connections {
72            c.weight = random_weight();
73        }
74        for c in &mut self.connections {
75            c.set_delta_weight(V::ZERO);
76        }
77    }
78}
79
80/// `IN` inputs -> `HID` hidden neurons (activation `H`) -> `OUT` outputs (activation `O`).
81///
82/// C++: `MultilayerPerceptron<ValueType, IN, 1, HID, OUT, TransferFunctions>`.
83///
84/// `Opt` is the optimizer: [`Sgd`] (the default) or an adaptive one from
85/// [`optimizer`](crate::optimizer), passed to [`with_optimizer`](Self::with_optimizer).
86pub struct MultilayerPerceptron<
87    V,
88    H,
89    O,
90    const IN: usize,
91    const HID: usize,
92    const OUT: usize,
93    Opt = Sgd,
94> {
95    input: [Neuron<V, HID>; IN],
96    input_bias: Neuron<V, HID>,
97    hidden: [Neuron<V, OUT>; HID],
98    hidden_bias: Neuron<V, OUT>,
99    /// Output neurons own one connection that is never used. It is kept because
100    /// the C++ output neuron has one, and initialising it consumes a random draw;
101    /// dropping it would shift every later random number.
102    output: [Neuron<V, 1>; OUT],
103    learning_rate: V,
104    momentum_rate: V,
105    acceleration_rate: V,
106    gradient_clip: Option<(V, V)>,
107    optimizer: Opt,
108    /// `H` and `O` are only used in static calls; `PhantomData` records that the
109    /// type "uses" them. `fn() -> _` keeps the struct `Send`/`Sync` regardless.
110    activations: PhantomData<fn() -> (H, O)>,
111}
112
113impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
114    MultilayerPerceptron<V, H, O, IN, HID, OUT, Sgd>
115where
116    V: Scalar,
117    H: Activation<V>,
118    O: Activation<V>,
119{
120    /// Build the network, trained with [`Sgd`], and initialise its weights from
121    /// `random_weight`, in the same order as the C++ constructor: input neurons,
122    /// input bias, hidden neurons, hidden bias, output neurons.
123    ///
124    /// The C++ code reaches a static `generateRandomWeight()` policy that reads
125    /// global `rand()` state; passing a closure makes that dependency explicit.
126    pub fn new(random_weight: impl FnMut() -> V) -> Self {
127        Self::with_optimizer(random_weight, Sgd)
128    }
129}
130
131impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
132    MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
133where
134    V: Scalar,
135    H: Activation<V>,
136    O: Activation<V>,
137    Opt: Optimizer<V>,
138{
139    /// As [`new`](MultilayerPerceptron::new), trained with `optimizer`, for
140    /// example [`Adam`](crate::Adam).
141    pub fn with_optimizer(mut random_weight: impl FnMut() -> V, optimizer: Opt) -> Self {
142        let mut nn = Self {
143            input: [Neuron::default(); IN],
144            input_bias: Neuron::default(),
145            hidden: [Neuron::default(); HID],
146            hidden_bias: Neuron::default(),
147            output: [Neuron::default(); OUT],
148            // DefaultNetworkInitializer: 1/4, 1/2, 1/16.
149            learning_rate: V::pow2_neg(2),
150            momentum_rate: V::pow2_neg(1),
151            acceleration_rate: V::pow2_neg(4),
152            gradient_clip: None,
153            optimizer,
154            activations: PhantomData,
155        };
156        nn.input_bias.output = V::ONE;
157        nn.hidden_bias.output = V::ONE;
158
159        for n in &mut nn.input {
160            n.initialize_weights(&mut random_weight);
161        }
162        nn.input_bias.initialize_weights(&mut random_weight);
163        for n in &mut nn.hidden {
164            n.initialize_weights(&mut random_weight);
165        }
166        nn.hidden_bias.initialize_weights(&mut random_weight);
167        for n in &mut nn.output {
168            n.initialize_weights(&mut random_weight);
169        }
170        nn
171    }
172
173    /// Replace the learning rate (default `2^-2`, tinymind (C++)'s
174    /// `DefaultNetworkInitializer`).
175    pub fn set_learning_rate(&mut self, rate: V) {
176        self.learning_rate = rate;
177    }
178
179    /// Replace the momentum rate (default `2^-1`).
180    pub fn set_momentum_rate(&mut self, rate: V) {
181        self.momentum_rate = rate;
182    }
183
184    /// Replace the acceleration rate, the weight on the delta weight from two
185    /// steps back (default `2^-4`).
186    pub fn set_acceleration_rate(&mut self, rate: V) {
187        self.acceleration_rate = rate;
188    }
189
190    /// Clip each weight's and bias weight's gradient to `[min, max]` before
191    /// the update, or `None` (the default) to leave gradients alone. C++
192    /// `GradientClipByValue<ValueType, I, F>` is `Some((-b, b))` with `b =
193    /// QValue(I, F)`, so the default `GradientClipByValue<ValueType>` is
194    /// `Some((-1.0, 1.0))`.
195    pub fn set_gradient_clip(&mut self, range: Option<(V, V)>) {
196        self.gradient_clip = range;
197    }
198
199    /// The learning rate the next training step will use: the one set with
200    /// [`set_learning_rate`](Self::set_learning_rate), as a
201    /// [`Scheduled`](crate::training::Scheduled) optimizer has decayed it so far.
202    pub fn learning_rate(&self) -> V {
203        self.learning_rate
204    }
205
206    /// Run one forward pass: load `inputs`, then compute the hidden and output
207    /// activations. Read the result with [`learned_values`](Self::learned_values).
208    pub fn feed_forward(&mut self, inputs: &[V; IN]) {
209        for (neuron, &value) in self.input.iter_mut().zip(inputs) {
210            neuron.output = value;
211        }
212
213        for h in 0..HID {
214            let sum = weighted_sum(&self.input_bias, &self.input, h);
215            self.hidden[h].output = H::activate(sum);
216        }
217
218        for o in 0..OUT {
219            let sum = weighted_sum(&self.hidden_bias, &self.hidden, o);
220            self.output[o].output = O::activate(sum);
221        }
222    }
223
224    /// The outputs for `inputs` without changing the network: the same sums,
225    /// in the same order, as [`feed_forward`](Self::feed_forward) followed by
226    /// [`learned_values`](Self::learned_values), but nothing is stored, so the
227    /// next training step still sees the last `feed_forward`. For readers that
228    /// hold the network by shared reference (`qlearn::QNetwork::q_value`).
229    pub(crate) fn evaluate(&self, inputs: &[V; IN]) -> [V; OUT] {
230        let mut hidden = [V::ZERO; HID];
231        for (h, out) in hidden.iter_mut().enumerate() {
232            let weight = |n: &Neuron<V, HID>| n.connections.get(h).map_or(V::ZERO, |c| c.weight);
233            let mut sum = self.input_bias.output * weight(&self.input_bias);
234            let mut layer_sum = V::ZERO;
235            for (&x, neuron) in inputs.iter().zip(&self.input) {
236                layer_sum += x * weight(neuron);
237            }
238            sum += layer_sum;
239            *out = H::activate(sum);
240        }
241        let mut output = [V::ZERO; OUT];
242        for (o, out) in output.iter_mut().enumerate() {
243            let weight = |n: &Neuron<V, OUT>| n.connections.get(o).map_or(V::ZERO, |c| c.weight);
244            let mut sum = self.hidden_bias.output * weight(&self.hidden_bias);
245            let mut layer_sum = V::ZERO;
246            for (&x, neuron) in hidden.iter().zip(&self.hidden) {
247                layer_sum += x * weight(neuron);
248            }
249            sum += layer_sum;
250            *out = O::activate(sum);
251        }
252        output
253    }
254
255    /// The output-layer activations from the latest
256    /// [`feed_forward`](Self::feed_forward).
257    pub fn learned_values(&self) -> [V; OUT] {
258        self.output.map(|n| n.output)
259    }
260
261    /// The output layer's pre-activations (the logits) for the latest
262    /// [`feed_forward`](Self::feed_forward) (C++ `getOutputPreActivations`).
263    ///
264    /// Recomputed from the hidden layer with the sum `feed_forward` forms, so
265    /// they match it bit for bit and cost no memory.
266    ///
267    /// Call it before [`train`](Self::train): training changes the weights it
268    /// is recomputed from.
269    pub fn output_pre_activations(&self) -> [V; OUT] {
270        core::array::from_fn(|o| weighted_sum(&self.hidden_bias, &self.hidden, o))
271    }
272
273    /// The index of the largest [output pre-activation](Self::output_pre_activations)
274    /// for the latest [`feed_forward`](Self::feed_forward), ties to the lower
275    /// index (C++ `getPredictedClass`).
276    ///
277    /// Use it, not an argmax of [`learned_values`](Self::learned_values), to
278    /// pick a class: the fixed-point sigmoid table is flat beyond ±6, so
279    /// confident outputs tie there and an argmax can only take the first.
280    ///
281    /// Call it before [`train`](Self::train): training changes the weights it
282    /// is recomputed from.
283    pub fn predicted_class(&self) -> usize {
284        argmax(&self.output_pre_activations())
285    }
286
287    /// The hidden-layer activations from the latest
288    /// [`feed_forward`](Self::feed_forward) (C++
289    /// `getLastHiddenLayer().getOutputValueForNeuron`): the embedding, when
290    /// the trained network becomes a frozen model with a
291    /// [`head`](crate::head) on top.
292    pub fn hidden_values(&self) -> [V; HID] {
293        self.hidden.map(|n| n.output)
294    }
295
296    /// Mean-squared error against `targets` (C++ `MeanSquaredErrorCalculator`).
297    pub fn calculate_error(&self, targets: &[V; OUT]) -> V {
298        let mut error = V::ZERO;
299        for (target, neuron) in targets.iter().zip(&self.output) {
300            let delta = *target - neuron.output;
301            error += delta * delta;
302        }
303        if OUT > 1 {
304            error = error.div_int(OUT as i32);
305        }
306        error
307    }
308
309    /// One back-propagation step with the network's optimizer (C++
310    /// `ChainBackPropagationPolicy`).
311    pub fn train(&mut self, targets: &[V; OUT]) {
312        self.calculate_node_deltas(targets);
313        self.calculate_gradients();
314        self.update_weights();
315        // C++ stepLearningRate, after the update (FixedLearningRatePolicy,
316        // the default, leaves the rate alone).
317        self.learning_rate = self.optimizer.next_learning_rate(self.learning_rate);
318    }
319
320    fn calculate_node_deltas(&mut self, targets: &[V; OUT]) {
321        for (neuron, &target) in self.output.iter_mut().zip(targets) {
322            let error = target - neuron.output;
323            neuron.node_delta = error * O::derivative(neuron.output);
324        }
325
326        for h in 0..HID {
327            let mut sum = V::ZERO;
328            for o in 0..OUT {
329                sum += self.hidden[h].connections[o].weight * self.output[o].node_delta;
330            }
331            self.hidden[h].node_delta = sum * H::derivative(self.hidden[h].output);
332        }
333        // The C++ code also computes node deltas for the input layer. Nothing
334        // reads them (there is no layer before the input), so they are skipped.
335    }
336
337    fn calculate_gradients(&mut self) {
338        // Hidden -> output connections, then the hidden bias.
339        for h in 0..HID {
340            let out = self.hidden[h].output;
341            for o in 0..OUT {
342                self.hidden[h].connections[o].gradient = out * self.output[o].node_delta;
343            }
344        }
345        for o in 0..OUT {
346            self.hidden_bias.connections[o].gradient =
347                self.hidden_bias.output * self.output[o].node_delta;
348        }
349
350        // Input -> hidden connections, then the input bias.
351        for i in 0..IN {
352            let out = self.input[i].output;
353            for h in 0..HID {
354                self.input[i].connections[h].gradient = out * self.hidden[h].node_delta;
355            }
356        }
357        for h in 0..HID {
358            self.input_bias.connections[h].gradient =
359                self.input_bias.output * self.hidden[h].node_delta;
360        }
361    }
362
363    fn update_weights(&mut self) {
364        let rates = (
365            self.learning_rate,
366            self.momentum_rate,
367            self.acceleration_rate,
368        );
369
370        // Clip every gradient first (weights and bias weights alike, as the
371        // C++ does), so the updates below see no clipping option. Each
372        // gradient was just computed and only its update reads it, so the
373        // results are the same as clipping inside the update. With the option
374        // inside, LLVM compiled the whole update twice, once per value of
375        // the option, at opt-level 3 (up to 944 B on Cortex-M).
376        if let Some(range) = self.gradient_clip {
377            let clip = |c: &mut Connection<V>| c.gradient = clip_gradient(c.gradient, range);
378            self.hidden
379                .iter_mut()
380                .for_each(|n| n.connections.iter_mut().for_each(clip));
381            self.hidden_bias.connections.iter_mut().for_each(clip);
382            self.input
383                .iter_mut()
384                .for_each(|n| n.connections.iter_mut().for_each(clip));
385            self.input_bias.connections.iter_mut().for_each(clip);
386        }
387        let clip = None;
388
389        // Weight decay (C++ `WeightDecayPolicy::applyDecay`) on every weight
390        // but the bias weights. The C++ decays each weight just before adding
391        // its step; no update reads the weight, so decaying them all first
392        // gives the same results and keeps the update loops unchanged.
393        if let Some(lambda) = self.optimizer.weight_decay() {
394            let factor = self.learning_rate * lambda;
395            for n in &mut self.hidden {
396                decay_weights(&mut n.connections, factor);
397            }
398            for n in &mut self.input {
399                decay_weights(&mut n.connections, factor);
400            }
401        }
402
403        // One optimizer step (C++ `beginTrainingStep`), then the output layer
404        // and the hidden layer, each neuron's incoming connections followed by
405        // its bias connection.
406        self.optimizer.begin_step();
407        for o in 0..OUT {
408            for h in 0..HID {
409                self.optimizer
410                    .update_weight(&mut self.hidden[h].connections[o], rates, clip);
411            }
412            self.optimizer
413                .update_weight(&mut self.hidden_bias.connections[o], rates, clip);
414        }
415        for h in 0..HID {
416            for i in 0..IN {
417                self.optimizer
418                    .update_weight(&mut self.input[i].connections[h], rates, clip);
419            }
420            self.optimizer
421                .update_weight(&mut self.input_bias.connections[h], rates, clip);
422        }
423    }
424}
425
426/// Weight getters. These need no activation bounds, so they live in their own
427/// `impl` block. Each returns a whole matrix rather than taking an index, so
428/// none of them can panic; the layout matches the order tinymind (C++)'s
429/// `NetworkPropertiesFileManager` writes the weights in.
430impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
431    MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
432{
433    /// The optimizer, for example to read [`Adam::timestep`](crate::Adam::timestep).
434    pub fn optimizer(&self) -> &Opt {
435        &self.optimizer
436    }
437
438    /// Input-to-hidden weights: `input_weights()[input][hidden]`.
439    pub fn input_weights(&self) -> [[V; HID]; IN] {
440        self.input.map(|n| n.connections.map(|c| c.weight))
441    }
442
443    /// Input-layer bias to hidden neuron weights: `input_bias_weights()[hidden]`.
444    pub fn input_bias_weights(&self) -> [V; HID] {
445        self.input_bias.connections.map(|c| c.weight)
446    }
447
448    /// Hidden-to-output weights: `hidden_weights()[hidden][output]`.
449    pub fn hidden_weights(&self) -> [[V; OUT]; HID] {
450        self.hidden.map(|n| n.connections.map(|c| c.weight))
451    }
452
453    /// Hidden-layer bias to output neuron weights: `hidden_bias_weights()[output]`.
454    pub fn hidden_bias_weights(&self) -> [V; OUT] {
455        self.hidden_bias.connections.map(|c| c.weight)
456    }
457
458    /// Replace the input-to-hidden weights, laid out as
459    /// [`input_weights`](Self::input_weights) returns them. Only the weights
460    /// change; the training state (delta weights, gradients) is kept, as with
461    /// the C++ `setInputLayerWeightForNeuronAndConnection`.
462    pub fn set_input_weights(&mut self, weights: &[[V; HID]; IN]) {
463        for (neuron, row) in self.input.iter_mut().zip(weights) {
464            for (c, &w) in neuron.connections.iter_mut().zip(row) {
465                c.weight = w;
466            }
467        }
468    }
469
470    /// Replace the input-layer bias weights (C++
471    /// `setInputLayerBiasWeightForConnection`).
472    pub fn set_input_bias_weights(&mut self, weights: &[V; HID]) {
473        for (c, &w) in self.input_bias.connections.iter_mut().zip(weights) {
474            c.weight = w;
475        }
476    }
477
478    /// Replace the hidden-to-output weights (C++
479    /// `setHiddenLayerWeightForNeuronAndConnection`).
480    pub fn set_hidden_weights(&mut self, weights: &[[V; OUT]; HID]) {
481        for (neuron, row) in self.hidden.iter_mut().zip(weights) {
482            for (c, &w) in neuron.connections.iter_mut().zip(row) {
483                c.weight = w;
484            }
485        }
486    }
487
488    /// Replace the hidden-layer bias weights (C++
489    /// `setHiddenLayerBiasNeuronWeightForConnection`).
490    pub fn set_hidden_bias_weights(&mut self, weights: &[V; OUT]) {
491        for (c, &w) in self.hidden_bias.connections.iter_mut().zip(weights) {
492            c.weight = w;
493        }
494    }
495
496    /// Load every weight from an inference network of the same shape, for
497    /// example to fine-tune shipped weights on the device.
498    pub fn set_weights(&mut self, from: &InferencePerceptron<V, H, O, IN, HID, OUT>) {
499        self.set_input_weights(&from.input_weights);
500        self.set_input_bias_weights(&from.input_bias_weights);
501        self.set_hidden_weights(&from.hidden_weights);
502        self.set_hidden_bias_weights(&from.hidden_bias_weights);
503    }
504
505    /// The trained network as an [`InferencePerceptron`]: the same weights and
506    /// the same outputs, bit for bit, without the training state.
507    pub fn to_inference(&self) -> InferencePerceptron<V, H, O, IN, HID, OUT> {
508        InferencePerceptron::new(
509            self.input_weights(),
510            self.input_bias_weights(),
511            self.hidden_weights(),
512            self.hidden_bias_weights(),
513        )
514    }
515}
516
517/// An inference-only multilayer perceptron: `IN` inputs -> `HID` hidden neurons
518/// (activation `H`) -> `OUT` outputs (activation `O`), holding only its weights.
519///
520/// C++: `MultilayerPerceptron<ValueType, IN, 1, HID, OUT, TransferFunctions,
521/// false>`, the untrainable network. Train offline, or on a host with
522/// [`MultilayerPerceptron`], then ship this: it stores one value per connection
523/// instead of four, has no per-neuron state, and has no training code. Its
524/// outputs are bit-identical to the trainable network's with the same weights.
525///
526/// [`feed_forward`](Self::feed_forward) takes `&self` and keeps nothing between
527/// calls, and [`new`](Self::new) is a `const fn`, so a trained network can be a
528/// `static` (in flash on a microcontroller):
529///
530/// ```
531/// use tinymind::{InferencePerceptron, Q8_8, Sigmoid, Tanh};
532///
533/// const fn q(x: i16) -> Q8_8 {
534///     Q8_8::from_int(x as i32)
535/// }
536///
537/// // XOR by hand: hidden neuron 0 is OR, hidden neuron 1 is AND, and the output
538/// // is "OR and not AND". Trained weights, e.g. from
539/// // `MultilayerPerceptron::to_inference` on a host, go here the same way.
540/// static XOR: InferencePerceptron<Q8_8, Tanh, Sigmoid, 2, 2, 1> = InferencePerceptron::new(
541///     [[q(4), q(4)], [q(4), q(4)]], // input -> hidden
542///     [q(-2), q(-6)],               // input bias -> hidden
543///     [[q(6)], [q(-6)]],            // hidden -> output
544///     [q(-3)],                      // hidden bias -> output
545/// );
546///
547/// let half = Q8_8::from_raw(128);
548/// for (a, b, want) in [(0, 0, false), (0, 1, true), (1, 0, true), (1, 1, false)] {
549///     let [y] = XOR.feed_forward(&[q(a), q(b)]);
550///     assert_eq!(y > half, want);
551/// }
552/// ```
553pub struct InferencePerceptron<V, H, O, const IN: usize, const HID: usize, const OUT: usize> {
554    /// Input-to-hidden weights: `input_weights[input][hidden]`.
555    pub input_weights: [[V; HID]; IN],
556    /// Input-layer bias to hidden neuron weights: `input_bias_weights[hidden]`.
557    pub input_bias_weights: [V; HID],
558    /// Hidden-to-output weights: `hidden_weights[hidden][output]`.
559    pub hidden_weights: [[V; OUT]; HID],
560    /// Hidden-layer bias to output neuron weights: `hidden_bias_weights[output]`.
561    pub hidden_bias_weights: [V; OUT],
562    activations: PhantomData<fn() -> (H, O)>,
563}
564
565impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
566    InferencePerceptron<V, H, O, IN, HID, OUT>
567{
568    /// A network with these weights, laid out as the
569    /// [`MultilayerPerceptron`] weight getters return them.
570    pub const fn new(
571        input_weights: [[V; HID]; IN],
572        input_bias_weights: [V; HID],
573        hidden_weights: [[V; OUT]; HID],
574        hidden_bias_weights: [V; OUT],
575    ) -> Self {
576        Self {
577            input_weights,
578            input_bias_weights,
579            hidden_weights,
580            hidden_bias_weights,
581            activations: PhantomData,
582        }
583    }
584}
585
586impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
587    InferencePerceptron<V, H, O, IN, HID, OUT>
588where
589    V: Scalar,
590    H: Activation<V>,
591    O: Activation<V>,
592{
593    /// One forward pass: the output-layer activations for `inputs`.
594    pub fn feed_forward(&self, inputs: &[V; IN]) -> [V; OUT] {
595        // The same sums, in the same order, as the trainable network: the bias
596        // neuron's output (1) times its weight, plus the layer sum from zero.
597        let mut hidden = [V::ZERO; HID];
598        for (h, out) in hidden.iter_mut().enumerate() {
599            let mut sum = V::ONE * self.input_bias_weights[h];
600            let mut layer_sum = V::ZERO;
601            for (&x, row) in inputs.iter().zip(&self.input_weights) {
602                layer_sum += x * row[h];
603            }
604            sum += layer_sum;
605            *out = H::activate(sum);
606        }
607
608        let mut output = [V::ZERO; OUT];
609        for (o, out) in output.iter_mut().enumerate() {
610            let mut sum = V::ONE * self.hidden_bias_weights[o];
611            let mut layer_sum = V::ZERO;
612            for (&x, row) in hidden.iter().zip(&self.hidden_weights) {
613                layer_sum += x * row[o];
614            }
615            sum += layer_sum;
616            *out = O::activate(sum);
617        }
618        output
619    }
620}
621
622// Written out rather than derived: a derive would also require the activation
623// marker types `H` and `O` to implement each trait.
624impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize> Clone
625    for InferencePerceptron<V, H, O, IN, HID, OUT>
626{
627    fn clone(&self) -> Self {
628        *self
629    }
630}
631
632impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize> Copy
633    for InferencePerceptron<V, H, O, IN, HID, OUT>
634{
635}
636
637impl<V: PartialEq, H, O, const IN: usize, const HID: usize, const OUT: usize> PartialEq
638    for InferencePerceptron<V, H, O, IN, HID, OUT>
639{
640    fn eq(&self, other: &Self) -> bool {
641        self.input_weights == other.input_weights
642            && self.input_bias_weights == other.input_bias_weights
643            && self.hidden_weights == other.hidden_weights
644            && self.hidden_bias_weights == other.hidden_bias_weights
645    }
646}
647
648impl<V: Eq, H, O, const IN: usize, const HID: usize, const OUT: usize> Eq
649    for InferencePerceptron<V, H, O, IN, HID, OUT>
650{
651}
652
653impl<V: core::fmt::Debug, H, O, const IN: usize, const HID: usize, const OUT: usize>
654    core::fmt::Debug for InferencePerceptron<V, H, O, IN, HID, OUT>
655{
656    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
657        f.debug_struct("InferencePerceptron")
658            .field("input_weights", &self.input_weights)
659            .field("input_bias_weights", &self.input_bias_weights)
660            .field("hidden_weights", &self.hidden_weights)
661            .field("hidden_bias_weights", &self.hidden_bias_weights)
662            .finish()
663    }
664}
665
666/// `bias.output * bias.w[target] + sum(layer[n].output * layer[n].w[target])`,
667/// summed in the C++ order: the layer sum starts from zero, then is added to the
668/// bias term.
669fn weighted_sum<V: Scalar, const N: usize, const C: usize>(
670    bias: &Neuron<V, C>,
671    layer: &[Neuron<V, C>; N],
672    target: usize,
673) -> V {
674    // Callers pass target < C. The lookup is total anyway (an out-of-range
675    // target would read 0), because when this function is not inlined, as at
676    // opt-level s and z, the compiler cannot see the callers' bound and would
677    // keep a bounds-check panic.
678    let weight = |n: &Neuron<V, C>| n.connections.get(target).map_or(V::ZERO, |c| c.weight);
679    let mut sum = bias.output * weight(bias);
680    let mut layer_sum = V::ZERO;
681    for neuron in layer {
682        layer_sum += neuron.output * weight(neuron);
683    }
684    sum += layer_sum;
685    sum
686}
687
688/// The first index of the largest value (later equal values lose, as in C++
689/// `getPredictedClass`); 0 for an empty slice. A NaN never wins a comparison.
690pub(crate) fn argmax<V: PartialOrd>(values: &[V]) -> usize {
691    let mut best = 0;
692    for (o, v) in values.iter().enumerate().skip(1) {
693        if values.get(best).is_some_and(|b| v > b) {
694            best = o;
695        }
696    }
697    best
698}
699
700/// SGD with momentum and "acceleration" (C++ `updateConnectionWeightsImpl`, SGD path):
701/// `dw = lr * g + momentum * dw[t-1] + acceleration * dw[t-2]`, `w += dw`, the
702/// step `lr * g` rounded to nearest and the two momentum products toward zero.
703///
704/// `clip` is the gradient clipping range, `(min, max)` (C++
705/// `GradientClipByValue`), applied to weights and bias weights alike.
706pub(crate) fn update_connection<V: Scalar>(
707    c: &mut Connection<V>,
708    (lr, momentum, acceleration): (V, V, V),
709    clip: Option<(V, V)>,
710) {
711    let gradient = match clip {
712        Some(range) => clip_gradient(c.gradient, range),
713        None => c.gradient,
714    };
715    // The step rounds to nearest (C++ `multiplyRoundNearest`, since tinymind
716    // (C++) #267), so steps below one LSB do not drift one way; the momentum
717    // terms round toward zero (C++ `multiplyRoundTowardZero`, since #266), so
718    // an undriven delta weight decays to 0.
719    let new_delta_weight = lr.mul_round_nearest(gradient)
720        + momentum.mul_round_toward_zero(c.delta_weight)
721        + acceleration.mul_round_toward_zero(c.previous_delta_weight);
722    let current_weight = c.weight;
723    c.set_delta_weight(new_delta_weight);
724    c.weight = current_weight + new_delta_weight;
725}
726
727/// C++ `GradientClipByValue::clip`: two tests, max first, so a range with
728/// `min > max` gives `max` for large gradients and `min` for small ones rather
729/// than panicking as `clamp` would.
730pub(crate) fn clip_gradient<V: Scalar>(gradient: V, (min, max): (V, V)) -> V {
731    if gradient > max {
732        max
733    } else if gradient < min {
734        min
735    } else {
736        gradient
737    }
738}
739
740#[cfg(test)]
741mod tests {
742    use super::*;
743    use crate::activation::{Relu, Sigmoid, Tanh};
744    use crate::rand::GlibcRand;
745    use crate::{Q8_8, Q16_16};
746
747    /// The inference network built from a trainable one gives the trainable
748    /// network's outputs bit for bit, for random weights and inputs. `raw` maps
749    /// a random `i32` to a value; `wide` draws from the whole storage range, so
750    /// the sums wrap too.
751    fn same_outputs<V, H, O, const IN: usize, const HID: usize, const OUT: usize>(
752        raw: impl Fn(i32) -> V,
753        seed: u32,
754    ) where
755        V: Scalar + PartialEq + core::fmt::Debug,
756        H: Activation<V>,
757        O: Activation<V>,
758    {
759        let mut rng = GlibcRand::new(seed);
760        for trial in 0..50 {
761            let mut nn = MultilayerPerceptron::<V, H, O, IN, HID, OUT>::new(|| raw(rng.next_i32()));
762            let frozen = nn.to_inference();
763            for _ in 0..20 {
764                let input: [V; IN] = core::array::from_fn(|_| raw(rng.next_i32()));
765                // `evaluate` (no state change) agrees with `feed_forward` too.
766                let evaluated = nn.evaluate(&input);
767                nn.feed_forward(&input);
768                assert_eq!(
769                    frozen.feed_forward(&input),
770                    nn.learned_values(),
771                    "trial {trial}"
772                );
773                assert_eq!(evaluated, nn.learned_values(), "trial {trial}");
774                // The pre-activations reproduce the output layer bit for bit,
775                // and the predicted class is their argmax.
776                let pre = nn.output_pre_activations();
777                assert_eq!(pre.map(O::activate), nn.learned_values(), "trial {trial}");
778                assert_eq!(nn.predicted_class(), argmax(&pre), "trial {trial}");
779            }
780        }
781    }
782
783    /// A value within +-2.0 (`one` is the format's 1.0 in raw units).
784    fn small(r: i32, one: i32) -> i32 {
785        r % (4 * one + 1) - 2 * one
786    }
787
788    #[test]
789    fn inference_matches_trainable_q16_16() {
790        let small_q = |r: i32| Q16_16::from_raw(small(r, 1 << 16));
791        let wide_q = |r: i32| Q16_16::from_raw(r.wrapping_mul(2_654_435_761u32 as i32));
792        same_outputs::<Q16_16, Tanh, Sigmoid, 2, 4, 1>(small_q, 1);
793        same_outputs::<Q16_16, Relu, Sigmoid, 4, 8, 3>(small_q, 2);
794        same_outputs::<Q16_16, Tanh, Sigmoid, 2, 4, 1>(wide_q, 3);
795        same_outputs::<Q16_16, Relu, Sigmoid, 4, 8, 3>(wide_q, 4);
796    }
797
798    #[cfg(feature = "std")]
799    #[test]
800    fn inference_matches_trainable_f64() {
801        let small_f = |r: i32| f64::from(small(r, 1 << 16)) / 65536.0;
802        same_outputs::<f64, Relu, Sigmoid, 2, 4, 3>(small_f, 9);
803        same_outputs::<f64, Tanh, Sigmoid, 4, 8, 3>(small_f, 10);
804    }
805
806    /// One hidden unit at ReLU(1) = 1 drives logits of 7, 9 and 0. The sigmoid
807    /// table is flat beyond 5.875, so outputs 0 and 1 read the same value and
808    /// an argmax over them takes output 0; the logits say 1 (C++
809    /// `predicted_class_separates_outputs_the_sigmoid_table_ties`).
810    #[test]
811    fn predicted_class_separates_outputs_the_sigmoid_table_ties() {
812        let q = Q16_16::from_int;
813        let mut nn = MultilayerPerceptron::<Q16_16, Relu, Sigmoid, 2, 4, 3>::new(|| q(0));
814        nn.set_input_weights(&[[q(0); 4]; 2]);
815        nn.set_input_bias_weights(&[q(1), q(0), q(0), q(0)]);
816        nn.set_hidden_weights(&[[q(7), q(9), q(0)], [q(0); 3], [q(0); 3], [q(0); 3]]);
817        nn.set_hidden_bias_weights(&[q(0); 3]);
818
819        nn.feed_forward(&[Q16_16::from_raw(1 << 15), Q16_16::from_raw(-(1 << 15))]);
820
821        let learned = nn.learned_values();
822        assert_eq!(nn.output_pre_activations(), [q(7), q(9), q(0)]);
823        assert_eq!(learned[0], learned[1]);
824        assert_eq!(argmax(&learned), 0);
825        assert_eq!(nn.predicted_class(), 1);
826    }
827
828    #[test]
829    fn inference_matches_trainable_q8_8() {
830        let small_q = |r: i32| Q8_8::from_raw(small(r, 1 << 8) as i16);
831        let wide_q = |r: i32| Q8_8::from_raw(r as i16);
832        same_outputs::<Q8_8, Tanh, Sigmoid, 2, 4, 1>(small_q, 5);
833        same_outputs::<Q8_8, Relu, Sigmoid, 4, 8, 3>(small_q, 6);
834        same_outputs::<Q8_8, Tanh, Sigmoid, 2, 4, 1>(wide_q, 7);
835        same_outputs::<Q8_8, Relu, Sigmoid, 4, 8, 3>(wide_q, 8);
836    }
837
838    /// Mid-training weights convert too, and `set_weights` loads them back.
839    #[test]
840    fn train_freeze_and_reload() {
841        type Net = MultilayerPerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
842        let mut rng = GlibcRand::new(9);
843        let mut nn = Net::new(|| Q16_16::from_raw(small(rng.next_i32(), 1 << 16)));
844        let samples = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)];
845        for step in 0..2000 {
846            let (a, b, y) = samples[step % 4];
847            nn.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
848            nn.train(&[Q16_16::from_int(y)]);
849        }
850        let frozen = nn.to_inference();
851        for (a, b, _) in samples {
852            let input = [Q16_16::from_int(a), Q16_16::from_int(b)];
853            nn.feed_forward(&input);
854            assert_eq!(frozen.feed_forward(&input), nn.learned_values());
855        }
856
857        let mut other = Net::new(|| Q16_16::ZERO);
858        other.set_weights(&frozen);
859        assert_eq!(other.to_inference(), frozen);
860        assert_eq!(other.input_weights(), frozen.input_weights);
861        assert_eq!(other.hidden_bias_weights(), frozen.hidden_bias_weights);
862    }
863
864    /// One value per connection and no per-neuron state.
865    #[test]
866    fn inference_network_is_smaller() {
867        use core::mem::size_of;
868        type Trainable = MultilayerPerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
869        type Inference = InferencePerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
870        // 2*4 + 4 + 4*1 + 1 = 17 weights of 4 bytes.
871        assert_eq!(size_of::<Inference>(), 17 * 4);
872        assert!(size_of::<Trainable>() > 4 * size_of::<Inference>());
873    }
874}