1use core::marker::PhantomData;
75
76use crate::activation::Activation;
77use crate::neuralnet::Connection;
78use crate::optimizer::{Optimizer, Sgd};
79use crate::qformat::Scalar;
80
81pub struct Dense<V, A, const IN: usize, const OUT: usize> {
87 weights: [[Connection<V>; OUT]; IN],
90 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 pub fn weights(&self) -> [[V; OUT]; IN] {
112 self.weights.map(|row| row.map(|c| c.weight))
113 }
114
115 pub fn bias_weights(&self) -> [V; OUT] {
117 self.bias.map(|c| c.weight)
118 }
119
120 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 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 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 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 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 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 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 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 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 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
238pub struct InferenceDense<V, A, const IN: usize, const OUT: usize> {
244 pub weights: [[V; OUT]; IN],
247 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 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 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 pub fn to_inference(&self) -> InferenceDense<V, A, IN, OUT> {
293 InferenceDense::new(self.weights(), self.bias_weights())
294 }
295
296 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 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 const OUTPUTS: usize;
330 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 pub trait InferenceLayersImpl {
339 type Inputs: Copy;
340 type Outputs: Copy;
341 fn feed_forward(&self, inputs: &Self::Inputs) -> Self::Outputs;
342 }
343}
344
345pub trait Layers: sealed::LayersImpl {}
349
350impl<T: sealed::LayersImpl> Layers for T {}
351
352pub trait InferenceLayers: sealed::InferenceLayersImpl {}
356
357impl<T: sealed::InferenceLayersImpl> InferenceLayers for T {}
358
359fn 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
374macro_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 self.$last.output_deltas(targets);
424 $(
425 let signal = self.$hi.back_signal();
426 self.$lo.hidden_deltas(&signal);
427 )*
428 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
490pub 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 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 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 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 pub fn optimizer(&self) -> &Opt {
541 &self.optimizer
542 }
543
544 pub fn set_learning_rate(&mut self, rate: V) {
546 self.learning_rate = rate;
547 }
548
549 pub fn set_momentum_rate(&mut self, rate: V) {
551 self.momentum_rate = rate;
552 }
553
554 pub fn set_acceleration_rate(&mut self, rate: V) {
557 self.acceleration_rate = rate;
558 }
559
560 pub fn set_gradient_clip(&mut self, range: Option<(V, V)>) {
566 self.gradient_clip = range;
567 }
568
569 pub fn feed_forward(&mut self, inputs: &L::Inputs) {
572 self.inputs = *inputs;
573 self.layers.feed_forward(inputs);
574 }
575
576 pub fn learned_values(&self) -> L::Outputs {
578 self.layers.outputs()
579 }
580
581 pub fn calculate_error(&self, targets: &L::Outputs) -> V {
584 self.layers.calculate_error(targets)
585 }
586
587 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 pub fn layers(&self) -> &L {
606 &self.layers
607 }
608
609 pub fn layers_mut(&mut self) -> &mut L {
611 &mut self.layers
612 }
613
614 pub fn to_inference(&self) -> InferenceNetwork<L::Inference> {
617 InferenceNetwork::new(self.layers.to_inference())
618 }
619
620 pub fn set_weights(&mut self, from: &InferenceNetwork<L::Inference>) {
624 self.layers.set_from(&from.layers);
625 }
626}
627
628pub struct InferenceNetwork<L> {
667 pub layers: L,
669}
670
671impl<L> InferenceNetwork<L> {
672 pub const fn new(layers: L) -> Self {
674 Self { layers }
675 }
676}
677
678impl<L: InferenceLayers> InferenceNetwork<L> {
679 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 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 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 #[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 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 #[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}