Skip to content
Transformers and LLMs Foundation 24 min read

Tokenisation and BPE

A language model never sees text. It sees a sequence of integers chosen by a small, frozen compression algorithm that ran before training began. Learn that algorithm — byte-pair encoding — and a long list of strange model behaviours stops being strange.

10,000 ft

Every large language model is a function from a sequence of integers to a probability distribution over the next integer. Tokenisation is the contract that turns text into those integers and back. It is the only part of an LLM that is not learned by gradient descent, so its choices are baked into everything downstream: how much text fits in the context window, what a request costs, how well the model does arithmetic or spells, and how fairly it treats languages other than English. Almost every modern model uses a variant of byte-pair encoding (BPE), a 1994 data-compression trick. The token ids it produces are the rows the model looks up in its embedding table; the next-token distribution it predicts (see the language-modelling objective) is a distribution over the same vocabulary.

2,000 ft

A tokeniser has a training phase (done once, on a sample of the corpus) and an encode/decode phase (done on every request).

  1. Normalise the text (optional: Unicode normalisation, lower-casing — modern LLM tokenisers mostly do nothing here, to stay lossless).
  2. Pre-tokenise: split the text into chunks with a regular expression (words with their leading space, runs of digits, punctuation), so merges never cross chunk boundaries.
  3. Bytes: encode each chunk as UTF-8 bytes. The base vocabulary is the 256 possible byte values, so any string can be represented — there is no "unknown word".
  4. Merge: repeatedly replace the most frequent adjacent pair of symbols with a new symbol. Each merge adds one entry to the vocabulary; stop at the target size (50k–200k).
  5. Encode new text by replaying the learned merges in the order they were learned; decode by concatenating each token's bytes.

From text to token ids and back
From text to token ids and back. Text 'Hello world', Pre-tokenise regex chunks, UTF-8 bytes (256 base symbols), Apply merges in learned order, Token ids [15496, 995], Embedding lookup → transformer, decode: concatenate bytesFrom text to token ids and back. Text 'Hello world', Pre-tokenise regex chunks, UTF-8 bytes (256 base symbols), Apply merges in learned order, Token ids [15496, 995], Embedding lookup → transformer, decode: concatenate bytes

Ground level

Why not characters, why not words?

A model processes a sequence one position at a time, and its cost grows with the sequence length — linearly for the feed-forward layers and quadratically for attention. So the unit you choose sets a trade-off:

Unit Vocabulary Length of "unbelievably" Problem
Characters (or bytes) ~256 12 Sequences 4–5× longer than subwords; each position carries little meaning; compute wasted re-assembling words
Words 10⁵–10⁶+ 1 Any word not in the vocabulary is [UNK]; morphology ("believe", "unbelievable") shares nothing; huge embedding table
Subwords (BPE) 30k–200k 3–4 A learned compromise: frequent strings become one token, rare ones fall back to pieces

Subword tokenisation keeps the open vocabulary of characters (any string can be written down) while spending tokens only where the text is surprising. For English with a modern tokeniser that is roughly four characters per token: Meta reports that the Llama 3 tokeniser improved English compression from 3.17 to 3.94 characters per token over Llama 2's (Llama 3 paper, §3.2).

Bytes first: why the base vocabulary is 256

Text is Unicode, and Unicode has well over a hundred thousand code points. Starting BPE from code points would need a base vocabulary that large before a single merge — the GPT-2 paper notes it "would result in a base vocabulary of over 130,000" (Radford et al., 2019). Instead, byte-level BPE starts from the UTF-8 encoding. UTF-8 writes ASCII characters as one byte and everything else as two to four:

  • a → 61 (1 byte)
  • ₹ → E2 82 B9 (3 bytes)
  • न (Devanagari "na") → E0 A4 A8 (3 bytes)

Every string is a sequence over just 256 symbols, so nothing is ever out of vocabulary. The price: a script the tokeniser rarely saw during training is stuck near its byte representation, three tokens per character.

Training BPE, merge by merge

