QuiddityML

By · 6 November 2026 · 8 min read

Teacher forcing and exposure bias explained

How decoders are fed during training, why generated text can drift after one wrong token, and how to write teacher forcing and scheduled sampling in PyTorch.

Teacher forcing is a way to train a model that writes text one token at a time, where a token is a word or a piece of a word. At every step of training, the model receives the correct previous token instead of the token it predicted itself. Exposure bias is the gap this leaves behind. Once training is over, the model has to read its own predictions and mistakes, which it never practiced doing. The two ideas come up when you train a decoder, the part of a model that generates output text. Examples are the decoder in a translation model and a language model that continues a prompt.

The examples below use whole words as tokens to keep things simple.

How a decoder generates text

A decoder writes one token per step. At each step it reads the tokens produced so far, predicts a probability for every token in its vocabulary, picks one and appends it. That new token becomes part of the input for the next step. Generating text this way, after training is done, is called inference.

So the decoder's input at step $u$ includes the token from step $u - 1$. During inference, that token can only come from the model itself, since nothing else exists yet.

What should the decoder receive during training?

Training has one extra piece of information that inference lacks: the correct output sequence, called the target, is already known. A translation dataset pairs each English sentence with its French translation, and a language model's training text is its own target. So at target step $u$, the decoder could receive one of two tokens:

If the decoder receives its own predictions while it is still learning, early mistakes push the rest of the sequence off track. Say the target is "The cat sat on the mat" and step 1 predicts "dog" instead of "cat". Step 2 now reads "The dog", so the decoder's internal state is already wrong, and every later step learns from inputs built on that mistake. Early in training many predictions are wrong, so much of the training signal would come from sequences far from the target.

Teacher forcing avoids this by always feeding the ground-truth previous token, the token from the target. Whatever the model predicted at step 1, step 2 receives "The cat".

Top: with teacher forcing the decoder reads the ground-truth prefix The cat sat on the and predicts mat, so it always sees the correct past and learning is stable. Bottom: without teacher forcing a wrong first prediction, dog, is fed back as input, the following tokens barked at the build on it, the model predicts rug, and errors compound.

Teacher forcing in code: shift the target by one

In practice, teacher forcing is one slicing step. Each target sequence starts with a start token written <bos> (beginning of sequence) and ends with an end token written <eos>. For the French target "je suis ici":

Position by position, the decoder receives <bos> and should predict je. Then it receives je and should predict suis, and so on. Every input is a correct target token, and every prediction is checked against the token right after it.

The loss is cross-entropy, which compares the model's predicted probabilities at each position with the correct next token. It is low when the model gives the correct token a high probability.

1decoder_input  = target_tokens[:, :-1]  # ground-truth prefix
2decoder_target = target_tokens[:, 1:]   # next token to predict
3 
4logits = model(src, decoder_input)
5logits_flat = logits.reshape(-1, logits.shape[-1])
6target_flat = decoder_target.reshape(-1)
7loss = F.cross_entropy(logits_flat, target_flat)

target_tokens has shape (batch, length). src is the source sentence for an encoder-decoder model, such as the English sentence in translation. logits are the model's raw scores, with shape (batch, length - 1, vocab_size). The two reshape calls flatten the batch and time axes together, because F.cross_entropy expects one row of scores per prediction and one target id per prediction.

The target tokens BOS je suis ici EOS, the decoder input target_tokens[:, :-1] with EOS dropped, and the decoder target target_tokens[:, 1:] with BOS dropped, with arrows from each input token to the next target token, then the cross-entropy code that feeds the true prefix and scores the next token.

Because every input is known before training starts, the model can process the whole target in one call. It never has to wait to see what it predicted at an earlier step. That makes teacher-forced training stable and fast, and it is a common way to train decoders.

A runnable example

The model below is a small decoder with no encoder, so it takes only the decoder input. In an encoder-decoder model the call becomes model(src, decoder_input) and nothing else in the training step changes.

1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4 
5torch.manual_seed(0)
6vocab = ["<bos>", "je", "suis", "ici", "<eos>"]
7target_tokens = torch.tensor([[0, 1, 2, 3, 4]])  # <bos> je suis ici <eos>
8 
9decoder_input = target_tokens[:, :-1]   # what the decoder receives
10decoder_target = target_tokens[:, 1:]   # what it should predict
11print([vocab[i] for i in decoder_input[0]])
12print([vocab[i] for i in decoder_target[0]])
13 
14class TinyDecoder(nn.Module):
15    def __init__(self, vocab_size, dim=16):
16        super().__init__()
17        self.embed = nn.Embedding(vocab_size, dim)
18        self.rnn = nn.GRU(dim, dim, batch_first=True)
19        self.out = nn.Linear(dim, vocab_size)
20 
21    def forward(self, tokens):
22        hidden, _ = self.rnn(self.embed(tokens))
23        return self.out(hidden)  # (batch, time, vocab_size)
24 
25model = TinyDecoder(len(vocab))
26logits = model(decoder_input)
27print(logits.shape)
28 
29loss = F.cross_entropy(
30    logits.reshape(-1, logits.shape[-1]),
31    decoder_target.reshape(-1),
32)
33print(round(loss.item(), 3))
1['<bos>', 'je', 'suis', 'ici']
2['je', 'suis', 'ici', '<eos>']
3torch.Size([1, 4, 5])
41.568

