1. Tokenization & BPE

How text becomes numbers

Neural networks are fundamentally number crunchers. Feed them pixels — those are already numbers. Feed them audio — sampled amplitudes, also numbers. But feed them text and you immediately hit a wall: how do you turn the word "hello" into something a matrix can multiply?

This is the job of a tokenizer. Before a single transformer layer runs, before any attention is computed, text has to pass through a tokenizer that chops it into pieces and maps each piece to an integer. Get this step wrong and no amount of clever architecture will save you. Get it right and you have a foundation that generalises remarkably well across languages, code, and domain-specific jargon.

Three Ways to Slice Text

The obvious approaches at the extremes both have fatal flaws.

Character-level tokenization treats every individual character as a token. "hello" becomes [h, e, l, l, o] — five tokens. The vocabulary is tiny (maybe 100–200 symbols for Unicode basics), which sounds appealing, but sequences get very long very fast. A 1,000-word document becomes ~5,000 tokens. More importantly, the model has to learn that c, a, t together mean something — that meaning is spread across many steps, which makes learning hard.

Word-level tokenization goes to the other extreme: every word is a token. "Hello, world!" becomes [Hello, ,, world, !]. This is intuitive, but the vocabulary explodes. English alone has hundreds of thousands of words, and once you add plurals, conjugations, hyphenated terms, and typos, you easily pass a million distinct tokens. Rare words and unknown words ("unseen" at training time) become a serious problem — what does the model do with a medical term it has never encountered?

Subword tokenization lives in the middle ground, and it is where all modern large language models operate. The idea: common words get their own token, rare words get split into meaningful fragments.

Why Subword Tokenization Works

"unbelievable" might be split into un + believ + able. Each piece is reusable. The model sees un in "unlikely", "unfair", and "unbelievable" and gradually learns it signals negation. You get generalisation for free — even for words the model has never seen whole.

The dominant algorithm for learning subword splits is called Byte Pair Encoding, or BPE. It was originally a data compression technique from 1994, repurposed for NLP in a 2016 paper by Sennrich et al., and is now the backbone of GPT-2, GPT-3, GPT-4, and many other models.

Byte Pair Encoding: The Algorithm

BPE starts from the most granular possible representation — individual characters — and iteratively merges the most frequent adjacent pair. Each merge adds one new symbol to the vocabulary. You run this until the vocabulary reaches the target size (often 50,000 or 100,000 tokens for large models).

Think of it like discovering the natural "words" in a language purely from statistics, without any linguistic knowledge upfront.

A Worked Example

Let's tokenize a tiny corpus: the four words low, lower, newest, widest, each occurring with some frequency. We start by splitting every word into characters and appending a special end-of-word marker </w> so the model can tell where words end:

Initial character sequences (with frequencies)

SequenceFrequency
l o w </w>5
l o w e r </w>2
n e w e s t </w>6
w i d e s t </w>3

Now we count every adjacent pair across the whole corpus and find the most frequent one:

  1. Count all adjacent pairs

    The pair e s appears in "newest" (×6) and "widest" (×3) — total 9. That's the most frequent pair. Merge it.

    Vocabulary now includes the new symbol es.

    l o w </w>           (×5)
    l o w e r </w>       (×2)
    n e w es t </w>      (×6)
    w i d es t </w>      (×3)
  2. Next merge: es t

    The pair es t now appears 9 times. Merge into est.

    l o w </w>           (×5)
    l o w e r </w>       (×2)
    n e w est </w>       (×6)
    w i d est </w>       (×3)
  3. Next merge: l o

    The pair l o appears 7 times (5 + 2). Merge into lo.

    lo w </w>            (×5)
    lo w e r </w>        (×2)
    n e w est </w>       (×6)
    w i d est </w>       (×3)
  4. Next merge: lo w

    The pair lo w appears 7 times. Merge into low.

    low </w>             (×5)
    low e r </w>         (×2)
    n e w est </w>       (×6)
    w i d est </w>       (×3)

Each merge round produces one new vocabulary entry. After enough rounds, common words like low and est become single tokens, while rare sequences remain as multi-character fragments.

