Simple Algorithm
Deep Learning · Representation · 22 min

Recurrent Neural Networks

Hidden states, weights shared across time and backpropagation through time.

An Elman network is three matrices and a tanh, applied again and again. That simplicity hides the central difficulty of recurrent networks. Here you set one up properly, with shapes, losses and a character-level language model in code, derive backpropagation through time, and prove why its gradients vanish or explode: they are products of Jacobians whose size the recurrent matrix controls.

What you’ll learn

  • Write the Elman RNN with its shapes and parameter count, and set it up for many-to-one and many-to-many tasks, including a character-level language model.
  • Derive backpropagation through time: the backward recursion for ∂L/∂ht\partial\loss/\partial\mathbf h_t and the weight gradient as a sum over time of Jacobian products.
  • Bound ∥∂ht/∂hk∥\lVert\partial\mathbf h_t/\partial\mathbf h_k\rVert by (γ∥W∥)t−k(\gamma\lVert W\rVert)^{t-k} and relate the spectral radius of WW to vanishing and exploding gradients.
  • Explain truncated BPTT and what it gives up, and build bidirectional and stacked recurrent networks.

The Elman network

Unrolled over TT steps, the network is a TT-layer computational graph whose layers share their weights. The training loss sums a per-step loss, typically the cross-entropy ℓt=−log⁡y^t,yt\ell_t=-\log\hat y_{t,y_t} of the target class yty_t: L=∑tℓt\loss=\sum_t\ell_t (often divided by TT). The same recurrence serves several input–output patterns:

  • Many-to-one: classify a whole sequence from hT\mathbf h_T (or from an average of the states), as in sentiment analysis; only one loss term.
  • Many-to-many, aligned: one output per input, as in part-of-speech tagging or language modeling, where the target at step tt is the next token xt+1x_{t+1}.
  • One-to-many: generate a sequence from an initial state, as in image captioning, feeding each output back as the next input.
  • Many-to-many, unaligned: input and output lengths differ (translation, speech recognition); that needs an encoder–decoder, the subject of Encoder–Decoder Models & Attention.

Cost. One step costs O(n2+nd)\order{n^2+nd} multiply-adds, so a sequence costs O(T(n2+nd))\order{T(n^2+nd)}. The work parallelizes across the batch and across the nn units, but not across time: step tt needs ht−1\mathbf h_{t-1}. A GPU therefore sees TT small matrix products in a row instead of one large one, and that sequential dependence is the deepest practical difference from a transformer.

Predict before you look

A character-level language model reads one-hot characters from a vocabulary of K=d=65K=d=65 symbols, has n=256n=256 tanh units and predicts the next character with a softmax over the same 65 symbols. How many parameters does it have?

Show the answer

99137 parameters

WW: 2562=65,536256^2=65{,}536; UU: 256×65=16,640256\times65=16{,}640; b\mathbf b: 256256; VV: 65×256=16,64065\times256=16{,}640; c\mathbf c: 6565. Total 99,13799{,}137, two-thirds of it in the recurrent matrix WW. PyTorch's nn.RNN keeps two bias vectors per layer, adding 256 more. With one-hot inputs, UxtU\mathbf x_t just selects a column of UU: an embedding lookup.

A character-level language model

A language model factorizes the probability of a text as p(x1,…,xT)=∏tp(xt+1∣x1,…,xt)p(x_1,\dots,x_T)=\prod_tp(x_{t+1}\mid x_1,\dots,x_t) and is trained by next-token prediction. An RNN supplies the conditional: ht\mathbf h_t summarizes x1,…,xtx_1,\dots,x_t and y^t\hat{\mathbf y}_t is the predicted distribution of xt+1x_{t+1}. Character-level RNNs trained this way on large text corpora learned to produce plausible-looking words, punctuation and formatting one character at a time (Sutskever, Martens & Hinton, 2011).

python
import torch, torch.nn as nn, torch.nn.functional as F

