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 core insight

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 x=(x1,x2,…,xT)\mathbf{x} = (x_1, x_2, \ldots, x_T) token by token. At each step tt, 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:

1
ht(enc)=fθ ⁣(ht−1(enc),  Esrc xt)\quad \mathbf{h}_t^{(\text{enc})} = f_\theta\!\left(\mathbf{h}_{t-1}^{(\text{enc})},\; \mathbf{E}_{\text{src}}\, x_t\right)

Explanation: The encoder hidden state at time tt 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:

  • ht(enc)∈Rd\mathbf{h}_t^{(\text{enc})} \in \mathbb{R}^d — encoder hidden state at step tt, dimensionality dd
  • fθf_\theta — the recurrent cell (GRU/LSTM) parameterized by weights θ\theta
  • Esrc∈Rd×∣Vsrc∣\mathbf{E}_{\text{src}} \in \mathbb{R}^{d \times |V_{\text{src}}|} — source embedding matrix, ∣Vsrc∣|V_{\text{src}}| is source vocabulary size
  • xt∈Zx_t \in \mathbb{Z} — integer token index at position tt

After processing all TT tokens, the final hidden state c=hT(enc)\mathbf{c} = \mathbf{h}_T^{(\text{enc})} becomes the context vector — the compressed encoding of the entire source.

Decoder

The decoder generates the target sequence y=(y1,y2,…,yT′)\mathbf{y} = (y_1, y_2, \ldots, y_{T'}) autoregressively. Its hidden state evolves as:

2
st=gϕ ⁣(st−1,  Etgt yt−1,  c)\quad \mathbf{s}_t = g_\phi\!\left(\mathbf{s}_{t-1},\; \mathbf{E}_{\text{tgt}}\, y_{t-1},\; \mathbf{c}\right)

Explanation: The decoder state at step tt 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:

  • st∈Rd′\mathbf{s}_t \in \mathbb{R}^{d'} — decoder hidden state at step tt
  • gϕg_\phi — decoder recurrent cell with separate parameters ϕ\phi
  • Etgt\mathbf{E}_{\text{tgt}} — target-side embedding matrix
  • yt−1y_{t-1} — the token generated at the previous step (or `` at t=1t=1)
  • c\mathbf{c} — 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:

3
P(yt∣y<t, x)=softmax ⁣(Wo st+bo)\quad P(y_t \mid y_{<t},\, \mathbf{x}) = \text{softmax}\!\left(\mathbf{W}_o\, \mathbf{s}_t + \mathbf{b}_o\right)

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:

  • Wo∈R∣Vtgt∣×d′\mathbf{W}_o \in \mathbb{R}^{|V_{\text{tgt}}| \times d'} — output projection weight matrix
  • bo∈R∣Vtgt∣\mathbf{b}_o \in \mathbb{R}^{|V_{\text{tgt}}|} — output bias
  • y<t=(y1,…,yt−1)y_{<t} = (y_1, \ldots, y_{t-1}) — 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 NN examples:

4
L=−1N∑n=1N∑t=1Tn′log⁡P ⁣(yt(n)∣y<t(n), x(n))\quad \mathcal{L} = -\frac{1}{N} \sum_{n=1}^{N} \sum_{t=1}^{T'_n} \log P\!\left(y_t^{(n)} \mid y_{<t}^{(n)},\, \mathbf{x}^{(n)}\right)

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:

  • NN — batch size
  • Tn′T'_n — length of the nn-th target sequence
  • yt(n)y_t^{(n)} — the ground-truth token at position tt for example nn

During training, teacher forcing is used: the ground-truth token yt−1(n)y_{t-1}^{(n)} (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 ```

researcher · Ilya Sutskever | b. 1986 | Seq2Seq with LSTMs for Machine Translation

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.

researcher · Kyunghyun Cho | b. 1986 | GRU and Encoder–Decoder Framework

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.

Figure
Seq2Seq Encoder–Decoder Architecture
Sequence-to-Sequence: Encoder → Context → Decoder ENCODER "The" "cat" "sat" "<EOS>" h₁ h₂ h₃ h₄ CONTEXT VECTOR c hT DECODER s₁ s₂ s₃ s₄ "Le" "chat" "était" "<EOS>" c injected at each step
Figure
Attention Mechanism — Alignment Weights
Attention: Dynamic Context per Decoder Step ENCODER HIDDEN STATES h₁ … h₄ h₁ h₂ h₃ h₄ 0.05 0.15 0.65 0.15 Dynamic Context cₜ = Σ αₜᵢ hᵢ Decoder step t sₜ Attention weights α sum to 1 (softmax). Largest weight → most relevant encoder state.

Intuition

The Mental Model

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