use core::marker::PhantomData;
use crate::activation::{Activation, Sigmoid, Tanh};
use crate::neuralnet::{Connection, Neuron};
use crate::optimizer::{Optimizer, Sgd, update_all};
use crate::qformat::Scalar;
use crate::training::decay_weights;
pub const LSTM_GATES: usize = 4;
pub const GATE_CANDIDATE: usize = 0;
pub const GATE_INPUT: usize = 1;
pub const GATE_FORGET: usize = 2;
pub const GATE_OUTPUT: usize = 3;
#[derive(Clone, Copy, Debug)]
struct GatedNeuron<V, const HID: usize> {
output: V,
connections: [[Connection<V>; LSTM_GATES]; HID],
}
impl<V: Scalar, const HID: usize> GatedNeuron<V, HID> {
fn new() -> Self {
Self {
output: V::ZERO,
connections: [[Connection::default(); LSTM_GATES]; HID],
}
}
fn initialize_weights(&mut self, random_weight: &mut impl FnMut() -> V) {
for c in self.connections.iter_mut().flatten() {
c.weight = random_weight();
}
for c in self.connections.iter_mut().flatten() {
c.set_delta_weight(V::ZERO);
}
}
fn accumulate(&self, sums: &mut [[V; LSTM_GATES]; HID]) {
for (cell_sums, cell_connections) in sums.iter_mut().zip(&self.connections) {
for (sum, c) in cell_sums.iter_mut().zip(cell_connections) {
*sum += self.output * c.weight;
}
}
}
fn set_gradients<const OUT: usize>(&mut self, cells: &[LstmCell<V, OUT>; HID]) {
let output = self.output;
for (cell_connections, cell) in self.connections.iter_mut().zip(cells) {
for (c, &delta) in cell_connections.iter_mut().zip(&cell.gate_deltas) {
c.gradient = output * delta;
}
}
}
fn weights(&self) -> [[V; LSTM_GATES]; HID] {
self.connections.map(|cell| cell.map(|c| c.weight))
}
fn set_weights(&mut self, weights: &[[V; LSTM_GATES]; HID]) {
for (cell_connections, cell_weights) in self.connections.iter_mut().zip(weights) {
for (c, &w) in cell_connections.iter_mut().zip(cell_weights) {
c.weight = w;
}
}
}
}
#[derive(Clone, Copy, Debug)]
struct LstmCell<V, const OUT: usize> {
output: V,
state: V,
previous_state: V,
candidate: V,
input_gate: V,
forget_gate: V,
output_gate: V,
node_delta: V,
gate_deltas: [V; LSTM_GATES],
connections: [Connection<V>; OUT],
}
impl<V: Scalar, const OUT: usize> LstmCell<V, OUT> {
fn new() -> Self {
Self {
output: V::ZERO,
state: V::ZERO,
previous_state: V::ZERO,
candidate: V::ZERO,
input_gate: V::ZERO,
forget_gate: V::ZERO,
output_gate: V::ZERO,
node_delta: V::ZERO,
gate_deltas: [V::ZERO; LSTM_GATES],
connections: [Connection::default(); OUT],
}
}
}
pub struct LstmNetwork<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt = Sgd> {
input: [GatedNeuron<V, HID>; IN],
input_bias: GatedNeuron<V, HID>,
hidden: [LstmCell<V, OUT>; HID],
hidden_bias: Neuron<V, OUT>,
output: [Neuron<V, 1>; OUT],
recurrent: [GatedNeuron<V, HID>; HID],
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>
LstmNetwork<V, H, O, IN, HID, OUT, Sgd>
where
V: Scalar,
H: Activation<V>,
O: Activation<V>,
Sigmoid: Activation<V>,
Tanh: 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>
LstmNetwork<V, H, O, IN, HID, OUT, Opt>
where
V: Scalar,
H: Activation<V>,
O: Activation<V>,
Sigmoid: Activation<V>,
Tanh: Activation<V>,
Opt: Optimizer<V>,
{
pub fn with_optimizer(mut random_weight: impl FnMut() -> V, optimizer: Opt) -> Self {
let mut nn = Self {
input: [GatedNeuron::new(); IN],
input_bias: GatedNeuron::new(),
hidden: [LstmCell::new(); HID],
hidden_bias: Neuron::default(),
output: [Neuron::default(); OUT],
recurrent: [GatedNeuron::new(); HID],
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 cell in &mut nn.hidden {
for c in &mut cell.connections {
c.weight = random_weight();
}
for c in &mut cell.connections {
c.set_delta_weight(V::ZERO);
}
}
nn.hidden_bias.initialize_weights(&mut random_weight);
for n in &mut nn.output {
n.initialize_weights(&mut random_weight);
}
for n in &mut nn.recurrent {
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 reset_state(&mut self) {
for cell in &mut self.hidden {
cell.state = V::ZERO;
cell.output = V::ZERO;
}
for r in &mut self.recurrent {
r.output = V::ZERO;
}
}
pub fn feed_forward(&mut self, inputs: &[V; IN]) {
for (neuron, &value) in self.input.iter_mut().zip(inputs) {
neuron.output = value;
}
for (r, cell) in self.recurrent.iter_mut().zip(&self.hidden) {
r.output = cell.output;
}
let mut input_sums = [[V::ZERO; LSTM_GATES]; HID];
for neuron in &self.input {
neuron.accumulate(&mut input_sums);
}
let mut recurrent_sums = [[V::ZERO; LSTM_GATES]; HID];
for neuron in &self.recurrent {
neuron.accumulate(&mut recurrent_sums);
}
let bias = self.input_bias.output;
for (((cell, bias_connections), input_sum), recurrent_sum) in self
.hidden
.iter_mut()
.zip(&self.input_bias.connections)
.zip(&input_sums)
.zip(&recurrent_sums)
{
let mut sums = [V::ZERO; LSTM_GATES];
for (((sum, c), &x), &r) in sums
.iter_mut()
.zip(bias_connections)
.zip(input_sum)
.zip(recurrent_sum)
{
let mut s = bias * c.weight;
s += x;
s += r;
*sum = s;
}
let [
candidate_sum,
input_gate_sum,
forget_gate_sum,
output_gate_sum,
] = sums;
let candidate = H::activate(candidate_sum);
let input_gate = Sigmoid::activate(input_gate_sum);
let forget_gate = Sigmoid::activate(forget_gate_sum);
let output_gate = Sigmoid::activate(output_gate_sum);
let previous_state = cell.state;
cell.candidate = candidate;
cell.input_gate = input_gate;
cell.forget_gate = forget_gate;
cell.output_gate = output_gate;
cell.previous_state = previous_state;
let state = (forget_gate * previous_state) + (candidate * input_gate);
cell.state = state;
cell.output = Tanh::activate(state) * output_gate;
}
let mut layer_sums = [V::ZERO; OUT];
for cell in &self.hidden {
for (sum, c) in layer_sums.iter_mut().zip(&cell.connections) {
*sum += cell.output * c.weight;
}
}
let bias = self.hidden_bias.output;
for ((neuron, c), &layer_sum) in self
.output
.iter_mut()
.zip(&self.hidden_bias.connections)
.zip(&layer_sums)
{
let mut sum = bias * c.weight;
sum += layer_sum;
neuron.output = O::activate(sum);
}
}
pub fn learned_values(&self) -> [V; OUT] {
self.output.map(|n| n.output)
}
pub fn hidden_outputs(&self) -> [V; HID] {
self.hidden.map(|cell| cell.output)
}
pub fn cell_states(&self) -> [V; HID] {
self.hidden.map(|cell| cell.state)
}
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_deltas(targets);
self.calculate_gradients();
self.update_weights();
self.learning_rate = self.optimizer.next_learning_rate(self.learning_rate);
}
fn calculate_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 cell in &mut self.hidden {
let mut sum = V::ZERO;
for (c, o) in cell.connections.iter().zip(&self.output) {
sum += c.weight * o.node_delta;
}
cell.node_delta = sum;
let dl_dh = sum;
let tanh_c = Tanh::activate(cell.state);
let dl_do = dl_dh * tanh_c;
let dl_dc = dl_dh * cell.output_gate * Tanh::derivative(tanh_c);
cell.gate_deltas = [
dl_dc * cell.input_gate * H::derivative(cell.candidate),
dl_dc * cell.candidate * Sigmoid::derivative(cell.input_gate),
dl_dc * cell.previous_state * Sigmoid::derivative(cell.forget_gate),
dl_do * Sigmoid::derivative(cell.output_gate),
];
}
}
fn calculate_gradients(&mut self) {
for cell in &mut self.hidden {
let out = cell.output;
for (c, o) in cell.connections.iter_mut().zip(&self.output) {
c.gradient = out * o.node_delta;
}
}
let bias = self.hidden_bias.output;
for (c, o) in self.hidden_bias.connections.iter_mut().zip(&self.output) {
c.gradient = bias * o.node_delta;
}
for r in &mut self.recurrent {
r.set_gradients(&self.hidden);
}
for n in &mut self.input {
n.set_gradients(&self.hidden);
}
self.input_bias.set_gradients(&self.hidden);
}
fn update_weights(&mut self) {
let rates = (
self.learning_rate,
self.momentum_rate,
self.acceleration_rate,
);
let clip = self.gradient_clip;
if let Some(lambda) = self.optimizer.weight_decay() {
let factor = self.learning_rate * lambda;
for cell in &mut self.hidden {
decay_weights(&mut cell.connections, factor);
}
for r in &mut self.recurrent {
decay_weights(r.connections.as_flattened_mut(), factor);
}
for n in &mut self.input {
decay_weights(n.connections.as_flattened_mut(), factor);
}
}
self.optimizer.begin_step();
let opt = &self.optimizer;
for cell in &mut self.hidden {
update_all(opt, &mut cell.connections, rates, clip);
}
update_all(opt, &mut self.hidden_bias.connections, rates, clip);
for r in &mut self.recurrent {
update_all(opt, r.connections.as_flattened_mut(), rates, clip);
}
for n in &mut self.input {
update_all(opt, n.connections.as_flattened_mut(), rates, clip);
}
update_all(
opt,
self.input_bias.connections.as_flattened_mut(),
rates,
clip,
);
}
}
impl<V: Scalar, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
LstmNetwork<V, H, O, IN, HID, OUT, Opt>
{
pub fn optimizer(&self) -> &Opt {
&self.optimizer
}
pub fn input_weights(&self) -> [[[V; LSTM_GATES]; HID]; IN] {
self.input.map(|n| n.weights())
}
pub fn input_bias_weights(&self) -> [[V; LSTM_GATES]; HID] {
self.input_bias.weights()
}
pub fn recurrent_weights(&self) -> [[[V; LSTM_GATES]; HID]; HID] {
self.recurrent.map(|n| n.weights())
}
pub fn hidden_weights(&self) -> [[V; OUT]; HID] {
self.hidden.map(|cell| cell.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; LSTM_GATES]; HID]; IN]) {
for (n, w) in self.input.iter_mut().zip(weights) {
n.set_weights(w);
}
}
pub fn set_input_bias_weights(&mut self, weights: &[[V; LSTM_GATES]; HID]) {
self.input_bias.set_weights(weights);
}
pub fn set_recurrent_weights(&mut self, weights: &[[[V; LSTM_GATES]; HID]; HID]) {
for (n, w) in self.recurrent.iter_mut().zip(weights) {
n.set_weights(w);
}
}
pub fn set_hidden_weights(&mut self, weights: &[[V; OUT]; HID]) {
for (cell, w) in self.hidden.iter_mut().zip(weights) {
for (c, &w) in cell.connections.iter_mut().zip(w) {
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;
}
}
}