Encoder–decoder sequence-to-sequence models
Encoder–decoder (seq2seq) models map an input sequence to an output sequence using an encoder to compress input information into a state and a decoder to generate the output, trained by maximum-likelihood (cross-entropy) and often improved with techniques such as teacher forcing and attention.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Encoder–decoder sequence-to-sequence models are used when the input and output are both sequences of possibly different lengths — for example, machine translation (English sentence → Hindi sentence), summarisation, or speech recognition. Engineers use them to build pipelines that convert one sequence type to another where alignment is not one-to-one.
Key ideas
Exact RNN update (example): For a simple RNN cell, h_t = tanh(W_h·h_{t-1} + W_x·x_t + b).
Draw a diagram: draw a sequence of encoder cells left-to-right. Label input tokens x1, x2, …, xT_x beneath each cell. Draw arrows between hidden states h0 → h1 → … → hT_x. Circle the final hidden state hT_x and label it “context” or c.
Decoder: A neural network (RNN/LSTM/GRU) that generates output tokens step-by-step. At decoder step s it computes a hidden state s_s = g(s_{s-1}, y_{s-1}, c) and produces a distribution over the next token: P(y_s | y_{<s}, x) = softmax(o_s). Decoding starts from a special BOS token y_0 and stops when an EOS token is produced or a maximum length is reached.
Draw a diagram: draw decoder cells left-to-right (or top-to-bottom). Show the context c (from encoder) feeding into each decoder cell. Label outputs y1, y2, … and predicted probabilities above each decoder cell.
Conditional probability factorisation: The decoder models P(y | x) = Π_{s=1}^{T_y} P(y_s | y_{<s}, x). This is the chain rule applied conditionally on x.
Training (maximum likelihood / cross-entropy): Given training pairs (x, y*), we maximise the conditional log-likelihood log P(y* | x). Equivalently, minimise the cross-entropy loss L = -Σ_{s=1}^{T_y} log P(y*s | y*{<s}, x).
Teacher forcing: During training, the decoder is often fed the true previous token y*_{s-1} instead of the decoder’s own previous prediction. This makes training faster and stabilises gradients but causes a mismatch between training and inference (exposure bias). Practical variants use a teacher-forcing ratio or scheduled sampling to mix gold and model tokens during training.
Inference (greedy and beam search): At test time we cannot condition on true y, so we must generate: common strategies are greedy decoding (choose argmax at each step) or beam search (keep top-k partial sequences and expand). Beam search improves quality at the cost of compute. Beam search typically accumulates sums of log-probabilities and often applies length normalisation to mitigate a short-output bias.
Bottleneck and attention: Encoding an entire input into a single fixed-size vector c can limit performance for long sequences. The attention mechanism (see the course topic "Attention mechanism") lets the decoder attend to different encoder states at each step, producing a context vector c_s = Σ_{t} α_{s,t}·h_t where α_{s,t} are attention weights. Attention relieves the fixed-size bottleneck and improves alignment.
Assumptions and limits: The chain-rule factorisation P(y | x) = Π_{s=1}^{T_y} P(y_s | y_{<s}, x) is an identity; the modeling assumption is that the parameterised encoder–decoder can approximate these conditionals with finite state and capacity. RNN-based encoders/decoders can suffer vanishing/exploding gradients for long sequences unless LSTM/GRU or gating is used. Attention is usually required for long or complex alignments.
Formulas
P(y | x) = Π_{s=1}^{T_y} P(y_s | y_{<s}, x) — P(y | x) is the probability of output sequence y given input x; unitless; applies to any autoregressive decoder.
h_t = f(h_{t-1}, x_t) — hidden state update for encoder at input step t; h_t is unitless vector; f is the RNN cell (e.g., tanh(W_h·h_{t-1} + W_x·x_t + b)).
s_s = g(s_{s-1}, y_{s-1}, c) — decoder hidden update at step s; s_s is unitless vector; g is the decoder cell (RNN/LSTM/GRU); c is context from encoder. In practice y_{s-1} is provided as its embedding e_{s-1} = Emb(y_{s-1}).
o_s = V·s_s + b_o — pre-softmax scores (logits) at decoder step s; o_s is a real vector of length |Vocab|; unitless.
P(y_s = i | y_{<s}, x) = softmax(o_s)_i = exp(o_{s,i}) / Σ_j exp(o_{s,j}) — probability of token i; unitless; applies to categorical outputs.
L(x,y*) = -Σ_{s=1}^{T_y} log P(y*_s | y*_{<s}, x) — negative log-likelihood (sequence cross-entropy); units: nats (if natural log) or bits (if log base 2). Minimised during training. In batched training, PAD tokens are masked in the sum; losses are often normalised by total target tokens (average per-token loss) rather than per-sequence.
c_s = Σ_{t=1}^{T_x} α_{s,t}·h_t and α_{s,t} = softmax(score(s_{s-1}, h_t)) — attention context and attention weights at decoder step s; α_{s,t} are unitless and sum to 1.
Per-token loss = -log P(y*_s | y*_{<s}, x) — contribution to L from one time step. Perplexity for a sequence is exp((1/T_y) Σ_{s=1}^{T_y} -log P(y*s | y*{<s}, x)); lower is better.
Worked examples
Example 1 — model answer (derivation): Show how training objective follows from maximum likelihood.
- Write conditional likelihood for a single training pair (x,y*): P(y* | x) = Π_{s=1}^{T_y} P(y*s | y*{<s}, x) by the chain rule.
- Take negative log to make optimisation convenient: -log P(y* | x) = -Σ_{s=1}^{T_y} log P(y*s | y*{<s}, x).
- For a dataset D of N pairs, total loss is L = (1/N) Σ_{(x,y*)∈D} [-Σ_{s=1}^{T_y} log P(y*s | y*{<s}, x)]. Many implementations instead divide by the total number of target tokens to report average per-token loss.
- Explain that each term -log P(y*_s | ·) is a cross-entropy between the one-hot target and the decoder's softmax output; gradients flow through the decoder and encoder via backpropagation through time.
- Conclude: training minimises L using stochastic gradient descent or variants (Adam, RMSProp). Mention teacher forcing: during computing P(y*s | y*{<s}, x) at training time we supply y*_{s-1} as input to the decoder cell.
Example 2 — numerical cross-entropy for one time step and a two-step sequence (numbers checked twice): Data: vocab size 3 tokens {A,B,C}. Ground-truth output y* = (A, C) with indices (0,2). Decoder logits at step 1: z1 = [2.0, 1.0, 0.1]; at step 2: z2 = [0.0, 0.5, 1.5]. Use natural logarithm. Step 1: softmax(z1): exp = [e^2.0, e^1.0, e^0.1] = [7.389, 2.718, 1.105]; sum = 11.212. p1 = 7.389/11.212 = 0.6590. Per-token loss1 = -ln(0.6590) = 0.4170 nats. Step 2: softmax(z2): exp = [1.000, 1.6487, 4.4817]; sum = 7.1304. p2 (target index 2) = 4.4817/7.1304 = 0.6285. Per-token loss2 = -ln(0.6285) = 0.4653 nats. Sequence loss = loss1 + loss2 = 0.4170 + 0.4653 = 0.8823 nats. Final answer: 0.8823 nats (average per token = 0.4412 nats).
Example 3 — exam-style short essay: "Why is attention needed?" A full-marks answer includes: definition of the fixed-size bottleneck, explanation that compressing long variable-length input into a single vector c loses information, empirical failures on long sentences, formal explanation how attention forms c_s = Σ α_{s,t} h_t allowing per-step alignment, and mention of scoring function options (dot-product, bilinear, MLP) and that attention weights are softmax-normalised. Conclude with practical improvement (better BLEU/accuracy) and reference to beam search working with attention.
Common mistakes
- Treating softmax outputs as logits; mixing up o_s and softmax(o_s).
- Not normalising attention weights (sum-to-one constraint). If using softmax, α must sum to 1. Also ensure PAD positions in the encoder are masked (excluded) before the softmax over t.
- During numerical loss work, using base-10 log but calling units "nats" (nats require natural log).
- Confusing training-time and inference-time behaviour (exposure bias): during training we can use true previous token; at inference we cannot.
For your exam
Typical question types:
- Definitions: define encoder, decoder, teacher forcing, cross-entropy, attention (brief).
- Short notes: explain inference (beam search), explain exposure bias, explain attention conceptually.
- Derivations: derive the training loss from maximum-likelihood; show how backprop passes through encoder and decoder states (outline BPTT); derive attention context formula.
- Numericals: compute softmax and cross-entropy for given logits and target sequence (carry units: nats if ln used). Apply masking to exclude PAD tokens from the loss.
- Diagrams: draw encoder stack, decoder stack, arrows for hidden-state flow, label context c and outputs; for attention, show connections from each decoder step to all encoder states with attention weights α_{s,t}.
What a full-marks answer includes: correct definitions with bold terms, the chain-rule factorisation P(y | x) = Π P(y_s | y_{<s}, x), the negative log-likelihood objective, teacher forcing explained, a clear diagram (labels for x_t, h_t, c, s_s, y_s), and mention of inference methods and limitations (bottleneck, need for attention).
Quick check
- Write the chain-rule factorisation used by the decoder for P(y | x).
- What is teacher forcing and why do we use it in training?
- Give the formula for attention context c_s using attention weights α_{s,t}. Answers: 1) P(y | x) = Π_{s=1}^{T_y} P(y_s | y_{<s}, x). 2) Teacher forcing: feeding the true previous target y*_{s-1} into the decoder during training to stabilise and speed up learning; it causes exposure bias at inference. 3) c_s = Σ_{t=1}^{T_x} α_{s,t}·h_t, with α_{s,t} = softmax(score(s_{s-1}, h_t)).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?