The algorithm is Philip Gage's compression scheme from 1994: "finding the most frequently occurring pairs of adjacent bytes in the data and replacing all instances of the pair with a byte that was not in the original data" (Gage, C Users Journal, 1994). Sennrich, Haddow and Birch repurposed it for neural machine translation in 2015 (arXiv:1508.07909). The only change for language models is that new symbols are not limited to unused byte values — each merge mints a fresh integer id (256, 257, …).

Take a 94-byte corpus: low ×5, lower ×2, newest ×6, widest ×3, separated by spaces. Running the trainer from Build it gives these first eight merges (real output):

Merge Pair New token Count Corpus length after
1 e + s es (256) 9 85
2 es + t est (257) 9 76
3 est + ␣ est␣ (258) 8 68
4 l + o lo (259) 7 61
5 lo + w low (260) 7 54
6 ␣ + low ␣low (261) 6 48
7 n + e ne (262) 6 42
8 ne + w new (263) 6 36

Three things to notice:

  1. Each merge shortens the corpus by exactly its count. Eight merges took 94 symbols to 36: a compression ratio of 2.6 with a vocabulary of 264.
  2. Merges build on merges. est is es + t; low is lo + w. The vocabulary is a forest of binary trees whose leaves are bytes.
  3. Merge 3 is a mistake. est␣ glues the suffix to the space that follows it, so newest. (with a full stop) can't use it. This is exactly the waste the GPT-2 authors saw at scale — "many versions of common words like dog since they occur in many variations such as dog. dog! dog?" — and why every serious tokeniser pre-tokenises first.
l o w e s t lo es low est merges 1, 4merges 2, 5bytes
Encoding the unseen word "lowest" with the eight merges above: six bytes become two tokens, low + est. Each token is a binary tree of earlier merges with bytes at the leaves.

Pre-tokenisation: the regex that shapes every token

GPT-2 splits text with this pattern before any merging (openai/gpt-2 encoder.py):

's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+

Read it alternative by alternative: common English contractions; an optional space followed by letters; an optional space followed by digits; an optional space followed by punctuation; whitespace. Two consequences show up in every GPT-family model:

  • The space belongs to the next word. " world" is one token and "world" is a different one. A model sees Hello world as ['Hello', ' world'], and a prompt that ends in a trailing space has split a token in an unusual place — a classic cause of worse completions.
  • Letters, digits and punctuation never merge with each other, so dog. is dog + ., and the vocabulary isn't wasted on punctuation variants.

Later tokenisers tweak the regex. OpenAI's cl100k_base splits digit runs into groups of at most three, which you can see below: " 12345678" becomes ' ', '123', '456', '78'.

Encoding new text

Training produces an ordered list of merges. To encode a string, start from its bytes and repeatedly apply the earliest-learned merge that is present anywhere in the sequence, until no learned pair remains. Order matters: replaying merges in a different order can give a different, longer segmentation. Decoding is trivial — look up each id's bytes and concatenate — and lossless, which is why byte-level BPE can round-trip any input exactly.

One subtlety: a single token can hold part of a UTF-8 character. Decoding token by token during streaming can therefore produce half a character (the � marks in the table below); real tokenisers buffer bytes until they form valid UTF-8.

Real tokenisers, real artefacts

Here are three OpenAI vocabularies on the same inputs (output of the second snippet in Build it, run with tiktoken 0.14):

Input (UTF-8 bytes) GPT-2 gpt2 (50,257) GPT-4 cl100k_base (100,277) GPT-4o o200k_base (200,019)
Hello world (11) 2: Hello·world 2 2
SolidGoldMagikarp (18) 1 token 5: Solid·Gold·Mag·ik·arp 5
strawberry (10) 3: st·raw·berry 3: str·aw·berry 3: st·raw·berry
12345678 (9) 3: 123·45·678 4: ·123·456·78 4
₹1,23,456.78 (14) 10 (₹ as 3 byte tokens) 9 8 (₹ is one token)
नमस्ते दुनिया (37) 23 13 5

(Vocabulary sizes are n_vocab as reported by tiktoken, which includes special tokens.)

