Advanced level · Module 4: Sequence-to-Sequence Architectures · Lesson 2 of 3
Training with Teacher Forcing
Learners implement a GRU encoder-decoder in PyTorch and train it with teacher forcing, observing the gap between training and free-running generation.
In this lesson you will
- Implement a GRU encoder-decoder
- Train with teacher forcing and understand exposure bias
Key concepts
nn.GRU encoder and decoderteacher forcingteacher forcing ratioexposure biassequence loss with padding ignored
The lesson
During training, teacher forcing feeds the decoder the correct previous token instead of its own prediction. This speeds up learning but creates exposure bias: at prediction time the decoder must use its own, possibly wrong, outputs.
A teacher forcing ratio (for example 0.5) mixes both modes during training. Use CrossEntropyLoss(ignore_index=pad_id) so that padding positions do not count.
Track exact-match accuracy on validation data, meaning the whole output string is correct, alongside the loss.
Step by step
- Implement Encoder and Decoder modules with nn.GRU.
- Train with a teacher forcing ratio of 0.5.
- Report validation exact-match accuracy per epoch.
- Compare outputs with teacher forcing on and off at prediction time.
Practice activity
Train the date-normalisation seq2seq model and report exact-match accuracy.
Expected result: A model that normalises most dates correctly, with a clear note on exposure bias.
Check your understanding
-
What is teacher forcing?
Show answer
Feeding the decoder the correct previous token during training.
-
What is exposure bias?
Show answer
The mismatch between training on correct inputs and predicting from the model's own outputs.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.