3.5.8 · D3Sequence Models

Worked examples — Encoder-decoder architecture

2,964 words13 min readBack to topic

This is a companion drill page for Encoder-decoder architecture. The parent note built the machinery: an encoder squeezes the input sequence into a single context vector , and a decoder unrolls that vector into an output sequence, one token at a time. Here we do nothing but crank the handle — we push real numbers through the formulas and check every corner case, so that when you meet these on an exam or in code you have already seen the exact scenario.

Before the examples, one promise: every symbol used here was defined in the parent, and we re-anchor each as it appears. If a number looks like it came from nowhere, that is a bug — hunt it.


The scenario matrix

Think of the encoder-decoder as a machine with knobs. Each knob can be at a "normal" setting, a "zero/edge" setting, or a "degenerate/broken" setting. The table below lists every case class this topic can throw at you — 10 cells labelled A–J. The 8 worked examples underneath are each tagged with the cell(s) they cover, and together they fill all 10 cells (some examples cover two cells at once, which is why 8 examples suffice for 10 cells).

Cell Case class What is weird about it Covered by
A Normal forward pass Ordinary lengths, everything defined Ex 1
B Length mismatch Input 3 tokens → output 4 tokens Ex 1, Ex 2
C Softmax numerics Turning raw scores into probabilities Ex 3
D Log-likelihood loss Product → sum via logs Ex 4
E Teacher forcing vs free-run Same weights, different fed inputs Ex 5
F Greedy vs beam (global search) Local best ≠ global best Ex 6
G Degenerate input: empty / single token or Ex 7
H Limiting behaviour: bottleneck large, fixed Ex 8
I Real-world word problem Translation with counts Ex 2
J Exam twist: perplexity Loss reported as a "surprise" number Ex 4

Prerequisites you may want open: 3.5.01-Recurrent-neural-networks, 3.5.03-LSTM-long-short-term-memory, 3.4.06-Beam-search, 3.5.09-Attention-mechanism.


Example 1 — Cell A, B: one full forward pass, by hand

Forecast: Guess the sign of . The last token is , but is a big negative pull. Which wins?

  1. Compute . Why this step? The parent's recursion says each state depends only on the current token and the previous state. With the "memory" term vanishes on step 1. .

  2. Compute . Why this step? Now the memory term carries what "token 1" left behind. The negative token dominates. .

  3. Compute . Why this step? The final hidden state is our context vector — the parent says , "the state that has seen the whole sequence." .

  4. Answer: (barely positive).

Verify: The negative pushed near ; the positive plus that decayed memory nearly cancelled to give . The near-zero result is the tug-of-war our forecast predicted — the recent positive token barely edged out the decayed negative memory. Range check: always outputs in , and is safely inside. ✓

Figure — Encoder-decoder architecture

How the figure reinforces the numbers: the three yellow dots are literally from steps 1–3 plotted against time. Notice the red arrow at step 2 — that is dragging the state down to ; then the green arrow at step 3 shows hauling it back up across the zero line to . The slope of each segment is exactly the "pull" of that token, so the near-flat final segment visually confirms our tug-of-war ended in a near-tie.


Example 2 — Cell B, I: length mismatch word problem

Forecast: Guess how many times fires. Is it 3? 4? 5?

  1. Encoder fires times, producing . Why this step? One encoder step per input token — the input length sets the encoder's loop count.

  2. Decoder fires once per output token, plus one final step to emit . Output has real tokens, so decoder runs times. Why this step? The decoder is autoregressive — it keeps generating until it produces the stop symbol. The stop symbol is itself a token requiring a step.

  3. Why the mismatch is fine: the context vector is a fixed-size bridge — the whole point from the parent's intuition. Once the input collapses to , the decoder can generate any number of tokens.

  4. Answer: encoder steps , decoder steps , total recurrent applications .

Verify: . If input and output were both length 3, we'd get ; the extra decoder step here is the emission plus the 4th French token. Counting is consistent. ✓


Example 3 — Cell C: softmax turned into real probabilities

Forecast: "am" has the biggest logit — will its probability be above or below 60%?

  1. Exponentiate each logit. . Why this step? Softmax is . The exponential is chosen (not, say, just dividing raw scores) because it is always positive — you cannot have a negative probability — and it magnifies gaps between scores.

  2. Sum them: . Why this step? The denominator is the normalizer that forces .

  3. Divide: . Why this step? This is the softmax ratio for the "am" slot.

  4. Answer: , i.e. about .

Verify: The other two are and . Sum: . A valid distribution. ✓ Above our 60% forecast — exponentiation exaggerated the lead.

Figure — Encoder-decoder architecture

How the figure reinforces the numbers: the blue bars are the raw logits and the yellow bars are the probabilities from step 3. Note that the logit gap between "am" and "is" is only , yet the yellow probability gap ( vs ) is far larger — that visual stretching is the exponential "magnifying gaps" that step 1 warned about. The three yellow bars are also drawn to sum to the height 1, which is the normalization from step 2 made visible.


Example 4 — Cell D, J: log-likelihood loss and perplexity (exam twist)