Each row explains a well-known model quirk:

  • Glitch tokens. SolidGoldMagikarp is a single GPT-2 token (id 43453). The tokeniser was trained on data where this Reddit username was frequent — Jessica Rumbelow and Matthew Watkins traced such tokens to users of the r/counting subreddit — but the model's training data barely contained it, so its embedding was almost untrained. Asked to repeat it, GPT-3-family models produced bizarre completions (SolidGoldMagikarp, LessWrong, Feb 2023). Lesson: train the tokeniser on data distributed like the model's training data.
  • Spelling and counting letters. "How many r's in strawberry?" asks about characters the model never sees; it sees three opaque ids. It must have memorised the spelling of each token to answer.
  • Arithmetic. GPT-2 splits 12345678 into 123, 45, 678 — chunk boundaries that have nothing to do with place value, and that change when the number changes. Splitting digits uniformly makes place value visible to the model: the original LLaMA tokeniser splits every number into individual digits (arXiv:2302.13971), and cl100k_base uses fixed groups of up to three.
  • Language fairness. The same Hindi greeting costs 23 GPT-2 tokens and 5 o200k_base tokens. Fewer tokens means cheaper API calls, more text per context window and more training signal per byte. Petrov et al. found that the same content translated into different languages can differ in tokenised length by up to 15× (arXiv:2305.15425). Larger, multilingual vocabularies (Llama 3 added 28K non-English tokens to 100K from tiktoken) are a direct response.

Special tokens and chat templates

A vocabulary also reserves special tokens that never come from text: GPT-2 has one, <|endoftext|> (id 50256), placed between documents during training so the model learns where one ends. Chat models add role markers (start of a system, user or assistant turn), tool-call delimiters and padding. A chat template is the exact string format — special tokens included — that the model was post-trained on. Feeding a model a different template than it was trained with is one of the most common silent bugs in open-weight deployments, and refusing to let user text produce special tokens is a basic prompt-injection defence.

The other two algorithms: WordPiece and Unigram

WordPiece (BERT) trains like BPE but chooses the pair with the highest \(\frac{c(ab)}{c(a)\,c(b)}\) instead of the highest \(c(ab)\) — it prefers pairs whose parts are rarely seen apart, a pointwise-mutual-information criterion. At encode time it takes the longest vocabulary match from the left, and marks word-internal pieces with ## (Hugging Face course, ch. 6).

Unigram language model tokenisation (Kudo, 2018, arXiv:1804.10959) runs the other way: start from a large candidate vocabulary, model a string as a product of independent token probabilities, fit those probabilities with EM, and repeatedly delete the tokens whose removal hurts corpus likelihood least. Encoding picks the most probable segmentation with the Viterbi algorithm, and — the original selling point — training can sample alternative segmentations as a regulariser.

SentencePiece (arXiv:1808.06226) is a library, not an algorithm: it implements BPE and Unigram directly on raw text, treating the space as an ordinary symbol ▁, with optional byte fallback for characters outside the vocabulary. Llama 1 and 2 used SentencePiece BPE with a 32K vocabulary, digits split individually and byte fallback (Llama 2 paper); Llama 3 moved to a tiktoken-style byte-level BPE with 128K (Llama 3 paper).

BPE (byte-level) WordPiece Unigram LM
Builds vocabulary by merging up from bytes merging up, PMI-style score pruning down from a big set
Encodes by replaying merges in order longest match first Viterbi max-probability path
Out-of-vocabulary text impossible [UNK] byte fallback (if enabled)
Used in GPT-2 → GPT-4o, Llama 3 BERT family T5, many SentencePiece models

Choosing the vocabulary size

A bigger vocabulary compresses text into fewer tokens (cheaper per word, more text per context) but costs parameters and makes each token rarer during training. Every token owns a row in the input embedding and the output projection, so with model width \(d\) the vocabulary costs \(V \cdot d\) parameters for each:

  • GPT-2 small: \(50{,}257 \times 768 = 38.6\text{M}\) — almost a third of its 124M parameters.
  • Llama 3 8B: \(128{,}000 \times 4{,}096 \approx 524\text{M}\) for each of the two matrices — about 13% of the model between them (dimensions from the Llama 3 paper, Table 3).

