Sub topic 4
Tokenisation, special tokens and target text
This chapter assumes you know basic Python and have used the Hugging Face transformers library. It also assumes you know that Transformers read sequences of integer ids rather than raw text. Here you will see how an encoder-decoder model turns source and target strings into those ids, which special tokens it adds, and how the target text becomes the labels used in training.
Why tokenisation matters in a text-to-text model
An encoder-decoder model has two text streams. The encoder reads the source (an article, an English sentence). The decoder produces the target (a summary, a German sentence). Both streams must be converted to integer ids, and the decoder must convert ids back to text. Most bugs in summarisation and translation pipelines come from this step: truncated sources, missing end tokens, padded labels that corrupt the loss, or the wrong target language.
The tokenizer is part of the model. Each checkpoint was trained with one specific tokenizer and vocabulary, so you load them together with the same name.
Subword tokenisation
Word-level vocabularies fail on rare words, names and inflected forms. Character-level sequences are too long. Subword tokenisation splits text into pieces that are frequent enough to learn well. A common word is often a single piece. A rare word is split into several pieces. Any string can be represented, so unknown words rarely occur.
Two families are common in encoder-decoder models:
- Byte-level BPE (byte-pair encoding) starts from bytes and merges frequent pairs. BART uses it. Any input can be encoded, because every string is a sequence of bytes.
- SentencePiece works directly on raw text, including spaces, and marks word starts with the symbol
▁. T5, MarianMT and mBART use it.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("t5-small")
text = "summarize: Unbelievably long compound words are split."
encoded = tokenizer(text)
print(encoded["input_ids"])
print(tokenizer.convert_ids_to_tokens(encoded["input_ids"]))
print(tokenizer.eos_token, tokenizer.eos_token_id)
print(tokenizer.pad_token, tokenizer.pad_token_id)In the printed tokens you will see pieces that begin with ▁ and the final token </s>. You did not type </s>. The tokenizer appended it. Exact splits vary by checkpoint, so run the code and read your own output rather than relying on any table of examples.
Special tokens
Special tokens are reserved vocabulary entries that carry structure rather than content.
| Token role | Purpose |
|---|---|
| Padding | Fills shorter sequences in a batch to equal length. Masked out in attention. |
| End of sequence (EOS) | Marks the end of a sequence. The decoder must learn to emit it so generation stops. |
| Beginning of sequence (BOS) | Marks the start of a sequence in some models, such as BART. |
| Unknown | Stands in for text outside the vocabulary. Rare with byte-level BPE. |
| Language code | Names the source or target language in multilingual models such as mBART. |
Conventions differ between model families, and mixing them up gives poor output without raising an error.
| Model | Tokeniser | Source input gets | Notes |
|---|---|---|---|
| BART | Byte-level BPE | `<s>` ... `</s>` | Generation starts from the EOS token as the decoder start token in `bart-large-cnn`. |
| T5 | SentencePiece | text ... `</s>` | A task prefix such as `summarize: ` is part of the input text. Decoder start token is the pad token. |
| MarianMT | SentencePiece, one model per language side | text ... `</s>` | One checkpoint per language pair, such as `opus-mt-en-de`. |
| mBART | SentencePiece, shared | text `</s>` plus a language code | You set source and target language codes. |
You do not add these tokens yourself. Calling the tokenizer adds the ones the checkpoint expects. Inspect tokenizer.special_tokens_map and model.config.decoder_start_token_id if you need to confirm.
Source text and target text
Early seq2seq code tokenised the target with the same call as the source. That is wrong for tokenizers that treat the two sides differently. Marian checkpoints, for example, use a separate SentencePiece model for the target language. Modern tokenizers therefore take a text_target argument. It applies target-side tokenisation and puts the result under the key labels.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("t5-small")
sources = [
"summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years.",
"summarize: Rain is expected across the region on Friday.",
]
targets = [
"The council approved 40 km of new bike lanes.",
"Rain expected on Friday.",
]
batch = tokenizer(
sources,
text_target=targets,
max_length=64,
truncation=True,
padding=True,
return_tensors="pt",
)
print(batch.keys())
print(batch["input_ids"].shape, batch["labels"].shape)
print(batch["attention_mask"])
print(batch["labels"])The batch holds three tensors: input_ids, attention_mask and labels. The attention mask has 1 for real tokens and 0 for padding, so the encoder ignores padding. The labels are the target ids, ending in the EOS id.
From labels to decoder inputs
During training the decoder receives the target shifted one position to the right, so that at each step it predicts the next target token from the earlier ones. The previous chapter covered this as teacher forcing. The practical point here is that you only supply labels. When you pass labels to an encoder-decoder model, it builds decoder_input_ids itself by shifting right and inserting the decoder start token at position 0.
Padding the labels correctly
When a batch holds targets of different lengths, the shorter ones are padded. If the loss counted those pad positions, the model would be trained to predict padding. Hugging Face models ignore label positions set to -100. So replace the pad id in the labels with -100 before computing the loss.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "t5-small"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForSeq2SeqLM.from_pretrained(name)
batch = tokenizer(
[
"summarize: The city council approved a plan to add 40 kilometres of bike lanes over three years.",
"summarize: Rain is expected on Friday.",
],
text_target=[
"The council approved 40 km of new bike lanes.",
"Rain on Friday.",
],
padding=True,
return_tensors="pt",
)
labels = batch["labels"]
labels[labels == tokenizer.pad_token_id] = -100
batch["labels"] = labels
print(labels)
output = model(**batch)
print(output.loss)You can also let DataCollatorForSeq2Seq do this for you. It pads each batch dynamically and sets label padding to -100 by default.
Truncation and length limits
Every model has a maximum input length, and the encoder cannot read past it. With truncation=True and max_length, the tokenizer cuts the source after that many tokens, keeping the end token. Text cut off this way never reaches the model, so a summary will silently ignore the end of a long article. Chapter 10 returns to this problem.
Targets need their own limit. Set max_length on the target side when you build training data. At generation time, set max_new_tokens to bound the output. These are separate settings with separate purposes: one limits what the encoder sees, the other limits what the decoder writes.
Language codes in multilingual models
A Marian checkpoint is trained for one direction, so the language pair is fixed by the model name. mBART is one model for many languages, so you must tell it which language is the source and which is the target. The source language is set on the tokenizer. The target language is forced as the first generated token.
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
name = "facebook/mbart-large-50-many-to-many-mmt"
tokenizer = AutoTokenizer.from_pretrained(name, src_lang="en_XX")
model = AutoModelForSeq2SeqLM.from_pretrained(name)
batch = tokenizer(["The weather is nice today."], return_tensors="pt")
outputs = model.generate(
**batch,
forced_bos_token_id=tokenizer.convert_tokens_to_ids("de_DE"),
num_beams=4,
max_new_tokens=64,
)
print(tokenizer.batch_decode(outputs, skip_special_tokens=True))The argument forced_bos_token_id makes the decoder's first token the German language code, which steers every later token toward German. If you leave it out, the model may answer in the wrong language or copy the source.
Decoding ids back to text
batch_decode converts generated ids to strings. Pass skip_special_tokens=True to drop padding, EOS and language codes from the output. Without it you will see literal <pad> and </s> in your results, which breaks metric scores and downstream parsing.
When you decode labels to compute metrics during evaluation, first replace -100 with the pad id. The decoder cannot map -100 to a token, and many tokenizers raise an error or produce garbage.
Common errors
- Wrong tokenizer for the checkpoint. Ids from a different vocabulary decode to nonsense. Always use
AutoTokenizer.from_pretrainedwith the same name as the model. - Missing task prefix for T5. The original T5 checkpoints were trained with prefixes like
summarize:andtranslate English to German:. Without one, the output is unpredictable. - Tokenising targets as sources. Use
text_target, especially for Marian and mBART. - Unmasked label padding. Replace pad ids with
-100. - Silent truncation. Compare
len(tokenizer(text)["input_ids"])withtokenizer.model_max_lengthfor long documents. - Special tokens left in output. Decode with
skip_special_tokens=True.
Exercise
You build a fine-tuning batch for T5 with padding=True. The training loss is surprisingly low from the first step, and the model later produces short outputs followed by runs of padding. What is the most likely cause, and what is the fix?
Show answer
The label padding was not masked. The pad token ids in labels count toward the cross-entropy loss, so the model is rewarded for predicting padding, which is easy. Replace every tokenizer.pad_token_id in labels with -100 (or use DataCollatorForSeq2Seq, which does this) so those positions are ignored.
Exercise
You translate English to German with mBART-50 and the output is English, a copy of the input. Which setting did you most likely omit, and where is it set?
Show answer
The forced target-language token. Pass forced_bos_token_id=tokenizer.convert_tokens_to_ids("de_DE") to model.generate. The source language is separately set with src_lang="en_XX" when loading the tokenizer.