3.5.7 · D3Sequence Models

Worked examples — Sequence-to-sequence models

2,880 words13 min readBack to topic

Before anything else, some symbols we will reuse. If you have never seen them, read this box slowly — every later example depends on it.


The scenario matrix

Every worked example below is tagged with the cell it covers.

# Cell (situation) What could go wrong / why it's distinct
A Short input, greedy decode Baseline — one token per step, always pick the max
B Cross-entropy loss numbers Turning three probabilities into one loss number
C Confident vs confused model Same math, different confidence → very different loss
D Beam search beats greedy Greedy's locally-best first word leads to a dead end
E Length normalization Without it, beam search prefers short garbage
F Degenerate: <EOS> on step 1 The empty-output edge case
G Teacher forcing vs free-running Same step, two different inputs → exposure bias
H Long input / bottleneck limit Why a fixed eventually fails (limiting behaviour)
I Real-world word problem End-to-end translation, all pieces at once
J Exam twist: pad/mask a batch Variable lengths in one batch

Example A — short input, greedy decode

Forecast: guess the output sentence before reading on.

  1. Step 1: take of . Why this step? Greedy decoding means "commit to the single most probable token now" — . The biggest entry of is at index .
  2. Step 2: of . Why? Same rule at the next time step; the previous winner \texttt{Estoy} was fed back in. Biggest is at index .
  3. Step 3: of . Why? Biggest is at index — this is the stop signal, so we halt.

Figure below: three bar charts, one per decoding step. Each bar is a token's probability; the tallest bar — the one greedy commits to — is drawn in red, with an "argmax" arrow. It shows visually that greedy simply keeps grabbing the red bar and never looks back.

Figure — Sequence-to-sequence models

Output: \texttt{Estoy feliz } → "Estoy feliz".

Verify: three probabilities are all , so greedy and any sensible strategy agree here — no risk. Indices decoded in order. ✓


Example B — cross-entropy loss from those numbers

Forecast: will the loss be near or near ? (High confidence → low loss.)

  1. Pick out the probability of the correct token at each step. Why? The loss only cares how much mass the model put on the right answer: .
  2. Take of each. Why? converts "probability of correct" into "penalty": a probability of gives penalty ; smaller probabilities give larger penalties.
  3. Sum them. Why? The whole-sequence probability is a product, and of a product is a sum, so total loss adds the per-step penalties.

Verify: all three probabilities are close to , so loss should be small — and is indeed tiny (a random 4-way guess would give ). ✓


Example C — same math, a confused model

Forecast: the loss should be much larger — the model is barely favouring the right words.

  1. each correct probability. Why? Same penalty rule.
  2. Sum. .

Figure below: the black curve is the penalty plotted against the probability of the correct token. The confident case (probabilities near ) sits low on the curve; the confused case (near , marked in red) sits high where the curve rears up. It shows why a small drop in confidence causes a large jump in loss: the penalty curve is steep near small .

Figure — Sequence-to-sequence models

Verify: . Same three-step structure, but confidence dropped from to , so loss climbed roughly . The red points on the steep part of the curve explain why. ✓


Example D — beam search beats greedy

Forecast: greedy picks \texttt{Estoy} first; will beam agree?

  1. Greedy step 1. Why? Greedy commits to () and can never reconsider.
  2. Greedy full score = . Why multiply? Sequence probability is the product of step probabilities.
  3. Beam keeps both \texttt{Estoy} and \texttt{Yo} after step 1. Why? Beam width retains the top- partial paths instead of one.
  4. Score each 2-token path. Why compute these scores? Beam ranks whole partial sequences by their probability so far, not just the newest token — this is the only way it can discover that a slightly-worse first word (\texttt{Yo}) leads to a far better second word. We multiply each first-token probability by its best continuation:
    • \texttt{Estoy …}:
    • \texttt{Yo soy}:
  5. Pick the max path. Why? Beam returns the highest-scoring complete sequence: \texttt{Yo soy} at .

Verify: , so beam finds a sequence nearly more probable than greedy's — exactly the payoff of keeping options open. See 4.2.01-Beam-search. ✓


Example E — length normalization

Forecast: raw scoring will unfairly reward the shorter sentence.

  1. Raw totals. Why? Adding log-probs = multiplying probabilities. . .
  2. Raw ranking: , so raw prefers the shorter . Why is that bad? Every extra token adds a negative number, so longer is punished automatically — even good long translations.
  3. Divide by length . Why? Averaging removes the "more tokens = more penalty" bias. . .
  4. Normalized ranking: — here still wins, but the gap shrank from to , showing the correction at work.