At small scales the embedding table dominates and a smaller vocabulary wins; at large scales it is a rounding error and compression wins. That is why vocabularies grew from 32K (Llama 2) and 50K (GPT-2) to 100K–200K as models grew.

History

From file compression to every LLM

1994 — Philip Gage publishes BPE as a compression algorithm in the C Users Journal. 2012 — Schuster and Nakajima introduce WordPiece for Japanese and Korean voice search at Google; it later tokenises Google's neural MT system (arXiv:1609.08144) and BERT. 2015 — Sennrich, Haddow and Birch apply BPE to rare words in translation (arXiv:1508.07909). 2018 — Kudo's unigram LM and the SentencePiece library. 2019 — GPT-2 introduces byte-level BPE with regex pre-tokenisation, the template for most LLM tokenisers since. 2021–2024 — byte-level models without a learned vocabulary, such as ByT5 (arXiv:2105.13626) and the Byte Latent Transformer, which groups bytes into dynamically sized patches (arXiv:2412.09871), test whether the tokeniser can be removed altogether.

First principles

Why compress at all? A transformer spends roughly the same compute on every position, regardless of how much information that position carries. A token is therefore a unit of compute. If most of what you feed the model is predictable (the ing after runn), you waste forward passes on it. Compression moves predictable structure out of the model's sequence and into the vocabulary, so each forward pass handles a more information-dense symbol. Information theory (see entropy and cross-entropy) says the best you can do is spend tokens in proportion to surprise, which is what a frequency-driven merge rule approximates.

Why greedy? Choosing the vocabulary that minimises the encoded length of a corpus is a hard combinatorial problem — Whittington et al. prove natural formulations of it NP-complete (arXiv:2412.15210). BPE is the greedy answer: at each step take the single merge that shortens the corpus most. It is fast, deterministic and good enough; Bostrom and Durrett argued Unigram segmentations align better with morphology and fine-tune slightly better (arXiv:2004.03720), but the industry stayed with BPE for its simplicity and exact round-tripping.

What breaks if you change it? The tokeniser is frozen at the start of pre-training; the embedding matrix is indexed by its ids. Changing it means re-learning embeddings — possible (people extend vocabularies for new languages and initialise new rows as averages of their pieces), but never free. It also changes what the loss means, which is the next point.

Loss per token is not comparable across tokenisers. If tokeniser A packs 4 bytes per token and B packs 3, A's model must predict more information per step, so its per-token loss is higher even if it models the text equally well. Compare models with bits per byte instead (derived below).

The maths

Let the training text be a sequence \(x = (x_1, \dots, x_N)\) over the current alphabet \(\Sigma\) (initially the 256 bytes). Let \(c(a, b)\) count the non-overlapping occurrences of the adjacent pair \((a,b)\) when scanning left to right.

BPE training step. Choose

\[ (a^\star, b^\star) = \arg\max_{(a,b) \in \Sigma \times \Sigma} c(a, b), \]

add a new symbol \(z = a^\star b^\star\) to \(\Sigma\), and rewrite \(x\) replacing each counted occurrence of \((a^\star, b^\star)\) by \(z\). The length drops from \(N\) to \(N - c(a^\star, b^\star)\): each replacement turns two symbols into one. After \(M\) merges the vocabulary is \(|V| = 256 + M\) (+ special tokens). "Non-overlapping" matters for runs like aaa, where the pair aa occurs twice overlapping but can only be replaced once.

Encoding. Give each merge a rank \(r(a,b)\) equal to the step at which it was learned. Given bytes \(y\), repeat: among adjacent pairs in \(y\) that have a rank, merge the one with the lowest rank (all its occurrences); stop when none has a rank.

Unigram LM. With vocabulary \(V\) and token probabilities \(p(t)\), \(\sum_{t \in V} p(t) = 1\), a segmentation \(\mathbf{s} = (t_1,\dots,t_k)\) of string \(x\) has probability \(P(\mathbf{s}) = \prod_{i=1}^{k} p(t_i)\). Encoding picks

\[ \mathbf{s}^\star(x) = \arg\max_{\mathbf{s} \in S(x)} \sum_{i=1}^{k} \log p(t_i), \]