Forecast: Perplexity is "the effective number of equally-likely choices the model was juggling." Guess: closer to 2, or closer to 10?

  1. Joint probability by chain rule: . Why this step? The parent decomposes — each token's probability conditioned on the ones before.

  2. Log-likelihood: . Why this step? We take logs (natural log here) to turn the product into a sum — this avoids tiny numbers underflowing to zero and matches the parent's . .

  3. Mean cross-entropy loss: . Why this step? The parent's objective divides by the number of tokens so sequences of different length are comparable.

  4. Perplexity: . Why this step? Perplexity is the exam-favourite reformatting of loss: . It reads as "on average the model behaved as if choosing among equally likely tokens."

Verify: Sanity check via geometric mean: . Matches step 4. Our forecast "closer to 2" was right. ✓


Example 5 — Cell E: teacher forcing vs free running, same weights

Forecast: Will the two hidden states differ by a little or a lot?

  1. Teacher forcing feeds . . Why this step? The parent's teacher forcing rule: at training time we feed the correct previous token regardless of what the model said.

  2. Free running feeds the model's own . . Why this step? At test time (or in scheduled sampling) the decoder eats its own output — this is where exposure bias lives.

  3. Gap: — nearly the whole range apart.

  4. Answer: one wrong token flipped the hidden state from strongly positive to negative.

Verify: Both outputs lie in ✓. The huge gap ( out of a max span of ) is a numerical demonstration of why early mistakes compound — exactly the parent's Mistake 2. ✓


Example 6 — Cell F: greedy decoding is NOT optimal

Forecast: Greedy grabs "The" first (it's more likely). Does greedy also win the whole sequence?

  1. Greedy step 1: pick the higher first-token probability → "The" (). Why this step? Greedy = argmax at each step, ignoring the future.

  2. Greedy full path: "The" → "dog", total . Why this step? Sequence probability multiplies step probabilities (chain rule again).

  3. Alternative path: "A" → "fox", total . Why this step? Beam search keeps this hypothesis alive even though "A" lost round 1.

  4. Answer: global best ("A fox") beats greedy ("The dog"). Greedy is sub-optimal.

Verify: ✓. The locally-losing first move led to the globally-winning sequence — the parent's Mistake 3, made concrete. Beam width would have caught it. ✓


Example 7 — Cell G: degenerate inputs (empty and single token)

Forecast: For the empty input, is undefined, or something specific?

  1. Empty input: no encoder step runs, so . Why this step? with means "the state before any token" — the initial state. It is not undefined; it is the neutral . In practice the model would then just decode from a blank context (often producing immediately).

  2. Single token, step 1: . Why this step? One token means the recursion runs exactly once; memory term is zero because .

  3. Context: — saturated near . Why this step? Large positive pre-activation () drives into its flat region.

  4. Answer: (a) ; (b) .

Verify: ✓ and ✓, both inside . The single-token case saturates — a hint that large inputs get squashed, foreshadowing the bottleneck problem. ✓


Example 8 — Cell H: the information bottleneck limit

Forecast: Is the fixed vector short of capacity at 50 tokens, at 1000 tokens, or only far beyond that?

  1. Bits needed per token. Using the log rule , each of the positions independently chooses one of words, costing bits. So Why this step? Encoding one choice out of equally-possible options costs exactly bits — that is the definition of a bit as a "yes/no halving." The base-2 log is chosen (not natural log) precisely because we measure storage in bits, and one bit halves the number of remaining possibilities. Total sequence cost is then .

  2. Bits available in the context vector. A float32 number stores bits; a -dimensional vector stacks of them: Why this step? This is the entire budget the encoder has to describe the whole input — everything the decoder ever sees about must fit in these bits. That hard ceiling is the bottleneck made literal.

  3. Crossover length (where "needed" first exceeds "available"): solve , giving Why this step? Below tokens the vector has enough raw bits to (in principle) store the sequence; above it, the vector is provably too small — no matter how clever the encoder, some sequences must collide onto the same , so information is guaranteed lost. This is the mathematical seed of the bottleneck.

  4. Deficit at . Bits needed ; available ; so Why this step? At 2000 tokens the vector falls short by over ten thousand bits — nearly 40% of the required information cannot physically be stored, so it is guaranteed lost. That lost information is exactly the "early tokens get forgotten" failure the parent described.

  5. Limiting behaviour (). Bits needed grow linearly in (), while bits available stay constant at . So the ratio (needed / available) : the fraction of information the vector can preserve . Why this step? This is the crisp statement of the limit — a fixed-size cannot keep pace with unboundedly long inputs, which is why attention lets the decoder read all encoder states rather than one squeezed vector.

  6. Answer: (a) bits available; (b) crossover at tokens; (c) a -bit deficit at .

Verify: ✓; and , minus gives ✓. The bottleneck is a genuine limiting-length phenomenon: short sentences fit comfortably, but past tokens the fixed vector cannot cope, and as its stored fraction of the input — which is precisely why attention (3.5.09-Attention-mechanism) was invented. ✓

Recall Self-test

What is the total number of recurrent-cell applications for a 4-token input and a 6-token output (including END)? ::: Encoder 4 + decoder , total . Why does softmax use rather than directly? ::: always (no negative probabilities) and it exaggerates score gaps, sharpening the distribution. Perplexity of a model that assigns joint prob to a 3-token target? ::: . Greedy picked "The dog" (); which path beats it and by how much? ::: "A fox" at , a margin of . Crossover length where a 512-dim float32 context runs out of bits (V=10^4)? ::: About tokens. As with a fixed context vector, what happens to the stored fraction of the input? ::: It tends to — needed bits grow linearly, available bits stay constant.