◆ AI All-in-One

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
↗ Plan a path here

Read first

LSTMs and GRUs

This leads to

Attention
The full path from zero — 20 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. Recurrent Neural Networks
  17. Backpropagation
  18. Activation Functions
  19. Vanishing and Exploding Gradients
  20. LSTMs and GRUs
  21. 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.
je suis étudiant <start> I I am am a a student student <end> encoder reads the source sentence context one fixed vector = the bottleneck decoder writes the translation one word at a time; dashed: each output becomes the next input
Fig. 1 An encoder–decoder translating "je suis étudiant". The encoder reads the source into one fixed vector, the context. The decoder starts from it and writes the English words one at a time, feeding each word back in as its next input.

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 x1,…,xSx_1, \dots, x_S. Each token is first turned into a vector by an embedding layer:

hs=RNNenc(hs−1,embed(xs)),c=hS\mathbf{h}_s = \text{RNN}_{\text{enc}}(\mathbf{h}_{s-1}, \text{embed}(x_s)), \qquad \mathbf{c} = \mathbf{h}_S

The encoder's outputs at intermediate steps are thrown away. Only the final state c\mathbf{c}, 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 c\mathbf{c}. Its hidden state starts at c\mathbf{c}. At each output step tt it takes the previous output token yt−1y_{t-1} (or a special <start> token at t=1t = 1) and produces a probability for every word in the target vocabulary:

dt=RNNdec(dt−1,embed(yt−1)),d0=c\mathbf{d}_t = \text{RNN}_{\text{dec}}(\mathbf{d}_{t-1}, \text{embed}(y_{t-1})), \qquad \mathbf{d}_0 = \mathbf{c}
P(yt∣y1,…,yt−1,x)=softmax(Wodt)P(y_t \mid y_1, \dots, y_{t-1}, \mathbf{x}) = \text{softmax}(\mathbf{W}_o \mathbf{d}_t)

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 tt 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.

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 VTV^T possible sentences of length TT for a vocabulary of size VV, 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 kk 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 kk again. With k=1k = 1 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.

start 0.5 the 0.4 a 0.1 one 0.4 the cat = 0.5 × 0.4 = 0.20 0.3 the cats = 0.5 × 0.3 = 0.15 0.3 the kitten = 0.5 × 0.3 = 0.15 0.9 a cat = 0.4 × 0.9 = 0.36 0.1 a kitten = 0.4 × 0.1 = 0.04 dropped: not in the top 2 step 1: keep the best 2 step 2: score whole sequences greedy picks “the” (0.5) first and ends with “the cat”: 0.20 beam search (width 2) also keeps “a” and finds “a cat”: 0.36
Fig. 2 Greedy decoding versus beam search with width 2. Greedy commits to "the" because it is the best first word, and ends up with "the cat" at probability 0.5 × 0.4 = 0.20. Beam search keeps "a" as a second candidate and finds "a cat" at 0.4 × 0.9 = 0.36.
  • Greedy: "the" (0.5), then "cat" (0.4). Total 0.5×0.4=0.200.5 \times 0.4 = 0.20.
  • Beam width 2: keep "the" and "a". Extend both: "the cat" 0.20, "the cats" 0.15, "the kitten" 0.15, "a cat" 0.4×0.9=0.360.4 \times 0.9 = 0.36, "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 c\mathbf{c}, 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=PAD to 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

  1. Change L to 16 and train again. What happens to whole-sequence accuracy and to the per-position accuracies? This is the bottleneck.
  2. 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.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. During training, the decoder is fed the correct previous word at every step, whatever it actually predicted. What is this called, and what problem can it cause?

  2. Step 1 probabilities are 'the' 0.5 and 'a' 0.4. P('cat' | 'the') = 0.4 and P('cat' | 'a') = 0.9. Which output does beam search with width 2 choose, and with what probability?

  3. A basic encoder–decoder translates short sentences well but long ones badly. What is the main reason?

  4. Your seq2seq model gets near-perfect teacher-forced training loss but outputs garbage when generating. You fed the target sequence itself, unshifted, as decoder input. What happened?

  5. Why do beam search implementations usually apply length normalisation?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/seq2seq.md