Level 3 In-Depth AI · Deep Learning
Sequence-to-Sequence Models
One network reads a whole input sequence into a vector, a second network writes an output sequence from it. The encoder–decoder design behind neural machine translation, and the bottleneck that led to attention.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 20 concepts →
- Quiz
- 5 questions ↓
Read first
LSTMs and GRUsThis leads to
AttentionThe full path from zero — 20 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- LSTMs and GRUs
- Sequence-to-Sequence Models
Read them roughly in this order. See it on the concept map →
Why it matters
Many useful tasks turn one sequence into another of a different length. Translation turns "je suis étudiant" (3 words) into "I am a student" (4 words). Summarisation turns 500 words into 50. Speech recognition turns thousands of audio frames into a short sentence. Answering a question, turning a description into code, and turning a chemical formula into its name are the same kind of problem.
A plain recurrent network gives one output per input step, so it can't do this directly. In 2014 two groups, Ilya Sutskever, Oriol Vinyals and Quoc Le at Google, and Kyunghyun Cho and colleagues in Yoshua Bengio's lab in Montreal, proposed the same fix. Use one network to read the input and a second to write the output. This sequence-to-sequence (seq2seq) or encoder–decoder design made neural networks competitive at machine translation for the first time. Within two years Google Translate had switched to it.
The design outlived the LSTMs it was first built from. The original The Transformer is an encoder–decoder. So are T5, Whisper (Speech Recognition) and most translation systems. And the techniques introduced for seq2seq — teacher forcing, autoregressive decoding, beam search — are how every large language model is trained and how it generates text today. This chapter also explains the weakness of the first design, which is the reason Attention was invented.
The intuition
Think of a human interpreter at a conference who listens to a whole sentence in French, forms an understanding of it in their head, and then says it in English, one word at a time.
- The encoder is the listening part. An LSTM or GRU reads the source sentence word by word and updates its hidden state. Its final hidden state is a single vector meant to capture the meaning of the whole sentence, the context vector.
- The decoder is the speaking part. A second recurrent network starts from the context vector and produces the output one word at a time. After each word it takes that word as its next input, so it knows what it has already said. It stops when it produces a special end-of-sequence token.
Key idea Seq2seq = encoder (read the whole input into a vector) + decoder (generate the output one token at a time, conditioned on that vector and on its own previous outputs). Input and output lengths can differ.
How it works
The encoder
The encoder is an ordinary recurrent network run over the source tokens . Each token is first turned into a vector by an embedding layer:
The encoder's outputs at intermediate steps are thrown away. Only the final state , the context vector, is passed on. In practice the encoder is often a stack of LSTM layers, sometimes bidirectional.
The decoder
The decoder is a second RNN with its own weights, a language model for the target language that is conditioned on . Its hidden state starts at . At each output step it takes the previous output token (or a special <start> token at ) and produces a probability for every word in the target vocabulary:
The whole output sentence's probability is the product of these step probabilities, by the chain rule of probability. Generating one token at a time, each conditioned on the ones before, is called autoregressive generation.
Training with teacher forcing
The model is trained on pairs of sentences with cross-entropy loss: at each output position, how much probability did the model give to the correct next word?
But what should the decoder receive as its input at step during training: its own previous guess, or the correct previous word? Early in training its guesses are nonsense. If it had to build on them, every later step would be conditioned on garbage and learning would crawl. So during training we feed it the correct previous word, whatever it actually predicted. This is teacher forcing, like a teacher who corrects a student after every word rather than letting them ramble on from an early mistake.
Teacher forcing has a big practical benefit: all output positions can be computed in one pass, because their inputs are known in advance. It also has a cost. At test time there is no teacher, and the model must build on its own outputs. It never practised recovering from its own mistakes, so one wrong word can push it into situations it never saw in training. This mismatch is called exposure bias. Remedies such as scheduled sampling (gradually replacing true inputs with the model's own predictions) exist, but in practice teacher forcing with a good model works well, and it is still how GPT-style models are trained.
Decoding: greedy and beam search
At test time, how do we turn step-by-step probabilities into one output sentence? The best sentence is the one with the highest total probability, but there are possible sentences of length for a vocabulary of size , far too many to check.
Greedy decoding takes the single most likely word at every step. It is fast, but a choice that looks best now can lead to a worse sentence overall.
Beam search keeps the best partial sentences at each step (the "beam width", typically 4–10 for translation). It extends each of them by every possible next word, scores all the extensions by total probability, and keeps the best again. With it is greedy decoding.
A worked example with made-up probabilities. At step 1 the model gives "the" 0.5, "a" 0.4, "one" 0.1. After "the" the best next word is "cat" with 0.4. After "a", "cat" has 0.9.
- Greedy: "the" (0.5), then "cat" (0.4). Total .
- Beam width 2: keep "the" and "a". Extend both: "the cat" 0.20, "the cats" 0.15, "the kitten" 0.15, "a cat" , "a kitten" 0.04. The winner is "a cat" at 0.36.
Real implementations add up log-probabilities rather than multiplying probabilities, which avoids numbers too small for the computer to store. Because every extra word multiplies in another probability below 1, raw scores favour short outputs. So scores are usually divided by the length, or by a function of it (length normalisation). For open-ended text generation, sampling methods are preferred over beam search (Decoding: Temperature, Top-k and Top-p).
The bottleneck problem
Here is the weakness. Everything the decoder knows about the source sentence must pass through one fixed-size vector , perhaps 1,000 numbers, whether the sentence has 5 words or 50. Long sentences get squeezed, and details from the beginning are the most likely to be lost, since the encoder read them longest ago. Studies in 2014, including Cho and colleagues' On the Properties of Neural Machine Translation, found that translation quality of basic encoder–decoders fell sharply as sentences got longer.
Sutskever and colleagues found a trick that helped: feed the source sentence in reverse. Then the first source words are read last, close to the first target words that depend on them. It worked, but it was a patch.
The real fix came from Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio, also in 2014. Don't throw away the encoder's intermediate hidden states. Let the decoder, at every step, look back at all of them and take a weighted average, with weights it computes on the fly according to which source words are relevant right now. That is Attention. It removed the bottleneck, improved translation of long sentences dramatically, and three years later grew into the Transformer.
In code
A complete seq2seq model in PyTorch that learns to "translate" a sequence of eight digits into the same digits in reverse. It uses GRU encoder and decoder, teacher forcing during training and greedy decoding at test time:
import torch
import torch.nn as nn
torch.manual_seed(0)
SOS, L, V = 10, 8, 11 # tokens 0-9 are digits, 10 = start-of-sequence; length 8
def make_batch(n):
src = torch.randint(0, 10, (n, L))
return src, src.flip(1) # the "translation" is the reversed sequence
class Seq2Seq(nn.Module):
def __init__(self, hidden=128):
super().__init__()
self.embed = nn.Embedding(V, 32)
self.encoder = nn.GRU(32, hidden, batch_first=True)
self.decoder = nn.GRU(32, hidden, batch_first=True)
self.out = nn.Linear(hidden, V)
def forward(self, src, tgt_in):
_, h = self.encoder(self.embed(src)) # h: the whole input squeezed into one vector
dec, _ = self.decoder(self.embed(tgt_in), h) # decoder starts from that vector
return self.out(dec)
@torch.no_grad()
def greedy(self, src):
_, h = self.encoder(self.embed(src))
tok = torch.full((src.size(0), 1), SOS)
result = []
for _ in range(L): # feed back its own previous guess
dec, h = self.decoder(self.embed(tok), h)
tok = self.out(dec).argmax(-1)
result.append(tok)
return torch.cat(result, 1)
model = Seq2Seq()
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for step in range(1501):
src, tgt = make_batch(64)
tgt_in = torch.cat([torch.full((64, 1), SOS), tgt[:, :-1]], 1) # teacher forcing: true previous tokens
loss = nn.functional.cross_entropy(model(src, tgt_in).reshape(-1, V), tgt.reshape(-1))
opt.zero_grad(); loss.backward(); opt.step()
if step % 500 == 0:
print(f"step {step:4d} loss {loss.item():.3f}")
src, tgt = make_batch(1000)
pred = model.greedy(src)
print(f"whole-sequence accuracy {(pred == tgt).all(1).float().mean():.3f}")
print("accuracy per output position", [round(a, 3) for a in (pred == tgt).float().mean(0).tolist()])
print("input ", src[0].tolist())
print("output ", pred[0].tolist())
# step 0 loss 2.403
# step 500 loss 0.217
# step 1000 loss 0.076
# step 1500 loss 0.041
# whole-sequence accuracy 0.893
# accuracy per output position [1.0, 0.995, 0.991, 0.987, 0.973, 0.948, 0.933, 0.95]
# input [3, 2, 4, 1, 3, 3, 5, 9]
# output [9, 5, 3, 3, 1, 4, 2, 3]
Look at the accuracy per position. The first outputs are the last digits the encoder read, still fresh in the context vector, and they are almost always right. The later outputs depend on digits read seven or eight steps earlier, and on the decoder's own earlier guesses, and they go wrong more often. That is the bottleneck and exposure bias in miniature. Attention was designed to remove exactly this problem.
Beam search fits in a few lines of plain Python. Here it is on the toy probabilities from the worked example:
import math
# A toy "decoder": probabilities of the next word given the words so far
def next_probs(prefix):
table = {(): {"the": 0.5, "a": 0.4, "one": 0.1},
("the",): {"cat": 0.4, "cats": 0.3, "kitten": 0.3},
("a",): {"cat": 0.9, "kitten": 0.1},
("one",): {"cat": 1.0}}
return table.get(tuple(prefix), {"<end>": 1.0})
def beam_search(width, steps=3):
beams = [([], 0.0)] # (words, log-probability)
for _ in range(steps):
candidates = [(words + [w], logp + math.log(p))
for words, logp in beams
for w, p in next_probs(words).items()]
beams = sorted(candidates, key=lambda c: c[1], reverse=True)[:width]
return [(" ".join(w), round(math.exp(lp), 2)) for w, lp in beams]
print("greedy (width 1):", beam_search(1))
print("beam (width 2):", beam_search(2))
# greedy (width 1): [('the cat <end>', 0.2)]
# beam (width 2): [('a cat <end>', 0.36), ('the cat <end>', 0.2)]
With Hugging Face Transformers, a pretrained encoder–decoder translator runs in a few lines, and beam search is one argument: model.generate(**inputs, num_beams=5). This needs an internet download, so it isn't run here.
Common pitfalls
- Off-by-one in teacher forcing. The decoder input must be the target shifted right by one (start token first, last token dropped), and the loss target is the unshifted sequence. If you feed the target itself as input, the model learns to copy the current token and scores perfectly in training, then fails completely at generation.
- Forgetting the end token. Without an
<end>token in the training targets, the model never learns when to stop, and generation runs to the maximum length. - Padding counted in the loss. Batches of different-length sentences are padded. Pass
ignore_index=PADto the loss so the model isn't trained to predict padding. - Judging by training loss alone. Teacher-forced loss can look excellent while free-running generation is poor, because of exposure bias. Always evaluate with real decoding, using a metric such as BLEU for translation or exact match for tasks like the digits.
- Beam width too large. Wider beams are slower and, perhaps surprisingly, often produce worse translations, typically too short or generic. Widths around 4–10 are usual.
Watch out The fixed-size context vector is a real limit, not a tuning issue. If your inputs are long, add attention (or use a Transformer) rather than making the hidden state bigger.
Where it leads
- Attention: lets the decoder look at every encoder state, removing the bottleneck. This is the direct successor of this chapter.
- The Transformer: an encoder–decoder built entirely from attention. BERT keeps only the encoder and GPT keeps only the decoder.
- Decoding: Temperature, Top-k and Top-p: greedy, beam, temperature, top-k and nucleus sampling for modern language models.
- Speech Recognition (Whisper is an encoder–decoder Transformer) and image-to-text models use the same reader–writer split.
A bit of history
Nal Kalchbrenner and Phil Blunsom published an early neural encoder–decoder for translation in 2013. In 2014 Cho and colleagues introduced the RNN encoder–decoder together with the GRU, and Sutskever, Vinyals and Le published Sequence to Sequence Learning with Neural Networks. The latter used deep LSTMs, reversed the source sentences, and reached a BLEU score of 34.8 on the WMT 2014 English-to-French task, competitive with the phrase-based systems that had dominated for a decade. Bahdanau, Cho and Bengio added attention the same year. In 2016 Google replaced the phrase-based Google Translate with GNMT, an LSTM encoder–decoder with attention and 8 layers on each side. The teacher forcing name and idea go back to Ronald Williams and David Zipser's work on recurrent networks in 1989. In 2017, Attention Is All You Need kept the encoder–decoder shape but replaced the recurrence with attention.
Try it
- Change
Lto 16 and train again. What happens to whole-sequence accuracy and to the per-position accuracies? This is the bottleneck.- Feed the source to the encoder reversed (
self.encoder(self.embed(src.flip(1)))), as Sutskever and colleagues did. Does accuracy get better or worse on this task? Look at the per-position accuracies.- In the beam-search code, change P("cat" | "a") from 0.9 to 0.4. Does beam search still beat greedy?
Hint for 2: count the steps between reading a digit and writing it. Without reversal the gaps are 1, 3, 5, … 15 steps: the first outputs are easy and the last are hard. With reversal the task becomes copying, and every gap is exactly 8. For real translation, where the first output words depend mostly on the first input words, reversal shortens the gaps that matter most.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Sequence to Sequence Learning with Neural Networks
The encoder–decoder LSTM for machine translation.
NLP From Scratch: Translation with a Sequence to Sequence Network and Attention
Official PyTorch tutorial that builds a GRU encoder–decoder with attention to translate French to English.
Visualizing A Neural Machine Translation Model (Mechanics of Seq2seq Models With Attention)
Animated, step-by-step pictures of an encoder–decoder translating a sentence, with and without attention.
Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation
Introduced the gated recurrent unit (GRU) and an RNN encoder–decoder for translation.
Neural Machine Translation by Jointly Learning to Align and Translate
Introduced attention to let a decoder look back at every input word.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Stanford CS224N: NLP with Deep Learning
Word vectors, RNNs, attention, Transformers and LLMs, with lecture videos on YouTube.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/seq2seq.md