Contents Language Models Code Course home

Chapter 12Recurrent Networks

After this chapter you will be able to

  • write the recurrence of a simple RNN and unroll it by hand for a short sentence;

  • count the parameters of an RNN and say why the count does not grow with the window;

  • derive the gradients of backpropagation through time, including shared weights adding up;

  • show why gradients decay or explode geometrically with distance, and compute how fast;

  • apply gradient clipping and truncation, and say what each does not repair.

This chapter builds on Chapters 11 and 8, which supply the fixed-window model and backpropagation.

A window that will not close

Chapter 11 fixed one blindness and left the other in plain sight. The feed-forward language model concatenates n−1n-1 embeddings into a single vector, that vector is its whole memory, and its length is decided before training begins. So the model reads a sentence through a slot of fixed width, and everything outside falls away as it did for the counter.

Consider “the book that the committee rejected was short”, where the verb agrees with book eight words back and a window of three cannot see it. Widening the window is not a fix, because the hidden matrix WhW_h has shape (n−1)d×H(n-1)d \times H and its size grows with every word you admit. And no fixed width is ever wide enough, since sentences have no maximum length.

What we want is a model that reads left to right, keeping a running summary of everything so far and updating it at each word. The summary is a state and the update rule is a recurrence.

The recurrence

A recurrent neural network keeps a hidden state hth_t and rewrites it at every time step:

ht=tanh⁡(Wxt+Uht−1+bh),ŷt=softmax⁡(Vht+by).\begin{align} h_t &= \tanh\!\big(W\,x_t + U\,h_{t-1} + b_h\big), \label{eq:rnn-state}\\ \hat{y}_t &= \operatorname{softmax}\!\big(V\,h_t + b_y\big). \label{eq:rnn-out} \end{align}

Here xtx_t is the embedding of the word read at step tt, while h0h_0 is conventionally the zero vector. Nothing has been read before the first word, so the state starts empty.

Figure 12.1. A recurrent network drawn as a loop and as an unrolled chain. The loop is the definition. The chain is what backpropagation sees. Both show the same three matrices used at every step.

Three matrices carry the whole model, where WW maps the current word into the state, UU maps the previous state into the new one, and VV maps the state to a score for every vocabulary word. The important word is same, because the same WW, UU and VV are used at every step however long the sentence, and that reuse is what recurrent means.

Equation (12.14) therefore does something the feed-forward model could not, since ht−1h_{t-1} was itself computed from ht−2h_{t-2} and so on back to the first word. The state at step tt depends on every word read so far, so there is no window and no cliff.

Unrolling, worked

Take a model small enough to print, with two hidden units, embeddings of size two and a vocabulary of three words. Every number below can be checked on paper.

W=(0.6−0.30.20.5),U=(0.40.1−0.20.7),bh=(0.05,−0.05).W = \begin{pmatrix} 0.6 & -0.3 \\ 0.2 & 0.5 \end{pmatrix}, \quad U = \begin{pmatrix} 0.4 & 0.1 \\ -0.2 & 0.7 \end{pmatrix}, \quad b_h = (0.05,\, -0.05).

Read the sentence the dog ran, starting from h0=(0,0)h_0 = (0, 0).

tt word xtx_t Wxt+Uht−1+bhWx_t + Uh_{t-1} + b_h hth_t
1 the (+0.5000,−0.2000)(+0.5000, -0.2000) (+0.4100,−0.0500)(+0.4100, -0.0500) (+0.3885,−0.0500)(+0.3885, -0.0500)
2 dog (+0.1000,+0.8000)(+0.1000, +0.8000) (+0.0204,+0.2573)(+0.0204, +0.2573) (+0.0204,+0.2518)(+0.0204, +0.2518)
3 ran (−0.6000,+0.3000)(-0.6000, +0.3000) (−0.3667,+0.1522)(-0.3667, +0.1522) (−0.3511,+0.1510)(-0.3511, +0.1510)

Follow the third row, whose input column depends only on ran while its hth_t depends on h2h_2, which depended on h1h_1, which depended on the. So h3h_3 is a summary of the whole prefix, nothing was thrown away, and no parameter was added to make room for it.

Why tanh\tanh

Why tanh\tanh and not the sigmoid? The answer is short. tanh\tanh is symmetric about the origin so its output is zero-centred, and states that average to zero train faster than states that average to 0.50.5. Its derivative is also steeper, since the sigmoid’s lies in [0,0.25][0, 0.25] while tanh\tanh’s lies in [0,1][0, 1].

A derivative capped at 0.250.25 shrinks the gradient by at least a factor of four at every step, and Section 12.5 shows why that is fatal, with tanh\tanh merely delaying the problem and not removing it. Modern architectures mostly use ReLU and its variants, which pass gradient unchanged on the positive side. ReLU has its own failure. A unit whose input is always negative stops passing any gradient at all and never recovers. Leaky ReLU, max⁡(αx,x)\max(\alpha x, x) with small α\alpha, exists to prevent that.

An RNN is a language model

Equation (12.15) already produces one distribution over the vocabulary per time step, which is what a language model needs. Train it by predicting the next word at every position, where the loss at step tt is the cross-entropy of Chapter 11 and the loss for a sentence is their sum:

Et=−∑kyt,klog⁡ŷt,k,ℒ=∑tEt.(12.1)\begin{equation} E_t \;=\; -\sum_k y_{t,k} \log \hat{y}_{t,k}, \qquad \mathcal{L} \;=\; \sum_t E_t . \label{eq:rnn-loss} \quad\text{(12.1)} \end{equation}

Everything from Chapter 10 carries over, since the task, the maximum likelihood objective and the perplexity of Section that section are all untouched. Only the machinery producing ŷt\hat{y}_t has changed again.

An RNN read three words with a hidden state and next-word distribution at each step
A recurrent network reads text one word at a time with the same weights at every step, carrying a hidden state forward and predicting the next word from it.

The parameter count stops growing

The clearest argument for the recurrence is a table of shapes. Take |V|=10,000|V| = 10{,}000, embeddings of size d=100d = 100 and H=500H = 500 hidden units, which are round numbers chosen for the example.

matrix shape parameters
EE 10,000×10010{,}000 \times 100 1,000,000
WW 500×100500 \times 100 50,000
UU 500×500500 \times 500 250,000
VV 500×10,000500 \times 10{,}000 5,000,000
bhb_h 500500 500
byb_y 10,00010{,}000 10,000
total 6,310,500

Not one of those shapes mentions the length of the sentence. Compare the feed-forward model, whose WhW_h has shape (n−1)d×H(n-1)d \times H and therefore grows with every word of context admitted.

context words feed-forward WhW_h recurrent UU
3 150,000 250,000
5 250,000 250,000
10 500,000 250,000
50 2,500,000 250,000
500 25,000,000 250,000

At a context of three the feed-forward model is actually smaller, the two cross over at five, and after that the comparison is not close. The left column grows without limit while the right column is a constant, and that one fact is what lets a recurrent network read a paragraph.

Backpropagation through time

Training needs gradients, and the loop has to be flattened before the chain rule can be applied. Unroll the network and a sentence of TT words becomes a feed-forward network TT layers deep, in which every layer shares the same weights.

Figure 12.2. The unrolled network. Each step contributes its own error, and every step uses the same three matrices. Gradients from a later step must travel back through every intermediate state to reach an earlier one.

This is backpropagation through time, which is ordinary backpropagation on the unrolled graph. Its result is short to state and easy to misremember, so this section derives it from the loss, one operation at a time, and then checks the derivation against a computer.

What is being differentiated

Give every intermediate quantity a name. At step tt the network computes

at=Wxt+Uht−1+bh,ht=tanh⁡(at),zt=Vht+by,ŷt=softmax⁡(zt),\begin{align} a_t &= W x_t + U h_{t-1} + b_h, & h_t &= \tanh(a_t), \label{eq:bptt-fwd-h}\\ z_t &= V h_t + b_y, & \hat{y}_t &= \operatorname{softmax}(z_t), \label{eq:bptt-fwd-y} \end{align}

which is Equations (12.14) and (12.15) with the pre-activation ata_t and the vocabulary scores ztz_t given names. The loss is Equation (12.1), where yty_t is the one-hot vector of the word that actually came next, so that Et=−∑iyt,ilog⁡ŷt,iE_t = -\sum_i y_{t,i}\log\hat{y}_{t,i} and ℒ=∑tEt\mathcal{L} = \sum_t E_t.

The aim is the derivative of ℒ\mathcal{L} with respect to VV, byb_y, UU, WW and bhb_h, and also with respect to the input xtx_t, which is how the embeddings learn. For a vector uu, the symbol ∂ℒ/∂u\partial\mathcal{L}/\partial u is the vector of the same length whose iith entry is ∂ℒ/∂ui\partial\mathcal{L}/\partial u_i. The quantities form a chain, running xtx_t and ht−1h_{t-1} into ata_t, then hth_t, then ztz_t, then ŷt\hat{y}_t, then EtE_t, and the method is to start at the loss and step back along that chain, taking one derivative per link.

Through the softmax and the cross-entropy

Drop the subscript tt for the length of this subsection. The loss gives the first link directly, because E=−∑iyilog⁡ŷiE = -\sum_i y_i \log\hat{y}_i means

∂E∂ŷi=−yiŷi.\frac{\partial E}{\partial \hat{y}_i} \;=\; -\frac{y_i}{\hat{y}_i}.

The second link is the softmax, ŷi=ezi/S\hat{y}_i = e^{z_i}/S with S=∑mezmS = \sum_m e^{z_m}. Every score appears in SS, so changing zjz_j changes every ŷi\hat{y}_i, and the quotient rule gives two cases. When i=ji = j the numerator also depends on zjz_j:

∂ŷj∂zj=ezjS−ezjezjS2=ŷj(1−ŷj).\frac{\partial \hat{y}_j}{\partial z_j} = \frac{e^{z_j} S - e^{z_j}e^{z_j}}{S^2} = \hat{y}_j\,(1 - \hat{y}_j).

When i≠ji \neq j only the denominator does:

