3.5.7 · D4Sequence Models

Exercises — Sequence-to-sequence models

3,292 words15 min readBack to topic

Before we start, three pieces of shared vocabulary that every exercise below leans on:

Now, one shared picture of the machine we are testing:

Figure — Sequence-to-sequence models

Figure 1 — the seq2seq pipeline. On the left (lavender boxes ) the encoder reads input tokens one at a time; each lavender arrow carries the running hidden state forward. The final encoder state is copied into the single context vector (the coral dot in the middle). On the right (mint boxes ) the decoder starts from and produces output tokens "Estoy", "feliz", <EOS> one at a time; the dashed butter-coloured arrows show each prediction being fed back in as the next step's input. Keep this drawing in mind for every exercise — most solutions refer back to one of its three regions.


Level 1 — Recognition

Goal: can you name and locate each part of the machine?

Exercise 1.1

An input sentence has tokens and its translation has tokens. In a basic (pre-attention) seq2seq model, how many context vectors does the encoder hand to the decoder, and what is the dimension of that vector if the hidden size is ?

Recall Solution

Count: exactly one context vector. In the basic architecture, is the final encoder hidden state — a single fixed vector no matter how long the input is. (Attention is what would give a different vector per step; we do not have it here.)

Dimension: . As defined above, the hidden size is the number of entries in every hidden state, and has that same length, so .

The mismatch is exactly the point of seq2seq: the fixed vector decouples the two lengths.

Exercise 1.2

