Skip to content

4.1 Tokenization

ready≈ 13 hoursNeeds: 3.8Unlocks: 4.2, 4.6, 5.5
  1. 1 Learn
  2. 2 Bridge & derive
  3. 3 Explore (Tokenizer playground, BPE merge stepper)
  4. 4 Do
  5. 5 Check

Why subwords. A language model reads a sequence of integers, so text has to be cut into pieces from a fixed vocabulary. Characters give short vocabularies but long sequences, and attention’s cost grows with length. Whole words give short sequences but an unbounded vocabulary that can never cover a new name or typo. Subword tokens sit in between: common words are one token, and rare ones fall apart into pieces (Karpathy, Let’s build the GPT Tokenizer).

Byte-pair encoding builds that vocabulary greedily. Encode the text as UTF-8 so that the base vocabulary is just the 256 byte values, which can represent any string in any script. Then count every adjacent pair of tokens, give the most frequent pair a new ID, replace it everywhere, and repeat until the vocabulary is the size you want. The list of merges, in order, is the tokenizer (Sennrich et al. 2016; Radford et al. 2019, §2.2).

Pre-tokenization. Run on raw text, BPE learns tokens like “dog.” and “dog!”, wasting vocabulary on combinations. GPT-2 first splits text with a regular expression into words (each keeping its leading space), numbers, punctuation and whitespace, and merges never cross those splits. GPT-4’s pattern also splits numbers into chunks of at most three digits, read from the left, so 1234 becomes 123|4. That caps how many number tokens the vocabulary needs, though the chunks don’t line up with place value (Karpathy, Let’s build the GPT Tokenizer, 01:11:38; GPT-2 §2.2).

Encoding and decoding. To encode new text, start from its bytes and apply the merges in the order they were learned: always the lowest-ranked merge available, not the most frequent pair in this text. Decoding looks up each token’s bytes, joins them, and decodes UTF-8 once at the end, since a single token can hold half of a multi-byte character (Karpathy, minbpe).

Consequences. Text that was rare in the tokenizer’s training data, such as other scripts, code or long numbers, costs more tokens per character. That means a shorter effective context and a higher price per word. Many odd model behaviours, such as miscounting letters in a word, come from the model never seeing the individual characters (Karpathy).

★ Tokenizer playground

Tokens, IDs, how words, numbers and other scripts split

Static view on small screens. Open this page on a laptop to interact.

The·tokenizer·splits·text·into·pieces·it·has·seen·often.·Unusual·words·break·into·smaller·pieces.
characters 97 UTF-8 bytes 97 tokens 52 bytes per token 1.87

A byte-level BPE trained in your browser on 50,000 characters of Shakespeare: a small cousin of GPT's tokenizer, which learned 50,000 merges from far more text. At 256 every byte is its own token. Each merge you add joins a frequent pair, so common English words become single tokens while numbers, code and other scripts, rare in the training text, stay split into many pieces; a ⟨hex⟩ token is part of a multi-byte character. Spaces show as ·, and a word's leading space belongs to the word.

A text box and preset texts (English, Shakespeare, numbers, code, other scripts, emoji). Below, the text is shown split into coloured tokens by a BPE tokenizer trained in the browser on Shakespeare, with optional token IDs and pre-token boundaries. A slider sets the vocabulary size from 256 to 1024; the readout gives characters, bytes, tokens and bytes per token. Keyboard: Tab to the buttons and the text box; arrow keys adjust the vocabulary slider.

BPE merge stepper

Merge rules and vocabulary growth

Static view on small screens. Open this page on a laptop to interact.

Most frequent adjacent pairs

e + s9
s + t9
w + e8
l + o7
o + w7
· + l6
· + n6
e + w6

Chunks as tokens (× how often each appears)

  • ·newest ×6
  • ·low ×4
  • ·widest ×3
  • ·lower ×2
  • low ×1
vocabulary 256 tokens in the text 94

Training counts every adjacent pair of tokens, weighted by how often each chunk occurs, and merges the most frequent one (ties go to the smaller pair of IDs) into a new token. The text is first split at spaces and punctuation, and merges never cross those splits. Encoding new text replays these rules in this order.

An editable toy corpus. Each press of “Merge the top pair” performs one BPE training step. A table shows the eight most frequent adjacent pairs with their counts, a list shows every distinct chunk split into its current tokens with its frequency, and the learned merge rules are listed in order. The readout gives the vocabulary size and the total number of tokens. Keyboard: Tab to the buttons and press Enter; the training text is editable.
BPE tokenizer stubs/m4_1_bpe.py

Loading starter file…

Prefer your own editor? Edit exercises/stubs/m4_1_bpe.py and run mlc check 4.1. The tests are identical; import the results on the progress page.

Hints · merge 0/3 revealed
Hints · train_bpe 0/3 revealed
Hints · encode 0/3 revealed

Then train on Tiny Shakespeare (locally; downloads about 1.1 MB once):

Terminal window
cd exercises && python projects/bpe_shakespeare.py 1024

The reference solution learns 768 merges in about 12 seconds and averages 2.3 bytes per token on held-out text. Look at how it splits a modern sentence, a number, code and non-Latin text.

1. Why start BPE from the 256 byte values rather than from characters?
2. What does pre-tokenization prevent?
3. When encoding new text, which merge is applied next?
4. A larger vocabulary…
  • not yet: All tests pass (0/?)
  • not yet: Checkpoint quiz ≥ 80%
Finish the items above first.
Learner log: time spent and points of confusion

Every confusion you note becomes a fix before the module is marked stable. Export it from the progress page and attach it to an issue.