class CharRNN(nn.Module):
    def __init__(self, vocab, hidden=256):
        super().__init__()
        self.vocab = vocab
        self.rnn = nn.RNN(vocab, hidden, batch_first=True)  # tanh by default
        self.head = nn.Linear(hidden, vocab)

    def forward(self, x, h=None):                  # x: (B, T) character codes
        x = F.one_hot(x, self.vocab).float()        # (B, T, vocab)
        out, h = self.rnn(x, h)                     # out: every h_t, (B, T, hidden)
        return self.head(out), h                    # next-character logits

def train_chunk(model, opt, x, y, h):              # y is x shifted left by one
    logits, h = model(x, h)
    loss = F.cross_entropy(logits.flatten(0, 1), y.flatten())
    opt.zero_grad()
    loss.backward()                                 # backpropagation through time
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    opt.step()
    return loss.item(), h.detach()                  # carry the state, cut the graph

A long text is cut into consecutive chunks of, say, 100 characters. The final state of one chunk becomes the initial state of the next, but detach() stops gradients from flowing across the boundary: this is truncated backpropagation through time (Step 5). To generate, feed a start character, sample the next one from the softmax, feed it back in, and repeat.

Think first During training the model always receives the true previous character; during generation it receives its own samples. Why might that mismatch matter?

At generation time an early mistake produces an input the model never saw during training, which can cause further mistakes, and errors can compound along the sequence. Feeding the ground truth during training is called teacher forcing; the mismatch is known as exposure bias. The Emergence lesson Training Recurrent Networks analyzes it and the proposed fixes.

Backpropagation through time

Backpropagation through time (BPTT) is reverse-mode differentiation of the unrolled graph (Werbos, 1990). The only subtlety is that ht\mathbf h_t influences the loss twice: directly through ℓt\ell_t, and indirectly through every later state. Collect both in δt=∂L/∂ht\boldsymbol\delta_t=\partial\loss/\partial\mathbf h_t, the total derivative, written as a column vector.

