AI Logic

Architectures

Sequence to Sequence

Updated:

Architecture of Sequence to Sequence. On the left, the encoder LSTM reads the input sentence A B C in reverse order and compresses it into a fixed-length vector v. On the right, the decoder LSTM starts from v and emits W X Y Z and <EOS>, feeding each previously emitted word back in as the next input

Background and overview

Sequence to Sequence (seq2seq) is a model that compresses an input sequence into a fixed-length vector with one LSTM (the encoder) and then generates the output sequence from that vector one word at a time with another LSTM (the decoder). Proposed by Sutskever et al. in 2014, it showed on English-to-French machine translation that purely neural translation could, for the first time, beat conventional (phrase-based) statistical machine translation on a large-scale task.

A plain RNN works for tasks where each input time step maps one-to-one to an output time step (such as tagging each word with its part of speech). In translation, however, the input and output differ in length and the word order changes. A plain RNN could not be applied directly to tasks where it is not known in advance which input word corresponds to which output word.

seq2seq solves this problem in two stages.

  • Encoder: reads the entire input sequence and uses its last hidden state as a "fixed-length vector representing the input", vv.
  • Decoder: starts from vv as its initial state and, like a language model, generates the output sequence one word at a time. It stops when it emits <EOS>, the end-of-sentence symbol.

In the same year, Cho et al. also proposed an "RNN Encoder–Decoder" consisting of two RNNs, an encoder and a decoder (the GRU was introduced in that paper). However, Cho et al. used their model to score candidates produced by an existing translation system, whereas Sutskever et al. used a deep LSTM to generate the translation itself directly.

The seq2seq framework of "splitting the model into an encoder and a decoder" was carried forward through additive attention to the Transformer.

Architecture: encoder and decoder

