Skip to content
LearnAI

2.1Tokenization & BPE

Before a language model reads a single word, text is chopped into tokens. Learn how byte-pair encoding builds that vocabulary, and why it explains so many LLM quirks.

⏱ 13 minBeginner

Computers want numbers, not text

A neural network is a big function that multiplies and adds numbers. Text is not numbers. So the very first thing any large language modelLarge language model (LLM)A very large neural network, usually a Transformer, trained to predict the next token of text. Chat assistants are post-trained LLMs. does is convert a string like "The cat sat." into a list of integers, and the very last thing it does is convert integers back into text. The program that does this conversion is the tokenizerTokenizerThe component that splits text into tokens and maps them to integer IDs (and back)., and the units it produces are tokensTokenA chunk of text (a word, part of a word, or a character) that a language model reads and writes as a single unit..

You might think the choice is obvious: use letters, or use words. Both turn out to be bad, for opposite reasons.

  • Characters give you a tiny alphabet (a few hundred symbols covers most text), and you can spell anything. But sequences get long: this paragraph is around 400 characters. The model would spend most of its effort reassembling letters into words, and its limited context windowContext windowThe maximum number of tokens a model can take into account at once, covering both prompt and output. would fill up fast.
  • Words give short sequences, but the list of possible words is effectively endless: names, typos, unfollowed, COVID-19, pneumonoultramicroscopic, every word in every language. Any word not in the list becomes a useless “unknown” symbol, and rare words get almost no training signal.

Modern tokenizers split the difference with subword units. Common words like the get their own token. Rarer words are built from a few pieces, like token + ization. Anything at all can still be spelled out, piece by piece, in the worst case byte by byte. The set of all tokens a model knows is its vocabularyVocabularyThe fixed set of tokens a model knows, typically 32k–260k entries for modern LLMs., and each token has a fixed integer token idToken idThe integer a tokenizer assigns to each token in its vocabulary. The model only ever sees these ids, never the underlying letters..

ANALOGY· Shorthand that writes itself

Imagine a court stenographer who invents shorthand on the fly. On day one she writes every letter. By day three she has noticed that “the” appears constantly and gives it a single squiggle. Then “ing”. Then “the defendant”. After a month her notes are a quarter the length, yet she can still write any unfamiliar name letter by letter.

The letters are the base vocabulary (bytes). Each new squiggle is a merge, and the order she invented them in is the merge list. Her finished shorthand dictionary is the tokenizer’s vocabulary. And because she only made squiggles for things she heard often, a word from a language she rarely hears still costs her many strokes.

Byte-pair encoding: learn the chunks from data

Byte-pair encodingByte-pair encoding (BPE)A tokenization algorithm that starts from characters or bytes and repeatedly merges the most frequent adjacent pair into a new token. started life in 1994 as a data-compression trick and was adapted for neural machine translation by Sennrich, Haddow and Birch in 2015. The training algorithm fits in one sentence: start with single symbols, count every adjacent pair in a corpus, merge the most frequent pair into a new symbol, and repeat until the vocabulary is the size you want.

A few details matter in practice:

  1. Pre-tokenization. Before counting, the text is cut into rough word-like pieces with a regular expression, so merges never cross from one word into the next. In GPT-style tokenizers a space sticks to the following word, which is why the (with a leading space) and the are different tokens. This is called pre-tokenizationPre-tokenizationThe step before BPE that cuts text into rough word-like chunks with a regular expression, so merges never cross word boundaries..
  2. Frequencies, not positions. Each distinct word is stored once with its count, so counting pairs is cheap even for large corpora.
  3. The merge list is the tokenizer. To tokenize new text, you split it into bytes and replay the learned merges in the order they were learned. The same text always produces the same tokens.

The demo below runs all of this live in your browser. It trains a real byte-level BPE tokenizer on five short paragraphs of English (you can read them at the bottom), then tokenizes whatever you type.

INTERACTIVETokenizer playground
The283␣baker367␣o267p112en265s115␣the258␣shop449␣every434␣m276or279ning393␣and277␣starts442␣m276i105x120ing264␣the258␣d311ough423.46
characters
67
words
12
UTF-8 bytes
67
tokens
22
chars / token
3.05

␣ marks a space (it belongs to the token after it). Hex like <E3> is a raw byte that has not been merged into a full character. Ids 0–255 are the raw bytes; ids from 256 up are learned merges.

