Skip to content
Deep learning Core 24 min read

RNNs, LSTMs and sequence-to-sequence

A recurrent network reads a sequence one step at a time and carries a fixed-size memory forward. Training it means backpropagating through time — a long product of Jacobians that vanishes or explodes — and the LSTM's gated, additive memory was the fix that made sequence learning work, until attention made the memory unnecessary.

10,000 ft

Language, speech, music, sensor streams and user sessions are sequences of arbitrary length. A recurrent neural network (RNN) handles them by applying the same function at every step — weight sharing across time, exactly as a CNN shares weights across space — and passing a hidden state from step to step. From about 2014 to 2017, LSTMs were the state of the art for speech recognition, machine translation and language modelling; Google Translate switched to an 8-layer LSTM system in 2016. The sequence-to-sequence model and its attention mechanism, invented to make RNN translation work, led directly to the transformer, which dropped recurrence altogether. The story has not ended: recurrence is back in linear-time architectures (state-space models, Mamba, RWKV, xLSTM — see beyond transformers) because a fixed-size state makes generation cheap.

2,000 ft

  1. State. At step \(t\) the network combines the new input \(\mathbf x_t\) with its previous state \(\mathbf h_{t-1}\) to produce a new state \(\mathbf h_t\) and, optionally, an output.
  2. Unroll. Over a sequence of length \(T\), the RNN is a \(T\)-layer-deep network whose layers all share weights.
  3. Backpropagation through time (BPTT). Gradients flow backwards along the chain; the gradient from step \(T\) to step \(t\) is a product of \(T-t\) Jacobians, so it shrinks or grows exponentially. Long-range dependencies become unlearnable.
  4. Gating. LSTMs and GRUs keep a memory that is updated additively under learned gates, giving gradients a path that is not repeatedly squashed.
  5. Encoder–decoder. One RNN reads the input sequence into a state; another generates the output from it. Attention lets the decoder look back at every encoder state instead of a single summary vector.

An RNN unrolled through time: one cell, shared weights
An RNN unrolled through time: one cell, shared weights. x₁, x₂, x₃, h₀, cell → h₁, cell → h₂, cell → h₃, ŷ₃An RNN unrolled through time: one cell, shared weights. x₁, x₂, x₃, h₀, cell → h₁, cell → h₂, cell → h₃, ŷ₃

Ground level

The vanilla RNN

The simplest ("Elman") RNN, from Jeffrey Elman's 1990 paper Finding Structure in Time:

\[ \mathbf h_t = \tanh\!\big(W_{hh}\mathbf h_{t-1} + W_{xh}\mathbf x_t + \mathbf b_h\big),\qquad \hat{\mathbf y}_t = W_{hy}\mathbf h_t + \mathbf b_y . \]

With hidden size \(H\) and input size \(X\): \(W_{hh}\) is \(H\times H\), \(W_{xh}\) is \(H\times X\), \(\mathbf h_t\) is a vector of \(H\) numbers that must summarise everything relevant from \(\mathbf x_1,\dots,\mathbf x_t\). The same three matrices are used at every step, so the model handles any length and learns a rule that applies at every position.

As a language model (the LM objective), \(\mathbf x_t\) is the embedding of token \(t\) and \(\hat{\mathbf y}_t\) are the logits for token \(t+1\); the loss is the sum of cross-entropies over positions. Andrej Karpathy's 2015 post The Unreasonable Effectiveness of Recurrent Neural Networks trained character-level LSTMs on Shakespeare, Wikipedia markup, LaTeX and the Linux source, and found individual hidden units that tracked line length, quotation marks and indentation depth (analysed in Karpathy, Johnson and Fei-Fei, 2015). It is still the best first read on what recurrence can learn.

RNNs come in several input–output shapes:

Shape Example Uses
many → one sentiment of a review final \(\mathbf h_T\) feeds a classifier
many → many (aligned) part-of-speech tagging, language modelling an output at every step
many → many (unaligned) translation, summarisation encoder–decoder (below)
one → many image captioning an image embedding initialises \(\mathbf h_0\)

