After this chapter you will be able to
state the noisy channel factorisation and say why it worked with the data of 1990;
carry out one EM iteration of IBM Model 1 by hand and explain a tie that does not break;
explain why one encoder vector cannot hold a long source, and how attention repairs it;
compute dot-product attention by hand, and compare global with local attention;
trace teacher forcing, beam search and length normalisation;
count the parameters of a realistic translation system and the directions of a multilingual one.
This chapter builds on Chapters 12 and 13, which supply the recurrent encoder and decoder.
Machine translation is the oldest application in this book and the one that paid for most of the machinery in it. It is also a clear place to see an arc, because the ideas of the earlier parts were tried on translation first and each new idea arrived when the previous one hit a specific wall.
| period | idea | unit | what broke it |
|---|---|---|---|
| 1954 to 1966 | rules and dictionaries | the word | ambiguity |
| 1988 to 1999 | statistics over pairs | the word | word order |
| 1999 to 2014 | phrase-based SMT | the phrase | no generalisation |
| 2014 onwards | neural, then attention | the sequence | one step at a time |
Read that last column downwards, where each generation was ended by a limitation the next one addressed, the shape Parts I to III have followed so far.
In 1949 Warren Weaver circulated a memorandum proposing that translation be treated as decoding. His formulation was that a Russian text is really English, encoded in a strange script, and the job is to recover it. That framing was premature by forty years and then turned out to be literally the right one, since Section 14.2 is Weaver’s idea written as an equation.
In 1966 the ALPAC report, from a committee of the US government, concluded that machine translation was slower, less accurate and more expensive than human translation, and recommended that funding stop, which it largely did for two decades. The report was correct about the systems it examined and wrong about the prospect, and it is still read for that reason. A negative evaluation of current systems is not a negative result about the problem, and the difference is easy to lose.
Weaver’s framing gives the objective directly, since given a foreign sentence we want the English sentence most likely to have produced it:
Apply Bayes’ rule and the denominator does not depend on , so it drops:
This is the noisy channel model, and the factorisation is the reason it worked. is a language model, which is Chapter 10 itself, and it can be estimated from monolingual English text, of which there is a great deal, so it is what makes the output fluent. is a translation model, which needs parallel text, which is scarce, and it is what makes the output faithful.
Splitting the problem this way means the scarce resource is only asked to do half the job. Fluency comes from cheap data and adequacy from expensive data, and the two are trained separately.
The translation model is the hard half, and the difficulty is stated in one sentence. A parallel corpus tells you that two sentences mean the same thing and does not tell you which word translates which. That correspondence is alignment and it is a hidden variable, since nobody annotated it and any usable translation model needs it.
The IBM models (Brown et al. 1993) estimate alignment and translation together from sentence pairs alone. Model 1 is the simplest of them and its simplifying assumption is severe, because every alignment is a priori equally likely and position therefore carries no information at all.
This is plainly false about language, and it is also what makes the model solvable in closed form at each step. Model 1’s output is therefore the starting point for every model above it. The estimation is expectation maximisation (EM), and on a small corpus you can do it by hand.
Here is a four-sentence corpus, with English on the left and Swahili on the right.
| English | Swahili |
|---|---|
| my dog | mbwa wangu |
| my house | nyumba yangu |
| my cycle | mzunguko wangu |
| his dog | mbwa wake |
Nobody has said which word translates which, and there is no dictionary and no alignment annotation. One wrinkle deserves a note before we start: Swahili marks possession by noun class, so my is wangu with dog and cycle but yangu with house. A model that assumed one translation per word would already be wrong, and Model 1 does not assume that.
Initialise uniformly, so that with six Swahili words every entry is .
The expectation step comes first. For each Swahili word in a pair, split one unit of count over the English words in that pair, in proportion to the current :
On the first pass the table is uniform and every pair has two English words, so every is . The first iteration cannot prefer anything, and what it can do is count.
The maximisation step then collects those counts and renormalises:
Look at what my collected. It occurred in three pairs so it gathered units of count, wangu appeared beside it twice and took of that, and every other word appeared once and took . That asymmetry is the entire seed, because one pass of counting is enough to notice that wangu keeps company with my more than anything else does.
Repeat and the preference compounds, because each iteration uses a slightly less uniform table, which makes the splits slightly less even, which makes the next table sharper still.
| iteration | |||
|---|---|---|---|
| 0, uniform | 0.1667 | 0.1667 | 0.1667 |
| 1 | 0.5000 | 0.3333 | 0.5000 |
| 5 | 0.8828 | 0.7838 | 0.5000 |
| 10 | 0.9914 | 0.9180 | 0.5000 |
Nothing pushed those numbers except counting and renormalising, repeated ten times.
After ten iterations, the best Swahili word for each English word:
| English | best | runner up | ||
|---|---|---|---|---|
| dog | mbwa | 0.9914 | wangu | 0.0047 |
| his | wake | 0.9169 | mbwa | 0.0831 |
| my | wangu | 0.9180 | nyumba | 0.0391 |
| cycle | mzunguko | 0.8936 | wangu | 0.1064 |
| house | nyumba | 0.5000 | yangu | 0.5000 |
Four of the five are settled, from four sentences and no supervision at all.
Now look at house, which sits at against both nyumba and yangu and stays there, so that at fifty iterations it is still and . This is EM reporting what the data supports.
House occurs in a single sentence pair, beside nyumba and yangu, and nothing anywhere else in the corpus distinguishes those two words. My correctly pushes both of them down, and pushes them down equally: at the fifty iterations just mentioned, and are each. The tables above stop at ten iterations, where the same two entries stand at , so the figures are the same quantity read at different points on the same curve.
So house inherits both in equal measure. The data contains a tie and the model reports a tie, and a model that broke it would be inventing something.
Add a fifth pair, his house and nyumba wake, so that house now meets nyumba twice and yangu once. This is the only new information, and it is enough.
| four pairs | five pairs | |
|---|---|---|
| 0.5000 | 0.8174 | |
| 0.5000 | 0.1824 | |
| 0.9180 | 0.7636 | |
| 0.0391 | 0.2335 |
The tie resolves and something else moves with it, since rises from to , which is more correct. Yangu is in fact Swahili for my in the noun class house belongs to, and freeing house from the tie let that evidence reach my.
One sentence pair did that. It is the argument for parallel corpus size in miniature, and it is why statistical translation waited for the Canadian Hansard and the European Parliament proceedings.
Run it.
code/worked_examples/ibm_model1.pyproduces every table in this section.--stepshows one iteration with every posterior and count,--learnedprints the final table and the tie,--extraadds the fifth pair, and--pair "my dog" "mbwa wangu"traces the alignment of a single sentence pair. The neural section has its own flags, listed at the end of it.
The higher IBM models relax Model 1’s assumptions one at a time. Model 2 adds a distortion term so that alignment probability depends on position, Model 3 adds fertility, the number of foreign words one English word produces, and Models 4 and 5 refine the distortion further.
Each addition is a correction to a specific falsehood in Model 1, and each is initialised from the model below it. That staircase has a pattern: a wrong but solvable model used to bootstrap a right but unsolvable one.
Word-level translation has a limitation no amount of better alignment fixes, which is that languages do not correspond word for word. Idioms translate as units, verb particles separate, and some languages need three words where another needs one, none of which a model whose unit is the word can express.
Phrase-based translation takes contiguous word sequences as the unit, and it was the state of the art from roughly 1999 to 2014. The pipeline has three steps and the first is the interesting one.
Align in both directions, running Model 1 English to foreign and foreign to English, where the two alignments disagree because each is a many-to-one map in a different direction. Symmetrise by taking the intersection of the two alignments as a high-precision core and then growing it outward with the union, under heuristics about which neighbouring points may be added. Then extract, so that any pair of contiguous spans consistent with the symmetrised alignment becomes a phrase pair, with its probability coming from counting.
The result is a phrase table and its size is its character, running to millions of entries, each a short span with a probability, memorised from the corpus. This is also its ceiling, because a phrase table generalises only to phrases it has seen and has no notion that two phrases are similar, which is precisely the complaint Chapter 11 made about count tables in general.
In 2014 the unit changed again, from the phrase to the whole sequence. An encoder-decoder model reads the source sentence with one recurrent network, compresses it into a vector, and generates the target with another (Sutskever et al. 2014).
Everything that made this work is in the chapters just before this one, since the encoder is Chapter 12’s recurrence, usually gated as in Chapter 13, while the decoder is a conditional language model trained with the cross-entropy of Chapter 11.
Two things changed at once. There is no phrase table and so no memorised inventory, which means the model generalises through the geometry of its embeddings, and the whole system is trained end to end on one objective.
The rest of this section builds a translator small enough to follow, one piece at a time. It states the objective and builds the encoder and the decoder. It shows where a single vector falls short and how attention repairs it. It trains the whole thing by hand, then translates a new sentence, counts a realistic system, and widens the model to many languages. Its weights are chosen and not trained, so the numbers show how a signal travels from the source words to a loss, and nothing in them is a translation.
The statistical models of the earlier sections cut translation in two, a translation model and a language model, and joined them with the noisy channel of Equation (14.2). A neural system models the quantity the task asks for directly. Let be a source sentence and a target. Translating is the search
and one network, with parameters , is trained on a parallel corpus of pairs to make the reference translations likely:
A whole sentence is far too rare an event to model as one outcome, so the chain rule cuts it into one factor for each target word, , and each factor is the softmax output of a decoder. This is the conditional language model of Chapter 11 with the source sentence added to what it conditions on.
Take two training pairs and the toy decoder of the next two subsections, with attention. The first is the dog ran with le chien courut and the end marker, the second is dog ran with chien courut and the end marker. At each step the table gives the probability the decoder assigned to the gold word.
| pair | gold word | step | (gold) | |
|---|---|---|---|---|
| 1 | le | 1 | 0.1763 | |
| 1 | chien | 2 | 0.1659 | |
| 1 | courut | 3 | 0.3177 | |
| 1 | </s> | 4 | 0.2858 | |
| , pair 1 | 0.002656 | |||
| 2 | chien | 1 | 0.1912 | |
| 2 | courut | 2 | 0.4431 | |
| 2 | </s> | 3 | 0.3611 | |
| , pair 2 | 0.030591 | |||
The two sentence probabilities, and , are tiny, so every system works with their logarithms. Averaging the two logs over pairs gives the objective,
and training minimises , which is here. The shorter sentence has the larger probability simply because it has fewer factors, and that observation returns when beam search has to compare hypotheses of different lengths. Dividing the total loss by the seven target words instead gives per word. Both are called the loss in the literature, so a number copied from a paper means little until you know which one it is.
The encoder is the recurrence of Equation (12.14) run over the source words, which leaves one state for each. The decoder is a second recurrence that also reads a context vector summarising the source, and its state is turned into a distribution over the target vocabulary:
Here is the embedding of the previous target word. The two sequences need not have the same length, because the encoder simply stops at the last source word and the decoder runs until it emits an end marker. Training minimises , the cross-entropy of Chapter 11 summed over the target sentence, and during training the decoder is fed the gold previous word and not its own guess. That practice is called teacher forcing.
Take the source the dog ran and the encoder of the unrolling example in Chapter 12, whose states are printed there:
| source | ||
|---|---|---|
| 1 | the | |
| 2 | dog | |
| 3 | ran |
The plainest encoder-decoder hands the decoder only the last state, so that at every output step, whatever is being written, and it also starts the decoder there, . The first decoder step then goes through the stages below. The previous word is the start marker, whose embedding is the zero vector, so the first term vanishes. The last two rows list the four target words in the order le, chien, courut, </s>.
| stage | value |
|---|---|
| sum, with the bias | |
| of the sum | |
| scores | |
| softmax |
The gold first word is le, and the model gave it , so the first term of the loss is . The distribution prefers courut, which is what an untrained network would do, and the point of training is to move that mass.
Cho and colleagues observed that the fixed-size vector is the weak point (Cho et al. 2014). Such a model needs far less memory than a phrase table, and it handles short sentences well, but its quality falls as the source sentence gets longer.
The cause shows up in the encoder’s arithmetic, and the toy makes it measurable. Take two sources that differ only in their first word, the against ran, each followed by copies of dog until the sentence has words. If the decoder is to tell the two apart, the last encoder state has to differ between them.
| distance between last states | distance between first states | |
|---|---|---|
| 1 | 0.769006 | 0.769006 |
| 2 | 0.335076 | 0.769006 |
| 3 | 0.153902 | 0.769006 |
| 5 | 0.024529 | 0.769006 |
| 8 | 0.001197 | 0.769006 |
| 12 | 0.000030 | 0.769006 |
The second column never changes, because the first state depends only on the first word. The first column shrinks with every word that follows, since each new state is built mostly from its own input and a decayed copy of the one before. It is the same product of Jacobians that Section that section met on the way backwards. By twelve words the two sentences hand a decoder that sees only the last state inputs that differ by . Nothing in training can repair that, because the information is already gone before the decoder starts.
Two patches came before the real fix. Sutskever and colleagues fed the source in reverse order (Sutskever et al. 2014), which puts the first source word next to the first target word and shortens the path between words that usually correspond. Gated cells, as in Chapter 13, hold on to information for longer. Both leave the single vector in place, and attention removes it.
The objective is a sum over target words of cross-entropy terms, so training is the backward pass of Chapter 12 applied to the decoder. At step the error at the scores is again prediction minus target, , and writing the output matrix as to separate the columns that read from those that read , the gradients are
and, as the recurrent chapter found for and ,
The recursion for is Equation (12.7) again. Each step receives its own error through and the error of every later step through , and it is evaluated from the last word back to the first. The context has no step index in this version, so it collects error from every step, , and the initial state collects as well. Together they are the gradient that leaves the decoder and enters the encoder, where the recurrent backward pass takes over.
Run it on the plain decoder, the one whose loss is in the teacher forcing table below. The backward pass gives, from the last word to the first:
| gold | from the output | from later steps | ||
|---|---|---|---|---|
| 4 | </s> | |||
| 3 | courut | |||
| 2 | chien | |||
| 1 | le |
The last step has nothing after it, so its middle column is zero. Every earlier step receives a correction from the steps that follow, and this is how the loss on </s> reaches the state that wrote le. The largest direct error is at the first word, which is where the model was most wrong. Summing over the four steps gives the gradients for the shared weights:
| matrix | row 1 | row 2 |
|---|---|---|
and the gradient handed to the encoder is
which enters the encoder’s own backward pass from the last source word. A derivation this long should be checked, and the check is cheap. Nudge each of the thirty numbers involved, the twenty-eight entries of the four matrices and the two entries of , by in each direction and recompute the loss. The slope agrees with the formula everywhere, the largest disagreement being .
With attention the context changes at every step, so each encoder state receives error from every output step through its weight , and the scores pass error back to the decoder state as well. Nothing in that needs more than the derivative of a softmax, which Chapter 12 has already used.
The choices in a recurrent translator are few: the direction the encoder reads, the number of layers and units, the kind of cell, and the learning algorithm. Vanilla, LSTM and GRU cells all appear in the literature, and production systems use the gated ones, though the toy here uses the plain cell so that every number can be checked by hand.
Direction deserves a worked example, because it changes what each annotation knows. A forward encoder’s state at word summarises only the words up to . A second recurrence, read from the last word to the first, summarises the words from onward, and the annotation of word is the two states side by side.
| source | forward | backward | |
|---|---|---|---|
| 1 | the | ||
| 2 | dog | ||
| 3 | ran |
The forward column is the encoder of the previous subsection. Now change the last word, ran, to the, and measure how far each state moves.
| source | forward state moves by | backward state moves by | |
|---|---|---|---|
| 1 | the | 0.0000 | 0.1196 |
| 2 | dog | 0.0000 | 0.2625 |
| 3 | ran | 0.7680 | 0.6958 |
A forward state cannot know what comes after it, so the first two do not move at all. The backward states do, and so the annotation of the now carries information about the words that follow it. This is the reason Bahdanau’s encoder reads both ways, and the reason it is legitimate here, where it was not for generation in Chapter 12: the whole source sentence is known before the first target word is written. The decoder stays one directional, since it has to produce its words in order. It is usually started from the encoder’s final states.
Depth is the other direction in which encoders grow. A second layer reads the first layer’s states in place of the words, so that the states of layer two are built from already contextual inputs.
| source | layer 1 | layer 2 | |
|---|---|---|---|
| 1 | the | ||
| 2 | dog | ||
| 3 | ran |
Systems of the period stacked four to eight such layers on each side, as the setup counted later in this section shows.
The fix for the bottleneck is attention (Bahdanau et al. 2014), which is to let the decoder look back at all the encoder states and learn a weighting over them at each output step. Different parts of the source matter to different parts of the output, and the decoder, not the encoder, is the one that knows which part it needs next. The decoder state asks every encoder annotation how relevant it is, a softmax turns the scores into weights, and the weighted average is the context:
Each of these quantities has a reading to keep. The score comes from a small alignment model, a function of the previous decoder state and one annotation, and it is trained jointly with the translation model. No one supplies alignments, and the network learns whichever ones help it translate. The weight is the probability that the target word being written is aligned to source word . The context is then the expected annotation under that distribution. The alignment is computed explicitly at every step, where a latent variable in a statistical model would have had to be summed out.
Suppose the decoder, about to write the first target word, is in the state , and take the score to be the dot product .
| source | score | weight | |
|---|---|---|---|
| 1 | the | 0.4996 | |
| 2 | dog | 0.2818 | |
| 3 | ran | 0.2186 |
The weights add to , and the first word takes half of them. The context is , against the that the plain encoder-decoder would have supplied. A decoder asking for a subject has pulled its context towards the first source word instead of the last. This is the mechanism. At the next output step the state is different, so the weights are too.
That weighting is a soft alignment, learned by gradient descent, computed fresh at every output position.
Put another way, attention is IBM Model 1’s hidden variable arrived at from the other end. The statistical models estimated alignment with EM and used it to build a table, whereas the neural model learns it as a by-product of translating and never writes it down. The decoder decides which part of the input matters for the word in hand, in place of depending on one vector for the whole sentence, and it does so with a different context for every word it writes.
The bottleneck table shows what this buys. Under attention the decoder can read , where the two sources of that table differ by however long the sentence grows, in place of a last state in which the difference has shrunk to . Two further benefits follow. The path from an output word’s loss to a source word’s state is one step through the weights, in place of a walk down the whole recurrence, which eases the vanishing gradient of Section that section. And the weights, collected over a sentence, are an alignment table that nobody had to annotate.
The score in Equation (14.8) can be computed in more than one way. Bahdanau’s is additive, a small network with its own weights, , and Luong’s is the dot product (Luong et al. 2015). On the same state and the same encoder they give different alignments:
| source | dot score | dot weight | additive score | additive weight | |
|---|---|---|---|---|---|
| 1 | the | 0.4996 | 0.3750 | ||
| 2 | dog | 0.2818 | 0.3375 | ||
| 3 | ran | 0.2186 | 0.2875 |
Neither is right until the weights are trained, and the example shows only that the choice of score is a modelling decision, not a detail. The dot product has no parameters of its own and is cheap, while the additive form has its own small network and can learn a more flexible comparison between a state and an annotation.
A second decision is how far to look. Global attention scores every source position at every output step, which is what the tables above do.
Local attention scores only a window of positions, centred on one that the model predicts. Luong’s version first predicts a position, for a source of words. It then scores only the positions within of it. Each score’s softmax weight is multiplied by a Gaussian centred on with , so that positions at the edge of the window count for less. A simpler variant assumes the translation is monotone and sets .
Take the same state , with , and . The predicted position is , so the window holds the positions within of it, which are the first two words, and the third is never scored.
| source | score | softmax in window | Gaussian | weight | |
|---|---|---|---|---|---|
| 1 | the | 0.6394 | 0.1634 | 0.1045 | |
| 2 | dog | 0.3606 | 0.9954 | 0.3589 |
The Gaussian has done its work. The first word had the larger score but sits nearly one position from the predicted centre, so it is cut to , while the second sits almost on the centre and keeps . In this formulation nothing renormalises the result, so the weights add to and the context is , against for global attention.
What the window buys is cost. Global attention does scores per output word. Local attention with does at most , whatever is.
| source length | global scores | local scores, |
|---|---|---|
| 10 | 10 | 10 |
| 50 | 50 | 21 |
| 200 | 200 | 21 |
Both forms look from the decoder at a different sequence, the source, and that is the shape of the idea so far. Chapter 17 takes the last step, which points the same mechanism at a sequence looking at itself.
Run the decoder over the whole target le chien courut followed by the end marker, feeding it the gold word at each step, once with the context and once with attention. At each step the loss is of the probability the model gave the gold word.
| step | gold | (gold), | (gold), attention |
|---|---|---|---|
| 1 | le | 0.0922 | 0.1763 |
| 2 | chien | 0.1584 | 0.1659 |
| 3 | courut | 0.4677 | 0.3177 |
| 4 | </s> | 0.2772 | 0.2858 |
| loss, the sum of | 6.2696 | 5.9310 | |
The two columns differ only through the context , and since nothing is trained the table does not show attention helping. What it shows is where the loss comes from, one term for each target word, and which weights a gradient would reach. Training is the backpropagation just described, applied to this graph, and it changes the decoder, the encoder and the attention weights together.
Collect the attention weights of the second column, one row for each target word. The result is an alignment table of the kind the statistical models produced, with one row for each target word and one column for each source word.
| the | dog | ran | largest | |
|---|---|---|---|---|
| le | 0.2835 | 0.3376 | 0.3789 | ran |
| chien | 0.3203 | 0.3369 | 0.3427 | ran |
| courut | 0.3558 | 0.3374 | 0.3068 | the |
| </s> | 0.3237 | 0.3487 | 0.3277 | dog |
Each row adds to , as a row of Model 1’s posterior table does. These rows are close to even, and the largest entries are in the wrong places, which is what untrained weights give. A trained model’s rows peak at the source word that the target word translates, and reading them off is how one inspects what the network has learned.
At test time there is no gold word, so the decoder feeds itself, and translating a new sentence runs in three phases.
In the first phase the source is tokenised, embedded and encoded, which leaves the annotations that serve as the encoder’s memory, and the decoder’s initial state is set, usually from the encoder’s final states. In the second phase the decoder loops. It takes the embedding of the word it produced last, starting from the start marker. It scores every annotation against its previous state, normalises the scores into weights, and forms the context. It updates its state from the previous state, the previous word and the context, and then computes a distribution over the target vocabulary, from which a decoding rule picks the next word. In the third phase the loop stops when the end marker is picked, or when a length limit is reached, and the words so far are the output. With beam search the output is the hypothesis with the best total log probability.
Run the loop on the toy, taking the likeliest word at each step, which is greedy decoding.
| previous word | weights on the, dog, ran | chosen | ||
|---|---|---|---|---|
| 1 | <s> | 0.283, 0.338, 0.379 | </s> | 0.2831 |
The loop stops at once, because the chosen weights give the end marker the highest probability at the first step, and the translation is empty. Systems guard against that with a minimum length, below which the end marker is barred. Barring it before step gives a run that shows the loop, and the other way phase three can end.
| previous word | weights on the, dog, ran | chosen | ||
|---|---|---|---|---|
| 1 | <s> | 0.283, 0.338, 0.379 | courut | 0.2764 |
| 2 | courut | 0.320, 0.337, 0.343 | chien | 0.3340 |
| 3 | chien | 0.295, 0.333, 0.372 | chien | 0.3995 |
| 4 | chien | 0.301, 0.348, 0.351 | chien | 0.4058 |
| 5 | chien | 0.308, 0.355, 0.337 | chien | 0.3979 |
| 6 | chien | 0.313, 0.357, 0.330 | chien | 0.3911 |
| 7 | chien | 0.316, 0.358, 0.326 | chien | 0.3872 |
| 8 | chien | 0.317, 0.359, 0.324 | chien | 0.3853 |
The loop then runs to the limit of eight words, and what it writes is courut chien chien chien chien chien chien chien. Neither run is a translation, since the weights are chosen. The two runs show two failures, an empty output and a repetition. Real systems also produce them when they are badly trained, and they are the reason a decoder needs a length limit, a minimum length and a way to look beyond the single likeliest word.
Greedy decoding commits to the likeliest word at every step and cannot take it back. Beam search keeps the best few partial translations at every step instead of only one, and Section that section in Part V treats it properly. Translation adds one difficulty to it. A hypothesis’s score is the sum of its token log probabilities, and every extra token adds a negative number, so a long hypothesis is punished for being long. Take two candidates for the same source:
| hypothesis | tokens | per token | |
|---|---|---|---|
| le chien </s> | 3 | ||
| le chien courut vite </s> | 5 |
The sum prefers the short hypothesis and the per-token average prefers the long one, and a system that uses the sum will tend to produce translations that stop early. The usual repair divides the score by a power of the length, , with giving the average of the table, and the power is chosen on held-out data. Beam widths of a handful are typical in translation, and the choice of width and of is part of the system as much as the network is.
The toy has two numbers in each vector. A system of the period that made neural translation competitive looked like this.
| sentence pairs | 3 to 5 million |
| English and French words | 110 million and 116 million |
| vocabulary | about 50,000, source and target |
| embedding size | 1000 |
| hidden layer | 1000 LSTM cells |
| stacked layers | 4 to 8 |
| learning rate | as high as 1 at first, then reduced |
| mini-batch | 128 sentence pairs |
| training time | one GPU, about 7 to 10 days |
| evaluation | BLEU, from 27 to 32 |
These settings can be counted. An LSTM layer has four gates, each with a weight matrix over the input and the previous state and a bias, which at size comes to parameters. Each embedding table has , and the output layer has .
| layers per side | LSTM layers | embeddings | output layer | total |
|---|---|---|---|---|
| 4 | 64,032,000 | 100,000,000 | 50,050,000 | 214,082,000 |
| 8 | 128,064,000 | 100,000,000 | 50,050,000 | 278,114,000 |
A model of two hundred million parameters is already large, and the layers are not where most of the cost per word sits. Choosing each target word costs multiply-adds at the output layer, against for a whole LSTM layer, so the softmax over the vocabulary is worth layers. That ratio is the practical reason for the subword vocabularies of Chapter 5, which shrink the table the softmax runs over. At an average of English and French words for each of four million pairs, a mini-batch of gives updates in one pass over the corpus.
A system built this way has one network for each language pair. With languages and every direction wanted, that is networks, so that three languages need six and a hundred need .
Sharing parts of the network reduces that count, as the figure shows, and the extreme case shares all of it. Johnson and colleagues trained one model on many pairs and put a token at the start of the source to name the language wanted, such as <2ko> the dog ran against <2ja> the dog ran (Johnson et al. 2017). The same network then serves every direction.
The result that drew attention is what the model can do without data. Suppose the training data contains only Japanese and English, and Korean and English, in both directions. The system translates Japanese to Korean reasonably well although it never saw such a pair. This is zero-shot translation, and the counts show how much of what the network serves was never trained.
| separate models | directions trained | directions served | zero-shot | |
|---|---|---|---|---|
| 3 | 6 | 4 | 6 | 2 |
| 10 | 90 | 18 | 90 | 72 |
| 100 | 9,900 | 198 | 9,900 | 9,702 |
With English at the centre only directions have data, and the other are zero-shot. At a hundred languages that is directions out of . The row for is Johnson’s experiment, with Japanese-English and Korean-English trained, in both directions, and the two Japanese-Korean directions served without data.
It only makes sense if the model has built something like a shared representation across languages, which it was never asked to do. Whether that is a true interlingua or a collection of translation knowledge that happens to compose is an open question, and the last exercise of this chapter asks how to tell them apart.
Nothing in the encoder-decoder belongs to translation. It maps one sequence to another, and wherever a task has that form the same machinery applies. Dialogue maps what was said to a reply. Code generation maps a description to a program. Summarisation, the subject of Chapter 26, maps a document to a shorter one. Translation was the first task on which the shape proved itself. It is still the cleanest place to see it, because the source and the target carry the same meaning and so the alignment between them is a meaningful thing to inspect.
The transformer removed the recurrence and kept the attention, and translation was its first task (Vaswani et al. 2017). Chapter 17 builds it. RNN encoder-decoders with attention had made attention the key ingredient of neural translation, and the transformer showed that it could be the only one, with feed-forward layers in between.
Three benefits follow from dropping the recurrence. Every position can be computed at once, so training parallelises across the sentence. Words far apart are one step apart, not many, which handles long-range dependencies. And there is no recurrence for a gradient to vanish along.
The consequences for translation are visible today. Transformer systems are the standard, and massively multilingual ones such as M2M-100 and NLLB translate between hundreds of language pairs (Fan et al. 2021; Team 2022). General-purpose large language models translate competitively when simply asked to, with no dedicated translation model, the machinery of Chapter 19 applied to one more task.
Run it. The script
ibm_model1.pyin the foldercode/worked_examplesproduces every table of this section. Run it with--neuralfor the encoder, the staged decoder step, the attention scores and the teacher forced loss, or with--bottleneckto measure what one vector forgets. The flag--objectivecomputes for two pairs, and--bpttruns the backward pass and checks all thirty gradients against finite differences. Add--encodersfor the backward and second layers,--localto compare global and local attention, and--inferfor the three phases and the alignment table. The flag--setupcounts the parameters of the typical system and--multicounts the zero-shot directions. Change a chosen weight at the top of the file and watch which numbers move.
The decoder has produced a translation, and the next question is whether it is any good. A label has one right answer and a translation has many, since It is raining, It’s raining and Rain is falling all translate Il pleut, so a metric that credits only one of them is measuring the wrong thing. Translation is where the automatic evaluation of generated text began, with BLEU (Papineni et al. 2002), and the same difficulty returns for every generated output after it. BLEU and the metrics that grew up around it, through ROUGE and the learned metrics, are collected in one place, Chapter 23, and not worked here.
Translation retraces the arc of this part. Counting words gives you a translation model, adding a hidden variable gives you alignment, adding phrases gives you local context, replacing tables with vectors gives you generalisation, and adding attention removes the bottleneck. Widening the model to many languages then gave translation between pairs nobody had trained. Each step was taken because the previous step had a named limitation.
Attention has so far been a decoder looking at an encoder, globally and then locally. It is not the end of the story, since the recurrence still has to run one step at a time, and Chapter 17 lets a sequence look at itself so that the recurrence can go.
How to judge a translation is a question about every generated text, and Chapter 23 takes it up. The next chapter first takes the simplest task these models are put to, classification, where there is one right label, and uses it to build the evaluation discipline that every later chapter depends on.
Summary
Translation drove the field through four generations, each ended by a limitation the next addressed. The noisy channel splits the problem into a language model, estimated from monolingual text, and a translation model, learned from aligned pairs. IBM Model 1 learns word alignments by expectation maximisation, and a tie in the data stays a tie. Phrase tables improved on words and still cannot generalise to unseen phrases. The neural encoder-decoder trains one network on the log likelihood of the target, but a single vector cannot hold a long source, and attention lets the decoder look back at every source state with weights that are a learned soft alignment. Teacher forcing trains on gold words, beam search decodes with length normalisation, and a multilingual model shares one network across many directions. The same shape, an encoder and a decoder that look at each other, carries over to other tasks.
Key terms
noisy channel model. the factorisation of translation into a language model of the target and a translation model.
alignment. a link between a target word and the source word it translates.
expectation maximisation. an iterative method that alternates expected counts and re-estimation of parameters.
encoder-decoder. a network that encodes the source into states and decodes the target from them.
attention. a weighted average of encoder states, with weights computed from the decoder state.
teacher forcing. training the decoder on the gold previous word, not on its own output.
beam search. decoding that keeps the best few partial hypotheses at each step.
zero-shot translation. translating between a language pair that was never seen together in training.
Brown et al. (1993) set out the IBM models, and the mathematics is more readable than its reputation suggests. Sutskever et al. (2014) introduced sequence to sequence learning and Bahdanau et al. (2014) added attention to it, while Luong et al. (2015) compare the ways of scoring and of looking, and Papineni et al. (2002) define BLEU. Cho et al. (2014) documented the failure of the single vector on long sentences, and Schuster and Paliwal (1997) is the source of the bidirectional recurrence. Johnson et al. (2017) describe the multilingual model with a target token, and Fan et al. (2021) and Team (2022) take the idea to hundreds of languages. The transformer arrived in Vaswani et al. (2017), whose experiments are translation experiments. Jurafsky and Martin (2025) cover the whole arc with more attention to the statistical models.
14.1 Split the problem. Explain why Equation (14.2) factorises into a translation model and a language model, and why that split was worth making given the data available in 1990. Which factor would you expect to improve fastest today, and why?
14.2 One EM iteration. On the four-pair corpus, carry out the first expectation and maximisation steps by hand. Confirm that every is , that my accumulates units of count, and that comes out at .
14.3 The honest tie. Explain why and remain at however long you iterate. Then design a different fifth sentence pair that would break the tie the other way, and predict what it would do to .
14.4 Alignment is not symmetric. Model 1 aligns each foreign word to one English word. Explain why running it in both directions gives two different alignments, and why phrase extraction begins with their intersection rather than either one.
14.5 The table’s ceiling. A phrase table contains the red house but not the crimson house. Describe what a phrase-based system does with the second, and what an encoder-decoder does instead. Which chapter of this book made the same argument about n-grams?
14.6 Attention as alignment. Argue that attention weights in a neural translation decoder are the same object as IBM Model 1’s alignment posterior. Then name two ways they differ, and say which of the two matters more in practice.
Build and measure
14.7 Attention by hand. Using the three encoder states of this chapter and the decoder state , recompute the dot-product scores, the softmax weights and the context, and confirm for the first word. Then use and say which source word the decoder now favours, and why.
14.8 Teacher forcing. During training the decoder is fed the gold previous word. Explain what is different at test time, and why a model that has only ever been fed correct words can compound its own first mistake.
14.9 Length and the beam. Score the two hypotheses of this chapter by for , and . Between which values of does the ranking change, and what does that say about choosing ?
14.10 Two contexts. The context vector of an encoder-decoder and the context of an -gram language model are both summaries of what has been read. Say what each contains, how large each is, and what each throws away.
14.11 The objective, by hand. Using the probabilities in the table of One model, one objective, recompute for the second pair and confirm . Then explain why the shorter pair has the higher probability, and say which of the two quantities, the total or the per word loss, you would compare across corpora with different sentence lengths.
14.12 What one vector forgets. Take the ratios of successive distances in the first column of the bottleneck table, over the steps from to , and compare them with and , the eigenvalues of the encoder’s . What would you expect the ratio to do for very long sources, and what does the second column say attention can do about it?
14.13 The error that arrives late.
In the backward table, the entry for step
in the middle column is
.
Say which later steps contributed to it, through which matrix, and why
the same column is zero at step
.
Then use --bptt after changing the gold word of the last
step and predict, before running, the sign of the change in
.
14.14 Read both ways. In the table that changes the last source word, the forward states of the first two words move by exactly zero. Explain why, and explain why a decoder could not use a backward recurrence in the same way, using Chapter 12.
14.15 Narrowing the window. Recompute the local attention weights with , which has , and check by hand that all three positions now fall in the window. For a source of words and an output of words, count the scores computed by global attention and by local attention with .
14.16 Three phases. Write the three phases of translating a new sentence as pseudocode with a length limit and a minimum length. The chapter’s toy produced two different endings for phase three. Name them, and say which of them a system with a well trained decoder should almost never reach.
In practice
14.17 Count a system. Repeat the parameter count for a hidden size of , four layers on each side and a subword vocabulary of , and say which of the three parts, the layers, the embeddings or the output layer, is now largest. Then say what that implies for a choice between a bigger vocabulary and a bigger hidden layer.
14.18 Languages and directions. For languages with English at the centre of the training data, count the directions trained, served and zero-shot. Then say how many zero-shot directions remain if data also exists for one direct pair, French and German, in both directions.
14.19 Zero-shot. A multilingual model trained on English to French and English to German translates French to German without ever seeing that pair. Propose an experiment that would distinguish a genuinely shared representation from translation that quietly routes through English.
14.20 Which generation? A client needs translation for a language with parallel sentences and a lot of monolingual text. Choose among the approaches of this chapter, justify the choice, and name what you would do with the monolingual text.
Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.
ibm_model1.pyEM learning an alignment
Four sentence pairs, and a translation table that arrives without anyone labelling a single word. Then the neural turn, worked in full: the objective, an encoder and decoder, what one vector forgets, backpropagation checked against finite differences, both directions and two layers, global and local attention, the three phases of translating, a counted system, and zero-shot directions.
runs in your browser Run itFrom Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.