How the merges were learned
1/12 · merge 1
Most frequent adjacent pairs in the corpus (before merge 1)
paircount
"␣" + "t" ← merge64
"t" + "h"55
"h" + "e"52
"␣" + "a"35
"e" + "r"33
"i" + "n"32
New token
"␣" + "t" → "␣t" (id 256)
Effect on a sample phrase
before␣the␣other␣thing␣they␣were␣learning
after␣the␣other␣thing␣they␣were␣learning
35 → 32 tokens.
Type anything, or pick an example. Drag the merges slider to 0 to see raw bytes, then slowly up to watch frequent chunks fuse into single tokens. Step through the first merges below to see exactly how each one was chosen.

Things to try:

  1. Slide merges to 0. Every byte is its own token, so the token count equals the UTF-8 byte count. That is the pure “character-level” extreme.
  2. Step through the first merges. The very first merge on this corpus joins a space and t, the second joins h and e, and the third joins those two into the. The most frequent word in English gets its own token within three steps.
  3. Pick “Other scripts”. French at least reuses a few English merges (on, ou). Russian and Japanese explode into hex bytes, because each of their characters takes 2–3 bytes in UTF-8 and our tokenizer never saw them during training, so it has no merges for them.
  4. Pick “Rare words”. Words from the corpus ( shop, baker) are single tokens. Antidisestablishmentarianism shatters into fragments.

Byte-level BPE: never an unknown token

Our demo, like GPT-2 and most modern models, uses byte-level BPEByte-level BPEBPE whose base vocabulary is the 256 possible UTF-8 byte values, so any text can be encoded and there is never an unknown token.. Instead of starting from Unicode characters (there are over 150,000 of them), it starts from the 256 possible byte values of UTF-8 text. Any string in any language, including emoji and binary junk, is some sequence of bytes, so it can always be encoded. There is no “unknown word” token, ever. The cost is that rare scripts start out as several bytes per character and only become efficient if the training corpus contains enough of them to earn merges.

Why tokens explain so many LLM quirks

Once you know the model sees token ids and not letters, a lot of strange behavior stops being mysterious.

Counting letters. Ask a model how many rs are in strawberry and older models famously said two. The word reaches the model as a couple of opaque ids, something like straw + berry, and nothing in the id berry spells out “b-e-r-r-y”. The model has to have memorized the spelling of each token from training data. Try the “strawberry” preset in the demo: our tiny tokenizer splits it into several fragments, none of which reveals its letters to a model that only sees ids.

Numbers. GPT-2’s tokenizer chunked numbers by frequency, so 2024 might be one token while 2025 was two, and arithmetic had to work across inconsistent pieces. Later designs fix this by rule: Llama 1 and 2 split every number into single digits, while the GPT-4 tokenizer groups digits into runs of at most three (our demo’s pre-tokenizer does the same). Try the “Numbers” preset: our corpus contains almost no digits, so every number falls apart into single digits, which happens to be exactly what Llama chose on purpose.

Spaces and capitalization. Hello, Hello, hello and HELLO are typically four unrelated ids. The model learns that they are related, but only by seeing them used in similar ways. Leading and trailing whitespace in a prompt can change the tokens and, occasionally, the answer.

Other languages cost more. A tokenizer trained mostly on English text gives English the most merges. The same sentence in Hindi, Burmese or Amharic can take several times as many tokens. Petrov and colleagues measured differences of up to 15 times between languages for some tokenizers. Since APIs charge per token and context windows are measured in tokens, speakers of those languages pay more and fit less.

Glitch tokens. Because the tokenizer and the model are trained separately, a tokenizer can contain tokens that almost never appear in the model’s training data. In 2023 people found that GPT-3 produced bizarre output when asked to repeat strings like SolidGoldMagikarp, a Reddit username that had earned its own token but whose embedding was barely trained.

What happens to the ids next

A token id like 464 is just a row number. The model’s first layer is a big lookup table, the embedding matrix, with one learned vector per vocabulary entry. Token 464 grabs row 464, and from then on everything is vectors. That lookup is the subject of the next lesson on embeddings. At the other end, the model outputs one score per vocabulary entry and picks the next id, which is how next-token prediction works.

MATH CORNER · optionalBPE as an algorithm, with a worked example