Two structural extensions are standard. Stacked RNNs feed the sequence of hidden states of one layer as the inputs of the next (2–8 layers was typical). Bidirectional RNNs run one RNN forwards and another backwards and concatenate their states, so each position's representation sees the whole sentence — fine for tagging or encoding, impossible for generation.

Backpropagation through time

Unrolled, the RNN is a deep feed-forward network with tied weights, so you train it with ordinary backpropagation on the unrolled graph — this is BPTT (Werbos, 1990). The gradient for a shared weight is the sum of its gradients at every time step. For long sequences you use truncated BPTT: process the sequence in chunks of, say, 100 steps, carry the hidden state across chunks but stop the gradient at the chunk boundary. Memory and compute stay bounded; the price is that the model cannot be taught dependencies longer than the chunk (though it may still carry information across).

The central difficulty: how does a loss at step \(T\) influence the state at step \(t \ll T\)? By the chain rule,

\[ \frac{\partial \mathbf h_T}{\partial \mathbf h_t} = \prod_{k=t+1}^{T}\frac{\partial \mathbf h_k}{\partial \mathbf h_{k-1}} = \prod_{k=t+1}^{T}\operatorname{diag}\!\big(1-\mathbf h_k^2\big)\,W_{hh}. \]

A product of \(T-t\) matrices. In one dimension, with weight \(w\) and the tanh slope near 1: \(0.9^{50} = 0.005\) and \(1.1^{50} = 117\). The gradient from 50 steps back is either negligible or overwhelming. In many dimensions the spectral radius of \(W_{hh}\) (its largest |eigenvalue|) plays the role of \(w\), and the tanh slopes, which are at most 1, only shrink things further.

Worked example: measured Jacobian norms (output of the code below)

A 64-unit tanh RNN, random inputs, \(W_{hh}\) rescaled to a chosen spectral radius \(\rho\):

\(\rho\) \(\lVert\partial\mathbf h_{10}/\partial\mathbf h_0\rVert\) \(\lVert\partial\mathbf h_{50}/\partial\mathbf h_0\rVert\)
0.5 \(7.4\times10^{-4}\) \(2.0\times10^{-18}\)
0.9 \(0.17\) \(3.2\times10^{-7}\)
1.5 \(11\) \(33\)
3.0 \(350\) \(6.8\times10^{6}\)

With \(\rho<1\) the signal from 50 steps ago is gone. With \(\rho>1\) it can blow up; tanh saturation tames the growth somewhat (at \(\rho = 1.5\)) but the dynamics become chaotic and the gradients erratic. There is no comfortable setting.

1e-181e-141e-101e-61e-21e21e611020304050steps back in time, tρ = 0.5ρ = 0.9ρ = 1.5ρ = 3.0
‖∂ht/∂h0‖ for a 64-unit tanh RNN (log scale), from the code in Build it. Below ρ = 1 the gradient decays exponentially — 18 orders of magnitude over 50 steps at ρ = 0.5. Above it, growth is erratic and tamed only by tanh saturation.

This vanishing and exploding gradient problem was analysed by Hochreiter in his 1991 diploma thesis and by Bengio, Simard and Frasconi (1994), and revisited for modern practice by Pascanu, Mikolov and Bengio (2013). Its two halves get different fixes:

  • Exploding gradients → gradient clipping. Rescale the whole gradient vector whenever its norm exceeds a threshold (Pascanu et al., 2013). The direction is kept; only the step length is capped. This is now standard for every architecture (optimisers).
  • Vanishing gradients → change the architecture so that some path through time is not a product of squashing Jacobians. That is the LSTM.

The LSTM: a memory that is written to, not rewritten

Hochreiter and Schmidhuber's Long Short-Term Memory (1997) adds a second state, the cell \(\mathbf c_t\), updated additively. Three gates — vectors of numbers in \((0,1)\) produced by sigmoids — control it. The modern form (with the forget gate added by Gers, Schmidhuber and Cummins, 2000):

