Tokenizers: Turn Text into Token IDs

A neural network computes with numbers, so before a language model can read a sentence, the sentence has to become a list of numbers. The tokenizer does that work: it cuts the text into pieces, gives each piece its number from a fixed list, and arranges several texts into one batch the model can take in at once. Knowing what it returns, and why, is what lets you read a model's input and spot when something has gone wrong before the model ever runs.

Tokens and the vocabulary

The pieces a tokenizer cuts text into are called tokens. A token is often a whole word, sometimes a part of a word, and a punctuation mark is a token of its own. Every token the tokenizer can produce is an entry of its vocabulary: a fixed list, built once before the model was trained, in which each entry has its own number, its token ID.

For a BERT-style tokenizer the vocabulary is a plain text file, vocab.txt, with one token per line. A token's ID is simply its line number minus one.

The tokenizer of distilbert/distilbert-base-uncased has 30,522 entries. It is also uncased: it lowercases the text first, so Card and card become the same token. Here is a short message cut into tokens, with the ID each one has in that vocabulary:

Lost my card, as tokens and IDs
  1. lost 2439
  2. my 2026
  3. card 4003

The numbers carry no meaning of their own: 4003 is not "bigger" than 2026 in any sense. An ID is only an address in the vocabulary. Inside the model, each ID selects one row of a learned table of vectors, and that vector is what the network actually computes with.

Subwords: common words whole, rare words in pieces

A vocabulary has to be fixed and limited, yet it must be able to write any text, including names, typos and words nobody listed. There are three ways to cut text, and they trade size against meaning:

Cut intoVocabularyWhat goes wrong
Whole wordsHuge: English alone has over 500,000 words"dog" and "dogs" are unrelated entries, and any word not listed cannot be written
Single charactersTiny: letters, digits, punctuationEach token means little, and one word easily becomes 10 or more tokens
SubwordsTens of thousands of entriesCommon words stay whole, rare words are split into known pieces

Subword tokenization takes the middle road. Frequent words get an entry of their own, and a rare word is written as a few pieces that are in the vocabulary, the way "annoyingly" can be written as "annoying" plus "ly". Each piece still carries some meaning, and the vocabulary stays small enough to learn.

BERT and DistilBERT use a subword method called WordPiece. To split a word, it takes the longest piece from the start of the word that is in the vocabulary, then does the same with what is left. Every piece after the first is marked with the prefix ##, which means it continues the word; a token without ## starts a new word. The cased BERT tokenizer, which keeps capital letters, shows it on one sentence:

Tokens and IDs of the cased BERT tokenizer
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")

tokens = tokenizer.tokenize("Using a Transformer network is simple")
print(tokens)
# ['Using', 'a', 'Trans', '##former', 'network', 'is', 'simple']

ids = tokenizer.convert_tokens_to_ids(tokens)
print(ids)
# [7993, 170, 13809, 23763, 2443, 1110, 3014]

print(tokenizer.decode(ids))
# Using a Transformer network is simple

"Transformer" has no entry of its own, so the longest known start, Trans, is taken first and the rest becomes ##former. decode() turns the IDs back into text and joins the ## pieces to the word they continue. Only when a word cannot be written with any pieces of the vocabulary does WordPiece give up and write the whole word as the unknown token [UNK]. Seeing many [UNK] tokens in your data is a sign that the tokenizer does not suit that text.

True or false?

A word that is not in the vocabulary becomes the unknown token.

False. WordPiece first writes it with known pieces, like Trans + ##former. It becomes [UNK] only when no split into vocabulary pieces exists.

A token marked with ## continues the word of the token before it.

True. In WordPiece, ## means "joined to the previous piece"; a token without it starts a new word.

Special tokens

Besides words and pieces, a vocabulary holds a few special tokens that never appear in ordinary text. They mark structure: where a text starts and ends, which positions are empty, which word is hidden. A model learns their roles during pretraining, so it expects to see them in the same places afterwards. The BERT family uses these, here with their IDs in the uncased DistilBERT vocabulary:

TokenIDWhat it marks
[CLS]101The start of every input
[SEP]102The end of a text, or the border between two texts
[PAD]0An empty position that only fills a row of a batch
[UNK]100A word that could not be written with the vocabulary
[MASK]103A hidden word, used when the model is pretrained to guess it

When you call the tokenizer on a text, it adds the start and end tokens for you (its setting add_special_tokens is True by default), so a single text is written as [CLS] text [SEP]. The two-step route of tokenize() and convert_tokens_to_ids() adds none, which is why its IDs are not exactly what the model receives:

What the model receives for Lost my card
  1. [CLS] 101
  2. lost 2439
  3. my 2026
  4. card 4003
  5. [SEP] 102

Other model families use other special tokens, or none, which is one more reason to let each model's own tokenizer add them. When you turn IDs back into text, decode(ids, skip_special_tokens=True) leaves them out.

True or false?

The IDs from tokenize() followed by convert_tokens_to_ids() are the same IDs the tokenizer returns when you call it on the text.

False. Calling the tokenizer also adds [CLS] at the start and [SEP] at the end; the two-step route adds no special tokens.

What the model receives: token IDs and an attention mask

