Sub topic 5
Training with Teacher Forcing and the Cross-Entropy Loss
Prerequisites and the training goal
This chapter assumes that you know basic Python, PyTorch tensors, neural-network loss functions, and the high-level structure of a Transformer. You should also know that an encoder reads the source sequence and a decoder produces the target sequence one token at a time.
An encoder-decoder model learns a mapping such as:
- Source:
The council approved a new plan. - Target:
Le conseil a approuvé un nouveau plan.
During training, the model receives the source text and the correct target tokens. Its task is to predict each next target token. This is a sequence-level prediction problem, but the loss is usually calculated separately for each target-token position.
Teacher forcing
The decoder generates an output autoregressively. This means that its prediction at position 3 can depend on the tokens it produced at positions 1 and 2.
During training, teacher forcing gives the decoder the correct previous tokens instead of its own previous predictions. For the target sequence:
<start> The council approved <end>
the decoder inputs and expected labels are shifted by one position:
| Decoder input | Expected label |
|---|---|
| `<start> The council approved` | `The council approved <end>` |
At the first position, the model predicts The after seeing the start token. At the next position, it sees the correct token The, even if its first prediction was wrong.
This makes training faster and more stable. The model does not have to wait for a complete generated sequence before receiving useful error information. However, teacher forcing creates a difference between training and inference. At inference time, the correct previous target is unavailable, so the decoder must use its own generated token.
Cross-entropy loss
At each position, the decoder produces a probability distribution over the vocabulary. If the vocabulary contains 32,000 tokens, the model produces 32,000 scores for each position. The correct target token identifies which probability should be rewarded.
Cross-entropy loss measures how much probability the model assigned to the correct token. A high probability for the correct token gives a low loss. A low probability gives a high loss.
For target tokens \(y1, y2, \ldots, y_T\), the token-level loss is commonly averaged as:
loss = -1/T × sum(log P(y_t | source, target prefix before t))
The model's output layer normally returns logits, which are unnormalised scores. A cross-entropy function applies the equivalent of a softmax internally and compares the scores with the integer token IDs in the labels.
Padding tokens need special treatment. They fill unused positions in a batch but are not real targets. Training code commonly replaces padded label IDs with -100, a value that PyTorch's cross-entropy implementation ignores.
Using labels with Transformers
Hugging Face encoder-decoder models handle the shift internally when you pass labels. You provide the complete target sequence as labels. The model creates decoder inputs by shifting those labels right and computes the loss against the original labels.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
source = "summarize: The council approved a plan to add 40 kilometres of bike lanes."
target = "The council approved 40 km of new bike lanes."
batch = tokenizer(
source,
text_target=target,
return_tensors="pt",
)
model.train()
output = model(**batch)
loss = output.loss
print(f"loss: {loss.item():.4f}")
loss.backward()For a real training loop, call optimizer.zero_grad(), compute the loss, call loss.backward(), and then call optimizer.step(). Repeat this for many batches. The loss should generally decrease on the training data, although a lower training loss does not guarantee useful or accurate generated text.
Teacher forcing during inference
The generate() method does not use the target labels. It starts with the model's decoder-start token, predicts a token, feeds that prediction back into the decoder, and continues until it reaches an end token or a length limit. Beam search and other decoding strategies change how candidate next tokens are selected, but they do not remove this autoregressive process.
Exercise
Why are the decoder inputs and labels shifted by one position during teacher forcing?
Show answer
The decoder must receive the previous target tokens while predicting the next target token. The shift prevents the correct token from being supplied at the same position that the model is expected to predict.