Verify: normalization brought the scores closer ( gap), confirming it counteracts the length bias without flipping a genuinely-better short answer. ✓


Example F — degenerate: <EOS> on the very first step

Forecast: what happens if the model wants to stop immediately?

  1. . Why? Greedy rule. Max is at \texttt{}.
  2. We halt at step 1. Why? <EOS> is the stop signal, so generation ends before any real word is emitted.
  3. Output = empty string (just \texttt{}). Why care? This is the degenerate/zero-length case — real systems clamp a minimum length so an over-eager model can't return nothing.

Verify: the single decoded index is , length of real output . A minimum-length guard would forbid index on step 1 and force the runner-up (\texttt{Hola}, ). ✓


Example G — teacher forcing vs free-running (same step, two inputs)

Forecast: which input does each mode use?

  1. Training / teacher forcing: feed the ground-truth \texttt{Estoy}. Why? Correct context each step stops early errors from snowballing and speeds convergence. See BPTT.
  2. Inference / free-running: feed the model's own \texttt{Yo}. Why? At test time there is no ground truth — the model must consume its own output.
  3. The mismatch = exposure bias. Why it matters? The model trained only on correct history, so at inference a wrong \texttt{Yo} pushes it into states it never practised.

Verify: the two inputs differ (\texttt{Estoy} vs \texttt{Yo}) → non-empty discrepancy → this is exactly the exposure-bias scenario the parent note warned about. ✓ (No number to compute; this cell is conceptual.)


Example H — long input, the bottleneck limit

Forecast: as grows, does a fixed keep up?

  1. Total input capacity. Why? Each token carries numbers; tokens carry numbers.
  2. Context capacity is fixed at . Why fixed? By construction has one size regardless of .
  3. Compression ratio . Why care? The encoder must squeeze its own size into . As the ratio , so early tokens must eventually be forgotten — the information bottleneck.

Figure below: two bars — a tall black bar for the numbers the input carries, and a short red bar for the slots inside — with a "bottleneck" arrow pointing at the small red one. It makes the mismatch visible at a glance and shows why long inputs overflow a fixed context vector.

Figure — Sequence-to-sequence models

Verify: ratio ; doubling to doubles it to while stays — the limit that motivates the attention mechanism and later Transformers. ✓


Example I — real-world word problem (end to end)

Forecast: which hidden state becomes , and what's the final loss?

  1. (a) Context vector = last encoder state. Why the last? It is the only state that has "seen" all tokens: . (The values are arbitrary placeholders chosen to make the shape concrete — only their count, , matters here.)
  2. (b) Decode greedily as in Example A. Each step takes of its distribution and feeds the winner forward, giving \texttt{Estoy}, then \texttt{feliz}, then \texttt{} → "Estoy feliz". Why? Same greedy rule; the final \texttt{} halts generation.
  3. (c) Loss as in Example B: . Why? Sum the per-step penalties of the correct tokens.

Verify: has entries ✓; output is a valid Spanish rendering ending in <EOS> ✓; loss matches Example B ✓.


Example J — exam twist: pad and mask a batch

Forecast: should the padded positions add to the loss?

  1. Pad the short sequence to length . Why? Every row in a batch tensor must share a shape; padding makes both sequences length so they stack into one array.
  2. Build a mask = for sequence 1 and for sequence 2. Why? A marks a padded slot whose loss is meaningless and must be excluded from training.
  3. Masked total loss = sum of losses only where the mask is . Why? Padded positions were never real target tokens, so counting them would teach the model to "predict" padding. Sequence 1: . Sequence 2: . Batch total .
  4. Mean over real tokens. Why divide by real-token count, not ? Averaging over the genuine tokens keeps the loss scale comparable across batches with different padding. Mean .
  5. Contrast the buggy sum. Why mention it? Even though the padded losses happened to be here, a real model would emit nonzero garbage there; the mask guarantees contribution regardless, which is the whole point.

Verify: masked total ; counted positions ; mean — averaging over real tokens only. ✓


Recall Quick self-test

Greedy decoding rule in one symbol ::: Meaning of ::: all output tokens before step , i.e. What does the beam width control ::: how many partial candidate sequences beam search keeps alive at each step Why divide beam scores by length ::: to remove the bias against longer sequences (each token adds a negative log-prob) Loss for correct-probs ::: What input does teacher forcing feed at step ::: the ground-truth token Compression ratio for input into ::: Masked batch total for losses and :::

Related: 3.5.01-Recurrent-neural-networks, 3.5.05-LSTM-networks, 3.5.06-GRU-networks, 3.5.07 Sequence-to-sequence models (Hinglish).