Search

Search papers and lessons

Teacher Forcing

Level 2 · 8 min read

Teacher forcing trains a sequence model by feeding it the true previous token at each step instead of its own prediction, which makes training fast and stable but leaves a gap at generation time.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Discrete math
  • Architectures
  • Sign in to see your progress

TL;DR

Teacher forcing is a way to train a model that writes a sequence one token at a time. At each training step the model is given the correct previous token from the training data, not the token it would have produced itself, and it is scored on predicting the next correct token. This makes every step independent of earlier mistakes, so training is fast and stable. At generation time the model has to use its own outputs, and the gap between those two situations is called exposure bias.

Where you'll see it: the default training recipe for language models, machine translation decoders, and speech recognition decoders built on recurrent or transformer networks.

Intuition

Think of a student learning to write a dictated sentence. A simple way to teach is to stop after every word, show the correct word so far, and ask for the next one. The student never has to recover from a mistake in the training session, so each lesson is clean. The cost is that the student has never practised continuing from a word they wrote wrong.

A sequence model works the same way. Each output depends on everything before it, so the natural training loop is: produce a token, feed it back in, produce the next. But if the model's early predictions are wrong, every later step is conditioned on garbage, and the loss is noisy and hard to interpret. Teacher forcing replaces the model's own early outputs with the true tokens. The model still predicts every token, but its inputs are always the correct history.

flowchart LR
  subgraph Training with teacher forcing
    T1[true y1] --> M1[model] --> P2[predict y2]
    T2[true y2] --> M2[model] --> P3[predict y3]
  end
  subgraph Generation
    G1[start token] --> N1[model] --> Q1[sampled y1]
    Q1 --> N2[model] --> Q2[sampled y2]
  end

The top row never uses the model's own predictions as input. The bottom row does, and that is the situation the top row never practised.

The math

Autoregressive factorisation

An Autoregressive Model writes the probability of a sequence y=(y1,…,yT)\mathbf{y} = (y_1, \ldots, y_T) as a product of next-token probabilities:

pθ(y)=∏t=1Tpθ(yt∣y<t)p_\theta(\mathbf{y}) = \prod_{t=1}^{T} p_\theta(y_t \mid y_{<t})

Here y<ty_{<t} means all tokens before position tt, and θ\theta are the model parameters. Maximum likelihood training maximises log⁡pθ(y)\log p_\theta(\mathbf{y}) over the training data, which is the same as minimising the negative log likelihood.

The teacher-forced loss

The model is used as a function of the history. In teacher forcing, the history is always the ground truth y∗y^\ast from the dataset, so the loss is

LTF(θ)=−∑t=1Tlog⁡pθ(yt∗∣y<t∗)\mathcal{L}_{\mathrm{TF}}(\theta) = -\sum_{t=1}^{T} \log p_\theta\big(y^\ast_t \mid y^\ast_{<t}\big)

Each term is a Cross-Entropy Loss for a classification over the vocabulary, with the correct token as the target. The terms do not depend on each other at evaluation time, because every input is known in advance. For architectures such as transformers, that makes training parallel across positions. A recurrent network still has to carry its hidden state from one step to the next, but it needs no sampling or decoding in the loop, so training stays simple and stable.

Free-running generation

At inference there is no ground truth. The model generates

y^t∼pθ( ⋅∣y^<t)\hat{y}_t \sim p_\theta\big(\,\cdot \mid \hat{y}_{<t}\big)

so its own samples (or the argmax, or a beam search over them) become the history. The distribution the model was trained on, pθ(⋅∣y<t∗)p_\theta(\cdot \mid y^\ast_{<t}), and the one it is used under, pθ(⋅∣y^<t)p_\theta(\cdot \mid \hat{y}_{<t}), differ whenever y^<t≠y<t∗\hat{y}_{<t} \neq y^\ast_{<t}.

Why the gap compounds

Suppose the probability of a mistake at each step, given a correct history, is ε\varepsilon. Once the model has erred, the history it sees is no longer one it was trained on, and its error rate can be higher. The expected number of errors grows with length, and the exposure gap explains why long free-running outputs drift. This is the core of the exposure-bias argument, covered in Exposure Bias.

Worked examples

Example
Loss on a three-token sequence