\[ \begin{aligned} \mathbf f_t &= \sigma(W_f[\mathbf h_{t-1};\mathbf x_t]+\mathbf b_f) && \text{forget gate: how much old memory to keep}\\ \mathbf i_t &= \sigma(W_i[\mathbf h_{t-1};\mathbf x_t]+\mathbf b_i) && \text{input gate: how much new content to write}\\ \tilde{\mathbf c}_t &= \tanh(W_c[\mathbf h_{t-1};\mathbf x_t]+\mathbf b_c) && \text{candidate content}\\ \mathbf c_t &= \mathbf f_t\odot\mathbf c_{t-1} + \mathbf i_t\odot\tilde{\mathbf c}_t && \text{the additive update}\\ \mathbf o_t &= \sigma(W_o[\mathbf h_{t-1};\mathbf x_t]+\mathbf b_o) && \text{output gate: how much memory to expose}\\ \mathbf h_t &= \mathbf o_t\odot\tanh(\mathbf c_t). \end{aligned} \]
Inside an LSTM cell: gates decide what to forget, write and show
Inside an LSTM cell: gates decide what to forget, write and show. [h_t−1 ; x_t], forget gate f σ, input gate i σ, candidate c̃ tanh, output gate o σ, c_t−1, c_t = f⊙c_t−1 + i⊙c̃, h_t = o⊙tanh(c_t), × fInside an LSTM cell: gates decide what to forget, write and show. [h_t−1 ; x_t], forget gate f σ, input gate i σ, candidate c̃ tanh, output gate o σ, c_t−1, c_t = f⊙c_t−1 + i⊙c̃, h_t = o⊙tanh(c_t), × f

The key line is \(\mathbf c_t = \mathbf f_t\odot\mathbf c_{t-1}+\dots\). Along the cell path,

\[ \frac{\partial\mathbf c_t}{\partial\mathbf c_{t-1}} = \operatorname{diag}(\mathbf f_t)\quad(\text{plus terms through } \mathbf h_{t-1}), \]

a diagonal matrix of gate values — no \(W_{hh}\), no tanh slope. If the network sets a unit's forget gate near 1, that unit's memory and its gradient pass through time essentially unchanged: Hochreiter and Schmidhuber called it the constant error carousel. The network learns which dimensions should remember for a long time and which should turn over quickly.

That learning has to start somewhere. With a forget-gate bias of 0, \(\mathbf f\approx\sigma(0) = 0.5\) at initialisation, and memory halves every step. Our code measures the average product of 50 forget gates: \(8.6\times10^{-16}\) with bias 0, \(8.0\times10^{-8}\) with bias 1, \(0.066\) with bias 3. Initialising the forget bias to 1 or more (recommended by Gers et al. and shown by Jozefowicz, Zaremba and Sutskever (2015) to close the gap between LSTMs and GRUs) is the single most important LSTM detail.

Parameter count. Four gate blocks, each with weights on \([\mathbf h;\mathbf x]\) and a bias: \(4\big(H(H+X)+H\big)\). For \(H = 64,\ X = 16\): \(4(64\cdot80+64) = 20{,}736\), as the code prints.

The GRU and the variant zoo

The gated recurrent unit (Cho et al., 2014) merges cell and hidden state and uses two gates:

\[ \mathbf z_t = \sigma(\cdot),\quad \mathbf r_t = \sigma(\cdot),\quad \tilde{\mathbf h}_t = \tanh\!\big(W[\mathbf r_t\odot\mathbf h_{t-1};\mathbf x_t]\big),\quad \mathbf h_t = (1-\mathbf z_t)\odot\mathbf h_{t-1} + \mathbf z_t\odot\tilde{\mathbf h}_t . \]

The update gate \(\mathbf z\) interpolates between keeping and replacing, so "forget" and "input" are tied (\(\mathbf f = 1-\mathbf i\)). Three blocks instead of four: 25% fewer parameters. Which is better? Greff et al. (2015) ran 5,400 experiments over eight LSTM variants and found none improved significantly on the standard LSTM, with the forget gate and the output activation the most critical components. Jozefowicz et al. (2015) searched over ten thousand architectures and found GRUs and LSTMs (with forget bias 1) roughly tied. Pick either.

