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.
Chapter 11 fixed one blindness and left the other in plain sight. The feed-forward language model concatenates 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 has shape 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.
A recurrent neural network keeps a hidden state and rewrites it at every time step:
Here is the embedding of the word read at step , while is conventionally the zero vector. Nothing has been read before the first word, so the state starts empty.
Three matrices carry the whole model, where maps the current word into the state, maps the previous state into the new one, and maps the state to a score for every vocabulary word. The important word is same, because the same , and 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 was itself computed from and so on back to the first word. The state at step depends on every word read so far, so there is no window and no cliff.
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.
Read the sentence the dog ran, starting from .
| word | ||||
|---|---|---|---|---|
| 1 | the | |||
| 2 | dog | |||
| 3 | ran |
Follow the third row, whose input column depends only on ran while its depends on , which depended on , which depended on the. So is a summary of the whole prefix, nothing was thrown away, and no parameter was added to make room for it.
Why and not the sigmoid? The answer is short. is symmetric about the origin so its output is zero-centred, and states that average to zero train faster than states that average to . Its derivative is also steeper, since the sigmoid’s lies in while ’s lies in .
A derivative capped at shrinks the gradient by at least a factor of four at every step, and Section 12.5 shows why that is fatal, with 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, with small , exists to prevent that.
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 is the cross-entropy of Chapter 11 and the loss for a sentence is their sum:
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 has changed again.
The clearest argument for the recurrence is a table of shapes. Take , embeddings of size and hidden units, which are round numbers chosen for the example.
| matrix | shape | parameters |
|---|---|---|
| 1,000,000 | ||
| 50,000 | ||
| 250,000 | ||
| 5,000,000 | ||
| 500 | ||
| 10,000 | ||
| total | 6,310,500 |
Not one of those shapes mentions the length of the sentence. Compare the feed-forward model, whose has shape and therefore grows with every word of context admitted.
| context words | feed-forward | recurrent |
|---|---|---|
| 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.
Training needs gradients, and the loop has to be flattened before the chain rule can be applied. Unroll the network and a sentence of words becomes a feed-forward network layers deep, in which every layer shares the same weights.
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.
Give every intermediate quantity a name. At step the network computes
which is Equations (12.14) and (12.15) with the pre-activation and the vocabulary scores given names. The loss is Equation (12.1), where is the one-hot vector of the word that actually came next, so that and .
The aim is the derivative of with respect to , , , and , and also with respect to the input , which is how the embeddings learn. For a vector , the symbol is the vector of the same length whose th entry is . The quantities form a chain, running and into , then , then , then , then , and the method is to start at the loss and step back along that chain, taking one derivative per link.
Drop the subscript for the length of this subsection. The loss gives the first link directly, because means
The second link is the softmax, with . Every score appears in , so changing changes every , and the quotient rule gives two cases. When the numerator also depends on :
When only the denominator does:
Both cases fit one formula, , where the bracket is if and otherwise. The chain rule now adds up the effect of on the loss through every :
The last step uses , which holds because is one-hot. The division by in the first factor cancels the in the second, and that cancellation is why softmax and cross-entropy are always used together. Restoring the subscript,
Every other gradient in this section begins from this vector, which is prediction minus target. It is the same signal that drove Chapter 8.
The scores are , so , and . Multiplying each by gives the gradient for the weight as , the entry of an outer product:
The state reaches every score, so the error it receives is a sum over , , the th entry of
The nonlinearity acts on each entry separately, , so the derivative is a diagonal one. Writing out and applying the quotient rule,
so the derivative can be computed from the output alone, as . Let be the error at the pre-activation, . It is the error arriving at multiplied entry by entry by :
The last link is the linear map . Its derivatives are , , , and . These have the same shape as the output layer’s, so the results do too. The use of the matrices at step contributes to , to and to . Two errors also flow onwards, to the previous state and to the embedding of the word read at step .
Equation (12.4) gave the error that the output at step sends to , but has a second job. It is read by the output at step and also by the state at step , so it influences the loss along two routes. The chain rule adds the routes. The first is . The second runs through , and the error at is already , which by construction contains every later step, so pulling it back one link through gives . Together,
and substituting into Equation (12.5) gives the recursion that the whole algorithm turns on:
The last step has nothing after it, so the recursion starts from zero. It is evaluated backwards, first and last, and each carries its own step’s error together with, inside the second term, the error of every step that follows.
The same is used at every step, so it helps to imagine copies that happen to be equal. Each copy affects the loss only through its own , so the gradient for copy is the product found above. Changing the one shared 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:
with and . The embedding of the word read at step receives , and a word that occurs twice in a sentence receives two contributions. The gradients are simplest for a single step, where 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
which differ from each other only in the last factor, since and are the two things is built from. These are the first term of what Equation (12.8) adds up once the recursion is allowed to run.
Take the model of the unrolling example, with the output matrix 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.
| read | target | (the, dog, ran) | |||
|---|---|---|---|---|---|
| 1 | the | dog | 1.3461 | ||
| 2 | dog | ran | 1.0944 | ||
| 3 | ran | the | 1.3905 |
The loss is . Equation (12.2) now gives the error at the scores, prediction minus target, with the target’s entry carrying the minus sign:
| 1 | |
| 2 | |
| 3 |
The backward sweep of Equation (12.7) starts at step . At each step two errors meet at the state, one from its own output and one handed back by the step after it.
| sum | |||
|---|---|---|---|
| 3 | |||
| 2 | |||
| 1 |
Multiplying each sum entry by entry by gives the error at the pre-activation.
| 3 | ||
| 2 | ||
| 1 |
Look at step . Its own output contributes almost nothing, , yet is large, because step was wrong and sent its blame back through . 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 , the first entry is , and the other matrices follow the same pattern:
A derivation this long deserves a check that does not rely on it. Nudge one parameter by 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 , the rounding error to be expected. The derivation holds.
Gradient descent now moves each matrix against its gradient, with the learning rate of Chapter 8:
and likewise and , while the embedding row of the word read at step moves by . With , one such step takes the loss on this sentence from to . Because the same matrices serve every step, each is updated once per sequence, after the backward sweep has produced every . Unrolling Equation (12.7) multiplies in a fresh factor of for every step the error travels back, and the next section follows that repeated product to see what it does to the early steps.
Take an error at step and ask what it says about the state at step , where the chain rule gives one factor per step in between:
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:
So the product in Equation (12.11) behaves like raised to the power , with the derivative damping it at each step.
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 satisfies then the product shrinks towards zero and gradients vanish, while if any eigenvalue satisfies then the product grows without bound and gradients explode. The ideal is therefore , where the gradient neither vanishes nor explodes, and nothing in training holds the eigenvalues there.
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 | |||||
|---|---|---|---|---|---|
| 1 | 1.00 | 1.10 | 1.20 | ||
| 5 | 1.00 | 1.61 | 2.49 | ||
| 10 | 1.00 | 2.59 | 6.19 | ||
| 20 | 1.00 | 6.73 | |||
| 47 | 1.00 | ||||
| 100 | 1.00 |
Notice how mild the failing factor is, because a per-step multiplier of looks harmless and yet after fifty steps it has removed more than per cent of the signal.
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 words, so the evidence is words behind the gap. The model steps over tokens, and punctuation marks and the split of start-up add several more, so call it steps as a round upper figure. Here is what reaches back that far.
A gradient of 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.
The two failures are not equally hard, and one of them has a cheap fix. The other needs a change of architecture.
Exploding gradients have a short remedy. If the gradient is longer than a threshold, rescale it while keeping its direction:
| step | before | 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 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.
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 samples becomes segments of . 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.
One more variant answers a limitation that has nothing to do with gradients. An RNN reads left to right, so 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.
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.pyproduces every table in this chapter.--unrollprints the three-step trace,--paramsthe two parameter tables,--vanishthe decay table and the forty-seven step arithmetic,--clipthe clipping demonstration with its unchanged directions, and--bpttthe whole backward pass of this chapter together with the numerical check that it is right.
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 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.
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.
12.1 Unroll by hand. Using the two by two matrices of this chapter, compute , and for the sentence the dog ran and confirm the table. Then recompute with set to the zero matrix. What has the model become, and which chapter was it?
12.2 Count the parameters. For , and , confirm the total of . Which matrix dominates, and what would you change first to shrink the model? Now find the context length at which a feed-forward overtakes the recurrent .
12.3 Measure the decay. For per-step factors of and , compute the gradient magnitude after , and steps. At which distance does the case fall below single precision, roughly ? State what that means for a model trying to learn a dependency at that range.
12.4 Why and not sigmoid. The sigmoid derivative is bounded by and the derivative by . Compute the gradient surviving steps under each bound. Then explain why 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 . 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 from the tables of this chapter and confirm . Then add to that entry of , rerun the forward pass, and compare the change in the loss with 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
,
and
into a torch.nn.RNN with two inputs, two hidden units and
tanh, feed it the three word sequence, and confirm that it
returns
,
and
.
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 of a -step unrolled RNN whose recurrent matrix has largest singular value . Then measure it and compare. Repeat with 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 . 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 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 repairs it.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
rnn.pyUnrolling, and the vanishing gradient
What unrolling does to the parameter count, and what it does to the gradient.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.