∂ŷi∂zj=−eziezjS2=−ŷiŷj.\frac{\partial \hat{y}_i}{\partial z_j} = -\frac{e^{z_i}e^{z_j}}{S^2} = -\hat{y}_i\,\hat{y}_j.

Both cases fit one formula, ∂ŷi/∂zj=ŷi([i=j]−ŷj)\partial\hat{y}_i/\partial z_j = \hat{y}_i\,([i{=}j] - \hat{y}_j), where the bracket [i=j][i{=}j] is 11 if i=ji = j and 00 otherwise. The chain rule now adds up the effect of zjz_j on the loss through every ŷi\hat{y}_i:

∂E∂zj=∑i∂E∂ŷi∂ŷi∂zj=−∑iyiŷiŷi([i=j]−ŷj)=−yj+ŷj∑iyi=ŷj−yj.\frac{\partial E}{\partial z_j} = \sum_i \frac{\partial E}{\partial \hat{y}_i}\,\frac{\partial \hat{y}_i}{\partial z_j} = -\sum_i \frac{y_i}{\hat{y}_i}\,\hat{y}_i\,([i{=}j] - \hat{y}_j) = -y_j + \hat{y}_j \sum_i y_i = \hat{y}_j - y_j.

The last step uses ∑iyi=1\sum_i y_i = 1, which holds because yy is one-hot. The division by ŷi\hat{y}_i in the first factor cancels the ŷi\hat{y}_i in the second, and that cancellation is why softmax and cross-entropy are always used together. Restoring the subscript,

∂Et∂zt=ŷt−yt=:δoutt.(12.2)\begin{equation} \frac{\partial E_t}{\partial z_t} \;=\; \hat{y}_t - y_t \;=:\; \delta_{\text{out}}^{t}. \label{eq:bptt-scores} \quad\text{(12.2)} \end{equation}

Every other gradient in this section begins from this vector, which is prediction minus target. It is the same signal that drove Chapter 8.

Through the output layer

The scores are zj=∑kVjkhk+by,jz_j = \sum_k V_{jk}h_k + b_{y,j}, so ∂zj/∂Vjk=hk\partial z_j/\partial V_{jk} = h_k, ∂zj/∂by,j=1\partial z_j/\partial b_{y,j} = 1 and ∂zj/∂hk=Vjk\partial z_j/\partial h_k = V_{jk}. Multiplying each by δout,j\delta_{\text{out},j} gives the gradient for the weight VjkV_{jk} as δout,jhk\delta_{\text{out},j}\,h_k, the (j,k)(j,k) entry of an outer product:

∂Et∂V=δouttht⊤,∂Et∂by=δoutt.(12.3)\begin{equation} \frac{\partial E_t}{\partial V} \;=\; \delta_{\text{out}}^{t}\, h_t^{\top}, \qquad \frac{\partial E_t}{\partial b_y} \;=\; \delta_{\text{out}}^{t}. \label{eq:bptt-v} \quad\text{(12.3)} \end{equation}

The state hkh_k reaches every score, so the error it receives is a sum over jj, ∑jδout,jVjk\sum_j \delta_{\text{out},j}V_{jk}, the kkth entry of

∂Et∂ht=V⊤δoutt.(12.4)\begin{equation} \frac{\partial E_t}{\partial h_t} \;=\; V^{\top}\delta_{\text{out}}^{t}. \label{eq:bptt-hout} \quad\text{(12.4)} \end{equation}

Through the tanh and the recurrent step

The nonlinearity acts on each entry separately, hi=tanh⁡(ai)h_i = \tanh(a_i), so the derivative is a diagonal one. Writing tanh\tanh out and applying the quotient rule,

ddatanh⁡a=(ea+e−a)2−(ea−e−a)2(ea+e−a)2=1−tanh⁡2a,\frac{d}{da}\tanh a = \frac{(e^{a}+e^{-a})^2 - (e^{a}-e^{-a})^2}{(e^{a}+e^{-a})^2} = 1 - \tanh^2 a ,

so the derivative can be computed from the output alone, as 1−hi21 - h_i^2. Let δht\delta_h^{t} be the error at the pre-activation, ∂ℒ/∂at\partial\mathcal{L}/\partial a_t. It is the error arriving at hth_t multiplied entry by entry by 1−ht21 - h_t^2:

δht=∂ℒ∂ht⊙(1−ht2).(12.5)\begin{equation} \delta_h^{t} \;=\; \frac{\partial\mathcal{L}}{\partial h_t} \odot (1 - h_t^{2}). \label{eq:bptt-tanh} \quad\text{(12.5)} \end{equation}