Calling the tokenizer returns a BatchEncoding, an object that behaves like a Python dictionary. Its two central entries are the two inputs a model like DistilBERT reads:

  • input_ids: the ID of every token, special tokens included.
  • attention_mask: one number per position, 1 where a real token sits and 0 where the position only holds padding.

Some tokenizers add more entries, such as token_type_ids, which say which of two texts each token belongs to. DistilBERT does not use them, so if they appear they hold only zeros. Printing the keys of the result shows what your tokenizer really returns.

With return_tensors="pt" the values come back as PyTorch tensors, already shaped as a batch, which is the shape a model expects; without it they are plain Python lists.

The mask exists because of how the model reads. An attention layer lets every token look at every other token of its text, to work out what each one means in context. A padding position is not part of the text, but without a mask the model would look at it like any other token, and the same text would get different results depending on how much padding happens to follow it. A 0 in the mask tells the attention layers to ignore that position, so a padded text gives the same output it gives alone.

True or false?

Padding a text with [PAD] tokens changes nothing for the model, even without an attention mask.

False. Without the mask, attention also looks at the padding positions, and the padded text gets different outputs than it gets alone.

An attention mask of all ones means the row holds no padding.

True. A 1 marks a real token at that position, so a row of ones is a text that fills its whole row.

Padding and truncation: one rectangular batch

A model takes a batch of texts as one tensor, and a tensor is rectangular: every row has the same length. Texts are not. Two settings of the tokenizer make them fit:

  • Padding fills the shorter rows with the padding token until they are as long as the others.
  • Truncation cuts the rows that are longer than a maximum length.

Both are off by default, so you switch them on when you tokenize a batch:

Tokenize two texts into one batch
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("distilbert/distilbert-base-uncased")

batch = tokenizer(
    ["Lost my card", "The card"],
    padding=True,
    truncation=True,
    return_tensors="pt",
)
print(batch["input_ids"])
print(batch["attention_mask"])

The first text takes five positions and the second only four, so the second row gets one [PAD] (ID 0) at its end, and its mask has a 0 there:

The batch, position by position
Row12345
input_ids, text 1101243920264003102
input_ids, text 2101199640031020
attention_mask, text 111111
attention_mask, text 211110

What the two settings do depends on the values you give them. Several values fall back to the model maximum, the longest input the model was built for: 512 tokens for BERT and DistilBERT. A longer input would make the model fail.

SettingWhat it does
padding=True (or "longest")Pads every row to the longest text in this batch; a single text gets no padding
padding="max_length"Pads every row to max_length, or to the model maximum when max_length is not set
truncation=TrueCuts rows longer than max_length, or longer than the model maximum when max_length is not set
max_length=nThe length to pad or cut to, counting the special tokens

So truncation=True on its own cuts only texts longer than 512 tokens and leaves short messages untouched. When a text is cut, the tokens at its end are dropped, but the special tokens are kept, so the row still ends with [SEP].

Each choice costs something. Padding to the longest text of the batch wastes little work, while padding="max_length" with no length set turns a three-word message into 512 positions, most of them padding the model must still carry. Truncation keeps every row within what the model can handle, but whatever it cuts off, the model never sees.

True or false?

padding=True pads every text to the model maximum of 512 tokens.

False. It pads to the longest text in the batch. Only padding="max_length" pads to a fixed length, which is the model maximum when no max_length is given.

With truncation=True and no max_length, a short message keeps all of its tokens.

True. Without max_length, truncation cuts only at the model maximum, which a short message never reaches.

max_length=5 leaves room for five tokens of the text, plus the special tokens.

False. max_length counts the special tokens too, so a row of five holds [CLS], three text tokens and [SEP].

A tokenizer belongs to its model

A token ID is an address in one particular vocabulary, and the model learned one vector for each address of that vocabulary during pretraining. Give the model IDs from another tokenizer and each ID still selects a row, only now it is the row of a different token: there is often no error at all, just input that means something else to the model.

The vocabulary is not the only thing that has to match. The tokenizer's rules for cutting text do too, such as whether it lowercases the text and which special tokens it puts where.

That is why the tokenizer and the model are loaded from the same checkpoint, the repository or folder that holds a trained model. Its tokenizer files sit beside its weights:

  • distilbert-base-uncased one checkpoint
  • Tokenizer files vocab.txt, tokenizer.json
  • Model files model.safetensors, config.json
  • AutoTokenizer text to token IDs
  • Model one vector per ID
  • distilbert-base-uncased to Tokenizer files
  • distilbert-base-uncased to Model files
  • Tokenizer files to AutoTokenizer: from_pretrained
  • Model files to Model
  • AutoTokenizer to Model: token IDs, mask

AutoTokenizer.from_pretrained() reads the checkpoint's tokenizer files and builds the right tokenizer for that model, so you pass it the same name you pass to load the model. When you later save a model of your own, you save its tokenizer with it for the same reason.

True or false?

Any tokenizer can feed any model, as long as both are for the same language.

False. Each model learned one vector per ID of its own vocabulary. IDs from another tokenizer point at the wrong tokens, often without any error.

Loading the tokenizer with the same checkpoint name as the model keeps its vocabulary and rules matched to the model.

True. The checkpoint stores the tokenizer files the model was pretrained with, next to its weights.