computed by dynamic programming over prefix positions: \(\text{best}[i] = \max_{j < i,\; x_{j+1:i} \in V} \big(\text{best}[j] + \log p(x_{j+1:i})\big)\). Training maximises the marginal likelihood \(\sum_{x \in \mathcal{D}} \log \sum_{\mathbf{s} \in S(x)} P(\mathbf{s})\) with EM, then prunes.

Bits per byte. Let a model's average cross-entropy be \(L_\text{tok}\) nats per token, on text that tokenises to \(T\) tokens from \(B\) bytes. The total code length is \(T \cdot L_\text{tok}\) nats, so

\[ \text{BPB} = \frac{T \cdot L_\text{tok}}{B \,\ln 2}. \]

Worked example: a loss of 2.0 nats/token at 4 bytes per token is \(2.0 / (4 \ln 2) = 0.72\) bits per byte. A rival with a loss of 1.7 nats/token but only 3 bytes per token scores \(1.7 / (3 \ln 2) = 0.82\) bits per byte — worse, despite the lower token loss. For scale, Shannon's 1951 human-prediction experiments put English at roughly one bit per letter once long-range context is used (Shannon, 1951).

Parameter cost. Input embedding \(E \in \mathbb{R}^{|V| \times d}\), output projection \(W_U \in \mathbb{R}^{d \times |V|}\); each costs \(|V|\,d\) parameters, and the output layer costs \(2|V|\,d\) FLOPs per token in the forward pass. GPT-2 ties them (\(W_U = E^\top\)), paying once.

Build it

A byte-level BPE trainer and encoder in plain Python (no NumPy needed — tokenisation is integer bookkeeping). This is the algorithm inside tiktoken, minus its speed.

from collections import Counter

def get_pair_counts(ids):
    """Count adjacent pairs in a list of token ids."""
    return Counter(zip(ids, ids[1:]))

def merge(ids, pair, new_id):
    """Replace every non-overlapping occurrence of `pair` (left to right) with new_id."""
    out, i = [], 0
    while i < len(ids):
        if i < len(ids) - 1 and (ids[i], ids[i + 1]) == pair:
            out.append(new_id); i += 2
        else:
            out.append(ids[i]); i += 1
    return out

def train_bpe(text, n_merges):
    ids = list(text.encode("utf-8"))             # start from raw bytes: 0..255
    merges, vocab = {}, {i: bytes([i]) for i in range(256)}
    for k in range(n_merges):
        counts = get_pair_counts(ids)
        pair, n = max(counts.items(), key=lambda kv: kv[1])
        new_id = 256 + k
        ids = merge(ids, pair, new_id)
        merges[pair] = new_id
        vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
        print(f"merge {k+1}: {vocab[pair[0]]!r:>10} + {vocab[pair[1]]!r:<10} -> {new_id} "
              f"{vocab[new_id]!r:<12} seen {n}x, length now {len(ids)}")
    return merges, vocab

def encode(text, merges):
    ids = list(text.encode("utf-8"))
    while len(ids) >= 2:
        counts = get_pair_counts(ids)
        # apply the merge that was learned EARLIEST (lowest new id) among pairs present
        pair = min(counts, key=lambda p: merges.get(p, float("inf")))
        if pair not in merges:
            break
        ids = merge(ids, pair, merges[pair])
    return ids

def decode(ids, vocab):
    return b"".join(vocab[i] for i in ids).decode("utf-8", errors="replace")

corpus = "low low low low low lower lower newest newest newest newest newest newest widest widest widest"
merges, vocab = train_bpe(corpus, 8)
print("bytes:", len(corpus.encode()))
for w in ["lowest", "newer", "slow"]:
    ids = encode(w, merges)
    print(w, "->", ids, [vocab[i] for i in ids], "| round trip:", decode(ids, vocab) == w)

Output:

merge 1:       b'e' + b's'       -> 256 b'es'        seen 9x, length now 85
merge 2:      b'es' + b't'       -> 257 b'est'       seen 9x, length now 76
merge 3:     b'est' + b' '       -> 258 b'est '      seen 8x, length now 68
merge 4:       b'l' + b'o'       -> 259 b'lo'        seen 7x, length now 61
merge 5:      b'lo' + b'w'       -> 260 b'low'       seen 7x, length now 54
merge 6:       b' ' + b'low'     -> 261 b' low'      seen 6x, length now 48
merge 7:       b'n' + b'e'       -> 262 b'ne'        seen 6x, length now 42
merge 8:      b'ne' + b'w'       -> 263 b'new'       seen 6x, length now 36
bytes: 94
lowest -> [260, 257] [b'low', b'est'] | round trip: True
newer -> [263, 101, 114] [b'new', b'e', b'r'] | round trip: True
slow -> [115, 260] [b's', b'low'] | round trip: True

Now add GPT-2-style pre-tokenisation so no merge can straddle a chunk boundary (append to the same file):

import re

def train_bpe_chunked(text, n_merges):
    chunks = re.findall(r" ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+", text)   # GPT-2-style split
    seqs = [list(c.encode("utf-8")) for c in chunks]
    merges, vocab = {}, {i: bytes([i]) for i in range(256)}
    for k in range(n_merges):
        counts = Counter()
        for s in seqs:
            counts.update(get_pair_counts(s))     # pairs never straddle two chunks
        pair, n = max(counts.items(), key=lambda kv: kv[1])
        new_id = 256 + k
        seqs = [merge(s, pair, new_id) for s in seqs]
        merges[pair] = new_id
        vocab[new_id] = vocab[pair[0]] + vocab[pair[1]]
        print(f"merge {k+1}: {vocab[new_id]!r} ({n}x)")
    return merges, vocab

train_bpe_chunked(corpus, 8)
merge 1: b'es' (9x)
merge 2: b'est' (9x)
merge 3: b'lo' (7x)
merge 4: b'low' (7x)
merge 5: b' low' (6x)
merge 6: b' n' (6x)
merge 7: b' ne' (6x)
merge 8: b' new' (6x)

The wasteful est␣ merge is gone, and the leading space now attaches to the word (' low', ' new') exactly as in GPT-2's vocabulary.

Finally, compare production tokenisers (pip install tiktoken):

import tiktoken

samples = ["Hello world", " SolidGoldMagikarp", "strawberry", " 12345678",
           "₹1,23,456.78", "नमस्ते दुनिया"]
for name in ("gpt2", "cl100k_base", "o200k_base"):
    enc = tiktoken.get_encoding(name)
    print(f"{name}  (vocabulary {enc.n_vocab:,})")
    for s in samples:
        ids = enc.encode(s)
        pieces = [enc.decode_single_token_bytes(i).decode("utf-8", "replace") for i in ids]
        print(f"  {len(s.encode()):2d} bytes -> {len(ids):2d} tokens  {pieces}")
gpt2  (vocabulary 50,257)
  11 bytes ->  2 tokens  ['Hello', ' world']
  18 bytes ->  1 tokens  [' SolidGoldMagikarp']
  10 bytes ->  3 tokens  ['st', 'raw', 'berry']
   9 bytes ->  3 tokens  [' 123', '45', '678']
  14 bytes -> 10 tokens  ['�', '�', '�', '1', ',', '23', ',', '456', '.', '78']
  37 bytes -> 23 tokens  ['�', '�', '�', '�', '�', '�', '�', '�', '�', '�', '�', '�', ' �', '�', '�', '�', '�', '�', '�', '�', '�', '�', 'ा']
cl100k_base  (vocabulary 100,277)
  11 bytes ->  2 tokens  ['Hello', ' world']
  18 bytes ->  5 tokens  [' Solid', 'Gold', 'Mag', 'ik', 'arp']
  10 bytes ->  3 tokens  ['str', 'aw', 'berry']
   9 bytes ->  4 tokens  [' ', '123', '456', '78']
  14 bytes ->  9 tokens  ['�', '�', '1', ',', '23', ',', '456', '.', '78']
  37 bytes -> 13 tokens  ['न', 'म', 'स', '्�', '�', 'े', ' �', '�', 'ु', 'न', 'ि�', '�', 'ा']
