tinymind/recurrent.rs
1//! Recurrent networks, ported from tinymind (C++)'s `cpp/neuralnet.hpp`:
2//! [`LstmNetwork`] is tinymind (C++)'s `LstmNeuralNetwork` with one LSTM hidden
3//! layer.
4//!
5//! An LSTM network reads a sequence one step at a time: each
6//! [`feed_forward`](LstmNetwork::feed_forward) takes one input vector, updates
7//! the hidden layer's state from it and from the previous step's outputs, and
8//! produces the outputs for that step. [`reset_state`](LstmNetwork::reset_state)
9//! clears the state between independent sequences. To train a network on
10//! its own predictions, [`ScheduledSampling`](crate::training::ScheduledSampling)
11//! picks each step's input.
12//! [`train`](LstmNetwork::train) back-propagates the current step's error
13//! one step back in time (truncated back-propagation through time, as the C++
14//! does), so it is called after each step's forward pass. The gradient stops at
15//! h[t-1]: the network learns to use what its state already carries, but no
16//! step is trained to store something only a later step needs, so a task like
17//! "repeat the previous input" is learned poorly unless the current step's
18//! target also depends on it.
19//!
20//! Each of the `HID` hidden cells has four gates, each with its own weights
21//! from the inputs, the input bias and the previous step's hidden outputs:
22//!
23//! ```text
24//! candidate = H(W_c x + b_c + U_c h[t-1]) (H: the cell activation, usually Tanh)
25//! input = sigmoid(W_i x + b_i + U_i h[t-1])
26//! forget = sigmoid(W_f x + b_f + U_f h[t-1])
27//! output = sigmoid(W_o x + b_o + U_o h[t-1])
28//! c[t] = forget * c[t-1] + candidate * input
29//! h[t] = tanh(c[t]) * output
30//! ```
31//!
32//! The weight getters and setters index gates in that order
33//! ([`GATE_CANDIDATE`], [`GATE_INPUT`], [`GATE_FORGET`], [`GATE_OUTPUT`]); the
34//! C++ stores gate `g` of hidden cell `n` as connection `n * 4 + g`. The
35//! hidden outputs feed an output layer with activation `O`.
36//!
37//! ```
38//! use tinymind::recurrent::LstmNetwork;
39//! use tinymind::{Q16_16, Sigmoid, Tanh};
40//!
41//! // 1 input -> 4 LSTM cells -> 1 sigmoid output. Each sequence is 8 values
42//! // of +0.5 or -0.5; the output should be 1 once a positive value has
43//! // appeared in the sequence, 0 before.
44//! let mut seed = 3u32;
45//! let mut nn = LstmNetwork::<Q16_16, Tanh, Sigmoid, 1, 4, 1>::new(|| {
46//! seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12_345);
47//! Q16_16::from_raw((seed >> 16) as i32 % 16_385 - 8_192)
48//! });
49//! let half = Q16_16::ONE / Q16_16::from_int(2);
50//! let neg = Q16_16::ZERO - half;
51//! let mut bits = 1u32;
52//! for _ in 0..1000 {
53//! nn.reset_state();
54//! let mut seen = false;
55//! for _ in 0..8 {
56//! bits = bits.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
57//! let x = if bits >> 30 == 3 { half } else { neg }; // positive 1 time in 4
58//! seen |= x > Q16_16::ZERO;
59//! nn.feed_forward(&[x]);
60//! nn.train(&[if seen { Q16_16::ONE } else { Q16_16::ZERO }]);
61//! }
62//! }
63//! nn.reset_state();
64//! let outputs = [neg, neg, half, neg, neg].map(|x| {
65//! nn.feed_forward(&[x]);
66//! nn.learned_values()[0]
67//! });
68//! assert!(outputs[..2].iter().all(|&y| y < half));
69//! assert!(outputs[2..].iter().all(|&y| y > half));
70//! ```
71//!
72//! The value type is any [`Scalar`] for which [`Tanh`] and [`Sigmoid`] are
73//! implemented: `Q16_16`, `Q8_8`, and `f32`/`f64` with the `std` or `libm`
74//! feature. Training is SGD with momentum by default, or Adam or RMSprop
75//! ([`crate::optimizer`]), with optional gradient clipping and optional L2
76//! weight decay and a step-decay learning-rate schedule ([`crate::training`],
77//! wrapping the optimizer; fixed point only on the C++ side); every result is
78//! bit-identical to the C++ network with the same initial weights.
79//!
80//! tinymind (C++)'s GRU and Elman networks are not ported yet.
81//!
82//! To pick a class, rank the output logits with `predicted_class()`
83//! (`output_pre_activations()` returns them) rather than `learned_values()`:
84//! the fixed-point sigmoid table is flat beyond ±6, so confident outputs tie.
85
86use core::marker::PhantomData;
87
88use crate::activation::{Activation, Sigmoid, Tanh};
89use crate::neuralnet::{Connection, Neuron, argmax};
90use crate::optimizer::{Optimizer, Sgd, update_all};
91use crate::qformat::Scalar;
92use crate::training::decay_weights;
93
94/// The number of gates of an LSTM cell.
95pub const LSTM_GATES: usize = 4;
96/// Gate index of the cell candidate (activation `H`).
97pub const GATE_CANDIDATE: usize = 0;
98/// Gate index of the input gate (sigmoid).
99pub const GATE_INPUT: usize = 1;
100/// Gate index of the forget gate (sigmoid).
101pub const GATE_FORGET: usize = 2;
102/// Gate index of the output gate (sigmoid).
103pub const GATE_OUTPUT: usize = 3;
104
105/// A neuron feeding every gate of every LSTM cell: an input, the input bias, or
106/// one of the previous step's hidden outputs (C++ `TrainableNeuron` with
107/// `HID * 4` connections, connection `n * 4 + g` = `connections[n][g]`).
108#[derive(Clone, Copy, Debug)]
109struct GatedNeuron<V, const HID: usize> {
110 output: V,
111 connections: [[Connection<V>; LSTM_GATES]; HID],
112}
113
114impl<V: Scalar, const HID: usize> GatedNeuron<V, HID> {
115 fn new() -> Self {
116 Self {
117 output: V::ZERO,
118 connections: [[Connection::default(); LSTM_GATES]; HID],
119 }
120 }
121
122 /// C++ `TrainableNeuron::initializeWeights`: one draw per connection in
123 /// connection order (cell, then gate), then zero delta weights.
124 fn initialize_weights(&mut self, random_weight: &mut impl FnMut() -> V) {
125 for c in self.connections.iter_mut().flatten() {
126 c.weight = random_weight();
127 }
128 for c in self.connections.iter_mut().flatten() {
129 c.set_delta_weight(V::ZERO);
130 }
131 }
132
133 /// Adds this neuron's contribution to every gate's sum, `output * weight`,
134 /// in the C++ order (each target's sum runs over the source neurons in
135 /// order, so iterating sources on the outside keeps it).
136 fn accumulate(&self, sums: &mut [[V; LSTM_GATES]; HID]) {
137 for (cell_sums, cell_connections) in sums.iter_mut().zip(&self.connections) {
138 for (sum, c) in cell_sums.iter_mut().zip(cell_connections) {
139 *sum += self.output * c.weight;
140 }
141 }
142 }
143
144 /// Sets each gate connection's gradient to `output * delta` for that gate's
145 /// delta (C++ `calculateAndUpdateGradientsGated`).
146 fn set_gradients<const OUT: usize>(&mut self, cells: &[LstmCell<V, OUT>; HID]) {
147 let output = self.output;
148 for (cell_connections, cell) in self.connections.iter_mut().zip(cells) {
149 for (c, &delta) in cell_connections.iter_mut().zip(&cell.gate_deltas) {
150 c.gradient = output * delta;
151 }
152 }
153 }
154
155 fn weights(&self) -> [[V; LSTM_GATES]; HID] {
156 self.connections.map(|cell| cell.map(|c| c.weight))
157 }
158
159 fn set_weights(&mut self, weights: &[[V; LSTM_GATES]; HID]) {
160 for (cell_connections, cell_weights) in self.connections.iter_mut().zip(weights) {
161 for (c, &w) in cell_connections.iter_mut().zip(cell_weights) {
162 c.weight = w;
163 }
164 }
165 }
166}
167
168/// One LSTM hidden cell (C++ `TrainableLstmHiddenLayerNeuron`): its output
169/// h, cell state c, the gate activations of the latest forward pass, its
170/// deltas, and its connections to the output layer.
171#[derive(Clone, Copy, Debug)]
172struct LstmCell<V, const OUT: usize> {
173 output: V,
174 state: V,
175 previous_state: V,
176 candidate: V,
177 input_gate: V,
178 forget_gate: V,
179 output_gate: V,
180 node_delta: V,
181 gate_deltas: [V; LSTM_GATES],
182 connections: [Connection<V>; OUT],
183}
184
185impl<V: Scalar, const OUT: usize> LstmCell<V, OUT> {
186 fn new() -> Self {
187 Self {
188 output: V::ZERO,
189 state: V::ZERO,
190 previous_state: V::ZERO,
191 candidate: V::ZERO,
192 input_gate: V::ZERO,
193 forget_gate: V::ZERO,
194 output_gate: V::ZERO,
195 node_delta: V::ZERO,
196 gate_deltas: [V::ZERO; LSTM_GATES],
197 connections: [Connection::default(); OUT],
198 }
199 }
200}
201
202/// An LSTM network: `IN` inputs -> `HID` LSTM cells (cell candidate
203/// activation `H`) -> `OUT` outputs (activation `O`).
204///
205/// C++: `LstmNeuralNetwork<ValueType, IN, HiddenLayers<HID>, OUT,
206/// TransferFunctions>` with `H` and `O` the transfer functions' hidden and
207/// output activations. See the [module documentation](self) for the cell
208/// equations and an example.
209///
210/// `Opt` is the optimizer: [`Sgd`] (the default) or an adaptive one from
211/// [`optimizer`](crate::optimizer), passed to
212/// [`with_optimizer`](Self::with_optimizer).
213pub struct LstmNetwork<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt = Sgd> {
214 input: [GatedNeuron<V, HID>; IN],
215 input_bias: GatedNeuron<V, HID>,
216 hidden: [LstmCell<V, OUT>; HID],
217 hidden_bias: Neuron<V, OUT>,
218 /// Output neurons own one connection that is never used, as in the C++,
219 /// whose initialisation consumes a random draw.
220 output: [Neuron<V, 1>; OUT],
221 /// The previous step's hidden outputs, h[t-1] (C++ recurrent layer), and
222 /// their connections to every gate.
223 recurrent: [GatedNeuron<V, HID>; HID],
224 learning_rate: V,
225 momentum_rate: V,
226 acceleration_rate: V,
227 gradient_clip: Option<(V, V)>,
228 optimizer: Opt,
229 activations: PhantomData<fn() -> (H, O)>,
230}
231
232impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize>
233 LstmNetwork<V, H, O, IN, HID, OUT, Sgd>
234where
235 V: Scalar,
236 H: Activation<V>,
237 O: Activation<V>,
238 Sigmoid: Activation<V>,
239 Tanh: Activation<V>,
240{
241 /// Build the network, trained with [`Sgd`], and initialise its weights from
242 /// `random_weight`, in the C++ constructor's order: each input's
243 /// connections, the input bias's, each hidden cell's connections to the
244 /// outputs, the hidden bias's, the output neurons' (one unused each), and
245 /// last each recurrent connection.
246 pub fn new(random_weight: impl FnMut() -> V) -> Self {
247 Self::with_optimizer(random_weight, Sgd)
248 }
249}
250
251impl<V, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
252 LstmNetwork<V, H, O, IN, HID, OUT, Opt>
253where
254 V: Scalar,
255 H: Activation<V>,
256 O: Activation<V>,
257 Sigmoid: Activation<V>,
258 Tanh: Activation<V>,
259 Opt: Optimizer<V>,
260{
261 /// As [`new`](LstmNetwork::new), trained with `optimizer`, for example
262 /// [`Adam`](crate::Adam).
263 pub fn with_optimizer(mut random_weight: impl FnMut() -> V, optimizer: Opt) -> Self {
264 let mut nn = Self {
265 input: [GatedNeuron::new(); IN],
266 input_bias: GatedNeuron::new(),
267 hidden: [LstmCell::new(); HID],
268 hidden_bias: Neuron::default(),
269 output: [Neuron::default(); OUT],
270 recurrent: [GatedNeuron::new(); HID],
271 // DefaultNetworkInitializer: 1/4, 1/2, 1/16.
272 learning_rate: V::pow2_neg(2),
273 momentum_rate: V::pow2_neg(1),
274 acceleration_rate: V::pow2_neg(4),
275 gradient_clip: None,
276 optimizer,
277 activations: PhantomData,
278 };
279 nn.input_bias.output = V::ONE;
280 nn.hidden_bias.output = V::ONE;
281
282 for n in &mut nn.input {
283 n.initialize_weights(&mut random_weight);
284 }
285 nn.input_bias.initialize_weights(&mut random_weight);
286 for cell in &mut nn.hidden {
287 for c in &mut cell.connections {
288 c.weight = random_weight();
289 }
290 for c in &mut cell.connections {
291 c.set_delta_weight(V::ZERO);
292 }
293 }
294 nn.hidden_bias.initialize_weights(&mut random_weight);
295 for n in &mut nn.output {
296 n.initialize_weights(&mut random_weight);
297 }
298 for n in &mut nn.recurrent {
299 n.initialize_weights(&mut random_weight);
300 }
301 nn
302 }
303
304 /// Replace the learning rate (default `2^-2`, tinymind (C++)'s
305 /// `DefaultNetworkInitializer`).
306 pub fn set_learning_rate(&mut self, rate: V) {
307 self.learning_rate = rate;
308 }
309
310 /// Replace the momentum rate (default `2^-1`).
311 pub fn set_momentum_rate(&mut self, rate: V) {
312 self.momentum_rate = rate;
313 }
314
315 /// Replace the acceleration rate, the weight on the delta weight from two
316 /// steps back (default `2^-4`).
317 pub fn set_acceleration_rate(&mut self, rate: V) {
318 self.acceleration_rate = rate;
319 }
320
321 /// Clip each weight's and bias weight's gradient to `[min, max]` before
322 /// the update, or `None` (the default) to leave gradients alone. C++
323 /// `GradientClipByValue<ValueType>` is `Some((-1.0, 1.0))`.
324 pub fn set_gradient_clip(&mut self, range: Option<(V, V)>) {
325 self.gradient_clip = range;
326 }
327
328 /// The learning rate the next training step will use: the one set with
329 /// [`set_learning_rate`](Self::set_learning_rate), as a
330 /// [`Scheduled`](crate::training::Scheduled) optimizer has decayed it so far.
331 pub fn learning_rate(&self) -> V {
332 self.learning_rate
333 }
334
335 /// Clear the recurrent state: every cell's output h and state c become 0,
336 /// so the next [`feed_forward`](Self::feed_forward) starts a new sequence
337 /// (C++ `resetState`). Weights and optimizer state are kept.
338 pub fn reset_state(&mut self) {
339 for cell in &mut self.hidden {
340 cell.state = V::ZERO;
341 cell.output = V::ZERO;
342 }
343 for r in &mut self.recurrent {
344 r.output = V::ZERO;
345 }
346 }
347
348 /// One time step: load `inputs`, latch the previous step's hidden outputs
349 /// as h[t-1], update every cell and compute the outputs. Read them with
350 /// [`learned_values`](Self::learned_values).
351 pub fn feed_forward(&mut self, inputs: &[V; IN]) {
352 for (neuron, &value) in self.input.iter_mut().zip(inputs) {
353 neuron.output = value;
354 }
355 // C++ latchPreviousOutputs: every cell reads the same h[t-1].
356 for (r, cell) in self.recurrent.iter_mut().zip(&self.hidden) {
357 r.output = cell.output;
358 }
359
360 let mut input_sums = [[V::ZERO; LSTM_GATES]; HID];
361 for neuron in &self.input {
362 neuron.accumulate(&mut input_sums);
363 }
364 let mut recurrent_sums = [[V::ZERO; LSTM_GATES]; HID];
365 for neuron in &self.recurrent {
366 neuron.accumulate(&mut recurrent_sums);
367 }
368
369 let bias = self.input_bias.output;
370 for (((cell, bias_connections), input_sum), recurrent_sum) in self
371 .hidden
372 .iter_mut()
373 .zip(&self.input_bias.connections)
374 .zip(&input_sums)
375 .zip(&recurrent_sums)
376 {
377 // Each gate's sum: bias term, then the inputs, then h[t-1].
378 let mut sums = [V::ZERO; LSTM_GATES];
379 for (((sum, c), &x), &r) in sums
380 .iter_mut()
381 .zip(bias_connections)
382 .zip(input_sum)
383 .zip(recurrent_sum)
384 {
385 let mut s = bias * c.weight;
386 s += x;
387 s += r;
388 *sum = s;
389 }
390 let [
391 candidate_sum,
392 input_gate_sum,
393 forget_gate_sum,
394 output_gate_sum,
395 ] = sums;
396 let candidate = H::activate(candidate_sum);
397 let input_gate = Sigmoid::activate(input_gate_sum);
398 let forget_gate = Sigmoid::activate(forget_gate_sum);
399 let output_gate = Sigmoid::activate(output_gate_sum);
400
401 let previous_state = cell.state;
402 cell.candidate = candidate;
403 cell.input_gate = input_gate;
404 cell.forget_gate = forget_gate;
405 cell.output_gate = output_gate;
406 cell.previous_state = previous_state;
407
408 let state = (forget_gate * previous_state) + (candidate * input_gate);
409 cell.state = state;
410 cell.output = Tanh::activate(state) * output_gate;
411 }
412
413 let sums = self.output_pre_activations();
414 for (neuron, sum) in self.output.iter_mut().zip(sums) {
415 neuron.output = O::activate(sum);
416 }
417 }
418
419 /// The output-layer activations from the latest
420 /// [`feed_forward`](Self::feed_forward).
421 pub fn learned_values(&self) -> [V; OUT] {
422 self.output.map(|n| n.output)
423 }
424
425 /// The output layer's pre-activations (the logits) for the latest
426 /// [`feed_forward`](Self::feed_forward) (C++ `getOutputPreActivations`):
427 /// `bias term + (0 + sum of h * w)`, the sum `feed_forward` forms (it
428 /// calls this), recomputed from the hidden outputs at no memory cost.
429 ///
430 /// Call it before [`train`](Self::train): training changes the weights it
431 /// is recomputed from.
432 pub fn output_pre_activations(&self) -> [V; OUT] {
433 let mut layer_sums = [V::ZERO; OUT];
434 for cell in &self.hidden {
435 for (sum, c) in layer_sums.iter_mut().zip(&cell.connections) {
436 *sum += cell.output * c.weight;
437 }
438 }
439 let bias = self.hidden_bias.output;
440 for (sum, c) in layer_sums.iter_mut().zip(&self.hidden_bias.connections) {
441 let mut total = bias * c.weight;
442 total += *sum;
443 *sum = total;
444 }
445 layer_sums
446 }
447
448 /// The index of the largest [output pre-activation](Self::output_pre_activations)
449 /// for the latest [`feed_forward`](Self::feed_forward), ties to the lower
450 /// index (C++ `getPredictedClass`).
451 ///
452 /// Use it, not an argmax of [`learned_values`](Self::learned_values), to
453 /// pick a class: the fixed-point sigmoid table is flat beyond ±6, so
454 /// confident outputs tie there and an argmax can only take the first.
455 ///
456 /// Call it before [`train`](Self::train): training changes the weights it
457 /// is recomputed from.
458 pub fn predicted_class(&self) -> usize {
459 argmax(&self.output_pre_activations())
460 }
461
462 /// The hidden cells' outputs h from the latest
463 /// [`feed_forward`](Self::feed_forward).
464 pub fn hidden_outputs(&self) -> [V; HID] {
465 self.hidden.map(|cell| cell.output)
466 }
467
468 /// The hidden cells' states c from the latest
469 /// [`feed_forward`](Self::feed_forward).
470 pub fn cell_states(&self) -> [V; HID] {
471 self.hidden.map(|cell| cell.state)
472 }
473
474 /// Mean-squared error against `targets` (C++ `MeanSquaredErrorCalculator`).
475 pub fn calculate_error(&self, targets: &[V; OUT]) -> V {
476 let mut error = V::ZERO;
477 for (target, neuron) in targets.iter().zip(&self.output) {
478 let delta = *target - neuron.output;
479 error += delta * delta;
480 }
481 if OUT > 1 {
482 error = error.div_int(OUT as i32);
483 }
484 error
485 }
486
487 /// One training step for the latest forward pass (C++
488 /// `ChainBackPropagationThruTimePolicy`): the error is propagated to the
489 /// gates of the current step and to the weights from the inputs, the
490 /// biases and h[t-1], not further back in time.
491 pub fn train(&mut self, targets: &[V; OUT]) {
492 self.calculate_deltas(targets);
493 self.calculate_gradients();
494 self.update_weights();
495 // C++ stepLearningRate, after the update.
496 self.learning_rate = self.optimizer.next_learning_rate(self.learning_rate);
497 }
498
499 fn calculate_deltas(&mut self, targets: &[V; OUT]) {
500 for (neuron, &target) in self.output.iter_mut().zip(targets) {
501 let error = target - neuron.output;
502 neuron.node_delta = error * O::derivative(neuron.output);
503 }
504
505 for cell in &mut self.hidden {
506 // dL/dh: the raw weighted sum of the output deltas
507 // (calculateAndSetRawNodeDeltas).
508 let mut sum = V::ZERO;
509 for (c, o) in cell.connections.iter().zip(&self.output) {
510 sum += c.weight * o.node_delta;
511 }
512 cell.node_delta = sum;
513
514 // computeGateDeltas.
515 let dl_dh = sum;
516 let tanh_c = Tanh::activate(cell.state);
517 let dl_do = dl_dh * tanh_c;
518 let dl_dc = dl_dh * cell.output_gate * Tanh::derivative(tanh_c);
519 cell.gate_deltas = [
520 dl_dc * cell.input_gate * H::derivative(cell.candidate),
521 dl_dc * cell.candidate * Sigmoid::derivative(cell.input_gate),
522 dl_dc * cell.previous_state * Sigmoid::derivative(cell.forget_gate),
523 dl_do * Sigmoid::derivative(cell.output_gate),
524 ];
525 }
526 // The C++ also computes node deltas for the recurrent layer and the
527 // input layer. Nothing reads them, so they are skipped.
528 }
529
530 fn calculate_gradients(&mut self) {
531 // Hidden -> output, then the hidden bias.
532 for cell in &mut self.hidden {
533 let out = cell.output;
534 for (c, o) in cell.connections.iter_mut().zip(&self.output) {
535 c.gradient = out * o.node_delta;
536 }
537 }
538 let bias = self.hidden_bias.output;
539 for (c, o) in self.hidden_bias.connections.iter_mut().zip(&self.output) {
540 c.gradient = bias * o.node_delta;
541 }
542
543 // h[t-1] -> gates (an LSTM gate adds U h[t-1] unscaled, so its
544 // recurrent weights take the gate delta itself), then inputs and the
545 // input bias -> gates.
546 for r in &mut self.recurrent {
547 r.set_gradients(&self.hidden);
548 }
549 for n in &mut self.input {
550 n.set_gradients(&self.hidden);
551 }
552 self.input_bias.set_gradients(&self.hidden);
553 }
554
555 fn update_weights(&mut self) {
556 let rates = (
557 self.learning_rate,
558 self.momentum_rate,
559 self.acceleration_rate,
560 );
561 let clip = self.gradient_clip;
562
563 // Weight decay on every weight but the bias weights (input, recurrent
564 // and hidden->output alike, as the C++ gated and plain updaters do),
565 // before the steps: no update reads the weight.
566 if let Some(lambda) = self.optimizer.weight_decay() {
567 let factor = self.learning_rate * lambda;
568 for cell in &mut self.hidden {
569 decay_weights(&mut cell.connections, factor);
570 }
571 for r in &mut self.recurrent {
572 decay_weights(r.connections.as_flattened_mut(), factor);
573 }
574 for n in &mut self.input {
575 decay_weights(n.connections.as_flattened_mut(), factor);
576 }
577 }
578
579 // One optimizer step (C++ `beginTrainingStep`), then layer by layer
580 // as the C++ does (output, recurrent, input). Each connection's update
581 // reads only itself, so the order does not matter. Bias connections
582 // are clipped like the weights; the recurrent layer has no bias.
583 self.optimizer.begin_step();
584 let opt = &self.optimizer;
585 for cell in &mut self.hidden {
586 update_all(opt, &mut cell.connections, rates, clip);
587 }
588 update_all(opt, &mut self.hidden_bias.connections, rates, clip);
589 for r in &mut self.recurrent {
590 update_all(opt, r.connections.as_flattened_mut(), rates, clip);
591 }
592 for n in &mut self.input {
593 update_all(opt, n.connections.as_flattened_mut(), rates, clip);
594 }
595 update_all(
596 opt,
597 self.input_bias.connections.as_flattened_mut(),
598 rates,
599 clip,
600 );
601 }
602}
603
604/// Weight getters and setters. Each takes or returns a whole matrix, so none
605/// can panic. Gates are indexed as [`GATE_CANDIDATE`], [`GATE_INPUT`],
606/// [`GATE_FORGET`] and [`GATE_OUTPUT`].
607impl<V: Scalar, H, O, const IN: usize, const HID: usize, const OUT: usize, Opt>
608 LstmNetwork<V, H, O, IN, HID, OUT, Opt>
609{
610 /// The optimizer, with its state.
611 pub fn optimizer(&self) -> &Opt {
612 &self.optimizer
613 }
614
615 /// `[input][cell][gate]`: the weights from each input to each gate.
616 pub fn input_weights(&self) -> [[[V; LSTM_GATES]; HID]; IN] {
617 self.input.map(|n| n.weights())
618 }
619
620 /// `[cell][gate]`: the input bias weights.
621 pub fn input_bias_weights(&self) -> [[V; LSTM_GATES]; HID] {
622 self.input_bias.weights()
623 }
624
625 /// `[from cell][to cell][gate]`: the weights from each cell's previous
626 /// output h[t-1] to each gate.
627 pub fn recurrent_weights(&self) -> [[[V; LSTM_GATES]; HID]; HID] {
628 self.recurrent.map(|n| n.weights())
629 }
630
631 /// `[cell][output]`: the weights from the cells to the outputs.
632 pub fn hidden_weights(&self) -> [[V; OUT]; HID] {
633 self.hidden.map(|cell| cell.connections.map(|c| c.weight))
634 }
635
636 /// `[output]`: the hidden bias weights.
637 pub fn hidden_bias_weights(&self) -> [V; OUT] {
638 self.hidden_bias.connections.map(|c| c.weight)
639 }
640
641 /// Replace the input weights (see [`input_weights`](Self::input_weights)).
642 pub fn set_input_weights(&mut self, weights: &[[[V; LSTM_GATES]; HID]; IN]) {
643 for (n, w) in self.input.iter_mut().zip(weights) {
644 n.set_weights(w);
645 }
646 }
647
648 /// Replace the input bias weights.
649 pub fn set_input_bias_weights(&mut self, weights: &[[V; LSTM_GATES]; HID]) {
650 self.input_bias.set_weights(weights);
651 }
652
653 /// Replace the recurrent weights (see
654 /// [`recurrent_weights`](Self::recurrent_weights)).
655 pub fn set_recurrent_weights(&mut self, weights: &[[[V; LSTM_GATES]; HID]; HID]) {
656 for (n, w) in self.recurrent.iter_mut().zip(weights) {
657 n.set_weights(w);
658 }
659 }
660
661 /// Replace the weights from the cells to the outputs.
662 pub fn set_hidden_weights(&mut self, weights: &[[V; OUT]; HID]) {
663 for (cell, w) in self.hidden.iter_mut().zip(weights) {
664 for (c, &w) in cell.connections.iter_mut().zip(w) {
665 c.weight = w;
666 }
667 }
668 }
669
670 /// Replace the hidden bias weights.
671 pub fn set_hidden_bias_weights(&mut self, weights: &[V; OUT]) {
672 for (c, &w) in self.hidden_bias.connections.iter_mut().zip(weights) {
673 c.weight = w;
674 }
675 }
676}
677
678#[cfg(test)]
679mod tests {
680 use super::*;
681 use crate::rand::GlibcRand;
682 use crate::{Q8_8, Q16_16};
683
684 /// Over a trained sequence, the output activation applied to the
685 /// pre-activations gives `learned_values`, and the predicted class is
686 /// their argmax (`har_golden` checks the classes against the C++).
687 fn pre_activations_reproduce_outputs<V>(raw: impl Fn(i32) -> V, seed: u32)
688 where
689 V: Scalar + PartialEq + core::fmt::Debug,
690 Tanh: Activation<V>,
691 Sigmoid: Activation<V>,
692 {
693 let mut w = GlibcRand::new(seed);
694 let mut nn = LstmNetwork::<V, Tanh, Sigmoid, 3, 5, 4>::new(|| raw(w.next_i32()));
695 let mut x = GlibcRand::new(seed + 1);
696 for step in 0..300 {
697 if step % 12 == 0 {
698 nn.reset_state();
699 }
700 nn.feed_forward(&core::array::from_fn(|_| raw(x.next_i32())));
701 let pre = nn.output_pre_activations();
702 assert_eq!(
703 pre.map(Sigmoid::activate),
704 nn.learned_values(),
705 "step {step}"
706 );
707 assert_eq!(nn.predicted_class(), argmax(&pre), "step {step}");
708 nn.train(&core::array::from_fn(|_| raw(x.next_i32())));
709 }
710 }
711
712 #[test]
713 fn lstm_pre_activations_reproduce_outputs() {
714 pre_activations_reproduce_outputs(|r| Q16_16::from_raw(r % (3 << 16)), 31);
715 pre_activations_reproduce_outputs(|r| Q8_8::from_raw((r % (3 << 8)) as i16), 32);
716 }
717}