Match each symbol to its role: , , , , . (Recall from the definition above that is the previous token in the decoder's output sequence.)

Recall Solution
  • ::: the -th input token fed to the encoder.
  • ::: the context vector, the compressed "meaning" of the whole input.
  • ::: the previous output token, fed back into the decoder to produce the next output .
  • ::: the start-of-sequence token that kicks off decoding (there is no otherwise).
  • ::: the end-of-sequence token; when the decoder emits it, generation stops.

Level 2 — Application

Goal: plug numbers into the formulas correctly.

Exercise 2.1

A decoder emits these correct-token probabilities across a 3-token target. Here is the ground-truth token at position (defined above), and is the probability the model assigned to that correct token: , , . Compute the cross-entropy loss (natural log). See cross-entropy loss.

Recall Solution

Step by step:

Sum of logs , so .

Why negative: each is negative (probabilities ), so negating gives a positive loss. A perfect model with all (full confidence in every correct token) would give .

Exercise 2.2

Using the worked example from the parent note, verify the reported loss for correct-token probabilities , , .

Recall Solution

Sum .

Where does the parent note's come from? It rounds each term to two decimals before adding: , , , and then pads for a comfortable upper estimate — a quick "back-of-envelope" figure. Rounding early like this accumulates error, which is why the precise sum is the smaller . Prefer the precise value (); the parent's is only a rough sanity check, acceptable when you just want to confirm "the loss is small." Either way the message holds: confident correct predictions give a small loss.

Exercise 2.3

A vocabulary has tokens. The decoder's pre-softmax scores (logits) at one step are . Compute the softmax probability of token index 0.

Recall Solution

Softmax turns logits into a probability distribution: Here the summation index runs over every token in the vocabulary (all 5 of them, indices through ); is the logit of token . So the denominator adds up the exponential of each token's score. Exponentials: , , , , . Denominator . Why softmax: we must pick one token from , so the outputs must be non-negative and sum to 1 — a probability distribution over the vocabulary.


Level 3 — Analysis

Goal: reason about why the machine behaves the way it does.

Exercise 3.1 — Beam search vs greedy

At step 1 the decoder gives , . The continuations are:

  • After "A": , .
  • After "B": , .

(a) What 2-token sequence does greedy decoding produce, and what is its probability? (b) What sequence does beam search with width find as the best, and its probability? Show the per-step pruning. (c) What does this reveal? See beam search.

Recall Solution

(a) Greedy commits to the highest token at each step, ignoring the future. Step 1: "A" (0.6 > 0.4). Step 2 from "A": "y" (0.7 > 0.3). Greedy output: "A y", probability .

(b) Beam search, width — follow the actual pruning, step by step:

Step 1 — score the length-1 hypotheses and keep top . Candidates: "A" , "B" . There are only two, so both survive. Beam after step 1: {"A" (0.6), "B" (0.4)}.

Step 2 — expand every surviving hypothesis, then prune back to . Expand "A": "A x" , "A y" . Expand "B": "B z" , "B w" . Now we have four candidates {0.42, 0.36, 0.18, 0.04}; prune to the top 2 → keep "A y" (0.42) and "B z" (0.36). The candidates "A x" and "B w" are discarded here — this pruning is the whole point of beam search (it never keeps more than live paths).

Both survivors are complete length-2 sequences, so beam's best output is "A y" (0.42).

What pruning bought us: notice "B z" (0.36) rose to second place even though its first token "B" was weaker — it survived because we carried more than one hypothesis. Greedy would have thrown "B" away at step 1.

When greedy fails: set instead. Greedy still picks "A" then its best child (0.4), giving "A y" . But beam keeps "B" alive and finds "B z" . Beam wins, greedy misses it.

(c) Greedy is locally optimal but can be globally wrong: a strong first token can lead only to weak continuations. Beam search hedges by carrying — and pruning down to — several hypotheses per step.

Exercise 3.2 — Length normalization

Two candidate translations have log-probabilities:

  • Sequence P (2 tokens):
  • Sequence Q (4 tokens): Which wins under raw log-prob, and which under length-normalized score ?
Recall Solution

Raw log-prob: has , so P wins (less negative = higher probability).

Length-normalized:

  • :
  • :

Now wins ().

Why the flip: every extra token multiplies in another probability , so raw score always favours shorter outputs — the model would learn to stop early. Dividing by length removes this bias, letting a longer-but-per-token-confident sequence win.


Level 4 — Synthesis

Goal: combine several ideas into one coherent argument.

Exercise 4.1 — Teacher forcing and exposure bias

Explain, using a concrete cascade, why a model trained only with teacher forcing can perform worse at inference than its training loss suggests. Then propose one mitigation.

Recall Solution

The setup: during training we feed the ground-truth previous token at every step. The decoder therefore never practices recovering from its own errors — this is exposure bias.

The cascade (inference): suppose target is "Estoy muy feliz".

  • : model predicts "Estoy" ✓.
  • : model predicts "contento" instead of "muy" (a plausible slip).
  • : now the decoder's input is its own "contento", a context it saw rarely in training. It predicts "" and stops. Output: "Estoy contento" — grammatical but wrong, and the error at propagated.

Why training loss looked fine: at training the decoder always received the correct "muy", so it never entered the off-track state and never paid for it.

Mitigation: scheduled sampling — during training, with growing probability feed the model's own prediction instead of ground truth, so it learns to recover. (Beam search at inference also helps by not committing to one early slip.)

Exercise 4.2 — Bidirectional encoder

A unidirectional encoder gives . You switch to a bidirectional encoder and concatenate directions. (a) What is the dimension of the per-step encoded vector now? (b) Why does the backward pass help, given a concrete word-sense example?

Recall Solution

(a) Concatenating forward and backward states of size 128 each gives per step. If you form by concatenating the two final states, .

(b) A forward-only encoder at token has seen only — the past. But meaning often depends on the future. In "the bank of the river", the word "bank" is ambiguous until you read "river". The backward LSTM reads right-to-left, so its representation of "bank" already contains "river". Concatenating both directions gives each token a representation informed by the entire sentence, not just its left context. See LSTM networks.


Level 5 — Mastery

Goal: quantify a design limit and connect to what comes next.

Exercise 5.1 — The information bottleneck, quantified

An encoder must compress an input of tokens, each carrying about 10 bits of task-relevant information, into a context vector of real numbers. Assume (a crude but instructive bound) that under fixed precision each dimension can reliably store bits. (a) How many bits must be stored vs. how many can hold? Repeat the comparison for a -token document. (b) What does this predict, and how does the attention mechanism escape the bound?

Recall Solution

(a) Demand vs capacity.

  • Capacity of : bits — this is fixed, independent of input length.
  • Demand, 50 tokens: bits. Since , the vector has room to spare — the bottleneck is not yet saturated. This matches the parent note's remark that Sutskever et al. (2014) got good results on moderate-length sentences.
  • Demand, 400-token document: bits. Now : the vector physically cannot hold everything, so some information (typically the earliest tokens, which the LSTM tends to forget) must be overwritten.

(b) What it predicts: translation/summarisation quality with a fixed should be fine for short inputs but degrade as inputs grow long — exactly the empirical curve reported for basic seq2seq.

How attention escapes the bound: instead of squeezing everything through one fixed vector, the decoder computes a fresh context vector at each output step. Concretely, it takes a weighted sum of all encoder hidden states , with weights ("attention scores") that say how relevant each input position is right now. Two consequences:

  • The information the decoder can draw on is no longer a single -vector but the whole set — capacity now grows with input length ( bits available, far exceeding the demanded).
  • There is no forced forgetting of early tokens: if step needs , its attention weight on simply rises.

So attention removes the fixed-size bottleneck entirely, which is why it is the natural sequel to this topic (and the foundation of transformers).

Exercise 5.2 — Gradient path and BPTT

In a basic seq2seq with encoder length and decoder length , trace the gradient path from the loss at the last decoder step back to the first encoder input. Roughly how many recurrent multiplications does it pass through, and why is this the vanishing-gradient danger zone? See BPTT.

Recall Solution

Trace the path (backwards). The loss at the last decoder step depends on , which depends on , ..., back to — that is recurrent steps inside the decoder. The first decoder state depends on the context vector . From there the gradient chains back through the encoder: — that is more recurrent steps.

The count. Total recurrent multiplications — the gradient must survive the full decoder plus the full encoder, chained end to end through two RNNs.

Why this is the danger zone. At each recurrent step, backprop multiplies the incoming gradient by that step's recurrent Jacobian (the derivative of one hidden state with respect to the previous one). Chaining such factors means the gradient reaching is a product of matrices. If those factors have magnitude consistently less than 1, the product shrinks geometrically toward zero — the gradient vanishes before it reaches the early encoder inputs, so the model barely learns to use . (Conversely, factors make it explode.) This is precisely why plain RNN cells are replaced by LSTM/GRU gates, whose near-identity gradient paths keep the product near 1 — and why very long sequences ultimately favour transformers, whose attention gives a constant-length (length-1) gradient path between any two positions.


Recall Self-test: three fast recalls

Basic seq2seq passes the decoder how many context vectors? ::: Exactly one — the final encoder state. Which log base does ML cross-entropy use? ::: Natural log (). Why can't the decoder be bidirectional? ::: Future output tokens don't exist yet at generation time.