The last link is the linear map aj=∑kWjkxk+∑kUjkht−1,k+bh,ja_j = \sum_k W_{jk}x_k + \sum_k U_{jk}h_{t-1,k} + b_{h,j}. Its derivatives are ∂aj/∂Wjk=xk\partial a_j/\partial W_{jk} = x_k, ∂aj/∂Ujk=ht−1,k\partial a_j/\partial U_{jk} = h_{t-1,k}, ∂aj/∂bh,j=1\partial a_j/\partial b_{h,j} = 1, ∂aj/∂ht−1,k=Ujk\partial a_j/\partial h_{t-1,k} = U_{jk} and ∂aj/∂xk=Wjk\partial a_j/\partial x_k = W_{jk}. These have the same shape as the output layer’s, so the results do too. The use of the matrices at step tt contributes δhtxt⊤\delta_h^{t}x_t^{\top} to WW, δhtht−1⊤\delta_h^{t}h_{t-1}^{\top} to UU and δht\delta_h^{t} to bhb_h. Two errors also flow onwards, U⊤δhtU^{\top}\delta_h^{t} to the previous state and W⊤δhtW^{\top}\delta_h^{t} to the embedding of the word read at step tt.

Two routes into every state

Equation (12.4) gave the error that the output at step kk sends to hkh_k, but hkh_k has a second job. It is read by the output at step kk and also by the state at step k+1k+1, so it influences the loss along two routes. The chain rule adds the routes. The first is V⊤δoutkV^{\top}\delta_{\text{out}}^{k}. The second runs through ak+1a_{k+1}, and the error at ak+1a_{k+1} is already δhk+1\delta_h^{k+1}, which by construction contains every later step, so pulling it back one link through UU gives U⊤δhk+1U^{\top}\delta_h^{k+1}. Together,

∂ℒ∂hk=V⊤δoutk+U⊤δhk+1,(12.6)\begin{equation} \frac{\partial\mathcal{L}}{\partial h_k} \;=\; V^{\top}\delta_{\text{out}}^{k} \;+\; U^{\top}\delta_h^{k+1}, \label{eq:bptt-hk} \quad\text{(12.6)} \end{equation}

and substituting into Equation (12.5) gives the recursion that the whole algorithm turns on:

δhk=[V⊤(ŷk−yk)+U⊤δhk+1]⊙(1−hk2),δhT+1=0.(12.7)\begin{equation} \delta_h^{k} \;=\; \Big[\,V^{\top}(\hat{y}_k - y_k) \;+\; U^{\top}\delta_h^{k+1}\Big] \odot (1 - h_k^2), \qquad \delta_h^{T+1} \;=\; 0 . \label{eq:bptt-delta} \quad\text{(12.7)} \end{equation}

The last step has nothing after it, so the recursion starts from zero. It is evaluated backwards, δhT\delta_h^{T} first and δh1\delta_h^{1} last, and each δhk\delta_h^{k} carries its own step’s error together with, inside the second term, the error of every step that follows.

Shared weights add up

The same WW is used at every step, so it helps to imagine TT copies W1,…,WTW_1,\dots,W_T that happen to be equal. Each copy affects the loss only through its own ata_t, so the gradient for copy WtW_t is the product δhtxt⊤\delta_h^{t}x_t^{\top} found above. Changing the one shared WW changes all the copies together, and derivatives of simultaneous changes add. The gradient for each shared parameter is therefore the sum over the steps of the per-step gradients:

∂ℒ∂V=∑t=1T(ŷt−yt)ht⊤,∂ℒ∂U=∑t=1Tδhtht−1⊤,∂ℒ∂W=∑t=1Tδhtxt⊤,(12.8)\begin{equation} \frac{\partial \mathcal{L}}{\partial V} = \sum_{t=1}^{T} (\hat{y}_t - y_t)\,h_t^{\top}, \quad \frac{\partial \mathcal{L}}{\partial U} = \sum_{t=1}^{T} \delta_h^{t}\,h_{t-1}^{\top}, \quad \frac{\partial \mathcal{L}}{\partial W} = \sum_{t=1}^{T} \delta_h^{t}\,x_t^{\top}, \label{eq:bptt-sum} \quad\text{(12.8)} \end{equation}

with ∂ℒ/∂bh=∑tδht\partial\mathcal{L}/\partial b_h = \sum_t \delta_h^{t} and ∂ℒ/∂by=∑t(ŷt−yt)\partial\mathcal{L}/\partial b_y = \sum_t (\hat{y}_t - y_t). The embedding of the word read at step tt receives W⊤δhtW^{\top}\delta_h^{t}, and a word that occurs twice in a sentence receives two contributions. The gradients are simplest for a single step, where ht−1h_{t-1} is held fixed and the error is not allowed to travel back past its own step. That cuts the second term from Equation (12.7), leaving

∂Et∂U=[(V⊤(ŷt−yt))⊙(1−ht2)]ht−1⊤,∂Et∂W=[(V⊤(ŷt−yt))⊙(1−ht2)]xt⊤,(12.9)\begin{equation} \frac{\partial E_t}{\partial U} \;=\; \Big[\big(V^{\top}(\hat{y}_t - y_t)\big) \odot (1 - h_t^2)\Big] h_{t-1}^{\top}, \qquad \frac{\partial E_t}{\partial W} \;=\; \Big[\big(V^{\top}(\hat{y}_t - y_t)\big) \odot (1 - h_t^2)\Big] x_t^{\top}, \label{eq:bptt-u} \quad\text{(12.9)} \end{equation}

which differ from each other only in the last factor, since ht−1h_{t-1} and xtx_t are the two things ata_t is built from. These are the first term of what Equation (12.8) adds up once the recursion is allowed to run.