seq2seq models the conditional probability of an output sequence (y1,…,yT′)(y_1, \dots, y_{T'}) given an input sequence (x1,…,xT)(x_1, \dots, x_T). T′T' may differ from TT. In the figure at the top of the article, the left side is the encoder and the right side is the decoder.

The computation proceeds as follows.

  1. The encoder LSTM reads the input sequence one word at a time. Each word is first converted into an embedding vector.
  2. The last hidden state (and cell state) of the encoder is taken as the fixed-length vector vv representing the input sequence.
  3. The initial state of the decoder LSTM is set to vv, and <EOS> is fed in as the first input.
  4. At each time step, the decoder outputs the probability of the next word with a softmax over the entire vocabulary.
  5. The emitted word is fed in as the input at the next time step, and step 4 repeats. Decoding stops when <EOS> is emitted.

The probability of the output sequence then factorizes into a product of per-word conditional probabilities.

p(y1,…,yT′∣x1,…,xT)=∏t=1T′p(yt∣v,y1,…,yt−1)p(y_1, \dots, y_{T'} \mid x_1, \dots, x_T) = \prod_{t=1}^{T'} p(y_t \mid v, y_1, \dots, y_{t-1})

Because every sentence always ends with <EOS>, the model can assign a probability to sequences of any length.

It is like an interpreter who listens to the whole speech, condenses it into a single page of notes, and then speaks the translation one word at a time while looking only at those notes. The size of the notes (vv) is fixed regardless of how long the speech is.

The actual model in the paper differs from this description in three ways.

  • Separate LSTMs for the encoder and decoder: they do not share weights. This increases the number of parameters at almost no extra computational cost and makes it easier to train on several language pairs at once.
  • A 4-layer LSTM: deep LSTMs clearly outperformed shallow ones, with each additional layer reducing perplexity by roughly 10%. Each layer has 1000 cells, word embeddings are 1000-dimensional, and a sentence is represented by 8000 real numbers.
  • Reading the input sentence in reverse: to translate a,b,ca, b, c into α,β,γ\alpha, \beta, \gamma, the model is given c,b,ac, b, a and asked to produce α,β,γ\alpha, \beta, \gamma (see "Why reversing the input helps" below).

Training and inference

Training maximizes the average log probability of the correct translation TT over the sentence pairs (S,T)(S, T) in the training data.

1∣S∣∑(T,S)∈Slog⁡p(T∣S)\frac{1}{|\mathcal{S}|} \sum_{(T, S) \in \mathcal{S}} \log p(T \mid S)

From the factorization above, this equals the sum over time steps of the cross-entropy of the next correct word given the correct words up to the previous one. During training, therefore, the decoder is fed the correct words rather than the words the model produced (this is called teacher forcing).

The training settings in the paper are as follows.

  • Weights initialized from a uniform distribution between −0.08 and 0.08
  • SGD without momentum, learning rate 0.7. After 5 epochs, the learning rate is halved every half epoch, for 7.5 epochs of training in total
  • Batches of 128 sentences. When the gradient norm s=∥g∥2s = \lVert g \rVert_2 exceeds 5, it is rescaled as g←5g/sg \leftarrow 5g/s (to prevent exploding gradients)
  • Sentences of similar length are grouped into the same batch (mixing short and long sentences wastes computation; this gave roughly a 2× speedup)

At inference, the most probable translation T^=arg⁡max⁡Tp(T∣S)\hat{T} = \arg\max_T p(T \mid S) is searched for with left-to-right beam search.

  1. Keep BB partial translation hypotheses.
  2. Extend each hypothesis with every word in the vocabulary.
  3. Keep only the BB hypotheses with the highest log probability under the model.
  4. Move hypotheses that end in <EOS> to the set of complete translations.

In the paper, even a beam size of 1 (always choosing the most probable word) translated well, and a beam size of 2 captured most of the benefit of beam search.

Why reversing the input helps

One of the key tricks in the paper is reversing only the input sentence (the output sentence is not reversed). This alone reduced test perplexity from 5.8 to 4.7 and raised BLEU from 25.9 to 30.6.

While admitting it lacks a complete explanation, the paper reasons as follows.

  • If the input and output sentences are concatenated into one sequence, then in normal order the first word of the input is separated from its corresponding first output word by the length of the whole input sentence.
  • Reversing the input leaves the average distance between corresponding words unchanged. But the first few words of the input (which are now read last) end up very close to the first few words of the output.
  • Having corresponding words nearby makes it easier for backpropagation to "establish communication" between input and output, which improves training overall.

The paper also notes that LSTMs trained on reversed inputs translated long sentences much better, and suggests that reversing may improve how the LSTM uses its memory.

The idea that "shortening the distance between the first words makes learning easier" was later realized more directly by attention. Attention lets the decoder look at every input position directly at each time step, making the distance between input and output 1 regardless of word order.

Experimental results

The paper evaluated the model on WMT'14 English→French translation. It trained on 12 million sentences (348 million French words and 304 million English words), with the vocabulary limited to 160,000 English words and 80,000 French words. Out-of-vocabulary words are replaced with UNK. Evaluation uses case-sensitive BLEU.

Translating with neural networks alone (BLEU on the ntst14 test set)

MethodBLEU
Bahdanau et al. (RNN with attention)28.45
Statistical machine translation baseline33.30
Single LSTM, input in original order, beam size 1226.17
Single LSTM, reversed input, beam size 1230.59
Ensemble of 5 reversed LSTMs, beam size 133.00
Ensemble of 2 reversed LSTMs, beam size 1233.27
Ensemble of 5 reversed LSTMs, beam size 234.50
Ensemble of 5 reversed LSTMs, beam size 1234.81

An ensemble of 5 LSTMs differing only in initialization and batch order surpassed the baseline's 33.30. This result was obtained with the vocabulary limited to 80,000 words, a handicap whenever the reference translation contains out-of-vocabulary words.

Rescoring the candidates of statistical machine translation (the LSTM computes the log probability of the baseline's top 1000 candidates, which is averaged with the baseline's score)

MethodBLEU
Statistical machine translation baseline33.30
RNN Encoder–Decoder of Cho et al.34.54
Rescoring with a single LSTM (input in original order)35.61
Rescoring with a single LSTM (reversed input)35.85
Rescoring with an ensemble of 5 reversed LSTMs36.5
Best WMT'14 result37.0

Broken down by sentence length, BLEU did not degrade for sentences shorter than 35 words and dropped only slightly even for the longest sentences. When the sentence vectors produced by the encoder were projected to two dimensions, sentences with similar meanings clustered together; the representations distinguished word order ("John respects Mary" vs. "Mary respects John") while being fairly insensitive to the difference between active and passive voice.

Practical considerations

Keep the following points in mind when using seq2seq.

  • Long inputs do not fit: the entire input must be squeezed into a single fixed-length vector vv. Bahdanau et al. (2014) argued that this is a performance bottleneck and pointed out that the performance of the basic encoder–decoder of Cho et al. drops sharply as input sentences get longer. For long inputs, add additive attention or multiplicative attention.
  • Out-of-vocabulary words cannot be produced: the output is a softmax over a fixed vocabulary, so words outside it become UNK.
  • Inference is sequential, one word at a time: the decoder takes its previous output as input, so it must compute step by step for the full length of the output sequence.
  • Use gradient clipping: exploding gradients can occur even with LSTMs, so clip by norm as in the paper.

During training the decoder receives the correct words, but during inference it receives the words it produced itself. Because the source of the inputs differs between training and inference, a single mistake at inference can derail the words that follow, even when the training loss is low. Always evaluate on outputs generated with the same procedure as inference (beam search, etc.).

Comparison with other models

The main ways of converting one sequence into another compare as follows.

ModelHow the input is passedInput/output length and orderLong inputs
Plain RNN (LSTM, GRU)The input at each time step is used directly for the corresponding outputMust have the same length and correspond one-to-one—
CTC (CTC Loss)Lay out the outputs of each time step and remove blanks and repeatsOutput cannot be longer than the input, and the order cannot change—
seq2seqCompresses the whole input into a single fixed-length vector vvAny length and orderPerformance tends to drop because the input does not fit in the vector
seq2seq + attention (additive attention, etc.)The decoder refers to all input positions with weights at each time stepAny length and orderHandled well
TransformerBuilds both the encoder and decoder from attention aloneAny length and orderHandled well, but computation grows with the square of the length

As a rule of thumb:

  • Conversions where both length and order change, such as translation, summarization, and dialogue: use the encoder–decoder form. Today the Transformer is the mainstream choice.
  • If building with RNNs: add attention to seq2seq. A bidirectional RNN, which can use context on both sides of each input position, is commonly used as the encoder.
  • When input and output follow the same order, as in speech recognition: CTC is also an option.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm

"""
Task: take a sequence of digits and output it sorted in ascending order (a small example that needs no data download)
Example: [3, 1, 4, 1, 5] → [1, 1, 3, 4, 5, <EOS>]
As in the paper, the encoder and decoder are separate LSTMs, and the input sequence is read in reverse order
"""

# Hyperparameters
seq_len = 8
num_digits = 10
EOS = num_digits            # End-of-sentence symbol (also the decoder's first input)
vocab = num_digits + 1
embed_dim = 32
hidden_size = 128
num_layers = 2
batch_size = 64
steps = 3000
learning_rate = 1e-3

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


def make_batch(n):
  src = torch.randint(0, num_digits, (n, seq_len))
  tgt = torch.sort(src, dim=1).values
  tgt = torch.cat([tgt, torch.full((n, 1), EOS)], dim=1)   # Append <EOS> to the end of the target
  return src.to(device), tgt.to(device)


class Seq2Seq(nn.Module):
  def __init__(self):
    super().__init__()
    self.src_embed = nn.Embedding(vocab, embed_dim)
    self.tgt_embed = nn.Embedding(vocab, embed_dim)
    self.encoder = nn.LSTM(embed_dim, hidden_size, num_layers, batch_first=True)
    self.decoder = nn.LSTM(embed_dim, hidden_size, num_layers, batch_first=True)  # Separate weights
    self.head = nn.Linear(hidden_size, vocab)   # Logits before the softmax over the whole vocabulary

  def encode(self, src):
    src = torch.flip(src, dims=[1])             # Reverse the input
    _, (h, c) = self.encoder(self.src_embed(src))
    return h, c                                 # The last (h, c) of all layers becomes v

  def forward(self, src, tgt):
    # Training: decoder input is "<EOS> + target words up to the previous one" (teacher forcing)
    h, c = self.encode(src)
    start = torch.full((tgt.shape[0], 1), EOS, device=tgt.device)
    dec_in = torch.cat([start, tgt[:, :-1]], dim=1)
    out, _ = self.decoder(self.tgt_embed(dec_in), (h, c))
    return self.head(out)                       # [B, T', vocab]

  @torch.no_grad()
  def greedy(self, src, max_len):
    # Inference: feed the previously emitted word as the next input (beam search with beam size 1)
    h, c = self.encode(src)
    y = torch.full((src.shape[0], 1), EOS, device=src.device)
    outputs = []
    for _ in range(max_len):
      out, (h, c) = self.decoder(self.tgt_embed(y), (h, c))
      y = self.head(out).argmax(dim=-1)         # [B, 1]
      outputs.append(y)
    return torch.cat(outputs, dim=1)


model = Seq2Seq().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop
model.train()
for step in tqdm(range(steps)):
  src, tgt = make_batch(batch_size)
  optimizer.zero_grad()
  logits = model(src, tgt)
  loss = criterion(logits.reshape(-1, vocab), tgt.reshape(-1))
  loss.backward()
  torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)   # As in the paper, rescale when the norm exceeds 5
  optimizer.step()

# Evaluation: generate with the same procedure as inference (own output as next input) and compare
model.eval()
src, tgt = make_batch(1000)
pred = model.greedy(src, max_len=tgt.shape[1])
seq_acc = (pred == tgt).all(dim=1).float().mean().item()
print(f"Fraction of fully correct sequences: {seq_acc * 100:.2f}%")
print("Input:", src[0].tolist(), "→ Output:", pred[0].tolist())

FAQ

Q. Are seq2seq and encoder–decoder the same thing?
A.

They are used almost interchangeably. "Encoder–decoder" is the name of the architecture that splits a model into a part that compresses the input into an intermediate representation (the encoder) and a part that produces the output from it. seq2seq usually refers to models within that family that perform "sequence-to-sequence" conversion with RNNs, originating with the 2014 papers by Sutskever et al. and Cho et al.

Q. Why use only the last hidden state rather than the encoder outputs?
A.

Because the original seq2seq absorbs the difference between input and output lengths by representing the input as a fixed-length vector. The last hidden state is the result of reading the entire input, so it serves as a summary of the whole input. On long inputs, however, this single vector cannot hold all the information, so later attention mechanisms keep the encoder outputs from every time step and let the decoder refer to the positions it needs.

Q. Is the trick of reversing the input still used today?
A.

In models with attention, the decoder can access any input position directly, so reversal is rarely needed. Reversing the input was a way to shorten the distance between the first few words in attention-free seq2seq, which compresses the whole input into a single vector. In attention-based models, it is common instead to use a bidirectional RNN as the encoder to capture context in both directions.

References

  1. Sutskever, I., Vinyals, O., & Le, Q. V. (2014). Sequence to Sequence Learning with Neural Networks. NeurIPS 2014. arXiv:1409.3215.
  2. Cho, K., van Merriënboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H., & Bengio, Y. (2014). Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation. EMNLP 2014. arXiv:1406.1078.
  3. Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015. arXiv:1409.0473.