Foundations to Frontier
Tests
E. Deep Learning › E11 Recurrent and Sequence Models

Teacher forcing, scheduled sampling, beam search

Autoregressive sequence models are trained with teacher forcing: each step is fed the true previous token. At test time they must feed their own predictions, so early mistakes can compound (exposure bias). Scheduled sampling (Bengio and colleagues, 2015) gradually feeds the model's own predictions during training. Beam search keeps the k most probable partial outputs instead of committing greedily. This page covers the three techniques, length normalisation and their known pitfalls. In the exercises you implement beam search and sampling schedules, then compare them on E11-8's reversal task. Beam search (k = 4) beat greedy decoding in every run, raising whole-sequence accuracy from 0.83 to 0.87, while scheduled sampling made no reliable difference.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Practising with answers, performing without them

While training a sequence model, we show it the correct previous word at every step, like a student who always sees the right answer so far. That is teacher forcing: fast and stable. At test time it must build on its own guesses, and one early slip can derail the rest. Scheduled sampling slowly makes training more like testing. Beam search keeps several candidate answers open instead of trusting the single best next word. The demo compares greedy choice with beam search on a small tree of probabilities.

Sequence-model lab
ABB0.1155
Best sequence ABB with probability 0.1155; greedy search gives ABB (0.1155). Greedy picks A first (0.55) and misses the better path through B.
Why engineers care

Decoding choices change outputs without retraining: beam width, length penalties and sampling settings decide what a deployed translation, captioning or planning model actually produces.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Teacher forcing feeds the model…
  2. 2. Exposure bias arises because at test time the model sees…
  3. 3. Beam search keeps…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Teacher forcing: minimise −Σₜ log p(yₜ | y₁ … yₜ₋₁, x) with the true prefix. Every step can be computed in parallel for convolutional or attention models.
  • Free running: with per-step accuracy q and independent errors, a length-L output is fully right with probability q^L. For q = 0.95 and L = 8 that is 0.66.
  • Scheduled sampling:
    • at training step i, feed the model’s own prediction with probability εᵢ, rising over training;
    • schedules: linear, exponential, inverse sigmoid;
    • with linear, step 5 of 10 gives 0.5.
  • Greedy versus beam:
    • in the tree P(A) = 0.55, P(B) = 0.45, P(·|A) = (0.3, 0.35, 0.35) and P(A|B) = 0.9;
    • greedy picks A and reaches at most 0.55·0.35 = 0.19;
    • the best sequence BA has 0.45·0.9 = 0.405, and a beam of 2 finds it.
  • Cost: beam search scores k·V candidates per step: 50,000 for k = 5 and V = 10,000.
  • Length normalisation:
    • log-probabilities are sums of negative terms, so longer outputs score lower;
    • GNMT divides by ((5 + |y|)/6)^α with α = 0.6;
    • a length-13 output’s log-probability −12 becomes −12/3^0.6 = −6.2.
📝 Quick check (Level 1)
0/3 answered
  1. 1. q^L for q = 0.95, L = 8:
  2. 2. Probability of BA in the example tree:
  3. 3. Candidates per step for k = 5, V = 10,000:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Decoding in code

Exercise 1.

  • A generic beam search found B, A (probability 0.405) with k = 2, where greedy search committed to A.
  • The scheduled-sampling and length-penalty functions matched their definitions.

Practice.

  • Teacher forcing in PyTorch: feed tgt[:, :-1] as decoder input and predict tgt[:, 1:].
  • Scheduled sampling with recurrent decoders requires sequential decoding during training. A common parallel approximation takes the model’s predictions from a teacher-forced pass (Duckworth et al., 2019), which is what exercise 2 uses.
  • Beam widths of 4–10 are typical for translation. Very wide beams can lower quality, the “beam search curse” (Koehn and Knowles, 2017), because the most probable outputs are often short or generic.
  • For open-ended generation, sampling with temperature, top-k or nucleus (top-p) often gives better text than beam search.