The logits have one row of 5 scores, one score per vocabulary token, for each of the 4 input positions. The model is untrained, so its loss of 1.568 is close to $\ln 5 \approx 1.609$, the loss of a model that gives all 5 tokens the same probability. From here, a normal training loop calls loss.backward() and an optimizer step on many target sequences.

What exposure bias is

Teacher forcing gives the decoder clean inputs during training. At inference there is no target to read from, so the decoder receives its own previous predictions, because those are the only previous tokens it has.

So the model is trained on prefixes where every token is correct and used on prefixes it generated itself. This mismatch between training and inference is called exposure bias: during training the model is only exposed to correct prefixes.

Top: during training with teacher forcing, the inputs start the cat sat are the true previous words and the outputs are the cat sat down. Bottom: at inference the model predicts ate at step 3, ate becomes the input at step 4, and the next output, everything, is wrong too. The gap is called exposure bias.

Why one mistake leads to more

The gap grows because each mistake becomes part of the input for the next step. With teacher forcing, the decoder saw a correct prefix at every step of every training example, so it got little practice recovering from a prefix that contains its own error.

At inference, one wrong token can put the model in a context that was rare or absent in training. From that unfamiliar context it is more likely to make another mistake, which pushes the sequence further from anything it trained on. This is one reason a small slip early in a generated sentence can turn into text that drifts off topic or stops making sense.

Training: the decoder only ever saw correct prefixes at steps t1 to t6. Inference: steps t1 and t2 are correct, step t3 is a slip into a context it never trained on, and steps t4 to t6 are wrong too, each further off the path, because it never learned to recover from a bad prefix.

Scheduled sampling: a partial fix

Scheduled sampling mixes the two options during training. At each step, a random draw decides whether the decoder receives the ground-truth token or its own prediction from the previous step.

Early in training the draw mostly picks the ground truth, so learning stays stable while the model's predictions are still poor. As training goes on, the chance of feeding the model's own prediction rises, so the decoder practices on the kind of prefixes it will create at inference.

1def scheduled_decoder_input(gold_token, pred_token, step, total_steps):
2    progress = min(step / total_steps, 1.0)
3    p_teacher = 1.0 - progress
4    if torch.rand(()) < p_teacher:
5        return gold_token
6    return pred_token.detach()

gold_token is the correct previous token and pred_token is the one the model predicted. p_teacher falls from 1 at the start of training to 0 at total_steps. torch.rand(()) draws one random number between 0 and 1, so the gold token is used with probability p_teacher. .detach() cuts the reused prediction off from the gradient computation, so no gradient flows back through the discrete choice of which token to feed.

The helper can be checked by calling it many times at a few training steps and counting how often it returns the prediction:

1torch.manual_seed(0)
2gold, pred = torch.tensor(1), torch.tensor(2)
3for step in [100, 400, 700]:
4    picks = [scheduled_decoder_input(gold, pred, step, 1000) for _ in range(10_000)]
5    share_pred = sum(p.item() == 2 for p in picks) / len(picks)
6    print(f"step {step}: model prediction used {share_pred:.2f} of the time")
1step 100: model prediction used 0.10 of the time
2step 400: model prediction used 0.41 of the time
3step 700: model prediction used 0.71 of the time

With 1,000 training steps, the model's own prediction is used about 10% of the time at step 100, 40% at step 400 and 70% at step 700.

Scheduled sampling: a coin flip decides whether the input at step t + 1 is the ground-truth token or the model's prediction. The chance of using the model's prediction is 0.1 early in training, 0.4 in the middle and 0.7 late, so the model gets more practice on its own mistakes. It is a partial fix, and plain teacher forcing is still the common default.

When an input can depend on what the model predicted one step earlier, the decoder has to run one step at a time during training, so scheduled sampling trains slower than plain teacher forcing. Scheduled sampling is a partial fix, and plain teacher forcing is still common because it is stable, simple and often good enough.

Common mistakes

Teacher forcing is how the decoder in an encoder-decoder (seq2seq) model is trained, and the same shift trains a language model on next-token prediction, as in how language models are trained. Exposure bias shows up at inference, where decoding strategies and beam search decide which token gets fed back at each step.

QuiddityML teaches teacher forcing and exposure bias as two concepts in the language models unit of its NLP track. The exercises include tracing the decoder's input after it predicted the wrong token, spotting the bugs in a teacher-forced loss, and writing scheduled_decoder_input from scratch (QuiddityML).