Tokenization

Updated · 10 min read
hardPython 3.13aillmtokenizationbpetokenizertransformers

Tokenization is the step that splits text into tokens, the units a language model reads and writes, and gives each token an ID number. Common words become one token, rarer words are split into pieces, and anything at all can still be written using single bytes. Most modern models use byte-pair encoding (BPE), a method that learns its pieces from a large amount of text.

"Tokens" introduced the idea. This lesson builds BPE from scratch and then looks at a real tokenizer.

Words, Characters and Subwords

ApproachDescription
Whole wordsSimple, but every new word, name or typo is unknown, and the vocabulary would be huge
CharactersNever unknown, but text becomes very long, and the model must learn spelling from scratch
Subwords (BPE)It is used to keep common words whole and split rare ones into known pieces; the standard choice
Bytes as a fallbackIt is used to write any character at all, including emoji and every language, as 1 to 4 bytes

Example: Byte-Pair Encoding from Scratch

BPE starts with single characters and repeatedly merges the pair of neighbors that appears most often into a new token. The list of merges, in order, is the tokenizer.

Common pieces get merged; anything else falls back to bytes
Python
from collections import Counter
 
# A tiny training text; real tokenizers learn from billions of words
text = "low lower lowest slow slower slowest new newer newest show shower showed"
words = Counter(text.split())
 
# Start with every word split into single characters, with _ marking the end of a word
vocab = {tuple(w) + ("_",): n for w, n in words.items()}
 
def most_common_pair(vocab):
    pairs = Counter()
    for symbols, n in vocab.items():
        for a, b in zip(symbols, symbols[1:]):
            pairs[a, b] += n
    return pairs.most_common(1)[0]
 
def merge(vocab, pair):
    merged = {}
    for symbols, n in vocab.items():
        out, i = [], 0
        while i < len(symbols):
            if symbols[i:i + 2] == pair:
                out.append(symbols[i] + symbols[i + 1])   # join the pair into one new token
                i += 2
            else:
                out.append(symbols[i])
                i += 1
        merged[tuple(out)] = n
    return merged
 
merges = []
for step in range(1, 9):
    pair, count = most_common_pair(vocab)
    vocab = merge(vocab, pair)
    merges.append(pair)
    print(f"merge {step}: {pair[0]!r} + {pair[1]!r} -> {pair[0] + pair[1]!r}  (seen {count} times)")
 
print("\nWords as tokens now:")
for symbols in list(vocab)[:6]:
    print(" ", " | ".join(symbols))
 
def tokenize(word):                                    # apply the learned merges, in order
    symbols = tuple(word) + ("_",)
    for pair in merges:
        symbols = tuple(merge({symbols: 1}, pair))[0]
    return symbols
 
print("\nA word it never saw, 'slowly':", " | ".join(tokenize("slowly")))
Output
merge 1: 'o' + 'w' -> 'ow'  (seen 9 times)
merge 2: 'l' + 'ow' -> 'low'  (seen 6 times)
merge 3: 'low' + 'e' -> 'lowe'  (seen 4 times)
merge 4: 'r' + '_' -> 'r_'  (seen 4 times)
merge 5: 's' + 't' -> 'st'  (seen 3 times)
merge 6: 'st' + '_' -> 'st_'  (seen 3 times)
merge 7: 'n' + 'e' -> 'ne'  (seen 3 times)
merge 8: 'ne' + 'w' -> 'new'  (seen 3 times)
 
Words as tokens now:
  low | _
  lowe | r_
  lowe | st_
  s | low | _
  s | lowe | r_
  s | lowe | st_
 
A word it never saw, 'slowly': s | low | l | y | _

Explanation:

  • Every word starts as single characters, with _ marking where the word ends, so the tokenizer can tell "low" at the end of a word from "low" inside "lower".
  • Merge 1 joins "o" and "w", the most common neighbors (9 times across all the words). Merge 2 joins "l" and the new "ow" into "low". Each merge adds one token to the vocabulary.
  • After 8 merges, "lowest" is two tokens, lowe | st_, and "slower" is three.
  • A new word still works. "slowly" never appeared, but it becomes s | low | l | y | _ from known pieces. No word is ever "unknown".
  • Real tokenizers do the same thing on billions of words, with tens of thousands of merges, and on bytes rather than characters.

Example: A Real Tokenizer

The programs in this chapter need pip install torch transformers. They use SmolLM2-135M, a small open language model from Hugging Face (Apache 2.0 license, about 270 MB), which runs on an ordinary laptop. The first run downloads it; the download and loading messages are left out of the output shown.

Python
from transformers import AutoTokenizer
 
tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M")
print("Vocabulary size:", f"{len(tokenizer):,}")
 
examples = [
    "The science fair is on Friday.",
    "unbelievably",
    "Navika Anamaneni",
    "Total: $1,234.56",
    "def add(a, b): return a + b",
    "La feria de ciencias es el viernes.",
    "విజ్ఞాన ప్రదర్శన",
    "🎉🎉",
]
for text in examples:
    ids = tokenizer.encode(text)
    pieces = [tokenizer.decode([i]) for i in ids]
    size = len(text.encode("utf-8"))                     # characters outside English take 2-4 bytes
    print(f"\n{text!r}: {len(text)} characters, {size} bytes -> {len(ids)} tokens")
    if any("\ufffd" in p for p in pieces):                # a token that is only part of a character
        print("   (tokens are pieces of bytes, not whole characters)")
    else:
        print("  ", pieces if len(pieces) <= 12 else pieces[:12] + ["..."])
 
