Skip to main content

Module recurrent

Module recurrent 

Source
Expand description

Recurrent networks, ported from tinymind (C++)’s cpp/neuralnet.hpp: LstmNetwork is tinymind (C++)’s LstmNeuralNetwork with one LSTM hidden layer.

An LSTM network reads a sequence one step at a time: each feed_forward takes one input vector, updates the hidden layer’s state from it and from the previous step’s outputs, and produces the outputs for that step. reset_state clears the state between independent sequences. To train a network on its own predictions, ScheduledSampling picks each step’s input. train back-propagates the current step’s error one step back in time (truncated back-propagation through time, as the C++ does), so it is called after each step’s forward pass. The gradient stops at h[t-1]: the network learns to use what its state already carries, but no step is trained to store something only a later step needs, so a task like “repeat the previous input” is learned poorly unless the current step’s target also depends on it.

Each of the HID hidden cells has four gates, each with its own weights from the inputs, the input bias and the previous step’s hidden outputs:

candidate = H(W_c x + b_c + U_c h[t-1])       (H: the cell activation, usually Tanh)
input     = sigmoid(W_i x + b_i + U_i h[t-1])
forget    = sigmoid(W_f x + b_f + U_f h[t-1])
output    = sigmoid(W_o x + b_o + U_o h[t-1])
c[t] = forget * c[t-1] + candidate * input
h[t] = tanh(c[t]) * output

The weight getters and setters index gates in that order (GATE_CANDIDATE, GATE_INPUT, GATE_FORGET, GATE_OUTPUT); the C++ stores gate g of hidden cell n as connection n * 4 + g. The hidden outputs feed an output layer with activation O.

use tinymind::recurrent::LstmNetwork;
use tinymind::{Q16_16, Sigmoid, Tanh};

// 1 input -> 4 LSTM cells -> 1 sigmoid output. Each sequence is 8 values
// of +0.5 or -0.5; the output should be 1 once a positive value has
// appeared in the sequence, 0 before.
let mut seed = 3u32;
let mut nn = LstmNetwork::<Q16_16, Tanh, Sigmoid, 1, 4, 1>::new(|| {
    seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
    Q16_16::from_raw((seed >> 16) as i32 % 16_385 - 8_192)
});
let half = Q16_16::ONE / Q16_16::from_int(2);
let neg = Q16_16::ZERO - half;
let mut bits = 1u32;
for _ in 0..1000 {
    nn.reset_state();
    let mut seen = false;
    for _ in 0..8 {
        bits = bits.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
        let x = if bits >> 30 == 3 { half } else { neg }; // positive 1 time in 4
        seen |= x > Q16_16::ZERO;
        nn.feed_forward(&[x]);
        nn.train(&[if seen { Q16_16::ONE } else { Q16_16::ZERO }]);
    }
}
nn.reset_state();
let outputs = [neg, neg, half, neg, neg].map(|x| {
    nn.feed_forward(&[x]);
    nn.learned_values()[0]
});
assert!(outputs[..2].iter().all(|&y| y < half));
assert!(outputs[2..].iter().all(|&y| y > half));

The value type is any Scalar for which Tanh and Sigmoid are implemented: Q16_16, Q8_8, and f32/f64 with the std or libm feature. Training is SGD with momentum by default, or Adam or RMSprop (crate::optimizer), with optional gradient clipping and optional L2 weight decay and a step-decay learning-rate schedule (crate::training, wrapping the optimizer; fixed point only on the C++ side); every result is bit-identical to the C++ network with the same initial weights.

tinymind (C++)’s GRU and Elman networks are not ported yet.

To pick a class, rank the output logits with predicted_class() (output_pre_activations() returns them) rather than learned_values(): the fixed-point sigmoid table is flat beyond ±6, so confident outputs tie.

Structs§

LstmNetwork
An LSTM network: IN inputs -> HID LSTM cells (cell candidate activation H) -> OUT outputs (activation O).

Constants§

GATE_CANDIDATE
Gate index of the cell candidate (activation H).
GATE_FORGET
Gate index of the forget gate (sigmoid).
GATE_INPUT
Gate index of the input gate (sigmoid).
GATE_OUTPUT
Gate index of the output gate (sigmoid).
LSTM_GATES
The number of gates of an LSTM cell.