13 / 37 · Neural Sequence Models
LSTM and GRU
Gated cells give the recurrent state an additive memory line whose gradient factor is a gate value rather than a weight matrix, so information can survive many steps; the note writes out both cells, traces one LSTM step numerically, and counts what the gates cost.
On this page 10
The plain recurrent cell of the previous note overwrites its whole state at every step through a multiplication by , and the gradient across steps is a product of such factors. The fix proposed by Hochreiter and Schmidhuber (1997) and simplified by Cho et al. (2014) is architectural: give the cell a path along which the state is added to rather than transformed, and let the network learn, per coordinate and per step, how much to keep, write and read.
Notation. As before, is the input, the hidden state. The LSTM adds a cell state . is the logistic function with range ; has range ; is element-wise multiplication. Each gate has its own weights (on ), (on ) and bias .
Baseline: one state, overwritten every step#
. The state is recomputed from scratch at each step; nothing in the cell can say “leave coordinate 7 alone”. Whether old information survives depends on , which is shared across all steps and all coordinates, and the gradient factor per step is .
LSTM#
Four quantities are computed from , three of them gates in and one a candidate value in :
Then the memory is updated and the working state read from it:
Every operation is per coordinate. A coordinate of with and is copied unchanged for as many steps as the gates stay that way; one with and is overwritten. The sigmoid range makes the gates fractions and the range makes the candidate and the exposed value bounded, so can grow only by repeated addition of bounded values, not geometrically.
Worked example#
One coordinate, one step. Previous memory , previous state , input . Take scalar weights (toy values) so that each pre-activation is a small sum:
| Gate | Pre-activation | Value |
|---|---|---|
| forget | ||
| input | ||
| candidate | ||
| output |
Memory update: . Exposed state: .
The old memory survived almost entirely (forget gate near 1) and a new value of about was added. Had the forget gate come out at , the memory would have dropped to : same input, different decision, chosen by weights that see and .
Step by step#
One LSTM step: what goes where
Following the numbers in the figure:
- Forget gate. : how much of the old memory to keep, coordinate by coordinate.
- Input gate and candidate. says how much to write, says what to write. The candidate is the plain RNN update of the previous note, with its own weights.
- Keep. The old memory is multiplied by the forget gate: .
- Write. The gated candidate is added: . Steps 3 and 4 are the only operations on the memory line, a multiplication by a number in and an addition.
- Output gate. : how much of the memory to expose.
- Read. . Both and go on to step : the gates of the next step read , and the memory line carries .
Against the RNN figure of the previous note, the inputs and the working state are drawn the same way; what is new is the memory line at the top, in the amber outline, and the three gates that act on it.
Why the gradient survives#
Differentiate the memory update with respect to the previous memory:
The first term is the forget gate itself. Along the memory line the gradient across steps contains the product , and the network can keep that near 1 by keeping the forget gates near 1 wherever memory is needed, whereas the plain RNN’s factor is a fixed matrix power. This does not prove that LSTMs learn arbitrary long dependencies (the other terms still vanish or explode, and gates saturate), but it removes the geometric decay that made the plain cell fail at tens of steps; in practice LSTMs learn dependencies over hundreds of tokens. The bias is often initialized to 1 so that the forget gates start open (Jozefowicz, Zaremba and Sutskever, 2015).
Cost#
Each of the four blocks has an matrix, an matrix and a bias, so an LSTM cell has parameters, four times the plain cell (PyTorch stores two bias vectors per block, giving ). The translation model of the seq2seq note uses : parameters per direction. The computation per step is also four matrix products instead of one, and still strictly sequential.
GRU#
The gated recurrent unit (Cho et al., 2014) merges the memory and the working state and uses two gates:
The update gate plays the roles of both and , tied as : what is not kept is overwritten. The reset gate controls how much of the previous state the candidate may read. There is no output gate; is the memory. The parameter count is , three quarters of an LSTM at the same size, and one fewer matrix product per step. The AG News classifier of the previous note is a GRU with and .
Conventions. The equations above write as the fraction of the state that is overwritten. The original paper (Cho et al., 2014, eqs. 5–8) and PyTorch’s nn.GRU interpolate the other way round, , so there is here. PyTorch also applies the reset after the recurrent linear map, , while the equations above, like Cho et al., reset before multiplying by ; the two candidates differ in general. With its second bias vector per gate, PyTorch’s count is . Both are standard GRUs, but a formula and an implementation must use the same one.
| Plain RNN | LSTM | GRU | |
|---|---|---|---|
| States | |||
| Gates | 0 | 3 () | 2 () |
| Memory update | overwrite | ||
| Parameters | |||
| Gradient factor along memory |
Which cell is better is empirical and task-dependent. Direct comparisons find the two close (Chung et al., 2014; Jozefowicz, Zaremba and Sutskever, 2015), and a large study of LSTM variants found that coupling the input and forget gates, as the GRU does, costs little (Greff et al., 2017).
Reading in both directions#
A recurrent state at position summarizes and knows nothing of . For a classifier or an encoder that sees the whole input at once, run a second cell from right to left and concatenate the two states at each position: the bidirectional RNN gives , a representation of each token informed by its full context, at twice the cost. The encoder in the next note is a bidirectional LSTM. A language model cannot be bidirectional, since it must not see the token it predicts; the BERT note finds a different way to use both directions.
What changed#
| Plain RNN | Gated RNN | |
|---|---|---|
| Can keep a coordinate unchanged | Only if happens to | Yes, by gating |
| Long dependencies | Tens of tokens | Hundreds, in practice |
| Parameters per cell | (GRU), (LSTM) | |
| Sequential | Yes | Yes |
| Fixed-size state | Yes | Yes |
Limitations#
- Still sequential. Step depends on step . Training and inference time grow with , and the sequence dimension cannot be parallelized.
- Still one vector. However well it remembers, the state at the end is (or ) numbers that must hold everything the next stage needs. The seq2seq note makes this failure visible in translation.
- Gates saturate. Sigmoids near 0 or 1 have small derivatives; a gate that has learned to close is slow to reopen.
- Capacity costs. Four matrices per step; a 2-layer bidirectional LSTM with over 512-dimensional inputs has 10.5 M parameters before any embedding.
What you should remember#
- LSTM: , ; gates in from , candidate in from .
- The additive memory update makes the gradient factor along approximately the forget gate, which the network can hold near 1.
- GRU: two gates, one state, ; three quarters of the LSTM’s parameters.
- Bidirectional cells give each position its full context; they cannot be used for next-token prediction.
- Gating fixes the gradient, not the sequential computation or the single-vector summary.
Notebook#
week04_lstm_attention_transformer.ipynb. Cell numbers count every cell, markdown included, from 1. Quoted numbers come from the run saved with the course; cells changed since then for current library versions have no saved output.
- Cell 39 defines
Seq2SeqLSTMwithnn.LSTM(128, 128, bidirectional=True)as the encoder and a unidirectionalnn.LSTM(128, 128)as the decoder; the encoder’s two final hidden and cell states (h_enc,c_encof shape[2, B, 128]) are concatenated to[1, B, 256]and projected back to 128 byh_projandc_projto initialize the decoder. - Cell 44 prints 8,380,474 parameters in total and 492,602 outside the embedding and output matrices; the latter is (bidirectional encoder) (decoder) (the two projections) (the output bias, which the notebook’s subtraction leaves in).
week02_NN_text_classification.ipynb, cell 40, is the GRU classifier referred to above. It uses nn.GRU, so its gates follow the PyTorch convention of the GRU section: its update gate is the fraction kept, and the reset acts after the recurrent matrix.
Next#
With a cell that can remember, the course takes on its first generation task with two sequences: translate a German sentence into English. One recurrent network reads the source, another writes the target. The next note builds that encoder–decoder, measures it with BLEU, and discovers that the single vector handed from encoder to decoder is now the limiting factor.
References#
- S. Hochreiter, J. Schmidhuber. Long Short-Term Memory. Neural Computation, 9(8), 1997.
- K. Cho, B. van Merriënboer, C. Gulcehre, D. Bahdanau, F. Bougares, H. Schwenk, Y. Bengio. Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation. EMNLP, 2014. The GRU.
- J. Chung, C. Gulcehre, K. Cho, Y. Bengio. Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling. NIPS Deep Learning Workshop, 2014. LSTM and GRU compared on music and speech modelling.
- R. Jozefowicz, W. Zaremba, I. Sutskever. An Empirical Exploration of Recurrent Network Architectures. ICML, 2015. Forget-gate bias initialization; LSTM and GRU compared.
- K. Greff, R. K. Srivastava, J. Koutník, B. R. Steunebrink, J. Schmidhuber. LSTM: A Search Space Odyssey. IEEE TNNLS, 28(10), 2017.
- C. Olah. Understanding LSTM Networks. 2015. The gate-by-gate walkthrough that the worked example follows.
- M. Schuster, K. K. Paliwal. Bidirectional recurrent neural networks. IEEE Transactions on Signal Processing, 45(11), 1997.