Visualising the Merge Tree

Here is a small merge tree showing how the characters in "low" get fused through successive BPE rounds:

Diagram

BPE merge tree

BPE merge tree for "low" l o w lo merge 1 low merge 2 e s es merge 1

The tree makes the intuition concrete: leaves are individual characters, and each internal node is a merge operation. The root of each sub-tree is the resulting token.

Building the Vocabulary: Token IDs

After all the merges are done, you have a vocabulary — an ordered list of tokens. Each token gets an integer ID. This lookup table is saved alongside the model and shipped with it; both the encoder and decoder need the exact same vocabulary to communicate.

A fragment of a real vocabulary (GPT-2 style)

IDTokenNotes
0!Single punctuation
262theVery common word
1643ingCommon suffix
8690neuralDomain-specific
47544walFragment of rarer words

To encode "the neural network", the tokenizer looks up each token and outputs the integer sequence [262, 8690, 2010] (roughly). Those integers are what the model actually sees.

The vocabulary size is a hyperparameter. GPT-2 uses 50,257 tokens. GPT-4 and similar models use roughly 100,000. Bigger vocabulary means fewer tokens per sentence (faster inference), but a larger embedding table to store.

BPE in Practice

A few details that matter in real deployments:

  • "Byte-level" BPE (used by GPT-2 and descendants) operates on raw UTF-8 bytes rather than Unicode characters. This means the vocabulary can cover any text in any language without ever producing an "unknown" token — there are only 256 possible bytes, so every possible document is expressible.

  • SentencePiece is a popular alternative library from Google. It implements both BPE and a related algorithm called Unigram, and it handles the pre-tokenization (whitespace, punctuation splitting) in a language-agnostic way. LLaMA, Gemma, and T5 all use SentencePiece.

  • The same tokenizer must be used at inference time as at training time. If you train on one vocabulary and decode with another, the IDs mean different things and the model outputs garbage. The tokenizer is part of the model.

Token Counting and Costs

API pricing for LLMs is measured in tokens, not characters or words. A rough rule of thumb: 1 token ≈ 4 characters of English text, so 1,000 tokens ≈ 750 words. Code, numbers, and non-English text often tokenize less efficiently — a single Chinese character may be one token, but individual digits are usually separate tokens, making long numbers expensive.

Common Surprises

BPE can produce splits that look bizarre to humans. The string "1234567890" might tokenize as [12, 345, 678, 90] or even ten separate single-digit tokens depending on what the model was trained on. The word "token" itself might be a single token, but "tokens" could be [token, s] or even [tok, ens].

This matters for tasks involving counting, arithmetic, or precise string manipulation. When a language model struggles to count the letters in a word, it is often because the word was never presented as individual characters — the tokenizer handed it over as an opaque blob.

Key Takeaways

  • Text must be converted to integers before a neural network can process it — this is tokenization
  • Character-level tokens are too granular (long sequences, hard to learn); word-level tokens have an unbounded vocabulary
  • Subword tokenization (BPE) balances sequence length against vocabulary size
  • BPE learns vocabulary by iteratively merging the most frequent adjacent pair in a training corpus
  • Each merge adds one entry to the vocabulary; you stop when you reach the target vocabulary size
  • The final token IDs are integers in a lookup table — what the model actually receives as input
  • GPT-style models use byte-level BPE (50k–100k tokens); Google models often use SentencePiece
  • Tokenization artefacts explain some surprising model failures around counting, arithmetic, and rare words

Try It — Interactive BPE Tokenizer

Type any text below and watch BPE run from scratch: first the corpus is split into characters, then the most-frequent adjacent pair is merged at each round, until no pair appears more than once. Each step shows which pair was merged, its frequency, and the resulting token sequence.

Merge Steps

Final Tokens

Token IDs

Statistics


Turning text into a sequence of integer IDs is only the first step. Those integers are just indices — they carry no information about meaning or relationship. To give the model a richer sense of what each token means, and how tokens relate to each other geometrically, we need embeddings: the topic of the next article.