Sub topic 5
Training with Teacher Forcing and the Cross-Entropy Loss
Prerequisites and scope
This chapter assumes you know basic Python, how a neural network is trained with a loss function and gradient descent, and the high-level idea of the Transformer and self-attention. You should also have used PyTorch tensors or the Hugging Face Transformers library at a basic level.
The chapter explains how an encoder-decoder model learns. You will see what the decoder receives during training, why it differs from what it receives at generation time, how the loss is computed, and which mistakes show up most often in practice. Fine-tuning on a full dataset is covered in a later chapter. Here the focus is one training step.
The training problem
An encoder-decoder model reads a source text and writes a target text one token at a time. A token is a unit of text, usually a word or a piece of a word, produced by the tokeniser. At each position the decoder outputs a probability distribution over the whole vocabulary. Training makes the distribution put high probability on the correct next token of the reference target.
Written as a formula, the model factorises the probability of a target sequence y given a source x:
P(y | x) = P(y1 | x) · P(y2 | x, y1) · P(y3 | x, y1, y2) · ...
Each factor is one decoder step. To compute step t, the decoder needs the previous target tokens y1 ... y(t-1). This raises the central question of this chapter: during training, which previous tokens should the decoder see?
What teacher forcing is
Teacher forcing means that during training the decoder is fed the true previous tokens from the reference target, not the tokens it predicted itself. The reference acts as a teacher that corrects the model at every step.
Suppose the target is "The council approved 40 km of new bike lanes." At step 4, the decoder sees "The council approved" and must predict "40". If the model had wrongly predicted "a" at step 3, the next step still receives "approved" from the reference. The model never builds on its own earlier mistakes during training.
Teacher forcing has two practical benefits:
- Parallel computation. Every target position is known in advance, so the decoder can compute all steps in one forward pass. A causal mask stops position
tfrom attending to positions aftert. Without teacher forcing, you would have to run one step at a time, which is far slower. - Stable learning signal. Early in training the model's own predictions are poor. Feeding them back would make later steps learn from garbage. The true prefix gives each step a clean, consistent input.
Shifting the target right
The decoder input is the target shifted one position to the right. A start token goes at the front, and the final target token is dropped from the input. The labels are the unshifted target.
| Position | Decoder input | Label (what to predict) |
|---|---|---|
| 1 | `<start>` | The |
| 2 | The | council |
| 3 | council | approved |
| 4 | approved | 40 |
| 5 | 40 | `</s>` (end of sequence) |
At every position the input is the label from one position earlier. The model therefore predicts each token from everything that came before it, plus the encoder's view of the source through cross-attention.
The start token depends on the model. BART uses the end-of-sequence token as the first decoder input. T5 and Marian models use the padding token. You rarely need to know this, because Hugging Face builds the shifted input for you, as the next section shows.
The cross-entropy loss
Cross-entropy loss measures how much probability the model gave to the correct token. For one position, the loss is the negative log of the probability assigned to the reference token:
loss_t = -log P(y_t | x, y_<t)
If the model gives the correct token probability 0.9, the loss is about 0.105. If it gives 0.01, the loss is about 4.6. The loss over a sequence is the average of the per-token losses over all non-padding positions. Minimising it is the same as maximising the likelihood of the reference targets.
Two details matter in practice:
- Padding must not count. Sequences in a batch have different lengths, so shorter ones are padded. Padded label positions are set to
-100, the value PyTorch's cross-entropy loss ignores by default. If you leave real padding token IDs in the labels, the model is trained to predict padding and the loss is distorted. - The loss is averaged per token, not per sequence. Long targets contribute more tokens, so they influence the average more than short ones within a batch.
One training step in code
Hugging Face does the shifting for you. When you pass labels, the model builds the decoder input by shifting the labels right and returns the loss. Passing the target through text_target makes the tokeniser encode it as a target, using the target-side settings.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
source = "summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years."
target = "The council approved 40 km of new bike lanes."
batch = tokenizer(source, text_target=target, return_tensors="pt")
output = model(**batch)
print(output.loss)The printed value is a single scalar tensor, the mean cross-entropy over the target tokens. A freshly loaded t5-small already knows the summarisation prefix from its pretraining, so the loss is not enormous, but it is still far from zero for this particular target wording.
You can inspect what happened by looking at the batch and the shifted input:
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
source = "summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years."
target = "The council approved 40 km of new bike lanes."
batch = tokenizer(source, text_target=target, return_tensors="pt")
print(batch.keys())
print("labels:", batch["labels"][0].tolist())
decoder_input_ids = model._shift_right(batch["labels"])
print("decoder input:", decoder_input_ids[0].tolist())
print("labels as text:", tokenizer.convert_ids_to_tokens(batch["labels"][0]))The decoder input starts with the padding token ID (0 for T5) and then repeats the labels without the last one. The method _shift_right is internal and is shown here only to make the mechanism visible. In your own code, pass labels and let the model do it.
Making the loss explicit
The same loss can be computed by hand from the logits, which helps when you need a custom weighting or want to check your understanding.
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
source = "summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years."
target = "The council approved 40 km of new bike lanes."
batch = tokenizer(source, text_target=target, return_tensors="pt")
with torch.no_grad():
output = model(**batch)
logits = output.logits
manual = F.cross_entropy(
logits.view(-1, logits.size(-1)),
batch["labels"].view(-1),
ignore_index=-100,
)
print("model loss: ", output.loss.item())
print("manual loss:", manual.item())The two numbers match. The logits have shape (batch, target_length, vocabulary_size), and the cross-entropy treats every position as one classification problem over the vocabulary.
The data flow in one step
The diagram shows one training step. The encoder reads the source once. The decoder reads the shifted target and attends to the encoder output. The loss compares each decoder output with the unshifted label.
Exposure bias: the cost of teacher forcing
Teacher forcing creates a mismatch between training and generation. During training the decoder always sees correct prefixes. During generation it sees its own previous outputs, which may contain errors. This gap is called exposure bias. The model was never trained to recover from its own mistakes, so one wrong token can push later tokens off course.
The effect is real but usually modest for pretrained models fine-tuned on enough data. It shows up as a drift into repetition or off-topic text in long outputs. Common mitigations are:
- Beam search, which keeps several candidate prefixes and so is less likely to commit to one early error. The chapter on decoding covers it.
- Repetition controls at generation time, such as blocking repeated n-grams.
- Scheduled sampling or sequence-level training, which mix the model's own predictions into training or optimise a sequence-level reward. These are more complex, less common in standard fine-tuning, and not needed for the examples in this tutorial.
A second consequence is that the training loss is a token-level measure. A low loss means each token is predicted well given the correct prefix. It does not guarantee that a freely generated summary or translation is good. This is why you also evaluate generated text with metrics such as ROUGE and BLEU, covered later.
Common errors
These mistakes appear often when people write their own training loops.
- Padding IDs left in the labels. Replace them with
-100after tokenising a padded batch. The Hugging FaceDataCollatorForSeq2Seqdoes this for you with its defaultlabel_pad_token_id=-100. - Passing the target as the model input. The source goes in
input_ids. The target goes inlabels. Mixing them trains the model to copy its input. - Forgetting the task prefix. T5 expects prefixes such as
summarize:ortranslate English to German:. BART and Marian do not use them. Using the wrong convention weakens the pretrained behaviour. - Encoding the target as a source. For models with different source and target tokenisation settings, such as language codes in mBART, use
text_targetso the target-side settings apply. - Truncating the target too aggressively. If labels are cut at a short maximum length, the model learns to stop early and never sees the full ending. Check that
max_lengthfor targets fits your reference summaries or translations. - Computing loss in evaluation mode and expecting it to track quality. Validation loss going down is a good sign, but compare generated outputs with a metric before you trust a checkpoint.
- Forgetting
model.train()andoptimizer.zero_grad()in a hand-written loop. Dropout stays off in evaluation mode, and gradients accumulate if you do not clear them.
A minimal hand-written loop with the padding fix looks like this:
import torch
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
sources = [
"summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years.",
"summarize: The museum will open a new wing next month and extend its opening hours on weekends.",
]
targets = [
"The council approved 40 km of new bike lanes.",
"The museum will open a new wing.",
]
batch = tokenizer(sources, text_target=targets, return_tensors="pt", padding=True)
batch["labels"][batch["labels"] == tokenizer.pad_token_id] = -100
model.train()
for step in range(3):
optimizer.zero_grad()
loss = model(**batch).loss
loss.backward()
optimizer.step()
print(step, round(loss.item(), 4))Repeating the same two examples makes the loss fall quickly, which confirms the plumbing works. It is not a useful training run, because the model is only memorising two pairs.
Label smoothing and other loss variations
The plain cross-entropy loss pushes the model toward putting all probability on the single reference token. Label smoothing spreads a small share of the probability (often 0.1) across the other tokens. It reduces overconfidence and often helps translation. In Hugging Face, you can set label_smoothing_factor in Seq2SeqTrainingArguments.
Be careful when comparing losses. A smoothed loss is higher than an unsmoothed one for the same model, so numbers from runs with different smoothing values are not comparable.
Summary of the key ideas
- The decoder predicts each target token given the source and the previous target tokens.
- Teacher forcing feeds the true previous tokens during training, so all positions train in parallel.
- The decoder input is the target shifted right. The labels are the target itself.
- Cross-entropy is the average negative log probability of the correct tokens, ignoring padding positions set to
-100. - Exposure bias is the price of teacher forcing, because generation uses the model's own outputs.
Exercise
A colleague tokenises a padded batch of targets and passes the result as labels without any other change. The training loss looks fine, but generated summaries often end with long runs of the padding token. What went wrong, and how do you fix it?
Show answer
The padding token IDs in the labels were counted by the cross-entropy loss, so the model was trained to predict padding at the end of each shorter target. Replace the padding positions in labels with -100, which the loss ignores, or use DataCollatorForSeq2Seq, which does this automatically.
Exercise
The target is "Das Haus ist wunderbar." and the decoder input at position 3 is "Haus". Which label is predicted at that position, and why is the full target never visible to the decoder at position 3?
Show answer
The label at position 3 is "ist", because the decoder input is the target shifted right by one position, so each input token is the label from the position before. The causal mask blocks attention to later positions, so the decoder cannot see "ist", "wunderbar" or the final period when predicting "ist".
Exercise
Your validation loss drops steadily for five epochs, but ROUGE on generated summaries stops improving after epoch two. Give two reasons this can happen.
Show answer
The loss is computed with teacher forcing on correct prefixes, so it measures token-level fit and ignores exposure bias, where generation feeds the model's own errors back in. The loss also keeps rewarding closer matching of the reference wording, which can mean overfitting to the training style without making generated summaries better by ROUGE. Choose checkpoints using generated-text metrics as well as loss.