Sequence to sequence

How do you map an input sequence to an output sequence of a different length, like an English sentence to its French translation? Sutskever, Vinyals and Le (2014) used two deep LSTMs: an encoder reads the source and its final state becomes a fixed-size vector; a decoder initialised with that vector generates the target one token at a time, feeding each generated token back in as the next input, until it emits an end-of-sequence token. On WMT'14 English→French their 4-layer LSTMs reached 34.8 BLEU, beating a phrase-based statistical system's 33.3, with one trick that sounds like a hack: reverse the source sentence. Reversal puts the first source words close to the first target words, creating short-range dependencies for the optimiser to latch onto.

That trick exposes the weakness. The entire source sentence must squeeze through one vector, and the decoder must reconstruct word 1 of the source from a state that has since absorbed 30 more words.

Attention: stop compressing, start looking back

Bahdanau, Cho and Bengio (2014) let the decoder consult all encoder states. At decoder step \(i\), score each encoder state \(\mathbf h_j\) against the decoder state \(\mathbf s_{i-1}\), turn the scores into weights with a softmax, and feed the weighted average — the context vector — into the decoder:

\[ e_{ij} = \operatorname{score}(\mathbf s_{i-1},\mathbf h_j),\qquad \alpha_{ij} = \frac{\exp e_{ij}}{\sum_k\exp e_{ik}},\qquad \mathbf c_i = \sum_j \alpha_{ij}\mathbf h_j . \]

Bahdanau used a small MLP as the score ("additive attention"); Luong, Pham and Manning (2015) showed a dot product \(\mathbf s^\top\mathbf h\) or bilinear \(\mathbf s^\top W\mathbf h\) works as well and is cheaper. The weights \(\alpha_{ij}\) turned out to be interpretable soft alignments: plotted as a matrix, they trace which source words each target word was translated from, including reorderings like French adjective–noun order.

Encoder–decoder with attention: the decoder looks back at every source state
Encoder–decoder with attention: the decoder looks back at every source state. Encoder (bi)LSTM h₁ … h_n, attention α = softmax(score(s, hⱼ)), context c = Σ αⱼ hⱼ, Decoder LSTM state s, next token, all states, query s, fed back inEncoder–decoder with attention: the decoder looks back at every source state. Encoder (bi)LSTM h₁ … h_n, attention α = softmax(score(s, hⱼ)), context c = Σ αⱼ hⱼ, Decoder LSTM state s, next token, all states, query s, fed back in

Attention fixed the bottleneck, and long sentences stopped degrading. Google's Neural Machine Translation system (Wu et al., 2016) — 8-layer LSTM encoder and decoder with attention and residual connections — went into production in 2016. A year later Vaswani et al. asked what happens if attention does all the work and recurrence is removed entirely: the transformer.

Training details that matter

  • Teacher forcing. During training the decoder is fed the true previous token, not its own prediction. This makes training parallel across target positions and stable, but at inference the model sees its own (possibly wrong) outputs — exposure bias. Scheduled sampling (Bengio et al., 2015) gradually mixes in model predictions during training. Transformer language models still train with teacher forcing.
  • Decoding. Greedy decoding or beam search over the decoder's outputs — see decoding.
  • Dropout in RNNs must not be applied naively to the recurrent connection (fresh noise at every step destroys memory). Zaremba, Sutskever and Vinyals (2014) applied it only to non-recurrent connections; Gal and Ghahramani (2015) used the same mask at every time step.
  • Clip gradients, initialise the forget bias to 1, and use orthogonal initialisation for \(W_{hh}\) (all singular values 1, so products neither shrink nor grow at the start).

Why transformers replaced RNNs — and why RNNs came back