A full backward pass, in numbers

Take the model of the unrolling example, with the output matrix V=(0.7−0.3−0.40.60.10.2),by=(0,0,0),V = \begin{pmatrix} 0.7 & -0.3 \\ -0.4 & 0.6 \\ 0.1 & 0.2 \end{pmatrix}, \qquad b_y = (0, 0, 0), whose three rows score the, dog and ran. Read the three words the dog ran and ask the model to predict dog, ran and the, as it would in the sentence the dog ran the race. The forward pass reuses the states of the earlier table.

tt read target hth_t ŷt\hat{y}_t (the, dog, ran) EtE_t
1 the dog (+0.3885,−0.0500)(+0.3885, -0.0500) (0.4173,0.2602,0.3224)(0.4173, 0.2602, 0.3224) 1.3461
2 dog ran (+0.0204,+0.2518)(+0.0204, +0.2518) (0.2988,0.3665,0.3347)(0.2988, 0.3665, 0.3347) 1.0944
3 ran the (−0.3511,+0.1510)(-0.3511, +0.1510) (0.2490,0.4196,0.3314)(0.2490, 0.4196, 0.3314) 1.3905

The loss is ℒ=1.3461+1.0944+1.3905=3.8310\mathcal{L} = 1.3461 + 1.0944 + 1.3905 = 3.8310. Equation (12.2) now gives the error at the scores, prediction minus target, with the target’s entry carrying the minus sign:

tt ŷt−yt\hat{y}_t - y_t
1 (+0.4173,−0.7398,+0.3224)(+0.4173, -0.7398, +0.3224)
2 (+0.2988,+0.3665,−0.6653)(+0.2988, +0.3665, -0.6653)
3 (−0.7510,+0.4196,+0.3314)(-0.7510, +0.4196, +0.3314)

The backward sweep of Equation (12.7) starts at step 33. At each step two errors meet at the state, one from its own output and one handed back by the step after it.

kk V⊤(ŷk−yk)V^{\top}(\hat{y}_k - y_k) U⊤δhk+1U^{\top}\delta_h^{k+1} sum
3 (−0.6604,+0.5434)(-0.6604, +0.5434) (+0.0000,+0.0000)(+0.0000, +0.0000) (−0.6604,+0.5434)(-0.6604, +0.5434)
2 (−0.0040,−0.0028)(-0.0040, -0.0028) (−0.3378,+0.3138)(-0.3378, +0.3138) (−0.3418,+0.3110)(-0.3418, +0.3110)
1 (+0.6203,−0.5046)(+0.6203, -0.5046) (−0.1949,+0.1697)(-0.1949, +0.1697) (+0.4254,−0.3349)(+0.4254, -0.3349)

Multiplying each sum entry by entry by 1−hk21 - h_k^2 gives the error at the pre-activation.

kk 1−hk21 - h_k^2 δhk\delta_h^{k}
3 (+0.8767,+0.9772)(+0.8767, +0.9772) (−0.5790,+0.5310)(-0.5790, +0.5310)
2 (+0.9996,+0.9366)(+0.9996, +0.9366) (−0.3416,+0.2913)(-0.3416, +0.2913)
1 (+0.8491,+0.9975)(+0.8491, +0.9975) (+0.3612,−0.3340)(+0.3612, -0.3340)

Look at step 22. Its own output contributes almost nothing, (−0.0040,−0.0028)(-0.0040, -0.0028), yet δh2\delta_h^{2} is large, because step 33 was wrong and sent its blame back through UU. That second term is the whole difference between this algorithm and treating every step separately.

Equation (12.8) now turns the three tables into gradients, each a sum over the three steps. For UU, the first entry is 0.3612×0+(−0.3416)(0.3885)+(−0.5790)(0.0204)=−0.14450.3612 \times 0 + (-0.3416)(0.3885) + (-0.5790)(0.0204) = -0.1445, and the other matrices follow the same pattern:

∂ℒ∂V=(+0.4319−0.0590−0.4272+0.1926−0.0047−0.1336),∂ℒ∂U=(−0.1445−0.1287+0.1240+0.1192),\frac{\partial\mathcal{L}}{\partial V} = \begin{pmatrix} +0.4319 & -0.0590 \\ -0.4272 & +0.1926 \\ -0.0047 & -0.1336 \end{pmatrix}, \quad \frac{\partial\mathcal{L}}{\partial U} = \begin{pmatrix} -0.1445 & -0.1287 \\ +0.1240 & +0.1192 \end{pmatrix}, ∂ℒ∂W=(+0.4939−0.5193−0.4565+0.4591),∂ℒ∂bh=(−0.5595,+0.4882),∂ℒ∂by=(−0.0349,+0.0463,−0.0114).\frac{\partial\mathcal{L}}{\partial W} = \begin{pmatrix} +0.4939 & -0.5193 \\ -0.4565 & +0.4591 \end{pmatrix}, \quad \frac{\partial\mathcal{L}}{\partial b_h} = (-0.5595, +0.4882), \quad \frac{\partial\mathcal{L}}{\partial b_y} = (-0.0349, +0.0463, -0.0114).

