use core::marker::PhantomData;
use crate::activation::Activation;
use crate::optimizer::{Optimizer, Sgd};
use crate::qformat::Scalar;
use crate::training::decay_weights;
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Connection<V> {
pub weight: V,
pub delta_weight: V,
pub previous_delta_weight: V,
pub gradient: V,
}
impl<V: Copy> Connection<V> {
pub(crate) fn set_delta_weight(&mut self, value: V) {
self.previous_delta_weight = self.delta_weight;
self.delta_weight = value;
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Neuron<V, const N: usize> {
pub output: V,
pub node_delta: V,
pub connections: [Connection<V>; N],
}
impl<V: Scalar, const N: usize> Default for Neuron<V, N> {
fn default() -> Self {
Self {
output: V::ZERO,
node_delta: V::ZERO,
connections: [Connection::default(); N],
}
}
}
impl<V: Scalar, const N: usize> Neuron<V, N> {
pub(crate) fn initialize_weights(&mut self, random_weight: &mut impl FnMut() -> V) {
for c in &mut self.connections {
c.weight = random_weight();
}
for c in &mut self.connections {
c.set_delta_weight(V::ZERO);
}
}
}
pub struct MultilayerPerceptron<
V,
H,
O,
const IN: usize,
const HID: usize,
const OUT: usize,
Opt = Sgd,
> {
input: [Neuron<V, HID>; IN],
input_bias: Neuron<V, HID>,
hidden: [Neuron<V, OUT>; HID],
hidden_bias: Neuron<V, OUT>,
output: [Neuron<V, 1>; OUT],
learning_rate: V,
momentum_rate: V,
acceleration_rate: V,
gradient_clip: Option<(V, V)>,
optimizer: Opt,
activations: PhantomData<fn() -> (H, O)>,
}
impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
MultilayerPerceptron<V, H, O, IN, HID, OUT, Sgd>
where
V: Scalar,
H: Activation<V>,
O: Activation<V>,
{
pub fn new(random_weight: impl FnMut() -> V) -> Self {
Self::with_optimizer(random_weight, Sgd)
}
}
impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
where
V: Scalar,
H: Activation<V>,
O: Activation<V>,
Opt: Optimizer<V>,
{
pub fn with_optimizer(mut random_weight: impl FnMut() -> V, optimizer: Opt) -> Self {
let mut nn = Self {
input: [Neuron::default(); IN],
input_bias: Neuron::default(),
hidden: [Neuron::default(); HID],
hidden_bias: Neuron::default(),
output: [Neuron::default(); OUT],
learning_rate: V::pow2_neg(2),
momentum_rate: V::pow2_neg(1),
acceleration_rate: V::pow2_neg(4),
gradient_clip: None,
optimizer,
activations: PhantomData,
};
nn.input_bias.output = V::ONE;
nn.hidden_bias.output = V::ONE;
for n in &mut nn.input {
n.initialize_weights(&mut random_weight);
}
nn.input_bias.initialize_weights(&mut random_weight);
for n in &mut nn.hidden {
n.initialize_weights(&mut random_weight);
}
nn.hidden_bias.initialize_weights(&mut random_weight);
for n in &mut nn.output {
n.initialize_weights(&mut random_weight);
}
nn
}
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 learning_rate(&self) -> V {
self.learning_rate
}
pub fn feed_forward(&mut self, inputs: &[V; IN]) {
for (neuron, &value) in self.input.iter_mut().zip(inputs) {
neuron.output = value;
}
for h in 0..HID {
let sum = weighted_sum(&self.input_bias, &self.input, h);
self.hidden[h].output = H::activate(sum);
}
for o in 0..OUT {
let sum = weighted_sum(&self.hidden_bias, &self.hidden, o);
self.output[o].output = O::activate(sum);
}
}
pub(crate) fn evaluate(&self, inputs: &[V; IN]) -> [V; OUT] {
let mut hidden = [V::ZERO; HID];
for (h, out) in hidden.iter_mut().enumerate() {
let weight = |n: &Neuron<V, HID>| n.connections.get(h).map_or(V::ZERO, |c| c.weight);
let mut sum = self.input_bias.output * weight(&self.input_bias);
let mut layer_sum = V::ZERO;
for (&x, neuron) in inputs.iter().zip(&self.input) {
layer_sum += x * weight(neuron);
}
sum += layer_sum;
*out = H::activate(sum);
}
let mut output = [V::ZERO; OUT];
for (o, out) in output.iter_mut().enumerate() {
let weight = |n: &Neuron<V, OUT>| n.connections.get(o).map_or(V::ZERO, |c| c.weight);
let mut sum = self.hidden_bias.output * weight(&self.hidden_bias);
let mut layer_sum = V::ZERO;
for (&x, neuron) in hidden.iter().zip(&self.hidden) {
layer_sum += x * weight(neuron);
}
sum += layer_sum;
*out = O::activate(sum);
}
output
}
pub fn learned_values(&self) -> [V; OUT] {
self.output.map(|n| n.output)
}
pub fn hidden_values(&self) -> [V; HID] {
self.hidden.map(|n| n.output)
}
pub fn calculate_error(&self, targets: &[V; OUT]) -> V {
let mut error = V::ZERO;
for (target, neuron) in targets.iter().zip(&self.output) {
let delta = *target - neuron.output;
error += delta * delta;
}
if OUT > 1 {
error = error.div_int(OUT as i32);
}
error
}
pub fn train(&mut self, targets: &[V; OUT]) {
self.calculate_node_deltas(targets);
self.calculate_gradients();
self.update_weights();
self.learning_rate = self.optimizer.next_learning_rate(self.learning_rate);
}
fn calculate_node_deltas(&mut self, targets: &[V; OUT]) {
for (neuron, &target) in self.output.iter_mut().zip(targets) {
let error = target - neuron.output;
neuron.node_delta = error * O::derivative(neuron.output);
}
for h in 0..HID {
let mut sum = V::ZERO;
for o in 0..OUT {
sum += self.hidden[h].connections[o].weight * self.output[o].node_delta;
}
self.hidden[h].node_delta = sum * H::derivative(self.hidden[h].output);
}
}
fn calculate_gradients(&mut self) {
for h in 0..HID {
let out = self.hidden[h].output;
for o in 0..OUT {
self.hidden[h].connections[o].gradient = out * self.output[o].node_delta;
}
}
for o in 0..OUT {
self.hidden_bias.connections[o].gradient =
self.hidden_bias.output * self.output[o].node_delta;
}
for i in 0..IN {
let out = self.input[i].output;
for h in 0..HID {
self.input[i].connections[h].gradient = out * self.hidden[h].node_delta;
}
}
for h in 0..HID {
self.input_bias.connections[h].gradient =
self.input_bias.output * self.hidden[h].node_delta;
}
}
fn update_weights(&mut self) {
let rates = (
self.learning_rate,
self.momentum_rate,
self.acceleration_rate,
);
if let Some(range) = self.gradient_clip {
let clip = |c: &mut Connection<V>| c.gradient = clip_gradient(c.gradient, range);
self.hidden
.iter_mut()
.for_each(|n| n.connections.iter_mut().for_each(clip));
self.hidden_bias.connections.iter_mut().for_each(clip);
self.input
.iter_mut()
.for_each(|n| n.connections.iter_mut().for_each(clip));
self.input_bias.connections.iter_mut().for_each(clip);
}
let clip = None;
if let Some(lambda) = self.optimizer.weight_decay() {
let factor = self.learning_rate * lambda;
for n in &mut self.hidden {
decay_weights(&mut n.connections, factor);
}
for n in &mut self.input {
decay_weights(&mut n.connections, factor);
}
}
self.optimizer.begin_step();
for o in 0..OUT {
for h in 0..HID {
self.optimizer
.update_weight(&mut self.hidden[h].connections[o], rates, clip);
}
self.optimizer
.update_weight(&mut self.hidden_bias.connections[o], rates, clip);
}
for h in 0..HID {
for i in 0..IN {
self.optimizer
.update_weight(&mut self.input[i].connections[h], rates, clip);
}
self.optimizer
.update_weight(&mut self.input_bias.connections[h], rates, clip);
}
}
}
impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
MultilayerPerceptron<V, H, O, IN, HID, OUT, Opt>
{
pub fn optimizer(&self) -> &Opt {
&self.optimizer
}
pub fn input_weights(&self) -> [[V; HID]; IN] {
self.input.map(|n| n.connections.map(|c| c.weight))
}
pub fn input_bias_weights(&self) -> [V; HID] {
self.input_bias.connections.map(|c| c.weight)
}
pub fn hidden_weights(&self) -> [[V; OUT]; HID] {
self.hidden.map(|n| n.connections.map(|c| c.weight))
}
pub fn hidden_bias_weights(&self) -> [V; OUT] {
self.hidden_bias.connections.map(|c| c.weight)
}
pub fn set_input_weights(&mut self, weights: &[[V; HID]; IN]) {
for (neuron, row) in self.input.iter_mut().zip(weights) {
for (c, &w) in neuron.connections.iter_mut().zip(row) {
c.weight = w;
}
}
}
pub fn set_input_bias_weights(&mut self, weights: &[V; HID]) {
for (c, &w) in self.input_bias.connections.iter_mut().zip(weights) {
c.weight = w;
}
}
pub fn set_hidden_weights(&mut self, weights: &[[V; OUT]; HID]) {
for (neuron, row) in self.hidden.iter_mut().zip(weights) {
for (c, &w) in neuron.connections.iter_mut().zip(row) {
c.weight = w;
}
}
}
pub fn set_hidden_bias_weights(&mut self, weights: &[V; OUT]) {
for (c, &w) in self.hidden_bias.connections.iter_mut().zip(weights) {
c.weight = w;
}
}
pub fn set_weights(&mut self, from: &InferencePerceptron<V, H, O, IN, HID, OUT>) {
self.set_input_weights(&from.input_weights);
self.set_input_bias_weights(&from.input_bias_weights);
self.set_hidden_weights(&from.hidden_weights);
self.set_hidden_bias_weights(&from.hidden_bias_weights);
}
pub fn to_inference(&self) -> InferencePerceptron<V, H, O, IN, HID, OUT> {
InferencePerceptron::new(
self.input_weights(),
self.input_bias_weights(),
self.hidden_weights(),
self.hidden_bias_weights(),
)
}
}
pub struct InferencePerceptron<V, H, O, const IN: usize, const HID: usize, const OUT: usize> {
pub input_weights: [[V; HID]; IN],
pub input_bias_weights: [V; HID],
pub hidden_weights: [[V; OUT]; HID],
pub hidden_bias_weights: [V; OUT],
activations: PhantomData<fn() -> (H, O)>,
}
impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
InferencePerceptron<V, H, O, IN, HID, OUT>
{
pub const fn new(
input_weights: [[V; HID]; IN],
input_bias_weights: [V; HID],
hidden_weights: [[V; OUT]; HID],
hidden_bias_weights: [V; OUT],
) -> Self {
Self {
input_weights,
input_bias_weights,
hidden_weights,
hidden_bias_weights,
activations: PhantomData,
}
}
}
impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
InferencePerceptron<V, H, O, IN, HID, OUT>
where
V: Scalar,
H: Activation<V>,
O: Activation<V>,
{
pub fn feed_forward(&self, inputs: &[V; IN]) -> [V; OUT] {
let mut hidden = [V::ZERO; HID];
for (h, out) in hidden.iter_mut().enumerate() {
let mut sum = V::ONE * self.input_bias_weights[h];
let mut layer_sum = V::ZERO;
for (&x, row) in inputs.iter().zip(&self.input_weights) {
layer_sum += x * row[h];
}
sum += layer_sum;
*out = H::activate(sum);
}
let mut output = [V::ZERO; OUT];
for (o, out) in output.iter_mut().enumerate() {
let mut sum = V::ONE * self.hidden_bias_weights[o];
let mut layer_sum = V::ZERO;
for (&x, row) in hidden.iter().zip(&self.hidden_weights) {
layer_sum += x * row[o];
}
sum += layer_sum;
*out = O::activate(sum);
}
output
}
}
impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize> Clone
for InferencePerceptron<V, H, O, IN, HID, OUT>
{
fn clone(&self) -> Self {
*self
}
}
impl<V: Copy, H, O, const IN: usize, const HID: usize, const OUT: usize> Copy
for InferencePerceptron<V, H, O, IN, HID, OUT>
{
}
impl<V: PartialEq, H, O, const IN: usize, const HID: usize, const OUT: usize> PartialEq
for InferencePerceptron<V, H, O, IN, HID, OUT>
{
fn eq(&self, other: &Self) -> bool {
self.input_weights == other.input_weights
&& self.input_bias_weights == other.input_bias_weights
&& self.hidden_weights == other.hidden_weights
&& self.hidden_bias_weights == other.hidden_bias_weights
}
}
impl<V: Eq, H, O, const IN: usize, const HID: usize, const OUT: usize> Eq
for InferencePerceptron<V, H, O, IN, HID, OUT>
{
}
impl<V: core::fmt::Debug, H, O, const IN: usize, const HID: usize, const OUT: usize>
core::fmt::Debug for InferencePerceptron<V, H, O, IN, HID, OUT>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("InferencePerceptron")
.field("input_weights", &self.input_weights)
.field("input_bias_weights", &self.input_bias_weights)
.field("hidden_weights", &self.hidden_weights)
.field("hidden_bias_weights", &self.hidden_bias_weights)
.finish()
}
}
fn weighted_sum<V: Scalar, const N: usize, const C: usize>(
bias: &Neuron<V, C>,
layer: &[Neuron<V, C>; N],
target: usize,
) -> V {
let weight = |n: &Neuron<V, C>| n.connections.get(target).map_or(V::ZERO, |c| c.weight);
let mut sum = bias.output * weight(bias);
let mut layer_sum = V::ZERO;
for neuron in layer {
layer_sum += neuron.output * weight(neuron);
}
sum += layer_sum;
sum
}
pub(crate) fn update_connection<V: Scalar>(
c: &mut Connection<V>,
(lr, momentum, acceleration): (V, V, V),
clip: Option<(V, V)>,
) {
let gradient = match clip {
Some(range) => clip_gradient(c.gradient, range),
None => c.gradient,
};
let new_delta_weight = lr.mul_round_nearest(gradient)
+ momentum.mul_round_toward_zero(c.delta_weight)
+ acceleration.mul_round_toward_zero(c.previous_delta_weight);
let current_weight = c.weight;
c.set_delta_weight(new_delta_weight);
c.weight = current_weight + new_delta_weight;
}
pub(crate) fn clip_gradient<V: Scalar>(gradient: V, (min, max): (V, V)) -> V {
if gradient > max {
max
} else if gradient < min {
min
} else {
gradient
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::activation::{Relu, Sigmoid, Tanh};
use crate::rand::GlibcRand;
use crate::{Q8_8, Q16_16};
fn same_outputs<V, H, O, const IN: usize, const HID: usize, const OUT: usize>(
raw: impl Fn(i32) -> V,
seed: u32,
) where
V: Scalar + PartialEq + core::fmt::Debug,
H: Activation<V>,
O: Activation<V>,
{
let mut rng = GlibcRand::new(seed);
for trial in 0..50 {
let mut nn = MultilayerPerceptron::<V, H, O, IN, HID, OUT>::new(|| raw(rng.next_i32()));
let frozen = nn.to_inference();
for _ in 0..20 {
let input: [V; IN] = core::array::from_fn(|_| raw(rng.next_i32()));
let evaluated = nn.evaluate(&input);
nn.feed_forward(&input);
assert_eq!(
frozen.feed_forward(&input),
nn.learned_values(),
"trial {trial}"
);
assert_eq!(evaluated, nn.learned_values(), "trial {trial}");
}
}
}
fn small(r: i32, one: i32) -> i32 {
r % (4 * one + 1) - 2 * one
}
#[test]
fn inference_matches_trainable_q16_16() {
let small_q = |r: i32| Q16_16::from_raw(small(r, 1 << 16));
let wide_q = |r: i32| Q16_16::from_raw(r.wrapping_mul(2_654_435_761u32 as i32));
same_outputs::<Q16_16, Tanh, Sigmoid, 2, 4, 1>(small_q, 1);
same_outputs::<Q16_16, Relu, Sigmoid, 4, 8, 3>(small_q, 2);
same_outputs::<Q16_16, Tanh, Sigmoid, 2, 4, 1>(wide_q, 3);
same_outputs::<Q16_16, Relu, Sigmoid, 4, 8, 3>(wide_q, 4);
}
#[test]
fn inference_matches_trainable_q8_8() {
let small_q = |r: i32| Q8_8::from_raw(small(r, 1 << 8) as i16);
let wide_q = |r: i32| Q8_8::from_raw(r as i16);
same_outputs::<Q8_8, Tanh, Sigmoid, 2, 4, 1>(small_q, 5);
same_outputs::<Q8_8, Relu, Sigmoid, 4, 8, 3>(small_q, 6);
same_outputs::<Q8_8, Tanh, Sigmoid, 2, 4, 1>(wide_q, 7);
same_outputs::<Q8_8, Relu, Sigmoid, 4, 8, 3>(wide_q, 8);
}
#[test]
fn train_freeze_and_reload() {
type Net = MultilayerPerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
let mut rng = GlibcRand::new(9);
let mut nn = Net::new(|| Q16_16::from_raw(small(rng.next_i32(), 1 << 16)));
let samples = [(0, 0, 0), (0, 1, 1), (1, 0, 1), (1, 1, 0)];
for step in 0..2000 {
let (a, b, y) = samples[step % 4];
nn.feed_forward(&[Q16_16::from_int(a), Q16_16::from_int(b)]);
nn.train(&[Q16_16::from_int(y)]);
}
let frozen = nn.to_inference();
for (a, b, _) in samples {
let input = [Q16_16::from_int(a), Q16_16::from_int(b)];
nn.feed_forward(&input);
assert_eq!(frozen.feed_forward(&input), nn.learned_values());
}
let mut other = Net::new(|| Q16_16::ZERO);
other.set_weights(&frozen);
assert_eq!(other.to_inference(), frozen);
assert_eq!(other.input_weights(), frozen.input_weights);
assert_eq!(other.hidden_bias_weights(), frozen.hidden_bias_weights);
}
#[test]
fn inference_network_is_smaller() {
use core::mem::size_of;
type Trainable = MultilayerPerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
type Inference = InferencePerceptron<Q16_16, Tanh, Sigmoid, 2, 4, 1>;
assert_eq!(size_of::<Inference>(), 17 * 4);
assert!(size_of::<Trainable>() > 4 * size_of::<Inference>());
}
}