RNN / LSTM Transformer
Training parallelism over time none: step \(t\) needs step \(t-1\) full: all positions at once
Path length between positions \(i, j\) \(\lvert i-j\rvert\) steps 1 (direct attention)
Memory of the past fixed-size state everything (KV cache grows with length)
Cost per generated token constant grows with context length
Total training cost for length \(T\) \(O(T)\) sequential \(O(T^2)\) attention, parallel

On GPUs, the parallelism and short paths won decisively in 2017–2018. But the last two rows favour recurrence at inference time, especially for long contexts. The modern revival keeps the fixed-size state while restoring parallel training by making the recurrence linear in the state, e.g. \(\mathbf h_t = \mathbf a_t\odot\mathbf h_{t-1} + \mathbf b_t\) with \(\mathbf a_t,\mathbf b_t\) computed from \(\mathbf x_t\) only. A linear recurrence can be computed for all \(t\) at once with a parallel prefix scan in \(O(\log T)\) depth. Mamba (Gu and Dao, 2023) makes \(\mathbf a_t\) input-dependent ("selective"); RWKV (Peng et al., 2023) scaled a linear-attention RNN to 14B parameters; Feng et al. (2024) showed that stripping the \(\mathbf h_{t-1}\) dependence out of the GRU and LSTM gates gives "minGRU" and "minLSTM", which become parallelisable and perform surprisingly well; xLSTM (Beck et al., 2024) is Hochreiter's own modernisation. Where these stand is covered in beyond transformers.

First principles

Why weight sharing over time? Because the rules of a sequence are (mostly) the same at every position — grammar does not change between word 3 and word 30 — and because sharing lets one set of weights handle any length. Without sharing you would need separate weights per position and a maximum length, and each would see only a fraction of the data.

Why a state? A fixed-size state \(\mathbf h_t\) is the network's attempt at a sufficient statistic of the past: everything about \(\mathbf x_{1:t}\) needed to predict the future. For a Markov process a small state suffices exactly. For language it cannot: the information that might matter later (a name introduced ten pages ago) grows with the length of the text, while \(\mathbf h\) does not. Every RNN is a lossy compressor of its history, and what it chooses to drop is learned. This is the information-theoretic argument for attention: give the model random access to the past instead of a summary of it.

Why do products of Jacobians vanish or explode? Any product of \(n\) random-ish matrices grows or shrinks like \(\lambda^n\) for some effective rate \(\lambda\); exactly 1 is a knife-edge that random weights will not sit on. Deep feed-forward networks face the same problem across layers, and the solutions rhyme: careful initialisation (initialisation and normalisation), normalisation, and — the LSTM's insight, rediscovered in ResNets — additive updates. \(\mathbf c_t = \mathbf c_{t-1} + \Delta\) has Jacobian \(I + \partial\Delta/\partial\mathbf c\), near the identity, so the product stays well-conditioned. A residual network is an LSTM with its forget gate fixed at 1, unrolled over depth instead of time (residual networks). Highway networks (Srivastava, Greff and Schmidhuber, 2015) made the link explicit by putting LSTM-style gates on feed-forward layers just before ResNets appeared.

What breaks if you remove each LSTM gate? Greff et al.'s ablations answer it: removing the forget gate or the output activation hurts most (no way to clear memory; unbounded cell values exposed directly); coupling input and forget gates (as GRU does) or removing peephole connections barely matters.

The maths

Shapes. Batch \(B\), sequence length \(T\), input size \(X\), hidden size \(H\). Inputs \(\mathbf x\in\mathbb R^{B\times T\times X}\); states \(\mathbf h_t,\mathbf c_t\in\mathbb R^{B\times H}\); LSTM weights \(W\in\mathbb R^{4H\times(X+H)}\), \(\mathbf b\in\mathbb R^{4H}\) (PyTorch splits \(W\) into weight_ih \(4H\times X\) and weight_hh \(4H\times H\) and has two bias vectors).

Derivation: BPTT for a vanilla RNN