DerivationGradients of the Elman RNN
  1. ∂ℓt∂ot=y^t−eyt,∂L∂V=∑t=1T(y^t−eyt) ht⊤,∂L∂c=∑t=1T(y^t−eyt)\frac{\partial\ell_t}{\partial\mathbf o_t}=\hat{\mathbf y}_t-\mathbf e_{y_t},\qquad\frac{\partial\loss}{\partial V}=\sum_{t=1}^T(\hat{\mathbf y}_t-\mathbf e_{y_t})\,\mathbf h_t^\top,\qquad\frac{\partial\loss}{\partial\mathbf c}=\sum_{t=1}^T(\hat{\mathbf y}_t-\mathbf e_{y_t})

    Softmax with cross-entropy has the familiar output gradient (with ey\mathbf e_{y} the one-hot target), which gives the readout gradients at once:

  2. δt=V⊤(y^t−eyt)+W⊤diag⁡(ϕ′(at+1)) δt+1\boldsymbol\delta_t=V^\top(\hat{\mathbf y}_t-\mathbf e_{y_t})+W^\top\operatorname{diag}\big(\phi'(\mathbf a_{t+1})\big)\,\boldsymbol\delta_{t+1}

    ht\mathbf h_t feeds ℓt\ell_t through VV and ht+1\mathbf h_{t+1} through at+1=Wht+…\mathbf a_{t+1}=W\mathbf h_t+\dots. The chain rule gives a backward recursion, run from t=Tt=T down to 11 with δT+1=0\boldsymbol\delta_{T+1}=\mathbf 0:

  3. ∂L∂W=∑t=1Tgt ht−1⊤,∂L∂U=∑t=1Tgt xt⊤,∂L∂b=∑t=1Tgt\frac{\partial\loss}{\partial W}=\sum_{t=1}^T\mathbf g_t\,\mathbf h_{t-1}^\top,\qquad\frac{\partial\loss}{\partial U}=\sum_{t=1}^T\mathbf g_t\,\mathbf x_t^\top,\qquad\frac{\partial\loss}{\partial\mathbf b}=\sum_{t=1}^T\mathbf g_t

    WW, UU and b\mathbf b are used at every step, so their gradients sum one outer product per step. Write gt=∂L/∂at=diag⁡(ϕ′(at)) δt\mathbf g_t=\partial\loss/\partial\mathbf a_t=\operatorname{diag}(\phi'(\mathbf a_t))\,\boldsymbol\delta_t:

  4. ∂L∂W=∑t=1T∑k=1tdiag⁡(ϕ′(ak))(∂ht∂hk) ⁣⊤∂ℓt∂ht hk−1⊤,∂ht∂hk=∏j=k+1tdiag⁡(ϕ′(aj)) W\frac{\partial\loss}{\partial W}=\sum_{t=1}^T\sum_{k=1}^{t}\operatorname{diag}\big(\phi'(\mathbf a_k)\big)\Big(\frac{\partial\mathbf h_t}{\partial\mathbf h_k}\Big)^{\!\top}\frac{\partial\ell_t}{\partial\mathbf h_t}\,\mathbf h_{k-1}^\top,\qquad\frac{\partial\mathbf h_t}{\partial\mathbf h_k}=\prod_{j=k+1}^{t}\operatorname{diag}\big(\phi'(\mathbf a_j)\big)\,W

    Unrolling the recursion shows what the sums contain. Loss ℓt\ell_t reaches the use of WW at an earlier step kk through the Jacobian product ∂ht/∂hk\partial\mathbf h_t/\partial\mathbf h_k, one factor per step in between:

Cost. The backward pass costs about twice the forward pass, O(T(n2+nd))\order{T(n^2+nd)}, but it needs every at\mathbf a_t and ht\mathbf h_t from the forward pass, so memory grows like O(Tn)\order{Tn} per sequence. For long sequences this activation memory, not arithmetic, is the binding constraint; gradient checkpointing trades it for recomputation, and truncation (Step 5) caps it.

Predict before you look

You backpropagate through T=10,000T=10{,}000 steps of an RNN with n=1,024n=1{,}024 units on a batch of 32 sequences, storing each hidden state in 32-bit floats (4 bytes). How many gigabytes do the stored hidden states alone take?

Show the answer

1.31 GB

10,000×1,024×32×4≈1.31×10910{,}000\times1{,}024\times32\times4\approx1.31\times10^9 bytes. The pre-activations double that, and a gated cell stores several such vectors per step. Memory grows linearly with TT, which is why long streams are trained in truncated chunks.

Why gradients vanish or explode

Everything hinges on the factors Jj=∂hj/∂hj−1=diag⁡(ϕ′(aj)) WJ_j=\partial\mathbf h_j/\partial\mathbf h_{j-1}=\operatorname{diag}(\phi'(\mathbf a_j))\,W. Start with a linear RNN, ϕ(a)=a\phi(a)=a, so that ∂ht/∂hk=Wt−k\partial\mathbf h_t/\partial\mathbf h_k=W^{t-k}. If W=QΛQ−1W=Q\Lambda Q^{-1} is diagonalizable, then Wm=QΛmQ−1W^m=Q\Lambda^mQ^{-1}: the component of a gradient along eigenvector ii is multiplied by λim\lambda_i^m. Components with ∣λi∣<1\abs{\lambda_i}<1 die out exponentially, those with ∣λi∣>1\abs{\lambda_i}>1 blow up, and the spectral radius ρ(W)=max⁡i∣λi∣\rho(W)=\max_i\abs{\lambda_i} decides the long-run behavior, since ∥Wm∥1/m→ρ(W)\lVert W^m\rVert^{1/m}\to\rho(W) for any matrix (Gelfand's formula). A nonlinearity adds the slopes ϕ′(aj)\phi'(\mathbf a_j), which for tanh never exceed 1.

Necessary is not sufficient. A large WW drives units into saturation, where tanh⁡′(a)=1−tanh⁡2(a)\tanh'(a)=1-\tanh^2(a) is tiny, and the slopes cancel much of the growth. The theorem also concerns norms: the spectral radius can be far below ∥W∥\lVert W\rVert for non-normal matrices, while for orthogonal or other normal matrices the two coincide.

Check your understanding

A tanh RNN has a recurrent matrix with spectral norm ∥W∥=1.5\lVert W\rVert=1.5. Must its gradients explode over long spans?

  1. Yes: any norm above 1 makes the Jacobian product grow
  2. No, they must vanish, because tanh slopes are below 1
  3. Not necessarily: ∥W∥>1\lVert W\rVert>1 is necessary for explosion, but saturated units can make the product shrink anyway
  4. The question is meaningless: the spectral norm says nothing about gradients
Show the answer

C. Not necessarily: ∥W∥>1\lVert W\rVert>1 is necessary for explosion, but saturated units can make the product shrink anyway

The bound (γ∥W∥)t−k=1.5t−k(\gamma\lVert W\rVert)^{t-k}=1.5^{t-k} is only an upper bound. Whether the product actually grows depends on the slopes ϕ′(aj)\phi'(\mathbf a_j) along the trajectory: small inputs keep units in their linear range and the gradient grows, while saturated units shrink it. In the widget's network, ρ=1.25\rho=1.25 gives a gradient of about 0.660.66 at step 0 after 50 steps, neither vanishing nor exploding.

Exploding gradients are tamed by clipping the norm, g←g min⁡{1, c/∥g∥}\mathbf g\leftarrow\mathbf g\,\min\{1,\,c/\lVert\mathbf g\rVert\}, which keeps the step's direction and caps its length (Pascanu, Mikolov & Bengio, 2013). Vanishing gradients have no such fix: the information is not in the gradient to begin with. Remedies change the network instead: gated cells (LSTMs & GRUs), orthogonal or identity initialization of WW, or linear recurrences with eigenvalues near the unit circle (State Space Models). The backprop topic's lesson Exploding Gradients & Clipping explains why clipping also speeds training.

Truncation, two directions and depth

Truncated BPTT. A text corpus or an audio stream is one sequence millions of steps long. Truncated BPTT runs the network forward over the whole stream, carrying the state, but every k1k_1 steps backpropagates only k2k_2 steps into the past (Williams & Peng, 1990; Sutskever, 2013); the common case k1=k2k_1=k_2 is exactly the chunked training of Step 2. Memory drops from O(Tn)\order{Tn} to O(k2n)\order{k_2n}.

The price is a biased gradient. Every term of the double sum in Step 3 that spans more steps than the window is dropped, so no gradient ever links a loss to an input more than k2k_2 steps earlier. The forward state still carries information further, and the network may use it if shorter-range training happens to shape it usefully, but it is never trained to keep that information. Training Recurrent Networks quantifies this bias and the online alternatives.

Bidirectional RNNs (Schuster & Paliwal, 1997) run one RNN forward and another backward over the sequence and combine both states at each position, so every output can depend on the whole input. That suits tagging and offline speech recognition, but not generation or streaming, since the backward pass needs inputs that have not arrived yet. Stacked (deep) RNNs feed the state sequence of layer ℓ−1\ell-1 as the input sequence of layer ℓ\ell, adding depth at every time step. Deep bidirectional LSTMs set a record on the TIMIT phoneme-recognition benchmark (Graves, Mohamed & Hinton, 2013), and Google's 2016 translation system used 8 LSTM layers in both encoder and decoder, with residual connections between layers (Wu et al., 2016).

h→t=ϕ(W→ h→t−1+U→xt),h←t=ϕ(W← h←t+1+U←xt),ht(ℓ)=ϕ(W(ℓ)ht−1(ℓ)+U(ℓ)ht(ℓ−1))\overrightarrow{\mathbf h}_t=\phi\big(\overrightarrow W\,\overrightarrow{\mathbf h}_{t-1}+\overrightarrow U\mathbf x_t\big),\quad\overleftarrow{\mathbf h}_t=\phi\big(\overleftarrow W\,\overleftarrow{\mathbf h}_{t+1}+\overleftarrow U\mathbf x_t\big),\qquad\mathbf h^{(\ell)}_t=\phi\big(W^{(\ell)}\mathbf h^{(\ell)}_{t-1}+U^{(\ell)}\mathbf h^{(\ell-1)}_t\big)
Left: a bidirectional layer outputs [h→t;h←t][\overrightarrow{\mathbf h}_t;\overleftarrow{\mathbf h}_t], with twice the parameters of one direction. Right: layer ℓ\ell of a stack, with ht(0)=xt\mathbf h^{(0)}_t=\mathbf x_t (biases omitted). A gradient now travels on a grid, back through time and down through layers.

Key takeaways

  • The Elman RNN computes ht=ϕ(Wht−1+Uxt+b)\mathbf h_t=\phi(W\mathbf h_{t-1}+U\mathbf x_t+\mathbf b) with n2+nd+nn^2+nd+n recurrent-layer parameters, shared across time; it serves many-to-one, aligned many-to-many and generative tasks, and costs O(T(n2+nd))\order{T(n^2+nd)} sequential work.
  • BPTT is reverse mode on the unrolled graph: δt=V⊤(y^t−eyt)+W⊤diag⁡(ϕ′(at+1))δt+1\boldsymbol\delta_t=V^\top(\hat{\mathbf y}_t-\mathbf e_{y_t})+W^\top\operatorname{diag}(\phi'(\mathbf a_{t+1}))\boldsymbol\delta_{t+1}, and each shared weight's gradient sums one term per step. Memory grows like O(Tn)\order{Tn}.
  • Long-range gradient terms contain ∂ht/∂hk=∏jdiag⁡(ϕ′(aj))W\partial\mathbf h_t/\partial\mathbf h_k=\prod_j\operatorname{diag}(\phi'(\mathbf a_j))W, bounded by (γ∥W∥)t−k(\gamma\lVert W\rVert)^{t-k}: γ∥W∥<1\gamma\lVert W\rVert<1 guarantees vanishing and ∥W∥>1/γ\lVert W\rVert>1/\gamma is necessary for explosion. Clipping fixes explosions; vanishing needs architectural remedies.
  • Truncated BPTT caps memory but biases the gradient against dependencies longer than the window; bidirectional RNNs need the whole input; stacked RNNs add depth at every step.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

With δt=∂L/∂ht\boldsymbol\delta_t=\partial\loss/\partial\mathbf h_t and the loss summed over all steps, which backward recursion is correct for the Elman RNN?

  1. δt=W⊤diag⁡(ϕ′(at+1)) δt+1\boldsymbol\delta_t=W^\top\operatorname{diag}(\phi'(\mathbf a_{t+1}))\,\boldsymbol\delta_{t+1}
  2. δt=V⊤(y^t−eyt)+Wdiag⁡(ϕ′(at+1)) δt+1\boldsymbol\delta_t=V^\top(\hat{\mathbf y}_t-\mathbf e_{y_t})+W\operatorname{diag}(\phi'(\mathbf a_{t+1}))\,\boldsymbol\delta_{t+1}
  3. δt=V⊤(y^t−eyt)+W⊤diag⁡(ϕ′(at+1)) δt+1\boldsymbol\delta_t=V^\top(\hat{\mathbf y}_t-\mathbf e_{y_t})+W^\top\operatorname{diag}(\phi'(\mathbf a_{t+1}))\,\boldsymbol\delta_{t+1}
  4. δt=V⊤(y^t−eyt)+W⊤diag⁡(ϕ′(at)) δt+1\boldsymbol\delta_t=V^\top(\hat{\mathbf y}_t-\mathbf e_{y_t})+W^\top\operatorname{diag}(\phi'(\mathbf a_{t}))\,\boldsymbol\delta_{t+1}
Show the answer

C. δt=V⊤(y^t−eyt)+W⊤diag⁡(ϕ′(at+1)) δt+1\boldsymbol\delta_t=V^\top(\hat{\mathbf y}_t-\mathbf e_{y_t})+W^\top\operatorname{diag}(\phi'(\mathbf a_{t+1}))\,\boldsymbol\delta_{t+1}

ht\mathbf h_t reaches the loss directly through ℓt\ell_t (the first term) and through at+1=Wht+…\mathbf a_{t+1}=W\mathbf h_t+\dots, whose Jacobian with respect to ht\mathbf h_t is WW; reverse mode multiplies by its transpose. The slope belongs to at+1\mathbf a_{t+1}, the pre-activation that ht\mathbf h_t feeds.

Question 2

A linear RNN ht=Wht−1+Uxt\mathbf h_t=W\mathbf h_{t-1}+U\mathbf x_t has a diagonalizable WW with eigenvalues 0.50.5 and 1.21.2. How does ∂ht/∂ht−20=W20\partial\mathbf h_t/\partial\mathbf h_{t-20}=W^{20} act on a gradient?

  1. Both components shrink, since the average eigenvalue is below 1
  2. The component along the first eigenvector shrinks by about 10−610^{-6}; the one along the second grows about 38-fold
  3. Both components are preserved, since a linear RNN has no saturation
  4. Both grow, since the spectral radius exceeds 1
Show the answer

B. The component along the first eigenvector shrinks by about 10−610^{-6}; the one along the second grows about 38-fold

W20W^{20} scales each eigencomponent by λi20\lambda_i^{20}: 0.520≈9.5×10−70.5^{20}\approx9.5\times10^{-7} and 1.220≈381.2^{20}\approx38. Over long spans the largest eigenvalue dominates, so with ρ(W)=1.2\rho(W)=1.2 the gradient explodes along that direction while information along the other is lost.

Question 3

A language model is trained with truncated BPTT, k1=k2=35k_1=k_2=35. In its training text, the right next word often depends on a word 100 tokens back. What does truncation imply?

  1. The forward state is reset every 35 tokens, so the model cannot see 100 tokens back at all
  2. The gradient is unbiased, only noisier
  3. Truncation makes the gradients explode on long dependencies
  4. No gradient term links a loss to an input more than 35 steps earlier, so the model is never directly trained to keep that information
Show the answer

D. No gradient term links a loss to an input more than 35 steps earlier, so the model is never directly trained to keep that information

Truncation keeps the state flowing forward but drops every gradient term spanning more than k2k_2 steps. The model may still carry some information further, but nothing in training rewards it for doing so: the gradient is biased toward short dependencies.

Question 4

Why is a bidirectional RNN unsuitable for a keyboard app that suggests the next word as you type?

  1. Its backward direction needs inputs from later in the sequence, which do not exist yet when the prediction is made
  2. It has twice the parameters, which is too many for a phone
  3. It cannot be trained with backpropagation through time
  4. Its two directions always cancel each other out
Show the answer

A. Its backward direction needs inputs from later in the sequence, which do not exist yet when the prediction is made

h←t\overleftarrow{\mathbf h}_t summarizes xT,…,xt\mathbf x_T,\dots,\mathbf x_t. For next-word prediction (and anything streaming) the future is unknown, so only the forward direction is usable. Bidirectional models suit tasks where the whole input is available first.

Go deeper

Further reading

  • J. L. Elman, "Finding structure in time," Cognitive Science 14(2), 179–211 (1990).
  • P. J. Werbos, "Backpropagation through time: what it does and how to do it," Proceedings of the IEEE 78(10), 1550–1560 (1990).
  • R. Pascanu, T. Mikolov & Y. Bengio, "On the difficulty of training recurrent neural networks," ICML (2013).
  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 10 (MIT Press, 2016), free at deeplearningbook.org.