1use 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
89pub struct Dense<V, A, const IN: usize, const OUT: usize> {
95 weights: [[Connection<V>; OUT]; IN],
98 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 pub fn weights(&self) -> [[V; OUT]; IN] {
120 self.weights.map(|row| row.map(|c| c.weight))
121 }
122
123 pub fn bias_weights(&self) -> [V; OUT] {
125 self.bias.map(|c| c.weight)
126 }
127
128 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 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 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 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 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 fn pre_activation(&self, input: &[V; IN], o: usize) -> V {
185 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 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 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 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 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 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 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
258pub struct InferenceDense<V, A, const IN: usize, const OUT: usize> {
264 pub weights: [[V; OUT]; IN],
267 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 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 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 pub fn to_inference(&self) -> InferenceDense<V, A, IN, OUT> {
313 InferenceDense::new(self.weights(), self.bias_weights())
314 }
315
316 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 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 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 const OUTPUTS: usize;
354 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 pub trait InferenceLayersImpl {
363 type Inputs: Copy;
364 type Outputs: Copy;
365 fn feed_forward(&self, inputs: &Self::Inputs) -> Self::Outputs;
366 }
367}
368
369pub trait Layers: sealed::LayersImpl {}
373
374impl<T: sealed::LayersImpl> Layers for T {}
375
376pub trait InferenceLayers: sealed::InferenceLayersImpl {}
380
381impl<T: sealed::InferenceLayersImpl> InferenceLayers for T {}
382
383fn 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
398macro_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 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 self.$last.output_deltas(targets);
458 $(
459 let signal = self.$hi.back_signal();
460 self.$lo.hidden_deltas(&signal);
461 )*
462 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
525pub 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 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 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 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 pub fn optimizer(&self) -> &Opt {
576 &self.optimizer
577 }
578
579 pub fn set_learning_rate(&mut self, rate: V) {
581 self.learning_rate = rate;
582 }
583
584 pub fn set_momentum_rate(&mut self, rate: V) {
586 self.momentum_rate = rate;
587 }
588
589 pub fn set_acceleration_rate(&mut self, rate: V) {
592 self.acceleration_rate = rate;
593 }
594
595 pub fn set_gradient_clip(&mut self, range: Option<(V, V)>) {
600 self.gradient_clip = range;
601 }
602
603 pub fn learning_rate(&self) -> V {
607 self.learning_rate
608 }
609
610 pub fn feed_forward(&mut self, inputs: &L::Inputs) {
613 self.inputs = *inputs;
614 self.layers.feed_forward(inputs);
615 }
616
617 pub fn learned_values(&self) -> L::Outputs {
619 self.layers.outputs()
620 }
621
622 pub fn output_pre_activations(&self) -> L::Outputs {
631 self.layers.output_pre_activations(&self.inputs)
632 }
633
634 pub fn predicted_class(&self) -> usize {
645 argmax(self.layers.output_pre_activations(&self.inputs).as_ref())
646 }
647
648 pub fn calculate_error(&self, targets: &L::Outputs) -> V {
651 self.layers.calculate_error(targets)
652 }
653
654 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 self.learning_rate = self.optimizer.next_learning_rate(self.learning_rate);
674 }
675
676 pub fn layers(&self) -> &L {
678 &self.layers
679 }
680
681 pub fn layers_mut(&mut self) -> &mut L {
683 &mut self.layers
684 }
685
686 pub fn to_inference(&self) -> InferenceNetwork<L::Inference> {
689 InferenceNetwork::new(self.layers.to_inference())
690 }
691
692 pub fn set_weights(&mut self, from: &InferenceNetwork<L::Inference>) {
696 self.layers.set_from(&from.layers);
697 }
698}
699
700pub struct InferenceNetwork<L> {
739 pub layers: L,
741}
742
743impl<L> InferenceNetwork<L> {
744 pub const fn new(layers: L) -> Self {
746 Self { layers }
747 }
748}
749
750impl<L: InferenceLayers> InferenceNetwork<L> {
751 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 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 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 #[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 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 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 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 #[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}