Let \(\mathbf a_t = W_{hh}\mathbf h_{t-1}+W_{xh}\mathbf x_t+\mathbf b\), \(\mathbf h_t = \tanh\mathbf a_t\), and total loss \(L = \sum_t \ell_t(\hat{\mathbf y}_t)\). Define \(\boldsymbol\delta_t = \partial L/\partial\mathbf h_t\). The state \(\mathbf h_t\) affects the loss directly through \(\ell_t\) and indirectly through \(\mathbf h_{t+1}\):

\[ \boldsymbol\delta_t = W_{hy}^\top\frac{\partial\ell_t}{\partial\hat{\mathbf y}_t} + W_{hh}^\top\Big(\boldsymbol\delta_{t+1}\odot(1-\mathbf h_{t+1}^2)\Big), \qquad \boldsymbol\delta_{T+1} = 0 . \]

Run this backwards from \(t = T\). The weight gradients sum over time (weight sharing):

\[ \frac{\partial L}{\partial W_{hh}} = \sum_t\big(\boldsymbol\delta_t\odot(1-\mathbf h_t^2)\big)\mathbf h_{t-1}^\top,\qquad \frac{\partial L}{\partial W_{xh}} = \sum_t\big(\boldsymbol\delta_t\odot(1-\mathbf h_t^2)\big)\mathbf x_t^\top . \]

Unrolling the recursion shows the contribution of loss \(\ell_T\) to \(\boldsymbol\delta_t\) contains \(\prod_{k=t+1}^{T}W_{hh}^\top\operatorname{diag}(1-\mathbf h_k^2)\). Since \(\|\operatorname{diag}(1-\mathbf h^2)\|\le1\), its norm is at most \(\|W_{hh}\|_2^{T-t}\): if the largest singular value of \(W_{hh}\) is below 1, the gradient provably vanishes exponentially (Pascanu et al., 2013). The converse (explosion) is only possible, not guaranteed, when it is above 1 — consistent with the saturated \(\rho = 1.5\) row in the table.

Derivation: the LSTM's gradient path through the cell

From \(\mathbf c_t = \mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\tilde{\mathbf c}_t\), holding the gates fixed, \(\partial\mathbf c_t/\partial\mathbf c_{t-1} = \operatorname{diag}(\mathbf f_t)\). The gates also depend on \(\mathbf h_{t-1}\), which depends on \(\mathbf c_{t-1}\), adding further terms, but the direct path gives

\[ \frac{\partial\mathbf c_T}{\partial\mathbf c_t}\Big|_{\text{direct}} = \operatorname{diag}\Big(\prod_{k=t+1}^{T}\mathbf f_k\Big). \]

Each coordinate decays at a rate the network chooses (through \(\mathbf f\)), independently of the others, with no weight matrix or tanh slope in the product. The gradient on unit \(j\) survives \(T-t\) steps iff the product of its forget gates stays away from zero — which the network can learn to arrange for exactly the units that must remember.

Attention (dot-product form). Encoder states \(E\in\mathbb R^{n\times H}\), decoder state \(\mathbf s\in\mathbb R^{H}\): scores \(\mathbf e = E\mathbf s\in\mathbb R^{n}\), weights \(\boldsymbol\alpha = \operatorname{softmax}(\mathbf e)\), context \(\mathbf c = E^\top\boldsymbol\alpha\in\mathbb R^{H}\). Batch the decoder states into a matrix \(Q\) and you have \(\operatorname{softmax}(QE^\top)E\) — transformer attention without the projections and the \(1/\sqrt d\) scale.

Linear recurrence as a scan. For \(h_t = a_th_{t-1}+b_t\), the pairs \((a, b)\) compose associatively: \((a_2,b_2)\circ(a_1,b_1) = (a_2a_1,\ a_2b_1+b_2)\). Associativity is what lets a parallel prefix scan compute all \(T\) states in \(O(\log T)\) sequential steps.

Build it

NumPy. Part 1 measures how the vanilla RNN's Jacobian \(\partial\mathbf h_t/\partial\mathbf h_0\) shrinks or grows with the spectral radius of \(W_{hh}\). Part 2 measures the LSTM cell path under different forget-gate biases. Part 3 is a complete LSTM step.

