Recurrent Neural Networks (RNNs, LSTMs, GRUs)
An RNN rewrites one hidden state at every step. Why distant signals fade or explode, how gates help, and where attention replaced recurrence.
Jump to a section
A note rewritten at every step
Picture a model reading a server log one record at a time and deciding, after each record, whether something is going wrong. It cannot look back at the raw log. All it has is a fixed-size summary of what it has read so far, which it must update with every new record. That is a recurrent neural network.
At step the network reads input and the previous hidden state , and produces a new state with the same weights every time:
Sharing the weights across time is what lets one model process sequences of any length. The hidden state is the only channel from the past to the present, and it has finite capacity, so an RNN does not remember everything it has seen. It remembers whatever its training taught it to keep.
Unroll the same state update through time
Each input and the previous hidden state enter the same recurrent function. U and W are shared across time.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
Exact forward states with W = [[0.6,0.2],[−0.1,0.5]], U = [1,0.5], and h₀ = [0,0]. Time, channel, and activation are separate axes. This is not a trained RNN or an LSTM/GRU gate simulation.
Elman · Finding Structure in TimeFigure 2, p. 184; hidden-state feedback described on p. 182
Authored unrolling of shared recurrent state. The unrolled tanh equation is a modern illustrative variant, not Elman’s original activation, initial context, or learned weights.
The hard part is learning what to keep when the relevant event lies many steps back. If an error 100 records ago explains the current failure, the network must have carried a trace of it through 100 rewrites, and training must have discovered that this was worth doing.
Why distant signals fade or explode
Training unrolls the network across the sequence and backpropagates through every step, which is called backpropagation through time. The gradient that reaches step 0 from step passes through a product of state-transition Jacobians, one per step:
A scalar case shows what repeated multiplication does. In , the sensitivity to the initial state is . At and it is about 0.00098; at it is about 57.7. Ten steps are enough to erase a signal or to amplify it fifty-fold.
Real networks multiply matrices and activation derivatives rather than one number, so the outcome depends on the weights and on the trajectory through the data. The tanh derivative is at most 1, though, so if the largest singular value of is below 1, the gradient is guaranteed to shrink exponentially with distance. Bengio, Simard and Frasconi analysed this difficulty in 1994. Exploding gradients are the easier half to fix: clipping the gradient norm, as Pascanu et al. proposed, stops a single bad step from wrecking training. Vanishing gradients need a different architecture.
Gates that make retention learnable
The LSTM adds a second state, the cell , and three gates that decide what happens to it:
The forget gate decides how much of the old cell to keep, the input gate how much of the candidate to write, and the output gate how much of the cell to expose as . The cell update is additive: along the direct path, , with no weight matrix and no squashing derivative in between.
That changes the arithmetic. If the network learns to hold at 0.99, a signal survives 100 steps at of its strength. At 0.9 it falls to about . The forget gate was not in the original 1997 LSTM; Gers, Schmidhuber and Cummins added it in 2000, and a common practical habit is to initialize its bias to 1 so that the cell starts out retaining.
None of this is a guarantee. Gates can saturate, the gradient also flows through the gates themselves, and the state is still finite. Holding near one and near zero is a behaviour the network can learn, not one it is given.
The GRU, from Cho et al. (2014), merges the cell and hidden state and uses two gates. In the convention PyTorch follows, , where is the fraction of the old state kept and is the new candidate. Libraries differ in gate names and in algebraic rearrangements, so check their equations before comparing parameters.
The cost difference is easy to count. In PyTorch, each gate or candidate block holds an input matrix, a recurrent matrix and two bias vectors. For 5 input features and a hidden size of 8:
| Cell | Carried state | Blocks | Parameters |
|---|---|---|---|
| Plain RNN | 1 | 120 | |
| GRU | 3 | 360 | |
| LSTM | and | 4 | 480 |
Whether the GRU's 25% saving over the LSTM costs accuracy depends on the task, so measure both on yours.
Recurrence against attention
An RNN is sequential across time. Batching many sequences keeps the hardware busy, but step cannot start until step has finished, so a long sequence is a long chain of small operations. A Transformer connects every position to every earlier one through attention and processes a whole training sequence in parallel, which is a large part of why it replaced recurrence for language modelling.
Recurrence keeps one real advantage. Its state has a fixed size, so processing step one million costs the same as step one, and memory does not grow with the stream. A Transformer's key-value cache grows with every token. For streaming sensors, on-device inference or very long event streams, that constant cost is worth testing against attention on the actual workload, alongside latency, context length, data scale and hardware.
In code
PyTorch returns the output at every step and the final state. The LSTM's final state is a pair (hidden and cell); the GRU's is one tensor. Check these shapes before adding a classifier or carrying state into another batch.
1import torch
2from torch import nn
3
4x = torch.randn(4, 7, 5) # batch, time, input features
5gru = nn.GRU(input_size=5, hidden_size=8, batch_first=True)
6lstm = nn.LSTM(input_size=5, hidden_size=8, batch_first=True)
7
8gru_steps, gru_final = gru(x)
9lstm_steps, (lstm_hidden, lstm_cell) = lstm(x)
10assert gru_steps.shape == lstm_steps.shape == (4, 7, 8)
11assert gru_final.shape == lstm_hidden.shape == lstm_cell.shape == (1, 4, 8)
12
13count = lambda module: sum(p.numel() for p in module.parameters())
14assert count(gru) == 3 * (8 * 5 + 8 * 8 + 8 + 8) == 360
15assert count(lstm) == 4 * (8 * 5 + 8 * 8 + 8 + 8) == 480The gradient arithmetic from the sections above needs only the standard library:
assert abs(0.5 ** 10 - 0.000977) < 1e-6 # plain recurrence, a = 0.5, ten steps
assert abs(1.5 ** 10 - 57.67) < 0.01 # a = 1.5 explodes instead
assert abs(0.99 ** 100 - 0.366) < 0.001 # forget gate held at 0.99 for 100 steps
assert 0.9 ** 100 < 3e-5 # at 0.9 the signal is goneWhere it goes wrong
State leaking between examples. For independent examples, start each sequence from a fresh state. For a continuous stream, carry state only across the boundary you intend. A loader that carries state from one user's session into the next leaks one user's history into another's predictions.
Unbounded graphs. Truncated backpropagation through time carries the forward state across chunks but cuts the backward graph. Call detach() on the carried state at each chunk boundary, or the graph grows with the stream until memory runs out.
Confusing the two horizons. With truncation, the state can carry information from far back, but gradients only reach as far as the chunk length. A dependency longer than the chunk can only be learned indirectly, through what the shorter-range gradients happened to teach the state to keep.
Padding treated as data. In a batch of variable-length sequences, the padding steps still update the state unless you pack the batch or mask them. The final state then summarizes zeros, not the sequence.
Sources and further reading
- Elman, Finding Structure in Time (1990): recurrent context as dynamic memory.
- Bengio, Simard, and Frasconi, Learning Long-Term Dependencies with Gradient Descent is Difficult (1994): analysis of distant-gradient difficulty.
- Hochreiter and Schmidhuber, Long Short-Term Memory (1997): gated cell-state method.
- Cho et al., Learning Phrase Representations using RNN Encoder-Decoder (2014): GRU-style recurrent encoder-decoder.
- Pascanu, Mikolov and Bengio, On the Difficulty of Training Recurrent Neural Networks (2013): vanishing and exploding gradients, and gradient-norm clipping.
- PyTorch recurrent layer documentation: current framework state shapes and gate conventions.