print("\nRound trip:", tokenizer.decode(tokenizer.encode("The science fair is on Friday.")))
Output
Vocabulary size: 49,152
 
'The science fair is on Friday.': 30 characters, 30 bytes -> 7 tokens
   ['The', ' science', ' fair', ' is', ' on', ' Friday', '.']
 
'unbelievably': 12 characters, 12 bytes -> 4 tokens
   ['un', 'belie', 'v', 'ably']
 
'Navika Anamaneni': 16 characters, 16 bytes -> 5 tokens
   ['Nav', 'ika', ' An', 'aman', 'eni']
 
'Total: $1,234.56': 16 characters, 16 bytes -> 11 tokens
   ['Total', ':', ' $', '1', ',', '2', '3', '4', '.', '5', '6']
 
'def add(a, b): return a + b': 27 characters, 27 bytes -> 11 tokens
   ['def', ' add', '(', 'a', ',', ' b', '):', ' return', ' a', ' +', ' b']
 
'La feria de ciencias es el viernes.': 35 characters, 35 bytes -> 14 tokens
   ['La', ' f', 'eria', ' de', ' c', 'ien', 'ci', 'as', ' es', ' el', ' vi', 'ern', '...']
 
'విజ్ఞాన ప్రదర్శన': 16 characters, 46 bytes -> 46 tokens
   (tokens are pieces of bytes, not whole characters)
 
'🎉🎉': 2 characters, 8 bytes -> 6 tokens
   (tokens are pieces of bytes, not whole characters)
 
Round trip: The science fair is on Friday.

Explanation:

TextCharactersTokensWhy
The science fair is on Friday.307Common English words are one token each, with the space attached
unbelievably124A rarer word is built from pieces: un, belie, v, ably
Navika Anamaneni165Names the tokenizer rarely saw are split into several pieces
Total: $1,234.561611Every digit is its own token in this tokenizer, which helps with arithmetic
def add(a, b): return a + b2711Code keywords are common enough to be whole tokens
The same sentence in Spanish3514Twice the tokens of English: the training text was mostly English
విజ్ఞాన ప్రదర్శన ("science fair" in Telugu)1646Each Telugu character is 3 bytes, and almost every byte is a separate token
Two party emoji26Each emoji is 4 bytes; the tokenizer has a few multi-byte pieces

Decoding the tokens gives back exactly the original text. Nothing is lost by tokenizing.

Why Tokenization Matters

EffectExample
Cost and limitsAPIs charge per token, and context windows are measured in tokens; see "Context and Context Windows"
Spelling and counting lettersThe model sees belie as one unit, not five letters, so counting letters is hard for it
ArithmeticSplitting numbers into single digits makes digit-by-digit math easier to learn
Each model has its own tokenizerToken IDs from one model mean nothing to another; always use the matching tokenizer
Special tokensReserved tokens mark where each chat message begins and ends; see "Instruction Tuning and RLHF"

Common Mistakes

Assuming one token is one word. In English, a token is about three quarters of a word on average, and other languages often use far more.

Using another model's tokenizer. IDs and splits differ between models; load the tokenizer with the same name as the model.

Forgetting the space is part of the token. " school" and "school" are different tokens, which is why a stray space at the end of a prompt can change the output.

Expecting reliable letter counts. Asking a model how many r's are in a word is hard for it because it never sees the letters separately.

Interview Corner

How does byte-pair encoding work?

It starts from single bytes or characters and repeatedly merges the most frequent pair of adjacent tokens into a new token, until it reaches the target vocabulary size. To tokenize new text, the learned merges are applied in the same order.

Why do language models use subword tokens instead of words?

Subwords keep the vocabulary a manageable size while still representing any word, name or typo from known pieces. Common words stay whole for efficiency, and bytes are the fallback for anything else.

Practice

Exercise: more merges. Change range(1, 9) to range(1, 15) in the BPE program. Which new tokens appear, and how does "slowly" split now?

Check your understanding:

  1. Why does BPE mark the end of each word with _?
  2. Why did the Telugu phrase need 46 tokens for 16 characters?
  3. Why does a model find it hard to count the letters in a word?

Quick check: tokenization

4 questions
1What does each BPE step do?
2How many tokens was "The science fair is on Friday."?
3How does this tokenizer handle the number 1,234.56?
4What happens to a word the tokenizer never saw?

Key Takeaways

Quick reference

NeedCode
Load a tokenizerAutoTokenizer.from_pretrained(name)
Text to IDstokenizer.encode(text)
IDs to texttokenizer.decode(ids)
See the tokenstokenizer.convert_ids_to_tokens(ids)
Vocabulary sizelen(tokenizer)
Bytes in a stringlen(text.encode("utf-8"))

Was this tutorial helpful?

Lesson 145 of 186