A derivation this long deserves a check that does not rely on it. Nudge one parameter by 10−610^{-6} in each direction, rerun the forward pass, and divide the change in the loss by the size of the nudge. That estimate uses no calculus, and over every entry of every parameter it differs from the numbers above by at most 3.5×10−103.5 \times 10^{-10}, the rounding error to be expected. The derivation holds.

Gradient descent now moves each matrix against its gradient, with the learning rate η\eta of Chapter 8:

Vnew=V−η∑t=1T(ŷt−yt)ht⊤,Unew=U−η∑t=1Tδhtht−1⊤,Wnew=W−η∑t=1Tδhtxt⊤,(12.10)\begin{equation} \begin{aligned} V^{\text{new}} &= V - \eta \sum_{t=1}^{T} (\hat{y}_t - y_t)\,h_t^{\top}, \\ U^{\text{new}} &= U - \eta \sum_{t=1}^{T} \delta_h^{t}\,h_{t-1}^{\top}, \\ W^{\text{new}} &= W - \eta \sum_{t=1}^{T} \delta_h^{t}\,x_t^{\top}, \end{aligned} \label{eq:bptt-update} \quad\text{(12.10)} \end{equation}

and likewise bhnew=bh−η∑tδhtb_h^{\text{new}} = b_h - \eta\sum_t \delta_h^{t} and bynew=by−η∑t(ŷt−yt)b_y^{\text{new}} = b_y - \eta\sum_t (\hat{y}_t - y_t), while the embedding row of the word read at step tt moves by −ηW⊤δht-\eta\,W^{\top}\delta_h^{t}. With η=0.1\eta = 0.1, one such step takes the loss on this sentence from 3.83103.8310 to 3.64703.6470. Because the same matrices serve every step, each is updated once per sequence, after the backward sweep has produced every δhk\delta_h^{k}. Unrolling Equation (12.7) multiplies in a fresh factor of U⊤U^{\top} for every step the error travels back, and the next section follows that repeated product to see what it does to the early steps.

Why the memory fades

Take an error at step τ\tau and ask what it says about the state at step 00, where the chain rule gives one factor per step in between:

∂E[τ]∂h[0]=∂E[τ]∂h[τ]∏t=1τ∂h[t]∂h[t−1].(12.11)\begin{equation} \frac{\partial E^{[\tau]}}{\partial h^{[0]}} \;=\; \frac{\partial E^{[\tau]}}{\partial h^{[\tau]}} \prod_{t=1}^{\tau} \frac{\partial h^{[t]}}{\partial h^{[t-1]}} . \label{eq:bptt-product} \quad\text{(12.11)} \end{equation}

Each factor is a Jacobian, the matrix of partial derivatives of one vector with respect to another, and Equation (12.14) says what one contains:

∂h[t]∂h[t−1]=diag⁡(tanh⁡′(⋅))U.(12.12)\begin{equation} \frac{\partial h^{[t]}}{\partial h^{[t-1]}} \;=\; \operatorname{diag}\!\big(\tanh'(\cdot)\big)\, U . \label{eq:bptt-jacobian} \quad\text{(12.12)} \end{equation}

So the product in Equation (12.11) behaves like UU raised to the power τ\tau, with the tanh\tanh derivative damping it at each step.

Figure 12.3. The dependency chain the gradient must travel. The error at step five depends on h[5]h^{[5]}, which depends on h[4]h^{[4]}, and so on back to h[0]h^{[0]}. Every arrow contributes one Jacobian factor.

Repeated multiplication by a matrix is governed by its eigenvalues, the factors by which it stretches vectors along its special directions, and the outcome is binary. If every eigenvalue of UU satisfies |λ|<1|\lambda| < 1 then the product shrinks towards zero and gradients vanish, while if any eigenvalue satisfies |λ|>1|\lambda| > 1 then the product grows without bound and gradients explode. The ideal is therefore |λ|≈1|\lambda| \approx 1, where the gradient neither vanishes nor explodes, and nothing in training holds the eigenvalues there.

How fast, in numbers

Treat the per-step factor as a single number and raise it to the distance travelled. This is a simplification, and it is enough to show the shape of the problem.

distance ×0.5\times 0.5 ×0.9\times 0.9 ×1.0\times 1.0 ×1.1\times 1.1 ×1.2\times 1.2
1 5.00×10−15.00 \times 10^{-1} 9.00×10−19.00 \times 10^{-1} 1.00 1.10 1.20
5 3.13×10−23.13 \times 10^{-2} 5.91×10−15.91 \times 10^{-1} 1.00 1.61 2.49
10 9.77×10−49.77 \times 10^{-4} 3.49×10−13.49 \times 10^{-1} 1.00 2.59 6.19
20 9.54×10−79.54 \times 10^{-7} 1.22×10−11.22 \times 10^{-1} 1.00 6.73 3.83×1013.83 \times 10^{1}
47 7.11×10−157.11 \times 10^{-15} 7.07×10−37.07 \times 10^{-3} 1.00 8.82×1018.82 \times 10^{1} 5.27×1035.27 \times 10^{3}
100 7.89×10−317.89 \times 10^{-31} 2.66×10−52.66 \times 10^{-5} 1.00 1.38×1041.38 \times 10^{4} 8.28×1078.28 \times 10^{7}

Notice how mild the failing factor is, because a per-step multiplier of 0.90.9 looks harmless and yet after fifty steps it has removed more than 9999 per cent of the signal.

A forty-seven step example

Take this passage, which makes the decay concrete. The dependency to be learned is long and the sentence is ordinary.

Raj entered CoffeeDay to meet his partner Dru. Raj said “Hi Dru”. In the next few hours they discussed their start-up and devised a plan to develop a product on knowledge management. After a long and fruitful discussion, Raj said goodbye to his .

The answer is partner. The passage runs to 4444 words, so the evidence is 3737 words behind the gap. The model steps over tokens, and punctuation marks and the split of start-up add several more, so call it 4747 steps as a round upper figure. Here is what reaches back that far.

0.0147=1.0×10−94,0.547=7.1×10−15,1.247=5266.46.0.01^{47} = 1.0 \times 10^{-94}, \qquad 0.5^{47} = 7.1 \times 10^{-15}, \qquad 1.2^{47} = 5266.46 .

A gradient of 10−9410^{-94} is no update at all, so the weights that would have captured the link never move and the network cannot learn the dependency however reliably it holds. One point deserves emphasis because it is easy to misread. The forward pass is fine and information does flow from the first step to the last. It is the backward pass that fails, since the network cannot assign blame across that distance and so never learns to use the information it is already carrying.

Ten recurrent states with the gradient reaching each shrinking, steady or growing
A gradient travelling back through time is multiplied at every step. A factor below 1 makes it fade and a factor above 1 makes it explode, so a plain recurrent network struggles to learn long-range links.

Two partial repairs

The two failures are not equally hard, and one of them has a cheap fix. The other needs a change of architecture.

Gradient clipping

Exploding gradients have a short remedy. If the gradient is longer than a threshold, rescale it while keeping its direction:

if ‖g‖>threshold,g←threshold‖g‖g.(12.13)\begin{equation} \text{if } \lVert g \rVert > \text{threshold}, \quad g \;\leftarrow\; \frac{\text{threshold}}{\lVert g \rVert}\, g . \label{eq:clipping} \quad\text{(12.13)} \end{equation}

step ‖g‖\lVert g \rVert before ‖g‖\lVert g \rVert after direction kept
1 0.3735 0.3735 1.0000
2 2.7058 2.7058 1.0000
3 8.4526 5.0000 1.0000
4 77.0045 5.0000 1.0000
5 1418.8820 5.0000 1.0000

The last column is 11 every time, because clipping changes how far the step goes and never which way it points, so it costs nothing in quality. It does nothing whatever for vanishing gradients, where the problem is that the number is already too small and scaling it up would amplify noise along with signal.

Truncated backpropagation

Unrolling a sequence of thousands of steps is expensive in memory and slow. Truncated backpropagation through time splits the sequence into fixed segments and backpropagates within each. A sequence of 50005000 samples becomes 5050 segments of 100100. The cost is plain. Any dependency spanning a segment boundary is invisible to training, and choosing the boundaries at sentence ends reduces the damage without removing it.

Truncation is therefore a concession, not a cure. It makes long sequences trainable by giving up on long dependencies, which were the reason for the recurrence in the first place.

Reading both ways

One more variant answers a limitation that has nothing to do with gradients. An RNN reads left to right, so hth_t summarises the past and knows nothing of the future, and for tagging a word that is often the wrong half of the sentence. A bidirectional RNN (Schuster and Paliwal 1997) runs two independent recurrences, one forward and one backward, then concatenates their states at each position so that every output sees the whole sentence.

Figure 12.4. A bidirectional recurrent network. One recurrence runs left to right and another right to left. The state at each position is the concatenation of the two, so it summarises the whole sentence, not only its prefix.

The restriction is obvious once stated. A bidirectional model cannot generate text, because the backward pass would need words that have not been produced yet, so it is for labelling instead of prediction. That distinction returns in Chapter 19, where BERT reads both ways and GPT reads one way, for this reason.

Run it. code/worked_examples/rnn.py produces every table in this chapter. --unroll prints the three-step trace, --params the two parameter tables, --vanish the decay table and the forty-seven step arithmetic, --clip the clipping demonstration with its unchanged directions, and --bptt the whole backward pass of this chapter together with the numerical check that it is right.

Run it

What the RNN did and did not buy

The window is gone. State carries an unbounded prefix, the parameter count no longer depends on sentence length, and the same three matrices serve a sentence of any size.

In exchange we inherited a new failure, and it is specific, since gradients decay geometrically with distance. The network therefore cannot be trained to use information from far back, even though it is perfectly capable of carrying it. Clipping handles one half and truncation manages the cost, while neither touches the vanishing case.

The repair has to be architectural. Multiplying by UU at every step is what destroys the gradient, so the state needs a path that does not pass through that multiplication. That path is a gate, and building one is the subject of Chapter 13.

Summary

A recurrent network reads a sentence one word at a time and carries a hidden state, so its window does not have a fixed width and its parameter count does not grow with the context. Unrolled in time it is a feed-forward network with shared weights, and backpropagation through time sums the per-step gradients of the shared parameters. The gradient reaching an early step is a product of Jacobians, which shrinks or grows geometrically with distance, so a network cannot be trained to use information from far back. Clipping rescales an exploding gradient and keeps its direction, and truncation limits the segment length, but neither cures vanishing. A bidirectional network reads both ways and suits tagging, not prediction. The failure that remains is the one the next chapter repairs.

Key terms

recurrent neural network. a network that updates a hidden state at each step from the previous state and the current input.

hidden state. the vector carrying a summary of the sequence so far.

backpropagation through time. backpropagation applied to the unrolled recurrence, summing the gradients of shared weights.

vanishing gradient. a gradient that shrinks geometrically with distance until it carries no signal.

exploding gradient. a gradient that grows geometrically with distance until training diverges.

gradient clipping. rescaling a gradient that exceeds a threshold while keeping its direction.

truncated backpropagation. splitting a long sequence into segments and backpropagating within each.

bidirectional RNN. two recurrent networks reading in opposite directions, with states concatenated.

Further reading.

Elman (1990) is the original recurrent network for language and remains the clearest short introduction. Rumelhart et al. (1986) introduced backpropagation, which backpropagation through time simply applies to an unrolled graph. Bengio et al. (1994) first proved that gradient descent cannot learn long-term dependencies in this architecture, and Pascanu et al. (2013) analyse both failures and propose clipping. Karpathy et al. (2015) inspect what a trained recurrent network actually stores in its state, and it is unusually readable. In a framework the recurrence of this chapter is torch.nn.RNN, which runs the same three lines over a whole batch of sequences at once. Graves (2014) shows what these models could already do with sequences.

Practice problems

12.1 Unroll by hand. Using the two by two matrices of this chapter, compute h1h_1, h2h_2 and h3h_3 for the sentence the dog ran and confirm the table. Then recompute with UU set to the zero matrix. What has the model become, and which chapter was it?

12.2 Count the parameters. For |V|=10,000|V| = 10{,}000, d=100d = 100 and H=500H = 500, confirm the total of 6,310,5006{,}310{,}500. Which matrix dominates, and what would you change first to shrink the model? Now find the context length at which a feed-forward WhW_h overtakes the recurrent UU.

12.3 Measure the decay. For per-step factors of 0.90.9 and 1.11.1, compute the gradient magnitude after 1010, 5050 and 100100 steps. At which distance does the 0.90.9 case fall below single precision, roughly 10−3810^{-38}? State what that means for a model trying to learn a dependency at that range.

12.4 Why tanh\tanh and not sigmoid. The sigmoid derivative is bounded by 0.250.25 and the tanh\tanh derivative by 11. Compute the gradient surviving 2020 steps under each bound. Then explain why tanh\tanh delays the vanishing problem without solving it.

12.5 Clipping preserves direction. Show from Equation (12.13) that the clipped gradient is a positive multiple of the original, so the cosine between them is 11. Then explain in one sentence why the same trick cannot rescue a vanishing gradient.

Build and measure

12.6 Check one gradient. Recompute the first entry of ∂ℒ/∂U\partial\mathcal{L}/\partial U from the tables of this chapter and confirm −0.1445-0.1445. Then add 0.0010.001 to that entry of UU, rerun the forward pass, and compare the change in the loss with 0.0010.001 times the gradient. Explain why the two agree better as the nudge shrinks.

12.7 Hand your weights to the library. Load this chapter’s WW, UU and bhb_h into a torch.nn.RNN with two inputs, two hidden units and tanh, feed it the three word sequence, and confirm that it returns h1=(0.3885,−0.0500)h_1 = (0.3885, -0.0500), h2=(0.0204,0.2518)h_2 = (0.0204, 0.2518) and h3=(−0.3511,0.1510)h_3 = (-0.3511, 0.1510). You will not get them on the first attempt, because the module holds two bias vectors where the equation above holds one. Find the second bias, say what it is for, and explain why leaving it at its initial value changes every state.

12.8 Predict the explosion. Before running anything, predict the gradient norm at step 11 of a 5050-step unrolled RNN whose recurrent matrix has largest singular value 1.21.2. Then measure it and compare. Repeat with 0.80.8 and say what the two runs show.

12.9 Clipping in practice. Train a small RNN language model on a corpus of your choice with and without gradient clipping at norm 55. Plot the loss and the gradient norm. Report how many steps the unclipped run survives, and what happens at the first spike.

In practice

12.10 The cost of truncation. A corpus is split into segments of 100100 tokens for truncated backpropagation. Describe a linguistic dependency that this makes unlearnable, and propose a segmentation rule that reduces the damage. What does your rule cost?

12.11 Which direction? A team wants to tag named entities in sentences and also to generate text. For each task, say whether a bidirectional RNN is appropriate and why.

12.12 The model that forgets. A user reports that a recurrent model forgets the subject of a long sentence by the time it reaches the verb. Say which mechanism of this chapter explains it, what you would measure to confirm it, and why neither clipping nor tanh\tanh repairs it.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.