Teacher force training PyTorch
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Teacher forcing is a training technique for sequence decoders where the model is fed the true previous token instead of always feeding back its own last prediction. In PyTorch, this usually appears in custom sequence-to-sequence training loops. It can make optimization much more stable, but it also creates a gap between training behavior and inference behavior.
Why Teacher Forcing Helps
In an autoregressive decoder, each prediction becomes part of the next step's input. If the model makes a bad prediction early, the error propagates forward and the rest of the sequence is now conditioned on a bad token.
Teacher forcing reduces that problem by replacing the model's previous prediction with the ground-truth token during training. This gives the decoder a cleaner context and lets it learn token transitions more easily in early training.
A Typical PyTorch Decoder Loop
In PyTorch, teacher forcing is usually not hidden inside a built-in layer. You implement it in the decoder loop yourself.
The key line is the branch between target_tokens[:, t] and predicted. That is teacher forcing.
Shift Inputs and Targets Correctly
One of the most common bugs is off-by-one alignment. If the decoder input at step t is the previous token, then the target for the prediction at step t is usually the current token.
For example, if the target sequence is:
- start token
- '
I' - '
agree' - end token
then the decoder might consume start token, predict I, then consume I, predict agree, and so on.
If you get the shifting wrong, the model can still train numerically while learning the wrong mapping.
Training and Inference Are Different
Teacher forcing exists only during training. At inference time, you do not have the ground-truth future tokens, so the decoder must feed back its own predictions.
That is why a model can show low training loss with strong teacher forcing and still behave badly in real generation. During inference, it has to recover from its own mistakes, and teacher forcing does not prepare it fully for that.
A common mitigation is to reduce the forcing ratio over time:
This kind of schedule gradually pushes training behavior closer to inference behavior.
Loss Computation Still Looks Normal
Teacher forcing changes decoder inputs, not the loss formula. You still compute token-level loss against the target sequence:
The important part is making sure the targets line up with the predicted time steps and that padding is masked properly.
When Too Much Teacher Forcing Hurts
Using a forcing ratio of 1.0 forever often produces a decoder that learns under unrealistically clean conditions. Training may look stable, but inference can degrade because the model rarely had to condition on its own outputs.
That does not mean teacher forcing is bad. It means it is a trade-off:
- high ratio: easier optimization, less realistic decoder context
- low ratio: harder optimization, more realistic context
The right value depends on model size, data difficulty, and how fragile autoregressive generation is in your task.
Common Pitfalls
- Using teacher forcing during inference by mistake.
- Misaligning decoder inputs and targets by one time step.
- Leaving the forcing ratio at
1.0forever and never checking free-running generation quality. - Forgetting to ignore padding tokens in the loss.
- Assuming teacher forcing solves all sequence-model instability when the real issue may be poor tokenization, weak data, or decoder design.
Summary
- Teacher forcing feeds the true previous token into the decoder during training.
- It helps optimization by reducing compounding errors early in the sequence.
- In PyTorch, it is usually implemented explicitly inside the decoder loop.
- Training and inference behave differently, so free-running evaluation still matters.
- Scheduled reduction of the forcing ratio is often more realistic than always forcing or never forcing.
Related reading
- Tensor-Tensor Element-wise Division in TensorFlow
- Tensor flow toggle between CPU/GPU
- Tensor is not an element of this graph; deploying Keras model
- Tensor with unspecified dimension in tensorflow
- tensorflow stop_gradient equivalent in pytorch
- tf.cast equivalent in pytorch?
- Techniques to ensure cluster wide consistency at distributed databases
- Tensor-typed variable initializers must either be wrapped in an init_scope or callable
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.