o200k_base  (vocabulary 200,019)
  11 bytes ->  2 tokens  ['Hello', ' world']
  18 bytes ->  5 tokens  [' Solid', 'Gold', 'Mag', 'ik', 'arp']
  10 bytes ->  3 tokens  ['st', 'raw', 'berry']
   9 bytes ->  4 tokens  [' ', '123', '456', '78']
  14 bytes ->  8 tokens  ['₹', '1', ',', '23', ',', '456', '.', '78']
  37 bytes ->  5 tokens  ['न', 'म', 'स्त', 'े', ' दुनिया']

Things to try

  • Train train_bpe_chunked on a few megabytes of text (a public-domain book) for 1,000 merges. Print the 50 longest tokens: you will see whole common words and frequent multi-word fragments.
  • Measure compression (bytes ÷ tokens) of your tokeniser on English vs. on another language it never saw. Then add 20% text in that language to the training corpus and measure again.
  • Make encode faster: instead of recounting all pairs every iteration, keep a priority queue of ranked pairs. (This is what production implementations do.)
  • Change the digit pattern to [0-9] (one digit per chunk) and check that 12345678 now always tokenises as eight digits.
  • Paste the same paragraph into Tiktokenizer under several model tokenisers and compare counts.

In practice

  • Count tokens with the model's own tokeniser, never with a characters ÷ 4 rule, when you are budgeting context or cost. Code, numbers, JSON and non-English text compress very differently from English prose.
  • Never assume a word maps to one token, or that "word" and " word" are the same token. When you need a model to output a fixed label, prefer labels that are single tokens or constrain decoding (see structured outputs).
  • Use the official chat template for an open-weight model; most "the fine-tune got worse" bugs start with a template or special-token mismatch.
  • Byte-level tokenisers make invalid UTF-8 mid-stream. When streaming, decode the accumulated byte buffer, not each token separately.
  • Data and tokeniser should match. The glitch-token story is what happens when they don't.

Check yourself

Why does byte-level BPE never produce an unknown token?

The base vocabulary contains all 256 byte values and every string has a UTF-8 byte encoding, so the worst case is one token per byte. Merges only ever combine existing symbols, so they can never remove the ability to represent a byte.

Each BPE merge shortens the training corpus by how much, exactly?

By the number of non-overlapping occurrences of the merged pair counted left to right: each occurrence turns two symbols into one. In the worked example merge 1 (e+s, 9 occurrences) took the corpus from 94 to 85 symbols.

A model scores 1.9 nats/token with a tokeniser averaging 3.8 bytes per token. Another scores 2.3 nats/token at 4.6 bytes per token. Which models the text better?

Convert to bits per byte. Model 1: \(1.9 / (3.8 \ln 2) = 0.721\). Model 2: \(2.3 / (4.6 \ln 2) = 0.721\). They are essentially tied — the difference in per-token loss is entirely explained by the tokeniser.

Why does a GPT-style model often perform worse if your prompt ends with a space?

Pre-tokenisation attaches a space to the following word, so in training data a space is almost always the start of a token like ' the'. A prompt ending in a bare ' ' token is an unusual position: the model must now predict a word without its leading space, a token sequence it has rarely seen.

Why did vocabularies grow from ~32–50K to 100–200K as models grew?

The vocabulary's parameter cost is \(2|V|d\) (or \(|V|d\) tied), which is a large fraction of a small model but a small fraction of a large one, while the benefit — fewer tokens per text, so less compute per document and more text per context window, especially for non-English text — grows with how much compute you spend per token. At large scale compression wins.

WordPiece would not merge un + ##able early even if the pair is very frequent. Why?

Its score is \(c(ab)/(c(a)c(b))\). Both un and ##able are individually very frequent, so the denominator is large and the score low. WordPiece prefers pairs that are much more frequent together than their parts' frequencies would predict.

Hard: why can't you fix the 'strawberry' problem just by adding more training data?

The information about which characters make up a token is not in the input at all — the model receives an id. It can only learn the spelling of a token indirectly, from contexts where that token's spelling is discussed or where the same word appears split differently. More data helps a little; changing the representation (character-aware inputs, byte-level models, or tool use that spells the word out) fixes the cause.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Code

Where this leads