use core::marker::PhantomData;
use crate::activation::Activation;
use crate::neuralnet::{Connection, update_connection};
use crate::qformat::Fixed;
pub struct Dense<V, A, const IN: usize, const OUT: usize> {
weights: [[Connection<V>; OUT]; IN],
bias: [Connection<V>; OUT],
outputs: [V; OUT],
deltas: [V; OUT],
activation: PhantomData<fn() -> A>,
}
impl<V: Fixed, A, const IN: usize, const OUT: usize> Default for Dense<V, A, IN, OUT> {
fn default() -> Self {
Self {
weights: [[Connection::default(); OUT]; IN],
bias: [Connection::default(); OUT],
outputs: [V::ZERO; OUT],
deltas: [V::ZERO; OUT],
activation: PhantomData,
}
}
}
impl<V: Copy, A, const IN: usize, const OUT: usize> Dense<V, A, IN, OUT> {
pub fn weights(&self) -> [[V; OUT]; IN] {
self.weights.map(|row| row.map(|c| c.weight))
}
pub fn bias_weights(&self) -> [V; OUT] {
self.bias.map(|c| c.weight)
}
pub fn set_weights(&mut self, weights: &[[V; OUT]; IN]) {
for (row, new) in self.weights.iter_mut().zip(weights) {
for (c, &w) in row.iter_mut().zip(new) {
c.weight = w;
}
}
}
pub fn set_bias_weights(&mut self, weights: &[V; OUT]) {
for (c, &w) in self.bias.iter_mut().zip(weights) {
c.weight = w;
}
}
pub fn outputs(&self) -> [V; OUT] {
self.outputs
}
}
impl<V: Fixed, A: Activation<V>, const IN: usize, const OUT: usize> Dense<V, A, IN, OUT> {
fn initialize(&mut self, random_weight: &mut dyn FnMut() -> V) {
for row in self
.weights
.iter_mut()
.chain(core::iter::once(&mut self.bias))
{
for c in row.iter_mut() {
c.weight = random_weight();
}
for c in row.iter_mut() {
c.set_delta_weight(V::ZERO);
}
}
}
fn forward(&mut self, input: &[V; IN]) {
for (o, out) in self.outputs.iter_mut().enumerate() {
let mut sum = V::ONE * self.bias[o].weight;
let mut layer_sum = V::ZERO;
for (&x, row) in input.iter().zip(&self.weights) {
layer_sum += x * row[o].weight;
}
sum += layer_sum;
*out = A::activate(sum);
}
}
fn output_deltas(&mut self, targets: &[V; OUT]) {
for ((delta, &out), &target) in self.deltas.iter_mut().zip(&self.outputs).zip(targets) {
*delta = (target - out) * A::derivative(out);
}
}
fn hidden_deltas(&mut self, signal: &[V; OUT]) {
for ((delta, &out), &s) in self.deltas.iter_mut().zip(&self.outputs).zip(signal) {
*delta = s * A::derivative(out);
}
}
fn back_signal(&self) -> [V; IN] {
self.weights.map(|row| {
let mut sum = V::ZERO;
for (c, &delta) in row.iter().zip(&self.deltas) {
sum += c.weight * delta;
}
sum
})
}
fn gradients(&mut self, input: &[V; IN]) {
for (row, &x) in self.weights.iter_mut().zip(input) {
for (c, &delta) in row.iter_mut().zip(&self.deltas) {
c.gradient = x * delta;
}
}
for (c, &delta) in self.bias.iter_mut().zip(&self.deltas) {
c.gradient = V::ONE * delta;
}
}
fn update(&mut self, rates: (V, V, V), clip: Option<(V, V)>) {
for row in self.weights.iter_mut() {
for c in row.iter_mut() {
update_connection(c, rates, clip);
}
}
for c in self.bias.iter_mut() {
update_connection(c, rates, None);
}
}
}
mod sealed {
pub trait LayersImpl {
type Value: Copy;
type Inputs: Copy;
type Outputs: Copy;
fn zero_inputs() -> Self::Inputs;
fn initialize(&mut self, random_weight: &mut dyn FnMut() -> Self::Value);
fn feed_forward(&mut self, inputs: &Self::Inputs);
fn outputs(&self) -> Self::Outputs;
fn calculate_error(&self, targets: &Self::Outputs) -> Self::Value;
fn train(
&mut self,
inputs: &Self::Inputs,
targets: &Self::Outputs,
rates: (Self::Value, Self::Value, Self::Value),
clip: Option<(Self::Value, Self::Value)>,
);
const OUTPUTS: usize;
}
}
pub trait Layers: sealed::LayersImpl {}
impl<T: sealed::LayersImpl> Layers for T {}
fn mean_squared_error<V: Fixed, const OUT: usize>(outputs: &[V; OUT], targets: &[V; OUT]) -> V {
let mut error = V::ZERO;
for (&target, &out) in targets.iter().zip(outputs) {
let delta = target - out;
error += delta * delta;
}
if OUT > 1 {
error = error.div_int(OUT as i32);
}
error
}
macro_rules! impl_layers {
(
[$($idx:tt: $act:ident, $din:ident, $dout:ident);+]
first $first:tt, $d0:ident; last $last:tt, $dn:ident;
fwd [$($prev:tt > $next:tt),*]; back [$($hi:tt > $lo:tt),*];
consts [$($d:ident),+]
) => {
impl<V: Fixed, $($act: Activation<V>,)+ $(const $d: usize,)+> sealed::LayersImpl
for ($(Dense<V, $act, $din, $dout>,)+)
{
type Value = V;
type Inputs = [V; $d0];
type Outputs = [V; $dn];
const OUTPUTS: usize = $dn;
fn zero_inputs() -> [V; $d0] {
[V::ZERO; $d0]
}
fn initialize(&mut self, random_weight: &mut dyn FnMut() -> V) {
$(self.$idx.initialize(random_weight);)+
}
fn feed_forward(&mut self, inputs: &[V; $d0]) {
self.$first.forward(inputs);
$(self.$next.forward(&self.$prev.outputs);)*
}
fn outputs(&self) -> [V; $dn] {
self.$last.outputs
}
fn calculate_error(&self, targets: &[V; $dn]) -> V {
mean_squared_error(&self.$last.outputs, targets)
}
fn train(
&mut self,
inputs: &[V; $d0],
targets: &[V; $dn],
rates: (V, V, V),
clip: Option<(V, V)>,
) {
self.$last.output_deltas(targets);
$(
let signal = self.$hi.back_signal();
self.$lo.hidden_deltas(&signal);
)*
self.$first.gradients(inputs);
$(self.$next.gradients(&self.$prev.outputs);)*
$(self.$idx.update(rates, clip);)+
}
}
};
}
impl_layers!([0: A0, D0, D1] first 0, D0; last 0, D1; fwd []; back []; consts [D0, D1]);
impl_layers!([0: A0, D0, D1; 1: A1, D1, D2] first 0, D0; last 1, D2;
fwd [0 > 1]; back [1 > 0]; consts [D0, D1, D2]);
impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3] first 0, D0; last 2, D3;
fwd [0 > 1, 1 > 2]; back [2 > 1, 1 > 0]; consts [D0, D1, D2, D3]);
impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4] first 0, D0; last 3, D4;
fwd [0 > 1, 1 > 2, 2 > 3]; back [3 > 2, 2 > 1, 1 > 0]; consts [D0, D1, D2, D3, D4]);
impl_layers!([0: A0, D0, D1; 1: A1, D1, D2; 2: A2, D2, D3; 3: A3, D3, D4; 4: A4, D4, D5]
first 0, D0; last 4, D5;
fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4]; back [4 > 3, 3 > 2, 2 > 1, 1 > 0];
consts [D0, D1, D2, D3, D4, D5]);
impl_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]
first 0, D0; last 5, D6;
fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4, 4 > 5]; back [5 > 4, 4 > 3, 3 > 2, 2 > 1, 1 > 0];
consts [D0, D1, D2, D3, D4, D5, D6]);
impl_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;
6: A6, D6, D7]
first 0, D0; last 6, D7;
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];
consts [D0, D1, D2, D3, D4, D5, D6, D7]);
impl_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;
6: A6, D6, D7; 7: A7, D7, D8]
first 0, D0; last 7, D8;
fwd [0 > 1, 1 > 2, 2 > 3, 3 > 4, 4 > 5, 5 > 6, 6 > 7];
back [7 > 6, 6 > 5, 5 > 4, 4 > 3, 3 > 2, 2 > 1, 1 > 0];
consts [D0, D1, D2, D3, D4, D5, D6, D7, D8]);
pub struct NeuralNetwork<L: Layers> {
layers: L,
inputs: L::Inputs,
learning_rate: L::Value,
momentum_rate: L::Value,
acceleration_rate: L::Value,
gradient_clip: Option<(L::Value, L::Value)>,
}
impl<V: Fixed, L: Layers<Value = V> + Default> NeuralNetwork<L> {
pub fn new(mut random_weight: impl FnMut() -> V) -> Self {
let mut layers = L::default();
layers.initialize(&mut random_weight);
for _ in 0..L::OUTPUTS {
random_weight();
}
Self {
layers,
inputs: L::zero_inputs(),
learning_rate: V::pow2_neg(2),
momentum_rate: V::pow2_neg(1),
acceleration_rate: V::pow2_neg(4),
gradient_clip: None,
}
}
}
impl<V: Fixed, L: Layers<Value = V>> NeuralNetwork<L> {
pub fn set_learning_rate(&mut self, rate: V) {
self.learning_rate = rate;
}
pub fn set_momentum_rate(&mut self, rate: V) {
self.momentum_rate = rate;
}
pub fn set_acceleration_rate(&mut self, rate: V) {
self.acceleration_rate = rate;
}
pub fn set_gradient_clip(&mut self, range: Option<(V, V)>) {
self.gradient_clip = range;
}
pub fn feed_forward(&mut self, inputs: &L::Inputs) {
self.inputs = *inputs;
self.layers.feed_forward(inputs);
}
pub fn learned_values(&self) -> L::Outputs {
self.layers.outputs()
}
pub fn calculate_error(&self, targets: &L::Outputs) -> V {
self.layers.calculate_error(targets)
}
pub fn train(&mut self, targets: &L::Outputs) {
let rates = (
self.learning_rate,
self.momentum_rate,
self.acceleration_rate,
);
self.layers
.train(&self.inputs, targets, rates, self.gradient_clip);
}
pub fn layers(&self) -> &L {
&self.layers
}
pub fn layers_mut(&mut self) -> &mut L {
&mut self.layers
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::activation::{Linear, Relu, Sigmoid, Tanh};
use crate::rand::GlibcRand;
use crate::{MultilayerPerceptron, Q8_8, Q16_16};
fn same_as_perceptron<V, H, O, const IN: usize, const HID: usize, const OUT: usize>(
raw: impl Fn(i32) -> V,
seed: u32,
) where
V: Fixed + PartialEq + core::fmt::Debug,
H: Activation<V>,
O: Activation<V>,
{
let mut a = GlibcRand::new(seed);
let mut b = GlibcRand::new(seed);
let mut mlp = MultilayerPerceptron::<V, H, O, IN, HID, OUT>::new(|| raw(a.next_i32()));
let mut net = NeuralNetwork::<(Dense<V, H, IN, HID>, Dense<V, O, HID, OUT>)>::new(|| {
raw(b.next_i32())
});
assert_eq!(a.next_i32(), b.next_i32(), "same number of draws");
let mut data = GlibcRand::new(seed + 1000);
for step in 0..500 {
let input: [V; IN] = core::array::from_fn(|_| raw(data.next_i32()));
let target: [V; OUT] = core::array::from_fn(|_| raw(data.next_i32()));
mlp.feed_forward(&input);
net.feed_forward(&input);
assert_eq!(net.learned_values(), mlp.learned_values(), "step {step}");
assert_eq!(net.calculate_error(&target), mlp.calculate_error(&target));
mlp.train(&target);
net.train(&target);
let (l0, l1) = net.layers();
assert_eq!(l0.weights(), mlp.input_weights(), "step {step}");
assert_eq!(l0.bias_weights(), mlp.input_bias_weights());
assert_eq!(l1.weights(), mlp.hidden_weights());
assert_eq!(l1.bias_weights(), mlp.hidden_bias_weights());
}
}
fn unit(r: i32, one: i32) -> i32 {
r % (2 * one + 1) - one
}
#[test]
fn two_layers_match_multilayer_perceptron() {
let q16 = |r: i32| Q16_16::from_raw(unit(r, 1 << 16));
let q8 = |r: i32| Q8_8::from_raw(unit(r, 1 << 8) as i16);
same_as_perceptron::<Q16_16, Tanh, Sigmoid, 2, 4, 1>(q16, 1);
same_as_perceptron::<Q16_16, Relu, Sigmoid, 4, 8, 3>(q16, 2);
same_as_perceptron::<Q8_8, Tanh, Sigmoid, 2, 4, 1>(q8, 3);
same_as_perceptron::<Q8_8, Relu, Sigmoid, 4, 8, 3>(q8, 4);
}
#[test]
fn two_layers_match_perceptron_with_clipping() {
let mut a = GlibcRand::new(11);
let mut b = GlibcRand::new(11);
let w = |r: i32| Q16_16::from_raw(unit(r, 1 << 15));
let mut mlp =
MultilayerPerceptron::<Q16_16, Relu, Linear, 3, 5, 2>::new(|| w(a.next_i32()));
let mut net =
NeuralNetwork::<(Dense<Q16_16, Relu, 3, 5>, Dense<Q16_16, Linear, 5, 2>)>::new(|| {
w(b.next_i32())
});
let range = (Q16_16::from_raw(-(1 << 15)), Q16_16::ONE);
let lr = Q16_16::from_raw(1 << 10);
mlp.set_learning_rate(lr);
net.set_learning_rate(lr);
mlp.set_acceleration_rate(Q16_16::from_raw(1 << 12));
net.set_acceleration_rate(Q16_16::from_raw(1 << 12));
mlp.set_gradient_clip(Some(range));
net.set_gradient_clip(Some(range));
let mut data = GlibcRand::new(12);
for step in 0..1000 {
let input: [Q16_16; 3] =
core::array::from_fn(|_| Q16_16::from_raw(unit(data.next_i32(), 1 << 16)));
let target: [Q16_16; 2] =
core::array::from_fn(|_| Q16_16::from_raw(unit(data.next_i32(), 8 << 16)));
mlp.feed_forward(&input);
net.feed_forward(&input);
assert_eq!(net.learned_values(), mlp.learned_values(), "step {step}");
mlp.train(&target);
net.train(&target);
assert_eq!(net.layers().0.weights(), mlp.input_weights(), "step {step}");
assert_eq!(
net.layers().1.bias_weights(),
mlp.hidden_bias_weights(),
"step {step}"
);
}
}
#[test]
fn linear_and_clip() {
use crate::activation::Linear;
let x = Q8_8::from_raw(-300);
assert_eq!(<Linear as Activation<Q8_8>>::activate(x), x);
assert_eq!(<Linear as Activation<Q8_8>>::derivative(x), Q8_8::ONE);
let range = (Q16_16::from_int(-1), Q16_16::ONE);
let clip = |g: i32| crate::neuralnet::clip_gradient(Q16_16::from_int(g), range);
assert_eq!(clip(5), Q16_16::ONE);
assert_eq!(clip(-5), Q16_16::from_int(-1));
assert_eq!(clip(0), Q16_16::ZERO);
let inverted = (Q16_16::ONE, Q16_16::ZERO);
assert_eq!(
crate::neuralnet::clip_gradient(Q16_16::from_int(3), inverted),
Q16_16::ZERO
);
}
#[test]
fn weights_round_trip() {
let mut net =
NeuralNetwork::<(Dense<Q16_16, Relu, 2, 3>, Dense<Q16_16, Sigmoid, 3, 1>)>::new(|| {
Q16_16::ZERO
});
let w = [[Q16_16::ONE; 3], [Q16_16::from_int(-2); 3]];
net.layers_mut().0.set_weights(&w);
net.layers_mut().1.set_bias_weights(&[Q16_16::from_int(3)]);
assert_eq!(net.layers().0.weights(), w);
assert_eq!(net.layers().1.bias_weights(), [Q16_16::from_int(3)]);
}
}