Sub topic 2
Turning text into model inputs
This chapter covers how a raw string becomes the tensors a transformer reads. It assumes you can write Python with dictionaries and functions, know what a PyTorch tensor is, and have installed transformers and datasets. The code uses distilbert-base-uncased and the IMDB movie review dataset, the same setup as the rest of the tutorial.
What the model actually receives
A transformer encoder cannot read text. It reads integer IDs, and each ID selects a row of an embedding table learned during pretraining. The tokenizer converts text to those IDs. It must be the exact tokenizer the checkpoint was pretrained with, because the IDs only mean something relative to that checkpoint's vocabulary.
Steps A to F happen once per example, in the map call. Step G happens every time the trainer builds a batch.
Subword tokenization
DistilBERT uses WordPiece. Whole words that are common in the training corpus get their own token. Rarer words are split into pieces, and a ## prefix marks a piece that continues the previous one. Because any word can be built from smaller pieces, the model rarely meets a word it cannot represent.
from transformers import AutoTokenizer
checkpoint = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
enc = tokenizer("Tokenization is unbelievably useful!")
print(enc)
print(tokenizer.convert_ids_to_tokens(enc["input_ids"]))The result has two keys:
input_idsis the list of integer token IDs.attention_maskis a list of 1s, one per token. A 1 means "real token" and a 0 means "padding, ignore this".
The token list will look like ['[CLS]', 'token', '##ization', ...] and end with '[SEP]'. The exact split of rarer words depends on the vocabulary. [CLS] and [SEP] are special tokens the tokenizer adds for you. [CLS] is placed first, and its final hidden state is what the classification head reads in the next chapter. [SEP] marks the end of the sequence.
Because this checkpoint is "uncased", the tokenizer lowercases the text and strips accents before splitting. If you switch to a cased checkpoint, such as bert-base-cased, case becomes visible to the model. Always load the tokenizer and the model from the same checkpoint name.
Truncation and max_length
Transformers have a fixed maximum sequence length. For DistilBERT it is 512 tokens, and you can read it from tokenizer.model_max_length. Self-attention cost grows with the square of the sequence length, so a shorter max_length makes training much cheaper. Longer inputs than the model's limit raise an error in the forward pass unless you truncate them.
Before you pick a max_length, measure how long your texts are:
import numpy as np
from datasets import load_dataset
raw = load_dataset("imdb")
sample = raw["train"].shuffle(seed=0).select(range(2000))["text"]
lengths = np.array([len(ids) for ids in tokenizer(sample)["input_ids"]])
print("median:", np.median(lengths))
print("95th percentile:", np.percentile(lengths, 95))
print("share over 256 tokens:", (lengths > 256).mean())Calling the tokenizer with no truncation on a few long reviews may print a warning that the sequence is longer than the model maximum. The warning is harmless here because you only count lengths and never feed them to the model.
IMDB reviews are long, and a noticeable share exceeds 256 tokens. Setting max_length=256 is a speed and memory trade-off. It cuts the tail of those reviews, and reviews often state their verdict at the end. If accuracy matters more than speed, raise max_length toward 512. If you need to keep the end, set tokenizer.truncation_side = "left", or keep the first part and the last part of each text yourself.
Padding: static versus dynamic
A batch is a rectangular tensor, so every sequence in it must have the same length. Shorter sequences are padded with the [PAD] token, and their attention_mask entries are set to 0 so attention ignores them.
There are two places to pad:
| Approach | Where it happens | Sequence length | Cost |
|---|---|---|---|
| Static padding | In the `map` function with `padding="max_length"` | Always `max_length` | Wasted compute on short examples, larger dataset on disk |
| Dynamic padding | In a data collator, per batch | Longest sequence in that batch | Little waste, one extra step at batch time |
The chapter's example uses dynamic padding. The map function only truncates, and DataCollatorWithPadding pads each batch to its longest member. Here is what the collator does on two short texts:
from transformers import DataCollatorWithPadding
collator = DataCollatorWithPadding(tokenizer)
texts = ["Great film.", "A slow, overlong story that never finds its footing."]
features = [dict(tokenizer(t, truncation=True, max_length=16), label=1) for t in texts]
batch = collator(features)
print(batch["input_ids"].shape)
print(batch["attention_mask"])
print(batch["labels"])The batch has shape (2, n), where n is the length of the longer text, and the attention mask for the short text ends in zeros. The collator also renames label to labels, which is the key the model's forward pass expects when it computes a loss. It returns PyTorch tensors, so you do not pass return_tensors yourself.
Tokenizing the whole dataset
Now apply the tokenizer to every split. This is the first code example of the tutorial, shown again with the reasoning behind each line.
from datasets import load_dataset
from transformers import AutoTokenizer
checkpoint = "distilbert-base-uncased"
raw = load_dataset("imdb")
split = raw["train"].train_test_split(test_size=0.1, seed=42)
train_ds, val_ds, test_ds = split["train"], split["test"], raw["test"]
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
def tokenize(batch):
return tokenizer(batch["text"], truncation=True, max_length=256)
train_ds = train_ds.map(tokenize, batched=True)
val_ds = val_ds.map(tokenize, batched=True)
test_ds = test_ds.map(tokenize, batched=True)
print(train_ds.column_names)Several details matter here:
batched=Truepasses a dictionary of lists, 1,000 rows at a time by default, totokenize.batch["text"]is therefore a list of strings. The fast tokenizer processes the whole list in one call, which is far quicker than one row at a time.mapadds columns. It does not replace the old ones. After tokenizing, the dataset hastext,label,input_ids, andattention_mask. TheTrainerdrops columns the model'sforwarddoes not accept (remove_unused_columns=Trueis the default), sotextis ignored at training time. You can also remove it yourself withremove_columns=["text"].datasetscaches results. A second run with the same function and data loads from the cache. If you change the tokenizer settings but get stale results, passload_from_cache_file=False.- Tokenize after splitting. Tokenization has no learned state, so splitting first does not leak information. Still, tokenizing each split separately keeps the habit safe for steps that do learn from data, such as building a label map or a vocabulary.
Common errors
These are the problems that show up most often at this stage.
- Tokenizer and model mismatch. Loading the tokenizer from one checkpoint and the model from another gives IDs that point at the wrong embeddings. Nothing crashes, but accuracy is poor. Use one
checkpointvariable for both. - Padding twice. If you use
padding="max_length"inmapand also a padding collator, the collator does nothing useful and you pay for full-length batches. Choose one. - Forgetting truncation. Without
truncation=True, a review over 512 tokens fails in the model with a size error, often as an index error in the position embeddings, typically far from the real cause. - Passing a single string to a
batched=Truefunction.batch["text"]is then a list, so any code that treats it as a string, such as calling.lower(), will fail. - Wrong label column. The trainer looks for
labelorlabels. If your dataset calls itsentiment, rename it withdataset.rename_column("sentiment", "label"). - Labels as strings. The loss needs integer class IDs. Convert string labels to integers with a mapping before training.
Checking your inputs before training
Spend a minute decoding a processed example. Most pipeline bugs are visible here.
example = train_ds[0]
print(example["label"], len(example["input_ids"]))
print(tokenizer.decode(example["input_ids"]))Check that the decoded text starts with [CLS], ends with [SEP], is lowercased, and is cut off where you expect it to be. Check that the label is 0 or 1. If everything matches, the data side of the pipeline is sound and the remaining problems will be in the model or the training settings.
Exercise
You tokenize with padding="max_length", max_length=256 inside map, and also pass DataCollatorWithPadding to the Trainer. A colleague says this is wasteful. Explain why, and say what single change makes batches shorter when most reviews are under 100 tokens.
Show answer
Every example is already padded to 256 tokens, so the collator finds nothing to pad and each batch is 256 tokens wide whatever the review length. Short reviews waste compute on padding positions. Remove padding="max_length" from the map function and keep only truncation=True, max_length=256. The collator then pads each batch to its longest sequence.
Exercise
A model trained on tokenized IMDB data scores near chance. The tokenizer was loaded from bert-base-cased and the model from distilbert-base-uncased. What is wrong, and why does no error appear?
Show answer
The tokenizer's vocabulary differs from the one the model was pretrained with, so the same ID refers to a different token in each. The IDs are all valid integers within the embedding table's range, so the forward pass runs without an error, but the embeddings the model looks up are meaningless for the text. Load both from the same checkpoint name.