Sub topic 2
Turning Text into Model Inputs
Assume you know Python functions and dictionaries, have seen training and validation sets, and understand that a transformer receives numeric tensors rather than raw text. This chapter explains how tokenization converts text into those tensors and how truncation and padding affect training.
Tokenization with a pretrained tokenizer
A tokenizer converts text into tokens, which are small pieces of words or punctuation. It then maps each token to an integer ID from the model’s vocabulary. A pretrained model must use the tokenizer associated with its checkpoint. Different tokenizers can produce different tokens and IDs, so do not substitute a generic tokenizer.
For example, the sentence “Unbelievable acting!” might become pieces such as ["un", "##believable", "acting", "!"]. The exact pieces depend on the tokenizer.
The tokenizer usually returns these fields:
| Field | Purpose |
|---|---|
| `input_ids` | Integer IDs for tokens, including special tokens |
| `attention_mask` | Marks real tokens with 1 and padding with 0 |
| `token_type_ids` | Separates segments for models that support paired inputs |
Special tokens mark boundaries or provide task-specific structure. For example, a tokenizer might add a start token and an end token automatically. Use the tokenizer’s output rather than adding these tokens by hand.
Truncation and padding
Models accept a limited number of tokens. max_length=256 sets the maximum sequence length, while truncation=True removes tokens beyond that limit.
Truncation can remove important information. If the label depends on the conclusion of a long review, keeping only the beginning may hurt accuracy. You can inspect length distributions before selecting a limit, or use a task-specific strategy such as keeping both the beginning and end.
Padding makes sequences in one batch the same length. Padding every example to the global maximum wastes memory when most examples are short. Dynamic padding waits until batching and pads each batch only to its longest example. This usually gives better memory use.
A data collator is an object that prepares a batch. DataCollatorWithPadding performs dynamic padding using the same tokenizer used during preprocessing.
from datasets import load_dataset
from transformers import AutoTokenizer, DataCollatorWithPadding
checkpoint = "distilbert-base-uncased"
dataset = load_dataset("imdb")
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(
batch["text"],
truncation=True,
max_length=256,
)
encoded = dataset.map(tokenize, batched=True)
collator = DataCollatorWithPadding(tokenizer=tokenizer)
batch = collator([encoded["train"][0], encoded["train"][1]])
print(batch["input_ids"].shape)
print(batch["attention_mask"].shape)The map operation applies the tokenizer to every example. With batched=True, the function receives a dictionary whose values are lists. The tokenizer handles that batch efficiently.
Do not pad during the map step when using dynamic padding. Leaving padding out keeps stored examples compact. The collator adds padding immediately before a batch enters the model.
Inspecting tokenization
Inspect a few examples before training. This catches unexpected truncation, missing fields, and unusual text formats.
example = tokenizer(
"A short example for inspection.",
truncation=True,
max_length=16,
)
print(example)
print(tokenizer.convert_ids_to_tokens(example["input_ids"]))The attention mask is important because padded positions contain token IDs but should not influence attention. The model uses the mask to ignore those positions.
Token length and task decisions
Choose max_length by balancing information retention, memory, and speed. Longer sequences require more computation, especially for transformer attention. A useful workflow is:
- Measure token lengths on a representative sample.
- Select a limit that retains most examples without excessive memory use.
- Inspect examples that exceed the limit.
- Compare validation results after changing the limit.
Paired tasks, such as textual entailment, pass two strings to the tokenizer. The tokenizer then creates the required segment structure and masks:
encoded_pair = tokenizer(
"The package arrived today.",
"The package was delivered.",
truncation=True,
max_length=128,
)
print(encoded_pair)Exercise
Why is dynamic padding usually preferable to padding every example to the model's maximum length?
Show answer
Dynamic padding adds padding only up to the longest sequence in each batch, reducing wasted memory and computation while preserving the same token content.