Let the corpus be a multiset of words ww with counts c(w)c(w), each word written as a sequence of symbols w=(s1,…,sn)w = (s_1, \dots, s_n). One BPE step computes, for every pair of symbols (a,b)(a, b),

count(a,b)=∑wc(w)⋅#{ i:si=a, si+1=b }\text{count}(a,b) = \sum_{w} c(w) \cdot \#\{\, i : s_i = a,\ s_{i+1} = b \,\}

then picks (a∗,b∗)=arg⁡max⁡(a,b)count(a,b)(a^*, b^*) = \arg\max_{(a,b)} \text{count}(a,b), adds the new symbol a∗b∗a^*b^* to the vocabulary, and rewrites every occurrence of the pair as that one symbol. After kk steps the vocabulary has 256+k256 + k entries (for byte-level BPE).

Worked example (the classic one from Sennrich et al.). The corpus has four words: low ×5, lower ×2, newest ×6, widest ×3. Initial pair counts include:

pairwhere it occurscount
e snewest (6) + widest (3)9
s tnewest (6) + widest (3)9
w elower (2) + newest (6)8
l olow (5) + lower (2)7
o wlow (5) + lower (2)7

Ties are broken by a fixed rule; say we take e s first. The merges then go:

stepmergecountnew symbol
1e + s9es
2es + t9est
3l + o7lo
4lo + w7low

Notice that after merge 1, w e drops from 8 to 2: in newest the e was absorbed into es. Counts must be recomputed after each merge.

Now tokenize lowest, a word that never appeared in the corpus. Start from l o w e s t and replay the merges in order: l o w es t → l o w est → lo w est → low est. Two tokens, both meaningful. That is the magic of subwords: unseen words are built from seen parts.

In code

A minimal BPE trainer in Python, followed by a real production tokenizer:

from collections import Counter

def train_bpe(words: dict[str, int], num_merges: int):
    vocab = {tuple(w): c for w, c in words.items()}   # word as tuple of symbols
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for syms, c in vocab.items():
            for a, b in zip(syms, syms[1:]):
                pairs[a, b] += c
        if not pairs:
            break
        (a, b), _ = pairs.most_common(1)[0]
        merges.append((a, b))
        new_vocab = {}
        for syms, c in vocab.items():
            out, i = [], 0
            while i < len(syms):
                if i + 1 < len(syms) and (syms[i], syms[i + 1]) == (a, b):
                    out.append(a + b); i += 2
                else:
                    out.append(syms[i]); i += 1
            new_vocab[tuple(out)] = c
        vocab = new_vocab
    return merges

print(train_bpe({"low": 5, "lower": 2, "newest": 6, "widest": 3}, 4))

import tiktoken                      # pip install tiktoken
enc = tiktoken.get_encoding("cl100k_base")
ids = enc.encode("Tokenization is surprisingly subtle.")
print(ids, [enc.decode([i]) for i in ids])
COMMON MISCONCEPTIONS
  • “A token is a word.” Often a token is a word with its leading space, but many words are split into several tokens, and some tokens are fragments, punctuation, or partial UTF-8 bytes. “About 0.75 words per token” is an English average, not a rule.
  • “The model reads the letters and decides how to split them.” The tokenizer is a separate, fixed preprocessing step trained before the model. The network only ever receives the ids.
  • “A bigger vocabulary is always better.” Larger vocabularies shorten sequences, but each extra token needs its own embedding row and output score, and rare tokens get little training. Vocabulary size is a trade-off chosen by the model designers.
  • “Tokenization is language-neutral.” A tokenizer trained mostly on English allocates most merges to English. Other languages and scripts can need several times more tokens for the same meaning.

Check your understanding

0/5 answered
  1. Q1.Why do modern LLMs use subword tokens instead of whole words?

  2. Q2.In one step of BPE training, what gets merged?

  3. Q3.A byte-level BPE tokenizer meets a word in a script it never saw during training. What happens?

  4. Q4.Why do LLMs sometimes miscount the letters in a word like 'strawberry'?

  5. Q5.With the merges learned from {low ×5, lower ×2, newest ×6, widest ×3} (e+s, es+t, l+o, lo+w), how is 'lowest' tokenized?

Further reading

Progress is saved in this browser only.
Type to search across all lessons and glossary terms.