Sub topic 4
Tokenisation, Special Tokens and Target Text
Assume you know basic Python, neural networks and loss functions, the Transformer self-attention mechanism, and the Hugging Face Transformers library. This chapter focuses on how text becomes model inputs and how the expected output becomes target labels.
From text to token IDs
An encoder-decoder model cannot read words directly. A tokenizer converts text into tokens, and then maps each token to an integer ID. A token may be a whole word, part of a word, punctuation, or a special marker.
For example, the word “unhappiness” might be split into several subword tokens. Subword tokenisation lets a model handle words that did not appear in its training vocabulary. The exact split depends on the model. BART commonly uses a byte-level BPE tokenizer, while T5 and many MarianMT models use SentencePiece-based tokenisation.
The tokenizer also creates an attention mask. An attention mask contains 1 for real tokens and 0 for padding. Padding makes sequences in the same batch the same length.
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("t5-small")
source = "summarize: The council approved a new bike lane."
target = "The council approved a bike lane."
batch = tokenizer(
source,
text_target=target,
return_tensors="pt",
)
print("Input IDs:", batch["input_ids"])
print("Attention mask:", batch["attention_mask"])
print("Labels:", batch["labels"])
print("Input tokens:", tokenizer.convert_ids_to_tokens(batch["input_ids"][0]))
print("Target text:", tokenizer.decode(batch["labels"][0], skip_special_tokens=True))The input_ids are sent to the encoder. The labels represent the target text that the decoder should produce. The text_target argument tells the tokenizer to apply the model's target-side tokenisation rules and return the result as labels.
Special tokens
Special tokens are reserved IDs with structural meanings. Their names and exact use vary between model families.
| Token | Typical purpose |
|---|---|
| Padding token | Fills unused positions so sequences in a batch have equal length |
| End-of-sequence token | Marks where the target sequence ends |
| Beginning-of-sequence token | Marks the start of a sequence when the model uses one |
| Decoder-start token | Gives the decoder its first input during generation |
| Unknown token | Represents text that cannot be mapped to the vocabulary |
During generation, the decoder starts with a model-specific start token. It predicts one token, feeds that prediction back into itself, and continues until it predicts the end-of-sequence token or reaches a length limit.
How source and target sequences connect
The source and target are separate sequences. The encoder reads the source sequence. At every decoder step, the decoder uses its previous target-side tokens and cross-attention to the encoder's hidden states.
During training, the target is shifted right to create decoder inputs. If the target is:
The council approved a lane.the decoder might receive:
decoder-start The council approved a laneThe labels remain:
The council approved a lane end-of-sequenceEach prediction is compared with the corresponding label using cross-entropy loss. Padding positions should not contribute to that loss. Hugging Face data collators usually replace padding label IDs with -100, which PyTorch's cross-entropy loss ignores.
When preparing batches manually, distinguish between padding in input_ids and ignored positions in labels. Padding is necessary for tensor shapes, but it should not become a learning target.
Practical checks
Before training or evaluating a model, inspect:
- The decoded source and target text.
- The token IDs and special tokens.
- The attention mask.
- The number of tokens compared with the model's context limit.
- Whether padded label positions are replaced with
-100.
Exercise
Why should padded positions in the target labels usually be replaced with -100 during training?
Show answer
Padding is added only to align examples in a batch. Replacing its label ID with -100 makes the loss function ignore those positions instead of teaching the model to generate padding.