Sub topic 2
Training with Teacher Forcing and the Cross-Entropy Loss
This chapter assumes you know Python, have loaded models with Hugging Face Transformers, and understand that training minimises a loss function.
How the decoder learns
An encoder-decoder model reads a source sequence and writes a target sequence one token at a time. During training, the decoder receives the correct target tokens shifted right by one position. This is teacher forcing: at each step the decoder conditions on the true previous token, not on its own earlier guess. Because every position can be computed in parallel, training is fast, and early mistakes do not feed forward into later training steps.
At each position, the decoder outputs a score for every token in the vocabulary. Cross-entropy loss measures how much probability the model gives the correct next token. The loss is the negative log of that probability, averaged over all non-padding positions.
Passing labels to the model builds the shifted decoder inputs and returns the loss:
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)Choosing a pretrained model
Pick a checkpoint that matches your task and languages.
- BART (
facebook/bart-large-cnn): summarisation of English news text. - T5 (
t5-small): summarisation and translation, selected by a task prefix such assummarize:ortranslate English to German:. - MarianMT (
Helsinki-NLP/opus-mt-en-de): translation, with one model per language pair. - mBART (
facebook/mbart-large-50-many-to-many-mmt): translation among many languages in one model, at a larger size.
Generating text: greedy search, beam search and length controls
Greedy search picks the single most probable token at each step. Beam search keeps the num_beams most probable partial outputs and returns the best complete one. Beam search usually scores better, but it costs more memory and time.
Useful controls include:
max_new_tokens: the maximum number of tokens to generate.min_length: the minimum output length.no_repeat_ngram_size: blocks any repeated n-gram of that size, which reduces repetition.do_sample=False: keeps decoding deterministic.
Summarising text with an encoder-decoder model
The following code runs a pretrained BART summariser with beam search and a repetition control:
from transformers import pipeline
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
article = (
"The city council voted on Tuesday to expand the bike lane network by 40 kilometres "
"over the next three years. Supporters said the plan would reduce traffic and emissions, "
"while some shop owners worried about losing parking spaces near their stores. "
"The first new lanes are expected to open next spring."
)
result = summarizer(
article,
max_new_tokens=60,
min_length=15,
num_beams=4,
no_repeat_ngram_size=3,
do_sample=False,
)
print(result[0]["summary_text"])The model truncates inputs beyond its context window, so long articles lose their final sentences unless you split them first.
Exercise
What goes wrong if you leave padding tokens in labels unmasked?
Show answer
The padding positions count toward the loss, so the model is trained to predict padding, and the reported loss is distorted. Set those label positions to -100 so the loss ignores them.