Training sequence: "the cat sat". The first token is given, so two tokens are scored. Suppose the model, after seeing the true prefix, assigns these probabilities (illustrative numbers):

  • p(cat∣the)=0.5p(\text{cat} \mid \text{the}) = 0.5
  • p(sat∣the cat)=0.4p(\text{sat} \mid \text{the cat}) = 0.4
  1. Teacher-forced loss terms: −ln⁡0.5=0.6931-\ln 0.5 = 0.6931 and −ln⁡0.4=0.9163-\ln 0.4 = 0.9163.
  2. Sum: LTF=0.6931+0.9163=1.6094\mathcal{L}_{\mathrm{TF}} = 0.6931 + 0.9163 = 1.6094.
  3. Each term is scored under the true history, so neither term depends on what the model would have generated.

Interpretation: the loss is 1.6094 for the sequence, and each step can be checked on its own. If the model had generated "a" instead of "the" as the first token, step 2 would be scored under a history it never saw in training. That is the exposure gap.

Example
Sequential cost of two regimes

Take a sequence of T=1000T = 1000 tokens and a transformer decoder.

  1. Teacher forcing: all inputs are known, so the predictions at all 1000 positions come from one forward pass with a causal mask.
  2. Free-running: token tt needs token t−1t - 1 generated first, so the steps must run one after another. That is T=1000T = 1000 sequential steps (a cache of past computations makes each cheaper, but they are still sequential).
  3. Count: 1 pass over 1000 positions in teacher-forced training, against 1000 sequential steps in generation.

Interpretation: teacher forcing removes the dependency between steps during training for models such as transformers. That is a computational reason it is used, and it is also why the model's behaviour during generation is not directly tested by training. A recurrent network still unrolls over time in training, but with the true tokens as inputs.

Tradeoffs and failure modes

SituationProblemBetter choice
Long generation at test timeErrors compound, output drifts (exposure bias)Scheduled sampling, or sequence-level training
Sequence-level metric such as BLEU is the goalPer-token loss is not the metricMinimum risk training or reinforcement learning on the metric
Model relies on a perfect historyIt has no practice recovering from its own errorsScheduled sampling, or noise injected into the input tokens

Teacher forcing is not wrong. The loss it optimises is the correct maximum likelihood objective. The failure is the mismatch between training and generation, which shows up most when the model's early mistakes are common and there is no mechanism for it to learn from its own errors.

History

The term comes from work on recurrent networks. Williams and Zipser's 1989 paper on learning algorithms for continually running recurrent networks describes feeding the target outputs back in place of the network's own outputs during training, and the technique has been called teacher forcing since. It became the standard recipe for recurrent language models and sequence-to-sequence models, and transformer language models use the same idea, since the causal mask exposes exactly the true prefix at each position. The mismatch it leaves between training and generation is what made exposure bias and its fixes, such as scheduled sampling, a research topic.

Check yourself

QuestionIn one sentence each, what does the model see as input during teacher-forced training, and what does it see during generation?Show answer

During teacher-forced training the model sees the true previous tokens from the dataset. During generation it sees its own previously generated tokens, which may differ from the true sequence.

QuestionA model assigns p(cat given the) = 0.25 and p(sat given the cat) = 0.8 on the true sequence. Compute the teacher-forced loss, using natural logarithms.Show answer

The terms are −ln⁡0.25=1.3863-\ln 0.25 = 1.3863 and −ln⁡0.8=0.2231-\ln 0.8 = 0.2231. Their sum is 1.60941.6094. The first step is the costly one because the model put little probability on the correct token. The second term is small because the model was confident and correct.

QuestionWhy does teacher forcing allow the training of a transformer language model to run in parallel across positions, while generation cannot?Show answer

In training, every input token is known in advance, so the model can compute the prediction at every position in one forward pass, with a causal mask so that each position only sees its true prefix. In generation, token tt is not known until the model has produced token t−1t - 1, so the steps have to run in sequence.

QuestionA chatbot trained with teacher forcing gives fluent answers for the first sentence and then drifts off topic. What is the likely cause, and name one fix.Show answer

The likely cause is exposure bias: the model was never trained on histories containing its own mistakes, so once an early token is off, the later tokens are conditioned on a history outside the training distribution. One fix is scheduled sampling, which gradually replaces true tokens in the training history with the model's own predictions, so it practises recovering from its errors.

QuestionWhy is the teacher-forced loss not a direct measure of the quality of generated sequences?Show answer

The loss scores the probability of the true next token given the true history at each step. It does not look at whole generated sequences, and it does not check whether the model's own generated history would yield good continuations. Two models with the same teacher-forced loss can generate very different text, because generation depends on the free-running distribution, which the loss never evaluates.

Sources