Why order matters
"Dog bites man" and "Man bites dog" use the same three words. How can a machine that reads them tell which story it is?
Two newspaper headlines. "Dog bites man." Nobody cares. "Man bites dog." Front page!
Both use the same three words. Only the order is different — and the order is the whole story. A machine that reads must notice the order.
In Unit 16 every word became a list of numbers. So how do we turn a whole sentence into numbers? Here are three ideas. The first two fail, and how they fail tells us what we need.
Idea 1 · Throw the words in a bag. Add up the word vectors, or just count the words. People call this a bag of words. It is quick. But "dog bites man" and "man bites dog" have exactly the same bag: one "dog", one "bites", one "man". The sums are the same. The order is lost.
Idea 2 · Look at the last few words. Keep a small window, say the last 3 words. This is what the neural language model of Unit 16 did: it saw only a fixed window of the words just before. A window keeps local order, but it forgets everything older. Take the announcement "The train to Delhi from platform four is late". When "late" arrives, a 3-word window holds only "four is late". What is late? The word "train" has already dropped out.
Idea 3 · Read one word at a time and keep a running note. Think of a shopkeeper with a notebook. After each customer, he updates one line. But a plain running total does not care about order either: 5 + 3 is the same as 3 + 5. So we add one twist. Before writing in the new word, we first change the old note a little — turn it, shrink it — with a matrix. Then an old word has been turned many times and a new word only once. The order leaves its mark.
A tiny example. Give each word a toy vector (hand-made, not trained): , , . The note starts at . At each word we do two things: turn the note a quarter turn with , then add the word. A quarter turn sends to .
- dog bites man: after "dog" the note is . Turn it: ; add "bites": . Turn it: ; add "man": .
- man bites dog: after "man", . Turn: ; add "bites": . Turn: ; add "dog": .
Two different notes: and . Without the turn, both would end at the plain sum . The turn is what makes the note remember order.
Unfold the rule over three words. The note ends as . Every position wears its own stamp: the last word goes in as it is, the one before is turned once, the first is turned twice. Swap two words and they trade stamps, so the note changes.
A plain sum gives every word the same stamp — no turn at all. That is exactly why it cannot see order.
A bag of words forgets order. A window forgets the past. A running note keeps both, if it changes the old note before adding the new word. Every word leaves its mark, and older marks have been changed more times.
The three readers side by side.
| sees word order? | remembers far back? | size of the summary | |
|---|---|---|---|
| bag of words | no | yes — every word counts, but order is gone | fixed |
| window of k words | only inside the window | no — only the last k words | fixed |
| running note | yes | yes, if old marks do not fade (§7) | fixed |
Rule of thumb. If the question is "which words appear?" (is this review about food or about service?), a bag is often enough. If the question is "who did what to whom?", you need a reader that keeps order — a running note.
A running total is still a bag. Adding numbers does not care about order, so "keep a sum of the words" loses order just as badly as counting them. The note only remembers order because the old note is changed (turned, shrunk) before each new word is added.
With a plain bag of words (just count the words), which pair of sentences looks different?
Use the same rule (quarter turn, then add) and the same toy vectors. What is the note after reading "bites dog" (just these two words)?
Change the turn to a half turn, 180°, which sends to . Can this reader still tell "dog bites man" from "man bites dog"?
The road ahead. The unit has five acts.
- Why a reader needs memory (§1–§3): order, the recurrent cell, and the same cell copied along time.
- A cell that talks (§4–§5): the many jobs one cell can do, and a small language model that learns to write, one character at a time.
- Blame through time (§6–§8): training sends blame back through every word; it is multiplied by the same matrix again and again, so eigenvalues decide whether memory fades or explodes; then first aid.
- Gates, and reading both ways (§9–§11): the LSTM's express lane, the GRU's blend dial, and readers that read in both directions or in floors.
- Translating through one summary (§12–§14): an encoder–decoder that turns English into Hindi, how it picks and grades its words, and the bottleneck that Unit 18 removes.
In one sentence: A sentence is an ordered list, so a reader must keep a running note and change the old note before adding each new word — a bag or a plain total would give "dog bites man" and "man bites dog" the same note.
The recurrent cell: one small machine, used again and again
What exactly happens inside the machine each time it reads one more word?
You sit in a long lecture with one small card for notes. After each new sentence from the teacher, you rewrite the card: keep some of what was there, add the new point, and squeeze it so it still fits on the card.
The card never grows. It can never hold everything, so you must choose what to keep. You use the same habit every time. That habit is the recurrent cell. The card is its memory.
Now we make the running note a real network part. The note is a list of numbers called the hidden state, — "the card after word ". At each word the cell does one small job:
Read it aloud, from the inside out. : take the old card and rewrite it — the matrix decides how each old number is carried over, mixed or shrunk. : write the new word in — the matrix decides where on the card each part of the word goes. : a small shift, as in every layer of Unit 15. And : squeeze every number to between −1 and 1, so the note never overflows the card. It is the bend of Unit 15.
The most important fact: , and are the same at every word. The cell does not grow a new set of weights for word 7. One small machine reads a sentence of any length.
A tiny example with one number. Let the note be a single number. Take , , , start with , and feed three inputs — one real word, then two blanks.
Watch the first word fade. Each step keeps half of the note (), and tanh squeezes it a little more. After three steps only 0.18 is left of the 0.76. Keep this in mind — it is the seed of the whole unit.
The note goes back into the cell, so the note after word 5 was built from the note after word 4, which was built from the note after word 3, and so on. That makes a summary of all five words, in order — without the cell ever looking at more than one word at a time. Training (§6) then tunes and so that the summary keeps what later guesses will need.
A recurrent cell is one layer of Unit 15 with a second input: its own note from one word ago. The same weights are used at every word. The note is the memory — and with , what an old word wrote there fades a little at every step.
The note is not a list of the words read so far. It is a fixed-size summary. A note of 4 numbers has 4 numbers after 3 words and still 4 numbers after 300 words. Something must be squeezed out — and the network has to learn what to keep.
Same cell, but : , , , inputs . What is ?
A recurrent cell reads a 100-word review. How many different matrices does it use?
If you want the algebra · 2 proofs, step by step
Claim. always lies strictly between −1 and 1, and its slope is , which is at most 1 (reached only at ).
Claim. For the scalar cell with , : . If every number stays small (so ), then .
In one sentence: A recurrent cell rewrites one fixed-size card at every word, , with the same weights each time — and with a small the first word fades: 0.7616, 0.3634, 0.1797.
Unrolling: the loop is a chain of twins
A 5-word sentence and a 500-word story: does the network need a bigger brain for the longer one?
A dabbawala carries a lunch box from station to station. Film him, and print one photo at every station. Lay the photos in a row. It looks like a long chain of dabbawalas passing the box along.
But it is one man, doing the same job again and again. The chain is just the loop, laid out in time.
We often draw the recurrent cell as one box with a loop arrow: its note goes out and comes straight back in. That is compact, but hard to reason about. So we unroll it: draw one copy of the box for every word, and turn the loop into an arrow from each copy to the next.
For a three-word sentence the unrolled picture is
with the words coming in from below. Look at it and you see an old friend: a deep network from Unit 15, three layers deep. There is one difference. In Unit 15 every layer had its own matrix. Here every "layer" uses the same , and . We say the weights are shared (or tied).
Count the numbers it learns. Say the note has numbers and each word has . Then is , is and has entries, so
With and : . For a 3-word sentence: 32. For a 3000-word book: still 32. The unrolled chain gets longer; the list of weights does not.
Because the rules of a language do not depend on where you are in the sentence. "A describing word comes before its noun" is as true at word 3 as at word 300. With shared weights, whatever the cell learns at one position works at every position, so every sentence it reads teaches the same small machine many times over. And it can read a sentence longer than any it saw in training: it just runs the same step more times.
A recurrent network is a loop. Unroll it and it is a chain as long as the sentence, one copy of the cell per word. So everything we learned about deep networks — forward pass, backward pass, blame that fades — carries over. The only new twist is that the copies are twins.
Unrolling does not make copies of the weights. The boxes in the picture are one cell drawn once per word. Change and every box changes at once. That is why, in training, the blame for is collected from every box and added up (§6).
A cell has a note of numbers and reads words of numbers. It reads a 50-word sentence. How many weights and shifts does it learn?
A recurrent network was trained only on sentences of 10 words. Now it is given a 25-word sentence. What happens?
If you want the algebra · 1 proof, step by step
Claim. A recurrent cell with note size and word size learns numbers, whatever the number of words . Without sharing, the -step chain would need times as many.
In one sentence: Unrolled, a recurrent cell is a deep network as long as the sentence whose layers are twins, so it learns only numbers — 32 for , — whether it reads 3 words or 3000.
Many jobs, one cell
The cell only reads. How do we make it say something — a label, a tag for every word, a caption, the next word?
One pen can write very different things: a caption under a photo, a single word on a review ("great!"), a label on each item of a list, or a full letter in another language.
The recurrent cell is that pen. What changes is only where the inputs go in and where we read the answers out.
So far the cell only reads. To make it say something, we add a read-out layer. At any word we can turn the note into scores and then into probabilities with softmax (Unit 14):
Read it aloud: "look at the card, give every possible answer a score, turn the scores into shares that add up to 1." Where we put inputs and read-outs gives the four classic shapes:
- Many → one. Read a whole review, then read out once at the end: happy or unhappy. (Sentiment.)
- One → many. Give it one input — a photo's vector — and let it write a caption word by word.
- Many → many, same length. Read out at every word: tag each word as a noun, a verb or other.
- Many → many, different length. Read a whole English sentence, then write a Hindi one. This needs two cells, and it is §12.
And one favourite: the language model. At every word, guess the next word. This is the neural language model of Unit 16, but now the note carries all earlier words, not just a fixed window.
A tiny example. After reading "the train to", the read-out gives the scores Delhi 2, Mumbai 1, late 0.5, the −1. Softmax turns them into probabilities: , , , , total . So Delhi gets , Mumbai , late , the . If the true next word is "Delhi", this step's loss is — the surprise of Unit 14. The loss for the whole sentence is the sum of these, one per word.
The note is a summary of everything read up to word . So any question about that part of the sentence can be answered from it by one small read-out layer.
Which job the cell learns is decided by where we attach the loss. Training only rewards the note for what the read-outs are asked. Ask once, at the end (sentiment), and the note learns to carry the gist all the way to the end. Ask at every word (tagging, next word), and it learns to keep what each word needs right then.
One cell, many jobs. Feed inputs at one step or at every step; read out at the end or at every step. When we read out at every step, each step adds its own surprise to the loss, and the total is what training makes small.
"Many → many" comes in two kinds, and they need different machines. Tagging gives one answer per input word, at the same position — one cell is enough. Translating writes a sentence of a different length, in a different order — it needs a reader and a separate writer (§12).
You want to read a customer's 40-word complaint and decide one thing: is it about delivery, price or quality? Which shape, and how many read-outs?
The read-out after "the train to" gives Delhi 0.609, Mumbai 0.224, late 0.136, the 0.030. The true next word is "Mumbai". What is this step's loss?
If you want the algebra · 1 proof, step by step
Claim. With , and , the blame at each read-out is (one-hot truth), and .
In one sentence: Put inputs in and read outputs out at one step or at every step, and the same cell can caption, judge, tag, translate or guess the next word — with the total loss the sum of each step's surprise.
An RNN language model: learning to talk, then talking
Your phone suggests the next word while you type. Could a machine write a whole sentence that way — and why does it so often get stuck repeating itself?
Open the keyboard on your phone, type "the train to", and keep tapping the middle suggestion. The phone writes a whole sentence by itself. Very often it gets stuck, repeating the same phrase again and again.
You have just watched a language model talk. It guesses one word, then listens to what it just said, and guesses the next. A machine that talks by listening to itself.
In §4 the read-out at every word guessed the next word. That is a language model. We use it in two ways: first to learn, then to talk.
1 · Learning to talk (training). Take a real sentence. At every position the cell reads the true words so far and guesses the next one. The true next word is the target. The step's loss is its surprise, , and the sentence's loss is the sum of the surprises. One detail matters a lot: at every step we feed in the true previous word — even when the model's own guess was wrong. This is called teacher forcing. It works like training wheels: it keeps the learner on the road while it learns.
2 · Talking (generating). Now there is no true sentence. Start from a few words — the seed. The read-out gives its probabilities; pick one word; feed that word back in as the next input; guess again. Repeat until the model writes a full stop.
3 · Which word to pick? Greedy: always take the top word. Safe, but dull — it tends to fall into a loop. Or sample: roll a die whose sides are weighted by the probabilities. A dial called the temperature makes the die bolder or tamer. Divide every score by before the softmax:
Read it aloud: "divide each score by the temperature, then softmax as usual." A small stretches the gaps between the scores, so the favourite takes even more. A big shrinks the gaps, so the long shots get a chance.
A tiny example. Take §4's scores after "the train to": Delhi 2, Mumbai 1, late 0.5, the −1.
- : the scores stay as they are: 0.609, 0.224, 0.136, 0.030.
- : the scores double to 4, 2, 1, −2: 0.842, 0.114, 0.042, 0.002. Bold and repetitive — Delhi nearly every time.
- : the scores halve to 1, 0.5, 0.25, −0.5: 0.434, 0.263, 0.205, 0.097. Adventurous — and "the train to the" now comes up about one time in ten.
| how to pick | what it does | how it writes | use it for |
|---|---|---|---|
| greedy | always the top word | safe, flat, often loops | short, exact answers |
| sample, T < 1 | favourite gets even more | bold, a little repetitive | factual text with some variety |
| sample, T = 1 | the model's own odds | as varied as its training text | faithful imitation |
| sample, T > 1 | long shots get a chance | adventurous, makes mistakes | brainstorming, surprise |
Everything written so far — the seed and the model's own words — has been folded into the note, one character at a time. So every guess is made with the whole text so far in mind, and training has tuned those guesses to match real text. Writing is nothing more than guessing the next character, again and again, and believing your own guesses.
A language model learns with the true text fed in (teacher forcing) and talks by feeding back its own picks. Greedy picking is dull and loops; sampling with a temperature trades safety for variety.
While training, the cell only ever saw true text. While talking, it sees its own guesses — including its mistakes — and it never practised recovering from one. So one early slip can snowball. To see it, pretend the model had slipped and written "trian" instead of "train": give it the seed "the trian to", and it carries on with "buny misun" — words that are in none of its 300 sentences. This mismatch between training and talking is called exposure bias.
Scores Delhi 2, Mumbai 1, late 0.5, the −1. At temperature , what probability does Delhi get?
You turn the temperature down, closer and closer to 0. What does sampling turn into?
A model is being trained on "the train to pune is late." At the 5th character it guesses "u" instead of "t". Under teacher forcing, what is fed in at the next step — and what would be fed in if the model were talking?
If you want the algebra · 2 proofs, step by step
Claim. With , the ratio of two shares is . So the order of the words never changes; as the top word takes everything (greedy), and as every share tends to (a fair die).
Claim. For a text , the teacher-forcing loss equals . So making small is exactly maximum likelihood (Unit 14).
In one sentence: A recurrent language model learns by guessing each next word with the true text fed in (teacher forcing) and talks by feeding back its own picks — greedy loops, and a temperature in turns the same scores 2, 1, 0.5, −1 into 0.842 of the time "Delhi" at or only 0.434 at .
Backprop through time: blame walks back along the words
The model guessed the last word wrong. How much of that is the fault of the way it handled word 1, word 2, word 3…?
A relay team loses the race. The coach starts at the finish line and walks back along the track, asking each runner: "How much of the delay was yours?"
Every runner here is the same person — our one cell, used at every word. So when the coach adds up the blame for that one person, he adds it from every leg of the race.
An unrolled cell is a deep network (§3), so we train it exactly as in Unit 15: a forward pass that stores every note, then a backward pass with the same two rules. We just walk back along time instead of along layers. People call this backpropagation through time, or BPTT.
- Rule A, at every tanh. Multiply the incoming blame by the slope of tanh, which is (you stored on the way forward).
- Rule B, at every . Blame for the old note: multiply by . Blame for the weight: blame times the note that came in, .
- The new twist: add up. The same is used at every step. So its gradient is the sum of what each step reports.
A tiny example. Take §2's cell (, inputs , notes ). How much does a small nudge to move ? Walk back one step at a time. Each step is "slope of tanh times ":
A nudge to the first note reaches the third note at only about a fifth of its size. The blame going back shrinks the same way. That is the first word's voice fading — now seen from the backward side.
Every word casts a vote. Look at the last card of the step machine. The copy of the cell at word 4 says "make bigger by this much", the copy at word 3 says its own amount, and so on. Because all the copies are one cell (§3), the one weight hears every vote and adds them up. A word near the end, where the blame is still loud, votes loudly; a word far back votes in a whisper.
With a real note, each step is a matrix. When the note is a list of numbers, one step back multiplies the blame by a matrix, not a number. Going forward, a small nudge to changes by times that nudge (the Jacobian of Unit 6): first mixes the nudge, then each entry is scaled by its own tanh slope. So the blame reaching word from word is a product of such matrices — and every one of them contains the same . Keep that sentence in mind: it is the whole of §7.
Truncated BPTT: cut the walk short. A novel has 100 000 words. Storing every note and walking the blame back through all of them for every update is far too slow. So in practice we cut the text into chunks of words — say — and walk the blame back only inside a chunk. A 1 000-word text with becomes 50 chunks. The note still flows forward from one chunk into the next, so the model can still use old words. But no blame crosses a cut, so the model can never learn a link between two words more than apart.
| blame walks back | cost per update | links it can learn | |
|---|---|---|---|
| full BPTT | to the first word | grows with the whole text | any distance (if the blame survives, §7) |
| truncated, k words | back to the last cut | about k steps, fixed | at most k words apart |
Rule of thumb. Choose a little longer than the longest link you need the model to learn — a sentence or two — and no longer than your memory allows.
An unrolled RNN is just a very deep network in disguise, so the chain rule of Unit 15 needs no new ideas: blame multiplies along the chain, and a shared weight adds up its blame from every place it was used. The only new facts are about time: the chain is as long as the text, and every link in it contains the same matrix.
Backprop through time is Unit 15's backward pass on the unrolled chain. The shared weight collects blame from every step, added up. The blame reaching an early word is a product of one factor per step, each containing the same — so if each factor shrinks things, the product shrinks fast.
Truncating the blame does not truncate the memory. The note is carried forward across every cut, so word 45 can still feel word 5. What is lost is only the training signal: the model gets no blame telling it how word 5 should have helped word 45.
Suppose every step's factor is exactly 0.5. How much of a nudge to reaches ?
In the step machine, the copies of the cell at words 2, 3 and 4 report , and for ; word 1 reports 0. The four copies are one cell. What is ?
A 1 000-word text is trained with truncated BPTT, chunks of words (1–20, 21–40, 41–60, …). Can training learn that word 5 should change the guess at word 45?
If you want the algebra · 4 proofs, step by step
Claim. For , : .
Claim. .
Claim. For : , and the blame moves back as .
Claim. Cutting a text of words into chunks of words gives chunks, and the blame from word reaches back at most to the first word of its chunk, words earlier. For , : 50 chunks, and word 45's blame stops at word 41.
In one sentence: Backprop through time runs Rule A and Rule B back along the unrolled chain, adds up the shared weight's votes from every step, and multiplies one factor per step on the way back — 0.4838 × 0.4340 ≈ 0.21 here — while truncated BPTT cuts that walk into chunks of words (50 chunks for 1 000 words and ).
Why memory fades or explodes
Why can a plain recurrent network remember the last few words but not something from twenty words ago?
Ten children stand in a line and play the whisper game. The teacher whispers a word to the first child, and each child passes on what they heard. Suppose every child speaks at exactly half the loudness they heard. That is ten halvings, so the tenth child says the word about a thousand times more quietly than the teacher did. Nobody hears it.
Now suppose every child speaks one and a half times louder. By the tenth child it is a shout, 58 times the start. Only a line where everyone speaks exactly as loud as they heard keeps the word alive. A recurrent network's memory and its blame both travel down such a line.
Strip the cell down to its loop: no tanh, no new words, just . Every step is one child in the line, passing on times what it heard. After steps,
The same power shows up forward (how much of the first word is left) and backward (how much blame reaches it). Put in numbers for :
- : . Less than a thousandth is left. The memory has faded.
- : . The blame is 58 times too big. It has exploded.
- : . Held steady — the knife edge.
Powers are ruthless. A number a little below 1 goes to 0; a little above 1 runs away. After 20 steps, leaves and gives . After 50 steps even leaves , and gives about 117.
Why this matters. Read "The keys to the old wooden cabinet in the hall are …". The verb must be "are", not "is", because of "keys" — nine words back. To learn that, the blame from "are" must travel back nine steps to "keys". If each step passes on half, only of it arrives. The network never finds out that "keys" was the word that mattered.
Now with a real note: a matrix. When the note is a list of numbers, the loop is , so . Powers of a matrix. How do we see where those go? With the eigenvectors of Unit 4: the special directions that only stretches, never turns. Along an eigenvector with eigenvalue , each step just multiplies by — back to the one-number whisper line.
A tiny example: . Its eigenvalues are and (check: they add to the trace and multiply to the determinant ). The directions are for and for .
Start the note at . Split it along the two directions: . Now every step keeps the first part whole and halves the second:
After one step, ; after two, ; after ten, almost exactly . The part along the direction survives. The part along the direction halves every step and is gone. So a matrix is a bundle of whisper lines, one per eigen-direction, each with its own loudness factor .
That gives the rule: look at the biggest eigenvalue size, (people call it the spectral radius). Below 1, everything fades. Above 1, something explodes. Backward, the blame is multiplied at each step by the transpose (rows and columns swapped) — and has the same eigenvalues as , so the same verdict holds for the blame. And the tanh slope is never more than 1, so it can only add fading.
| biggest |λ| | forward: the note | backward: the blame | what helps |
|---|---|---|---|
| below 1 | old words fade away | vanishes before it reaches early words | gates: an express lane (§9, §10) |
| exactly 1 | kept along that direction | reaches back at full size | the knife edge gates try to hold |
| above 1 | grows until tanh flattens it | explodes while the note is small, and training jumps wildly (once tanh has squeezed the note flat, the blame fades instead) | clip the gradient, start near 1 (§8) |
Split the note along the eigen-directions and the matrix stops mixing: each part is multiplied by its own at every step, exactly like one child in the whisper line. After many steps, the part with the biggest outgrows or outlasts all the others. That is why one number — the spectral radius — decides the fate of both the memory and the blame.
The gradient through time carries powers of one matrix. So its eigenvalues decide: along each eigen-direction, memory is multiplied by at every step. Below 1 it fades away, above 1 it blows up, and only exactly 1 holds on. This is the central fact of recurrent networks.
Small entries do not mean fading. Every entry of is below 1, yet one eigenvalue is exactly 1 and part of its memory never fades. And a matrix with big entries can still fade. Look at the eigenvalues, not the entries.
A one-number loop has . After how many steps is the memory first below one thousandth ()?
and the note starts at . What happens over many steps?
In the eigen-memory widget, load rotate. Its matrix turns the note by about 37° each step without stretching it. What are the sizes of its eigenvalues, and what does the note's length do?
Every entry of is smaller than 1. Start the note at and multiply by again and again. Where does the note end up?
If you want the algebra · 3 proofs, step by step
Claim. If , and , then . For , : .
Claim. For the scalar cell, . So if the blame fades at least as fast as . For a vector note the same holds with the largest stretch of in place of .
Claim. with has eigenvalues , of size , and for every . For the rotate preset, , , .
In one sentence: Memory and blame pass down a whisper line that multiplies by the same matrix at every step, so after steps they carry — and the biggest eigenvalue size decides whether they fade (0.5¹⁰ ≈ 0.000977) or explode (1.5¹⁰ ≈ 57.67).
First aid for explosions: clip the gradient, start at the right volume
If the blame can explode, one bad step can undo hours of training. What stops that from happening?
School buses in India carry a speed governor. The driver can press the pedal as hard as he likes; the bus will not go faster than the limit. It still goes where he steers — only not at a crazy speed.
Gradient clipping is a speed governor for training.
When blame explodes, the gradient can become enormous for a single step. Picture the loss as a landscape: mostly gentle slopes, but here and there a cliff — a sudden wall where the loss jumps. That wall is what exploding powers of look like. Touch the edge of the cliff and the slope is huge. A plain step (Unit 9) then throws the weights far away, and all the progress so far is lost.
The fix is simple. Pick a limit . If the gradient is longer than , shrink it to length and keep its direction:
Read it aloud: "divide the arrow by its own length, so it has length 1, then stretch it to length ." A tiny example. , so . With : . Same direction, length 5. A gradient like , of length 3, is shorter than 5 and passes through untouched.
Clipping only helps with explosions. It cannot help with fading: if the blame reaching word 1 is , there is no signal left to rescue. For fading we need a new design — that is §9.
Start at the right volume. The whisper line also tells us how to set up before training begins. If is orthogonal — a pure turn or mirror, one of the "motions that don't lie" of Unit 3 — it never changes the length of any note. All its eigenvalues then have size exactly 1: the whisper starts at normal volume, neither fading nor exploding, and training can move it from there. So a common start is a random orthogonal , or even , the identity ("copy the old note"). The talking model of §5 was started at times an orthogonal matrix — every , just under the knife edge.
An explosion is a long gradient, and a long gradient is dangerous only because of its length: the direction still points downhill. Clipping keeps the useful part (the direction) and throws away the dangerous part (the length). A good start helps from the other side: with every near 1, there is little to explode or to fade in the first place.
Clipping keeps the direction of the gradient and caps its length. One exploding step can no longer throw training off a cliff. It is cheap first aid for explosions — and no cure for fading.
Do not clip each entry on its own. Capping every entry of at 5 gives , which points at 45° instead of the gradient's 53.13° — you are now walking a different way. Clip the whole arrow by one factor: still points at 53.13°.
The gradient is and the limit is . What is the clipped gradient?
In a plain recurrent network, the blame reaching word 1 of a long text is about . You switch on clipping with . What happens to that blame?
If you want the algebra · 2 proofs, step by step
Claim. The clipped gradient points the same way as , has length , and the step is never longer than . It is still a downhill direction.
Claim. If , then for every , and every eigenvalue of has size . So has every .
In one sentence: When the gradient is longer than a limit , shrink it to length without turning it — becomes — and start with every near 1; this tames explosions but cannot rescue memory that has faded.
The LSTM: a memory with an express lane
If every step multiplies the memory by a number below 1, how can a network ever carry a word across fifty steps?
A shopkeeper's ledger — the bahi-khata — passes from day to day. Each evening he makes three small choices. With an eraser: what to rub out. With a pen: what to write in. And at the window: what to read out to the customer.
The ledger itself is never torn up and rewritten. It rides from day to day almost untouched. That is the LSTM's secret.
Why does the plain cell forget? At every step its whole note is multiplied by and squeezed by tanh — the whisper line of §7. There is no way to carry a number along unchanged. So in 1997 Hochreiter and Schmidhuber added a second note that runs along the top: the cell state . People call the whole design LSTM, "long short-term memory". (The eraser below, the forget gate, came three years later, from Gers, Schmidhuber and Cummins.) Think of the cell state as an express lane: at each step only two gentle things happen to it.
First, three gates are computed. A gate is a list of numbers between 0 and 1, made with a sigmoid (Unit 15). 0 means "shut", 1 means "wide open". Each gate looks at the new word and the last note:
- the forget gate — the eraser: how much of the old cell state to keep;
- the input gate — the pen: how much of the new candidate to write in;
- the output gate — the window: how much of the cell state to show as the note.
The candidate is what the pen would write. Then:
Read the first line aloud: "keep the part of the old ledger the eraser allows, and add the part of the draft the pen allows." The second: "show the ledger through the window, squeezed." The symbol just means "multiply entry by entry". Each gate has its own weights, like a small layer: , and the same shape for , and (with tanh for ).
A tiny example. Forget gate , old cell state , input gate , candidate :
We erased a tenth, then wrote in a little. With the window fully open (), the note is .
The full step, from the weights. In a real cell nobody sets the gates by hand: each gate adds up its weighted inputs into a score, then squeezes it. Take a one-number LSTM with , , input , and weights that give the four scores , , , :
Notice is bigger than 1: nothing squeezes the ledger itself. Only the note is squeezed, on its way out through the window.
Why the express lane saves the blame. Look at how the cell state moves from one step to the next: Along this lane there is no to multiply by, and no tanh to squeeze. So walking back along the lane, the blame is multiplied by just at each step (§6's product, with a much kinder factor):
With for ten steps: . Compare the plain cell with : . The express lane carries about 350 times more blame back to the start.
Be honest, though: a gate of 0.9 still fades over long distances. After 50 steps, . What saves the LSTM is that the network chooses at every word. When it needs to remember, it learns to hold very close to 1: . And when it wants to forget — at a full stop, say — it can drop to 0 and wipe the slate.
Start with the lane open. At the start of training all weights are small, so every gate score is near 0 and every gate near . A forget gate of 0.5 is the whisper line again: . So people start the forget gate's shift at 1 or 2. Then begins near or , and of the blame survives ten steps instead of a thousandth.
This idea — a lane where the signal is added to, never rewritten — is worth remembering. It returns in Unit 18 as the residual path of every transformer block.
The plain cell must rewrite its whole note at every word, and every rewrite multiplies by . The LSTM does not rewrite its ledger: it only erases a little () and adds a little (). Adding does not shrink the blame on its way back, and the erasing is a number the network chooses — so when it matters, the network can keep near 1 and hear a word from fifty steps away.
The LSTM keeps a second memory on an express lane. Nothing multiplies it by or squeezes it — only the forget gate scales it and the input gate adds to it. So blame travels back along the lane multiplied only by , which the network can hold near 1 for as long as it needs to remember.
The "forget gate" is really a keep gate. means "keep everything", and means "forget everything". Read it as "how much of the old ledger survives" and you will never get the sign of the story backwards.
One LSTM step: , , , . What is the new cell state ?
Along the express lane the forget gate stays at . How much blame reaches a word 20 steps back?
In the memory lab, keep the filler noise at 0.5, press honest LSTM (f = 0.9) and look at the accuracy curves at 50 words. What do you see?
At the start of training every gate score is near 0. If the forget gate's shift starts at , about how much blame survives 10 steps along the lane? And with ?
If you want the algebra · 2 proofs, step by step
Claim. If the gates do not depend on (as in the memory lab), then . In a full LSTM this product is the direct path along the lane; other paths go through and and fade like a plain cell's.
Claim. With : . What word wrote is still there, scaled by the forget gates after it.
In one sentence: The LSTM carries a cell state on an express lane, — 0.8808 · 1 + 0.5 · 0.7616 = 1.2616 in the full step — so blame flows back multiplied only by the forget gate, instead of , and a forget shift of 1–2 starts that lane open.
The GRU: a lighter cousin with one blend dial
Does an express lane really need a separate tank and three gates — or can one dial do the job?
A chaiwala keeps one big pot on the stove all day. Every hour he pours in some fresh tea. A little fresh, and the pot tastes much as before. A lot fresh, and the old taste is gone.
How much fresh tea to pour — that is one dial. The GRU is built around this dial.
In 2014 Cho and colleagues asked: can we keep the express lane with fewer parts? Their GRU ("gated recurrent unit") drops the separate cell state. It keeps one note and two gates:
- the update gate — the dial: how much new to pour in;
- the reset gate — how much of the old note to consult while drafting the new one.
Read the first line aloud: "draft a fresh note from the new word and the part of the old note the reset gate lets you look at." The second line is a blend: part old note, part fresh draft, with the dial between 0 and 1. When is near 0, the old note passes straight through — the express lane again, now multiplied by at each step. The reset gate is how a GRU starts a new thought: with near 0 the draft ignores the old note, as if the sentence had just begun.
A tiny example. Old note , candidate , dial :
Three quarters old, one quarter new. And since it is a blend, the new note always lies between the old note and the candidate.
The full step, from the weights. A one-number GRU with and input . The update score is 0 and the reset score is 2, so and . The draft uses weight 1 on the word and 1 on the consulted old note:
What do the gates cost? Each gate, and each candidate, is a small layer of its own: a matrix for the old note (), a matrix for the word () and a shift (). That is numbers — exactly a plain cell's worth. A plain cell has one such block, a GRU has three (, , the candidate), an LSTM four (, , , ).
For a note of numbers and words of numbers: one block is . So a plain cell has 24 704 numbers to learn, a GRU , and an LSTM .
Plain, GRU or LSTM?
| plain cell | GRU | LSTM | |
|---|---|---|---|
| gates | none | 2: update , reset | 3: forget , input , output |
| memories | one note | one note | note + ledger |
| numbers (h = 128, d = 64) | 24 704 | 74 112 | 98 816 |
| blame along the lane | : fades | : can stay near 1 | : can stay near 1 |
| choose it when | short patterns, speed | you want gates at ¾ of the cost | long, complex sequences |
Rule of thumb. On most tasks the GRU and the LSTM do about equally well; try the GRU first when data or memory is short, the LSTM when the sequences are long and rich. The plain cell is best kept for short memories — and for understanding the other two.
A blend never has to shrink what it keeps: with near 0 the old note is copied almost exactly, so both the memory and the blame ride along at per step. The GRU simply merges the LSTM's eraser and pen into one dial — whatever is not kept is replaced — and that turns out to be enough.
A GRU is one blend dial: keep the old note, or pour in the new. With near 0 the old note rides straight through — an express lane without a separate tank. It learns three blocks of weights where an LSTM learns four and a plain cell one.
Check which way the dial turns. On this page near 0 means "keep the old note" and near 1 means "replace it". Some books and code libraries swap the roles of and . The idea is the same; read which one multiplies the old note before you compute.
A GRU step with , old note and candidate . What is ?
An LSTM has a note of numbers and words of numbers. How many numbers does it learn?
The reset gate is shut: . What does the GRU's draft depend on?
A GRU's update gate stays at exactly for 50 words. What happens to its note?
If you want the algebra · 2 proofs, step by step
Claim. With note size and word size , a plain cell learns numbers, a GRU and an LSTM . For , : 24 704, 74 112, 98 816.
Claim. If , then lies between and . So if (and , a tanh), then .
In one sentence: A GRU blends old and new with one dial, — 0.5 · 0.5 + 0.5 · 0.8938 ≈ 0.6969 in the full step — uses a reset gate to decide how much old note to consult, and costs three blocks of numbers against the LSTM's four.
Reading both ways, and stacking floors
"He said Teddy…" — is Teddy a person? You cannot tell until you read the next word. How can a reader use the words that come later?
Two friends read the same sentence. One starts at the left end, the other at the right end. Then, for every word, they put their two notes side by side.
Now every word knows what came before it and what comes after it.
Compare "He said Teddy bears are on sale" with "He said Teddy Roosevelt was a president". In the first, Teddy is part of "teddy bears" — a toy. In the second, Teddy is a man's name. The words before Teddy are identical. Only the words after it decide. A one-way reader standing at "Teddy" has read "He said Teddy" in both cases, so its note there must be the same. It cannot tell them apart.
A bidirectional RNN runs two cells over the sentence. The forward cell reads left → right, as before. The backward cell reads right → left. Each word's final note is the two notes side by side: . The forward half knows the past; the backward half knows the future.
A tiny example. Two one-number cells, both with , , , read : nothing, nothing, then one real word at the end.
- Forward (words 1, 2, 3): . Words 1 and 2 have not seen anything yet.
- Backward (words 3, 2, 1): , , — §2's fading numbers, read from the other end.
So word 1's note is . Its forward half is blind; its backward half carries word 3's news. Word 1 learns about word 3 only through the backward reader.
Stacking floors. We can also build a recurrent network in floors, like a building. Floor 1 reads the words. Floor 2 reads floor 1's notes as its inputs, one per word, and keeps a note of its own. Time runs along each corridor; depth goes up the stairs. Lower floors catch short, local patterns — letters into words, words into phrases. Higher floors build on those and can follow longer-range patterns. Two to four floors are common.
What they cost (, ). One-way, one floor: 24 704 (§10). Two-way: two cells, . Two floors: floor 1 is 24 704, and floor 2 reads 128-number notes instead of 64-number words, so it is — together 57 600.
| each word's note knows | numbers (h = 128, d = 64) | can it write text? | typical use | |
|---|---|---|---|---|
| one-way | the words before it | 24 704 | yes | language models, live speech |
| two-way | the whole sentence | 49 408 | no | tagging, reading a whole text, the encoder of §12 |
| two floors | the words before it, in two layers of detail | 57 600 | yes | harder language tasks |
Each reader is an ordinary recurrent cell, so each half of the note is an honest summary of one side of the sentence. Putting the halves side by side costs nothing extra to compute and gives every word a view of the whole sentence. Floors work for the same reason deep networks do (Unit 15): each floor builds a slightly more abstract summary on top of the one below.
A two-way reader gives every word both its past and its future. Floors give the reader depth. Both are built from the same cell, run in a different direction or on a different input.
A two-way reader cannot write text. Its backward half needs the words to the right — and while you are writing, they do not exist yet. Two-way readers are for jobs where the whole sentence is already there: tagging words, judging a review, or reading the source sentence of a translation (§12).
In the toy example, . Which reader gives word 1 a non-zero note, and how big is it?
Can you use a two-way RNN as a language model that writes a sentence word by word, as in §5?
Two floors of plain cells, , . Floor 1 has 24 704 numbers. How many does floor 2 have?
If you want the algebra · 1 proof, step by step
Claim. With note size and word size , one plain cell learns . A two-way reader learns , and a second floor that reads the first floor's notes learns . For , : 24 704, 49 408, and for two floors.
In one sentence: A two-way reader puts a forward note and a backward note side by side — word 1 of gets — so every word sees the whole sentence (but it cannot write text), and floors stack readers on readers: 24 704, 49 408 and 57 600 numbers for one-way, two-way and two floors.
Encoder–decoder: translate through one summary
English and Hindi sentences have different lengths and different word orders. How can one machine read one and write the other?
An interpreter at a meeting listens to a whole sentence in English. She holds its meaning in her head. Then she speaks it in Hindi, word by word.
Now give her a rule: she may keep only one small card of notes between listening and speaking. A short sentence fits easily. A very long speech does not.
To translate, the input and the output have different lengths and different word orders. "The train to Delhi is late" is six English words; in Hindi it is "Delhi ki train late hai", five words, in another order. So we use two recurrent cells:
- The encoder reads the English sentence word by word. Its final note, , is the summary of the whole sentence (people also call it the context vector). The encoder is often a two-way reader (§11), because the whole English sentence is already there; then the summary puts the two readers' final notes side by side.
- The decoder is a language model (§5) that starts from that summary and writes the Hindi sentence one word at a time. After each word it reads what it just wrote as its next input, and it stops when it writes a special word, .
Training uses §5's trick. While learning, we feed the decoder the true previous Hindi word, not its own guess — teacher forcing — so one early slip does not ruin the rest of the sentence. At test time there is no teacher, and the decoder must use its own words.
The bottleneck. The summary has a fixed size — say 8 numbers in our toy, 512 in a real system. Picture a 5-word sentence and a 50-word paragraph, each word bringing 8 numbers of its own. The short one pours 40 numbers into the 8-number card: a squeeze of 5 to 1. The long one pours 400 numbers into the same 8: a squeeze of 50 to 1. And the first word must survive the whole encoder: if the encoder keeps 90% of an old word at each step (a toy rate), word 1 of a 50-word sentence speaks in the summary at of its first strength. This is what researchers found with the first neural translation systems in 2014 (Cho and colleagues): good on short sentences, worse and worse on long ones.
The encoder is trained together with the decoder, through the summary. So the blame from every wrong Hindi word flows back into the encoder and teaches it what to put on the card: whatever the decoder needs to write a good translation. The two halves learn a private code between them — and for short sentences, one card is enough.
An encoder–decoder translates through one summary vector. It works, and it was a breakthrough. But everything the decoder knows about the source sentence must pass through that one fixed-size vector — a bottleneck that hurts more with every extra word. What if the decoder could look back at every English word, whenever it needs to? That question is Unit 18.
The summary is not a shorter sentence, and it is not a list of the English words. It is one note — the encoder's last card, a fixed list of numbers. Everything the decoder will ever know about the English sentence is on that card, however long the sentence was.
An encoder has a note of 256 numbers. It reads a 40-word sentence whose words are vectors of 100 numbers. How many numbers go in, and how many come out as the summary?
An encoder with a 512-number note reads a 20-word sentence, then a 40-word one. With the toy rate of 0.9 per step, what happens to the summary's size, and to word 1's voice in it?
If you want the algebra · 1 proof, step by step
Claim. A toy linear encoder (keep a fraction of the old summary, add the new word) gives . With , word 1 is weighted : for 6 words, for 50, and it first drops below 0.01 at .
In one sentence: An encoder squeezes the whole source sentence into one fixed-size summary and a decoder writes the translation from it, trained with teacher forcing — and that single card is the bottleneck: 40 numbers into 8 for five words, 400 into the same 8 for fifty, with word 1 at 0.9⁴⁹ ≈ 0.0057.
Choosing the words, and grading them: greedy, beam search, BLEU
The decoder gives a probability to every possible next word. Which sentence should it actually write — and how do we score its translation without asking a human?
You are driving across a city. At every junction you take the road that looks fastest right now. Sometimes that road leads straight into a traffic jam, and a road that looked a little slower at first would have got you home sooner.
Keeping two or three routes in mind, instead of one, often finds the better trip.
At each step the decoder gives a probability for every possible next word. The probability of a whole sentence is the product of its word probabilities (the chain rule of probability, Unit 16). We want the sentence with the biggest product. But there are far too many sentences to try them all.
Greedy decoding takes the single most likely word at each step and never looks back. Beam search keeps the best partial sentences at every step ( is the beam width), grows each by one word, and again keeps only the best . With it is greedy.
A tiny example. The decoder is writing the English for "hamari train late hai". First word: "the" 0.5, "our" 0.4, "a" 0.1. Second word, after "the": "train" 0.4, "bus" 0.3, "rain" 0.3. After "our": "train" 0.9, "bus" 0.1. After "a": "train" 0.6, "bus" 0.4.
- Greedy: take "the" (0.5), then its best, "train" (0.4). The sentence "the train" gets .
- Beam, : keep "the" (0.5) and "our" (0.4). Grow both: the train 0.20, the bus 0.15, the rain 0.15, our train , our bus 0.04. The best is "our train", 0.36.
Greedy lost because "our" looked slightly worse at the first step, even though it led to a far surer second word. In practice we add log-probabilities instead of multiplying (products of many small numbers become too tiny for a computer): beats .
Three ways to choose, side by side — greedy and beam from this section, sampling from §5.
| greedy | beam search, width k | sampling, temperature T | |
|---|---|---|---|
| keeps | one best sentence-so-far | the k best sentences-so-far | one random path |
| work | 1 path | about k paths | 1 path |
| gets | a likely sentence, fast | a more likely sentence | a different sentence each time |
| weakness | locks in early choices | can be bland and generic | makes mistakes at high T |
| use it for | quick, short answers | translation, captions | stories, chat, ideas |
Grading a translation without a human: BLEU. Checking thousands of translations by hand is slow. BLEU (Papineni and colleagues, 2002) gives a quick score by counting how many short pieces of the candidate also appear in a human's reference translation. A piece of words in a row is an -gram. Reference: "the train is running late". Candidate: "the train is late".
- Words that match. Of the candidate's 4 words, how many appear in the reference? the ✓, train ✓, is ✓, late ✓: unigram precision .
- Pairs that match. Of its 3 word pairs, how many appear in the reference? "the train" ✓, "train is" ✓, "is late" ✗ (the reference says "is running"): bigram precision .
- Too short is punished. A candidate could get perfect precision by saying almost nothing. So when the candidate ( words) is shorter than the reference (), multiply by the brevity penalty .
- Combine. Take the geometric mean of the precisions: .
One more rule: each word of the reference can be matched only as many times as it appears there. The candidate "the the the the" matches "the" only once, so , not . Real systems use pieces up to four words long (BLEU-4) and add up the counts over thousands of sentences before combining, but the recipe is the same.
A good translation shares many words, and many short runs of words, with a careful human one. Word matches check that the right content is there; pair matches check that it comes in a sensible order; the brevity penalty stops a machine from winning by saying less. None of this understands meaning — but averaged over thousands of sentences, it ranks translation systems much as people do.
Greedy picks the best word now; beam search keeps the best sentences-so-far and can recover when a slightly weaker first word leads somewhere much better. BLEU grades the result by the pieces it shares with a reference, with a penalty for being too short.
BLEU only counts overlapping pieces. "the train is delayed" means the same as "the train is running late", yet it scores only about 0.55, because "delayed" appears nowhere in the reference. A correct translation in different words can score low. BLEU is a quick average over many sentences, not a judge of one.
On this tree, does beam width 3 find a better sentence than beam width 2?
Reference "the train is running late" (5 words). Candidate "the train" (2 words). What is its BLEU-2?
Reference "the train is running late". The candidate "the the the the" has four words, and every one of them is "the", which does appear in the reference. What is its unigram precision?
If you want the algebra · 2 proofs, step by step
Claim. For sentences and , exactly when . A 200-word sentence whose words each have probability 0.01 has product , which a computer's usual numbers round to 0, but log-score .
Claim. With clipped precisions over the candidate's -grams , and : is 0 whenever or is 0, and for "the train is late" against "the train is running late" it is .
In one sentence: Greedy takes the best word each time and can land on 0.20, a beam of width 2 keeps two candidates and finds 0.36, and BLEU grades the result by matching pieces with a reference — "the train is late" scores 0.7788 · √(1 · ⅔) ≈ 0.636.
What to carry forward
The whole unit, one card at a time.
Order needs memory
A bag of words loses order; a window loses the past. A running note that changes the old note before adding the new word keeps both.The recurrent cell
One card of fixed size, rewritten at every word: , the same weights every time.Unrolled twins
A deep network as long as the sentence whose layers are one cell: numbers for any length.A cell that talks
Train with the true text fed in (teacher forcing); talk by feeding back your own picks. : small bold, big adventurous. Beware exposure bias.Backprop through time
Rule A and Rule B on the unrolled chain; the shared weight adds up every step's vote. Truncated BPTT cuts the blame into chunks of words.The whisper line
Blame is multiplied by the same matrix at every step, so the biggest decides: , .First aid
If , rescale to length : a cure for explosions, not for fading. Start with every near 1.LSTM
: an express lane where blame is multiplied only by the forget (keep) gate. Start its shift at 1–2.GRU
: one blend dial and a reset gate. Blocks: plain 1, GRU 3, LSTM 4.Both ways, and floors
Two-way notes see the whole sentence but cannot write; floors stack readers for depth.Encoder–decoder
Squeeze the source into one summary, write the target from it. The summary is a fixed-size bottleneck.Choose and grade
Greedy, beam search or sampling to choose; BLEU = brevity penalty × geometric mean of matching pieces to grade.Where this goes next.
- Unit 18 · Attention and Transformers. Two problems are left over from this unit. The decoder sees the source only through one summary card, and every word must wait for the word before it. Attention fixes both at once: the decoder — and then every word — can look directly at every other word, with weights from dot products (Unit 3) and softmax (Unit 14). The transformer's residual path is another express lane, and its causal mask is a one-way reader in disguise.
- Unit 19 · The Maths Inside an LLM. A language model at huge scale: next-word probabilities, and how chat models pick their words — the temperature of §5, and its cousins top-k and top-p.
A machine with memory multiplies by the same matrix at every word, so its memory and its blame live or die by that matrix's eigenvalues. Gates build an express lane where the multiplier is a number the network controls, close to 1 when it wants to remember.
In one sentence: A recurrent cell reads one word at a time with shared weights, learns to talk by guessing the next word, trains by backprop through time where powers of one matrix make memory fade or explode, is rescued by gates that open an express lane, reads both ways or in floors, and translates through a single summary — the bottleneck that attention removes next.
Practice arena — sixteen problems, solved in full
Sixteen problems, easy to hard: a forward pass by hand, one step with matrices, counting weights for every design in the unit, a read-out and its loss, temperature forwards and backwards, blame through three steps, truncated BPTT, the step at which memory is gone, eigenvalues that decide, clipping, a full LSTM step, recorded runs to diagnose, a full GRU step, notes read both ways, greedy against beam, and BLEU. Every number was checked by machine.
Three habits do most of the work. Write the notes down: keep a table of every (and ) on the way forward, because the way back needs them. Count steps, not words: from to there are factors. And look for the power: whenever something is multiplied by the same number again and again, it is , and turns "how many steps?" into a division.
A one-number recurrent cell has , , and . It reads . Find , and (four decimals).
What this tests. , one step at a time. Plan. Keep old, add new, squeeze — three times.
Show the full solution
answers at a glance: , , .
The note is a running mix: the old note, scaled by , plus the new word, then squeezed. A negative word can flip the sign of the whole note.
A cell has a note of 2 numbers and words of 1 number: (a) Find for the word . (b) Find for the word .
What this tests. The vector cell , with tanh applied entry by entry. Plan. Three pieces, add, squeeze each entry.
Show the full solution
answers at a glance: (a) . (b) .
The shift acts at every step, even when the word is 0. Here it pushes the second entry to on its own.
A word tagger uses notes of numbers and words of numbers. (a) How many numbers does one plain cell learn? (b) A two-way plain reader? (c) Two floors of one-way plain cells? (d) A one-way LSTM, and a one-way GRU? (e) A two-way LSTM with a read-out over 12 tags on top of each word's two-way note (read-out and included)?
What this tests. The block count and what changes when you add directions, floors and gates. Plan. Write the general block once; then ask, for each design, how many blocks and what each block reads.
Show the full solution
answers at a glance: (a) 6208. (b) 12 416. (c) 14 464. (d) LSTM 24 832, GRU 18 624. (e) 51 212.
Every design is built from the same block. Count the blocks, and check what each block reads: words ( numbers), notes () or two-way notes ().
After reading "the chai is", a language model's read-out gives the scores hot 3, sweet 1, ready 0, cold −1. (a) Turn them into probabilities (four decimals). (b) The true next word is "sweet". What is this step's loss? What would it have been if the true word were "hot"? (c) What blame does the read-out send back (prediction minus truth)?
What this tests. Softmax, the surprise of the true word, and Unit 15's "prediction − truth". Plan. Exponentiate, add, divide; then read off the true word's share.
Show the full solution
answers at a glance: (a) 0.8310, 0.1125, 0.0414, 0.0152. (b) ≈ 2.185 (and ≈ 0.185 for "hot"). (c) (0.8310, −0.8875, 0.0414, 0.0152).
A confident wrong guess is expensive: "sweet" had 0.11 and costs 2.19. The blame pushes "hot" down by 0.83 and pulls "sweet" up by 0.89.
A model has two candidate next words with scores 2 and 0. (a) Find the first word's probability at , and . (b) Another model gives two words the probabilities 0.8 and 0.2 at . At what temperature would it give them 0.6 and 0.4? (c) What does it give them as ?
What this tests. , and the ratio rule used backwards. Plan. For two words, softmax is a sigmoid of the gap; for (b) find the gap first, then the that gives the new ratio.
Show the full solution
answers at a glance: (a) 0.8808, 0.9820, 0.7311. (b) . (c) 1 and 0.
Temperature only rescales the score gaps. Two shares always stand in the ratio , so you can run the rule forwards or backwards.
A one-number cell has , , , and reads . (a) Find . (b) Find , and . (c) Find .
What this tests. The BPTT product . Plan. Forward first and store every note; then one factor per step.
Show the full solution
answers at a glance: (a) 0.7616, 0.5436, 0.4094. (b) 0.6659, 0.5636, 0.3753. (c) .
With instead of 0.5, each factor is bigger, and the first word still reaches at more than a third of its size. The factors decide everything.
A 2 500-character text is trained with truncated BPTT in chunks of characters (1–50, 51–100, …). (a) Give the general number of chunks for a text of characters, then apply it. (b) The blame from character 130 walks back to which character? (c) Can training learn a link between characters 30 and 70? Between 60 and 90? (d) Full BPTT would walk the blame from the last character back to the first. How many steps is that, against the longest walk in the truncated run?
What this tests. What truncation cuts (the blame) and what it keeps (the forward note). Plan. Find each character's chunk with ; blame never leaves its chunk.
Show the full solution
answers at a glance: (a) , here 50. (b) character 101. (c) 30 and 70: no; 60 and 90: yes. (d) 2 499 steps against at most 49.
Truncation makes training cheap and limits what can be learned to links shorter than — but the note still carries every earlier character forward.
In the loop , the blame after steps is . (a) Write a formula for the first at which drops below (for ). (b) Apply it for , . (c) For , find the first at which exceeds 1000.
What this tests. Turning "how many steps?" into a division with logarithms. Plan. Take of both sides; mind that flips the inequality.
Show the full solution
answers at a glance: (a) . (b) 31. (c) 38.
Even gentle numbers are ruthless over a few dozen steps: 0.8 loses a factor of 1000 in 31 steps, and 1.2 gains one in 38.
Two recurrent matrices: and . (a) Find the eigenvalues and eigenvectors of each and say whether memory fades or explodes. (b) Find and for .
What this tests. Splitting along eigen-directions (Unit 4) and powering each part. Plan. Both matrices have the form : eigenvectors , , eigenvalues .
Show the full solution
answers at a glance: (a) : 0.8 on , 0.4 on — fades; : 1.4 on , 0.8 on — explodes. (b) , .
After many steps the note points along the eigenvector with the biggest , and its size goes like .
The limit is and the step size . (a) Clip and give the weight change . (b) Clip .
What this tests. . Plan. Length first; scale only if it is too long.
Show the full solution
answers at a glance: (a) , change . (b) , unchanged.
Clipping scales the whole vector by one number. The direction — the ratio 6 : −8 — is kept.
A one-number LSTM has . Before their squeezes, the gates and the candidate come out as: forget 2, input 0, output 1, candidate 1. Find , then and .
What this tests. Gates are sigmoids, the candidate is a tanh; , . Plan. Four squeezes, then the two formulas.
Show the full solution
answers at a glance: , , , ; , .
The cell state may grow past 1 — it is never squeezed on the lane. Only the note is squeezed, when it is read out through the window.
Three recurrent models were trained on the same task. For each, the size of the blame reaching the note steps back from the end was recorded:
| run | k = 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| A | 1 | 0.42 | 0.176 | 0.0741 | 0.0311 | 0.0131 |
| B | 1 | 2.1 | 4.41 | 9.26 | 19.4 | 40.8 |
| C | 1 | 0.97 | 0.941 | 0.913 | 0.885 | 0.859 |
What this tests. Reading a geometric sequence, and matching it to fade, explode or express lane. Plan. Divide neighbours; then raise the factor to the 20th power.
Show the full solution
answers at a glance: (a) 0.42, 2.1, 0.97. (b) , , . (c) A = plain, small weights → gates; B = plain, big weights → clipping; C = LSTM. (d) . (e) .
Blame through time is a geometric sequence. One ratio tells you everything: below 1 it fades, above 1 it explodes, near 1 you have an express lane.
A one-number GRU has old note and input . Its update score is 1 and its reset score is −1. The draft uses weight 1 on the word and 2 on the consulted old note: . (a) Find , , and (four decimals). (b) Redo and with the reset gate wide open, . What did the reset gate change?
What this tests. The two GRU gates in the right places: inside the draft, in the blend. Plan. Squeeze the scores, draft, then blend .
Show the full solution
answers at a glance: (a) , , , . (b) , .
The reset gate decides how much of the old note the draft may consult; the update gate decides how much of the draft enters the note. The old note still passes through either way.
Two one-number cells, both with , , , read : the forward cell left to right, the backward cell right to left. (a) Find the three forward notes. (b) Find the three backward notes. (c) Write word 2's two-way note. (d) If changes, which half of word 1's note changes?
What this tests. Running the same cell in two directions, and which half carries which side of the sentence. Plan. Forward: start at word 1. Backward: start at word 3 and walk left.
Show the full solution
answers at a glance: (a) 0.7616, 0.3634, 0.5926. (b) 0.4621, 0.2270, 0.8053 (words 3, 2, 1: in word order). (c) (0.3634, 0.2270). (d) The backward half.
Same cell, same weights, opposite direction. The forward half of a note knows the past; the backward half knows the future.
A decoder's choices. First word: "the" 0.6, "my" 0.4. After "the": "tea" 0.3, "chai" 0.3, "cup" 0.4. After "my": "chai" 0.8, "tea" 0.2. (a) What does greedy decoding output, with what probability? (b) What does beam search with width 2 output? (c) Give both log-scores.
What this tests. Sentence probability as a product; keeping the best. Plan. List every two-word candidate the beam sees.
Show the full solution
answers at a glance: (a) "the cup", 0.24. (b) "my chai", 0.32. (c) −1.427 and −1.139.
A first word that looks a little worse can lead to a much surer second word. Greedy never finds out; a beam of width 2 does.
Reference: "we drink chai every morning". (a) Candidate A: "each morning we drink chai". Find , , the brevity penalty and BLEU-2. (b) Candidate B: "we drink chai every evening". Find the same. (c) Candidate C: "we drink chai". Find the same. (d) Which candidate keeps the meaning, which scores highest, and what does that say about BLEU?
What this tests. Clipped -gram precision, the brevity penalty and the geometric mean. Plan. List the candidate's words and pairs, tick those in the reference, count lengths.
Show the full solution
answers at a glance: (a) , , BP = 1, BLEU-2 ≈ 0.6325. (b) , , BP = 1, BLEU-2 ≈ 0.7746. (c) , BP ≈ 0.5134, BLEU-2 ≈ 0.5134. (d) A keeps the meaning, but B — which gets a fact wrong — scores highest: BLEU rewards overlap, so it is trusted only as an average over many sentences.
BLEU-2 = BP · √(p₁ p₂). Clip the counts, punish short candidates, and never read one sentence's BLEU as a verdict on its meaning.