import numpy as np
rng = np.random.default_rng(0)
H, X, T = 64, 16, 50                                  # hidden size, input size, sequence length

def vanilla_jacobian_norms(rho):
    """Run h_t = tanh(W h_{t-1} + U x_t) for T steps; return ||dh_t/dh_0|| (spectral norm) over t."""
    W = rng.normal(size=(H, H)); W *= rho / np.max(np.abs(np.linalg.eigvals(W)))   # set spectral radius
    U = rng.normal(size=(H, X)) * 0.1
    h, J, norms = np.zeros(H), np.eye(H), []
    for t in range(T):
        h = np.tanh(W @ h + U @ rng.normal(size=X))
        J = (1 - h**2)[:, None] * W @ J              # dh_t/dh_0 = diag(tanh') W  dh_{t-1}/dh_0
        norms.append(np.linalg.norm(J, 2))
    return norms

for rho in (0.5, 0.9, 1.5, 3.0):
    n = vanilla_jacobian_norms(rho)
    print(f"vanilla RNN, spectral radius {rho}: |dh_t/dh_0| at t=10: {n[9]:.1e}, t=50: {n[-1]:.1e}")

# LSTM cell path: c_t = f_t * c_{t-1} + i_t * g_t, so dc_t/dc_{t-1} = diag(f_t) (ignoring paths through h)
for bias in (0.0, 1.0, 3.0):
    f = 1 / (1 + np.exp(-(bias + 0.5 * rng.normal(size=(T, H)))))   # forget gates over 50 steps
    print(f"LSTM forget bias {bias}: mean f = {f.mean():.2f}, mean dc_50/dc_0 = {np.prod(f, axis=0).mean():.1e}")

def lstm_step(x, h, c, W, b):
    """One LSTM step. W: (4H, X+H), b: (4H,). Gates stacked as [input, forget, cell, output]."""
    z = W @ np.concatenate([x, h]) + b
    i, f, g, o = np.split(z, 4)
    sig = lambda a: 1 / (1 + np.exp(-a))
    c = sig(f) * c + sig(i) * np.tanh(g)
    h = sig(o) * np.tanh(c)
    return h, c

W, b = rng.normal(size=(4 * H, X + H)) * 0.1, np.zeros(4 * H)
b[H:2 * H] = 1.0                                       # forget-gate bias = 1 (Gers et al.; Jozefowicz et al.)
h, c = np.zeros(H), np.zeros(H)
for t in range(T):
    h, c = lstm_step(rng.normal(size=X), h, c, W, b)
print("LSTM params:", W.size + b.size, " final |h|:", round(float(np.linalg.norm(h)), 3))

Output:

vanilla RNN, spectral radius 0.5: |dh_t/dh_0| at t=10: 7.4e-04, t=50: 2.0e-18
vanilla RNN, spectral radius 0.9: |dh_t/dh_0| at t=10: 1.7e-01, t=50: 3.2e-07
vanilla RNN, spectral radius 1.5: |dh_t/dh_0| at t=10: 1.1e+01, t=50: 3.3e+01
vanilla RNN, spectral radius 3.0: |dh_t/dh_0| at t=10: 3.5e+02, t=50: 6.8e+06
LSTM forget bias 0.0: mean f = 0.50, mean dc_50/dc_0 = 8.6e-16
LSTM forget bias 1.0: mean f = 0.72, mean dc_50/dc_0 = 8.0e-08
LSTM forget bias 3.0: mean f = 0.95, mean dc_50/dc_0 = 6.6e-02
LSTM params: 20736  final |h|: 1.036

Read the LSTM rows carefully: even bias 1 gives a tiny product over 50 steps at initialisation. The LSTM's advantage is not that it remembers by default; it is that a single scalar per unit (the forget gate) controls memory, with no matrix in the way, so gradient descent can easily learn \(f\approx1\) for the units that need it.

In PyTorch, a 2-layer LSTM language model:

import torch.nn as nn
class CharLSTM(nn.Module):
    def __init__(self, vocab, d=256, layers=2):
        super().__init__()
        self.emb = nn.Embedding(vocab, d)
        self.rnn = nn.LSTM(d, d, num_layers=layers, batch_first=True, dropout=0.2)
        self.head = nn.Linear(d, vocab)
    def forward(self, idx, state=None):                # idx: (B, T) token ids
        out, state = self.rnn(self.emb(idx), state)    # out: (B, T, d)
        return self.head(out), state                   # logits (B, T, vocab); carry state across chunks

Things to try

  • Replace \(W_{hh}\) by a random orthogonal matrix (np.linalg.qr) and rerun Part 1. What happens to the \(t = 50\) norm, and why does tanh saturation still matter?
  • Implement BPTT for the vanilla RNN on a "copy the first input after \(T\) steps" task and plot the gradient norm reaching step 1 as \(T\) grows. Then swap in lstm_step and repeat.
  • Train CharLSTM on a text file you like (Karpathy's tinyshakespeare is the classic) with truncated BPTT of 128 steps; sample from it every few hundred steps. Then find a hidden unit that tracks something interpretable, as in Karpathy, Johnson and Fei-Fei (2015).
  • Implement the parallel scan for \(h_t = a_th_{t-1}+b_t\) with np.cumprod and np.cumsum (hint: divide by the cumulative product) and check it against the loop.

Check yourself

Why is an RNN unrolled over 100 steps as hard to train as a 100-layer MLP — and in one way harder?

Both backpropagate through 100 Jacobians, so gradients vanish or explode exponentially. The RNN is harder because its layers share one \(W_{hh}\): the same spectrum is multiplied 100 times, so there is no way for different "layers" to compensate for each other, and a single eigenvalue above 1 compounds.

What does gradient clipping fix, and what doesn't it fix?

It caps the step length when gradients explode, preventing a single huge update from wrecking the weights. It does nothing for vanishing gradients: a tiny gradient stays tiny.

Write the LSTM cell update and explain in one sentence why it helps gradients.

\(\mathbf c_t = \mathbf f_t\odot\mathbf c_{t-1}+\mathbf i_t\odot\tilde{\mathbf c}_t\). The Jacobian along the cell path is \(\operatorname{diag}(\mathbf f_t)\) — no weight matrix and no squashing derivative — so with forget gates near 1 the gradient passes through many steps nearly unchanged.

Why initialise the forget-gate bias to 1 (or higher)?

With bias 0 the gate starts at \(\sigma(0) = 0.5\) and memory halves each step, so long-range gradients vanish before the network can learn to keep anything. A positive bias starts the cell in "remember" mode (\(\sigma(1) = 0.73\), \(\sigma(3) = 0.95\)).

What was the bottleneck in the original seq2seq model, and how did reversing the source help?

The whole source had to be compressed into the encoder's final state. Reversing the source put the beginning of the source sentence right before the beginning of the target, creating short dependencies that made optimisation easier — a workaround for the bottleneck that attention later removed.

How many parameters does a GRU with H = 512 and X = 256 have (one bias per gate block)?

Three blocks: \(3\big(512(512+256)+512\big) = 3(393{,}216+512) = 1{,}181{,}184\). (PyTorch's GRU has two bias vectors per block, adding another \(3\times512\).)

Hard: why can a linear recurrence be trained in parallel but an LSTM cannot?

In \(h_t = a_th_{t-1}+b_t\) with \(a_t,b_t\) depending only on \(x_t\), the map from \(h_{t-1}\) to \(h_t\) is affine and affine maps compose associatively, so a prefix scan computes all states in \(O(\log T)\) depth. In an LSTM the gates depend on \(\mathbf h_{t-1}\) through a nonlinearity, so step \(t\)'s transformation is unknown until step \(t-1\) is computed.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

  • karpathy/char-rnn — The original multi-layer character-level LSTM (Lua/Torch); read alongside the blog post.

Where this leads