Skip to main content
Open In Colab A language model never reads text. It reads a sequence of integer IDs, and the tokenizer decides how text is cut into the pieces those IDs stand for. Each ID selects one row of the model’s embedding matrix, so the tokenizer is fixed the moment pretraining starts. This has a practical consequence. When you fine-tune a pretrained model, you must use exactly the tokenizer it was pretrained with: the same vocabulary, the same merge rules and the same special tokens. A different tokenizer of the same kind assigns different IDs to the same text, and the model then looks up unrelated embedding rows. If no pretrained model covers your language, or your text is very different from what it saw, you train a new tokenizer on your own corpus and pretrain the model with it. The Hugging Face course shows how. This section moves from words and characters to the subword tokenizers that current language models use, and ends with what the choice of tokenizer costs a model.

Word-level tokenization

The simplest tokenizer splits text at spaces and punctuation and gives every distinct word an ID. Any word that was not in the training text maps to a single unknown token, usually written <unk>. The model cannot tell one unknown word from another.
The word “running” maps to <unk> although “runs” is in the vocabulary. A word-level vocabulary does not record that the words run, runs and running share a stem, so each form needs its own entry and its own training examples. Covering a real corpus this way takes hundreds of thousands of entries, and new names, misspellings and technical terms still fall outside it.

Character-level tokenization

At the other extreme, every character is a token. The vocabulary is small and nothing is ever unknown. The price is sequence length.
The same sentence becomes more than five times as many tokens. Self-attention compares every token with every other token, so its cost grows with the square of the sequence length, and a context window of fixed size holds about a fifth as much text. A single character also carries little meaning, so the model has to spend some of its capacity assembling characters into words. Subword tokenizers sit between the two extremes. Frequent words get a token of their own, and rare words are split into smaller pieces that are still in the vocabulary.

Byte pair encoding

Byte pair encoding (BPE) was a text compression method before Sennrich et al. adapted it to build subword vocabularies for machine translation (Sennrich et al., 2015). Training starts with every word split into characters, plus an end-of-word marker, which is written _ below. Then it repeats two steps:
  1. Count every pair of adjacent symbols across the corpus, weighted by how often each word occurs.
  2. Merge the most frequent pair into a new symbol, add it to the vocabulary and record the merge.
Training stops when the vocabulary reaches the size you chose. The ordered list of merges is the tokenizer. The trainer below runs on a corpus of one sentence.
The counts are recomputed after every merge. At the start, s h, h e, s e and e _ all occur 3 times, and the tie is broken by the order in which the pairs were first seen. Once s and h merge into sh, the pair h e survives only in “the”, so its count drops from 3 to 1 and it never wins. Counting the pairs once on the starting corpus and merging them in that order gives a different and incorrect sequence. The whole word she_ appears only at merge 9. After ten merges, the corpus words look like this:
To tokenize new text, BPE splits each word into characters and replays the learned merges in the order they were learned. A word the trainer never saw still gets a segmentation, because in the worst case it falls back to single characters.

Byte-level BPE in GPT-2

A character-level starting vocabulary has a gap: a character that never appeared in training, such as an emoji or a letter from another alphabet, still has no ID. GPT-2 closes it by running BPE over the UTF-8 bytes of the text instead of its characters (Radford et al., 2019). The starting vocabulary is the 256 possible byte values, so every string can be encoded. On top of them sit 50,000 learned merges and one special end-of-text token, 50,257 entries in all. GPT-3 uses the same tokenizer.
The Ġ in front of most tokens is a space. Before training, GPT-2 maps each of the 256 byte values to a printable Unicode character, so that the vocabulary and merge files can be stored and read as ordinary text. The 188 bytes that already print as a visible character keep it. The remaining 68, which include space, newline, tab and the other control characters, are assigned the code points from 256 upward in byte order. Space is the 33rd of them, so it lands on code point 288, which is Ġ. The function below rebuilds the table.
The mapping is not a uniform shift by 256: byte 127 lands on 289, right after space. It only exists to make the files printable, and decoding reverses it exactly. GPT-2 also splits the text with a regular expression before any merge is applied. The pieces are words with their leading space, runs of digits, runs of punctuation and runs of whitespace, and merges never cross a piece boundary. This keeps tokens such as dog. and dog! out of the vocabulary.
In a run of spaces, the last space joins the following word and each of the others stays a separate piece. GPT-2 has no merges for runs of spaces, so each extra space becomes a token of its own. This matters for indented code, as the last part of this section shows. The byte fallback also shows which languages the merges were learned from. GPT-2 was trained mostly on English web text, so an English phrase becomes a few word tokens while a Greek phrase of similar length breaks into pieces of single letters and bytes.