beams = [(0.0, [BOS], h0)]
for _ in range(max_len):
    cand = [(lp + lw, seq + [w], h2) for lp, seq, h in beams
            for (w, lw), h2 in topk_next(seq[-1], h, k)]
    beams = sorted(cand, key=lambda b: -b[0] / lp_norm(len(b[1])))[:k]
🐍 Exercise 1: beam search and schedules
Implement generic beam search, scheduled-sampling probabilities and the GNMT length penalty.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Very wide beams can…
  2. 2. Open-ended text generation often prefers…
  3. 3. Teacher-forced decoder input is…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Exposure bias.

  • Teacher forcing trains p(yₜ | true prefix), but generation conditions on generated prefixes, whose distribution differs.
  • Errors can push the model into states never seen in training (Ranzato et al., 2016).
  • How much this matters in practice is debated. Strong models trained with teacher forcing often recover well.

Scheduled sampling’s problems.

  • Huszár (2015) showed that its objective is improper: its optimum need not be the true distribution, since it mixes conditionals inconsistently.
  • Gains are task-dependent and modest.
  • Alternatives include sequence-level training (minimum risk, reinforcement learning on BLEU) and professor forcing.

Search and model errors.

  • Beam search approximates arg max_y p(y | x), which greedy decoding can miss when a locally worse first token leads to a better whole.
  • If the model’s most probable output is itself poor, more search exposes the model error. This explains why very wide beams can hurt.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Huszár showed scheduled sampling's objective is…
  2. 2. Beam search approximates…
  3. 3. Wider beams hurting reveals…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Do scheduled sampling and beam search help?

History.

  • R. Williams and D. Zipser described teacher forcing (1989).
  • S. Bengio, O. Vinyals, N. Jaitly and N. Shazeer proposed scheduled sampling (NeurIPS 2015). F. Huszár analysed its objective (2015).
  • M. Ranzato et al. named exposure bias and trained at the sequence level (ICLR 2016).
  • Beam search with length penalties was standard in neural translation (Wu et al., 2016). P. Koehn and R. Knowles documented the beam search curse (2017).

Exercise 2.

  • Model: E11-8’s tanh-RNN encoder–decoder (32 units, vocabulary 6), trained to reverse length-8 sequences for 600 Adam steps.
  • Training schemes:
    • teacher forcing;
    • scheduled sampling: own predictions from a teacher-forced pass fed with probability rising linearly to 0.5.
  • Decoding: greedy and beam search (k = 4), whole-sequence accuracy on 200 test sequences, mean of 2 seeds.
training greedy beam (k = 4)
teacher forcing 0.828 0.867
scheduled sampling 0.830 0.863
  • Beam search helps consistently. Over 3 seeds per scheme, beam beat greedy in all 6 runs, by 3–6 points, without retraining.
  • Scheduled sampling made no reliable difference. Over 3 seeds the means were 0.808 (teacher forcing) and 0.790 (scheduled), with a seed-to-seed spread of 0.17. This fits the mixed results in the literature. Our parallel approximation and a short, forgiving task may also hide any benefit.
🐍 Exercise 2 (research): do scheduled sampling and beam search help?
Train an encoder–decoder with teacher forcing or scheduled sampling and decode greedily or with beam search.

Decoding in AI, robotics and aerospace

  • Command generation: beam search with constraints can enforce valid command grammars for robot or spacecraft operations.
  • Trajectory rollouts: autoregressive forecasters suffer exposure bias; training on their own rollouts (as in scheduled sampling or DAgger for policies) can stabilise long horizons.
  • Deployment knobs: beam width, length penalty and sampling temperature are tuned per application, separately from training.

References

  1. S. Bengio, O. Vinyals, N. Jaitly, N. Shazeer (2015). “Scheduled sampling for sequence prediction with recurrent neural networks.” Proc. NeurIPS.
  2. F. Huszár (2015). “How (not) to train your generative model: scheduled sampling, likelihood, adversary?” arXiv:1511.05101.
  3. M. Ranzato, S. Chopra, M. Auli, W. Zaremba (2016). “Sequence level training with recurrent neural networks.” Proc. ICLR.
  4. P. Koehn, R. Knowles (2017). “Six challenges for neural machine translation.” Proc. Workshop on NMT.