Sequence-to-Sequence Models
Sequence-to-Sequence (Seq2Seq) models are neural architectures that map an input sequence of arbitrary length to an output sequence of arbitrary (and different) length, using an encoder–decoder structure connected through a compressed latent representation called the context vector. They matter because they unified disparate NLP tasks — machine translation, summarization, question answering, speech recognition — under a single trainable framework, replacing decades of hand-engineered pipelines. The counterintuitive fact: the entire meaning of a variable-length source sentence is initially compressed into a single fixed-size vector of typically 256–1024 floats — a bottleneck so severe it nearly killed the architecture before attention mechanisms saved it.
The "aha moment" for Seq2Seq is that language generation can be factored into two separate problems: understanding (encoding the input into a meaning-rich representation) and production (decoding that representation step-by-step into output tokens). The encoder runs over the full source sequence and summarizes it; the decoder then generates one token at a time, conditioning each choice on everything generated so far plus that summary. This autoregressive decoding loop — where each output becomes part of the context for the next — is what makes Seq2Seq fundamentally different from a simple classifier or tagger. The magic is that both halves are trained jointly end-to-end from raw (source, target) pairs, with no explicit supervision on what the internal representation should look like.
How It Works
Encoder
The encoder reads the source sequence token by token. At each step , an embedding lookup converts the token index into a dense vector, which is fed into a recurrent cell (GRU or LSTM) to update the hidden state:
Explanation: The encoder hidden state at time is a deterministic function of the previous hidden state and the current token's embedding — it accumulates a running summary of the source sequence.
Symbols:
- — encoder hidden state at step , dimensionality
- — the recurrent cell (GRU/LSTM) parameterized by weights
- — source embedding matrix, is source vocabulary size
- — integer token index at position
After processing all tokens, the final hidden state becomes the context vector — the compressed encoding of the entire source.
Decoder
The decoder generates the target sequence autoregressively. Its hidden state evolves as:
Explanation: The decoder state at step depends on the previous decoder state, the embedding of the previously generated token, and the fixed context vector — the context is re-injected at every step.
Symbols:
- — decoder hidden state at step
- — decoder recurrent cell with separate parameters
- — target-side embedding matrix
- — the token generated at the previous step (or `` at )
- — context vector from encoder
Output Distribution
At each decoding step the hidden state is projected onto the target vocabulary via a linear layer followed by a softmax:
Explanation: This converts the decoder's internal state into a probability distribution over all target vocabulary words, from which the next token is sampled or argmax-selected.
Symbols:
- — output projection weight matrix
- — output bias
- — all previously generated tokens
Training Objective
The model is trained by minimizing the cross-entropy loss summed over all target positions, averaged across a batch of examples:
Explanation: The model is penalized for assigning low probability to the correct next token at every position in every target sequence — equivalently, it is maximizing the likelihood of the ground-truth translations.
Symbols:
- — batch size
- — length of the -th target sequence
- — the ground-truth token at position for example
During training, teacher forcing is used: the ground-truth token (not the model's own prediction) is fed as input at each decoder step, which stabilizes gradients but introduces a train/inference discrepancy known as exposure bias.
PyTorch Sketch
```python import torch import torch.nn as nn class Encoder(nn.Module): def __init__(self, vocab_size, emb_dim, hid_dim): super().__init__() self.embed = nn.Embedding(vocab_size, emb_dim, padding_idx=0) self.rnn = nn.GRU(emb_dim, hid_dim, batch_first=True) def forward(self, src): # src: (B, T) embedded = self.embed(src) # (B, T, emb_dim) outputs, hidden = self.rnn(embedded) # outputs: (B, T, hid_dim) return outputs, hidden # hidden: (1, B, hid_dim) class Decoder(nn.Module): def __init__(self, vocab_size, emb_dim, hid_dim): super().__init__() self.embed = nn.Embedding(vocab_size, emb_dim, padding_idx=0) self.rnn = nn.GRU(emb_dim + hid_dim, hid_dim, batch_first=True) self.fc_out = nn.Linear(hid_dim, vocab_size) def forward(self, tgt_tok, hidden, context): # tgt_tok: (B,1), context: (B,1,hid_dim) emb = self.embed(tgt_tok) # (B, 1, emb_dim) rnn_in = torch.cat([emb, context], dim=2)# (B, 1, emb_dim+hid_dim) out, hidden = self.rnn(rnn_in, hidden) # out: (B, 1, hid_dim) logits = self.fc_out(out.squeeze(1)) # (B, vocab_size) return logits, hidden ```
Sutskever completed his PhD under Geoffrey Hinton at the University of Toronto and later became a co-founder of OpenAI. His 2014 NeurIPS paper "Sequence to Sequence Learning with Neural Networks" (with Vinyals and Le) introduced the canonical encoder–decoder LSTM architecture that first achieved competitive machine translation performance end-to-end. Remarkably, the paper showed that reversing the source sentence before encoding substantially improved translation quality — a simple empirical trick that reduced the "minimum time lag" between aligned source and target words.
Cho developed the Gated Recurrent Unit (GRU) and the encoder–decoder framework for neural machine translation simultaneously with Sutskever's group, publishing the landmark paper "Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation" at EMNLP 2014. His formulation explicitly characterized the bottleneck problem and laid the groundwork for the attention mechanism introduced in his follow-up work with Bahdanau. A little-known fact: Cho and Bahdanau's attention paper was initially rejected for oral presentation at ICLR 2015 before becoming one of the most-cited papers in NLP history.
Intuition
Imagine you are a professional translator hired to translate an English speech into French. The vanilla Seq2Seq model is like giving you a single index card to take notes during the entire speech — you must compress everything you hear onto that card, then speak the translation from memory. If the speech is five sentences, fine. If it's a dissertation, your notes will be catastrophically incomplete.
Attention is like letting you re-read a full transcript at any moment during your translation. When you are translating the word "gouvernement" you can glance back and find that the English word "government" appeared mid-way through — you don't have to trust that your index card captured it. The attention weights are your eyes moving across