WordPiece

BERT uses WordPiece, which builds its vocabulary by merging pairs like BPE but chooses the pair differently (Wu et al., 2016). Instead of the most frequent pair, it merges the pair with the highest score score(a,b)=count(ab)count(a) count(b),\mathrm{score}(a, b) = \frac{\mathrm{count}(ab)}{\mathrm{count}(a)\,\mathrm{count}(b)}, which favors pairs whose parts rarely occur apart. Encoding is also different. WordPiece does not replay merges. It takes the longest vocabulary entry that matches the start of the word, then the longest entry that matches what remains, and so on. Pieces that continue a word carry the prefix ##, which tells the decoder to attach them to the previous piece without a space.
The bert-base-uncased tokenizer lowercases its input before anything else, so “GPU” is looked up as “gpu”. That word is not in the vocabulary of 30,522 entries, and the longest match from the left is gp, followed by ##u.

Unigram and SentencePiece

The Unigram tokenizer of Kudo works in the opposite direction. It starts from a large candidate vocabulary and assigns each token a probability. It then repeatedly removes the tokens whose removal reduces the likelihood of the training corpus the least, until the vocabulary has the target size. To tokenize a word, it picks the segmentation with the highest probability. SentencePiece is a library that trains BPE or Unigram tokenizers directly on raw text. It treats the space as an ordinary symbol, written ▁, so it needs no language-specific rules for splitting words. That is useful for languages such as Japanese and Chinese, which do not separate words with spaces. T5 uses a SentencePiece Unigram model, and Llama 2 a SentencePiece BPE model.

Vocabulary size and sequence length

The tiktokenizer app runs several tokenizers in the browser and colors each token. Paste the following program into it and switch between the gpt2 and cl100k_base tokenizers.
The comparison below uses three OpenAI tokenizers: gpt2, cl100k_base (GPT-3.5 and GPT-4) and o200k_base (GPT-4o). For each one it counts the tokens of the program, the tokens that contain only whitespace, and the tokens left once the indentation is removed.
Whitespace accounts for 23 of the 38 extra tokens that gpt2 needs: it spends 40 tokens on pieces that hold only spaces or newlines, against 17 for cl100k_base. The newer tokenizer has merges for runs of spaces, so the indentation of a line costs one token instead of one per space. It also has merges that join a newline to the punctuation before it, such as .\n, and to other newlines. One line of the docstring shows both.
Removing the indentation only narrows the gap from 38 tokens to 32, because the newlines remain. The rest of the gap comes from the larger vocabulary, which holds more whole words and more common code fragments. Doubling the vocabulary again, from cl100k_base to o200k_base, saves nothing on this program. The extra entries pay off on other languages, as the Greek sentence below shows.
Fewer tokens for the same text have three effects. More text fits in a context window of fixed length. Each self-attention layer compares every pair of tokens, so its cost scales with the square of the length, and 187 tokens cost about 1.6 times as much as 149. Text generation is also faster, because the model produces one token per step. A larger vocabulary has a cost too. The embedding matrix has one row of width dd per vocabulary entry, and the output layer that predicts the next token has the same shape. GPT-2 shares a single matrix between the two, and the calculation below assumes GPT-3 does as well.
For GPT-2 small, the embedding matrix is almost a third of the parameters, and switching to the cl100k_base vocabulary would add another 38 million. For a model the size of GPT-3, the same matrix is well under one percent of the parameters. At that scale the extra parameters cost little compared with the shorter sequences they buy, which is one reason recent large models use vocabularies of 100,000 to 200,000 entries.

References

  • Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., et al. (2019). Language models are unsupervised multitask learners. OpenAI Blog. Link
  • Sennrich, R., Haddow, B., Birch, A. (2015). Neural Machine Translation of Rare Words with Subword Units. arXiv [cs.CL]. Link
  • Wu, Y., Schuster, M., Chen, Z., Le, Q., Norouzi, M., et al. (2016). Google’s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation. arXiv [cs.CL]. Link

Found an error on this page? Report an issue.