Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

LABS · 02  /  TOKENIZATION

The Tokenizer.

A language model can't read letters or words — it reads tokens. Before a single neuron fires, your text is shattered into sub-word chunks and turned into numbers. You'll watch it happen, race three ways to do it, then build the real algorithm by hand.

THE GIST · 20 SECONDS

An LLM only understands token IDs — integers. A tokenizer maps text to those IDs and back. Modern tokenizers use sub-word units: common words become a single token, rare words split into reusable pieces, so nothing is ever truly unknown. The algorithm that finds those pieces is Byte-Pair Encoding — merge the most frequent pair, over and over.

  • Tokena sub-word chunk — the unit a model reads
  • Vocabularythe fixed set of tokens the model knows
  • BPEmerge the most common pair, repeatedly
  • Token IDthe integer each token maps to

① Watch text become tokens  →  ② Char vs word vs sub-word  →  ③ Build BPE by merging pairs  →  ④ Tune the vocabulary size  →  ⑤ Cost, context & the 'strawberry' bug

one token just merged word boundary ·

Each colored chip is one token — the unit the model reads. The number under it is its token ID. Notice tokens don't line up with words.

UNDER THE HOOD

What you just played, written down

You shattered text, raced three tokenizers, grew a vocabulary by merging pairs, and felt the cost. Here's the same thing as the algorithm inside every LLM tokenizer.

Byte-Pair Encoding — four steps

  1. Start from characters. Split every word into single characters plus an end-of-word marker. The vocabulary is just the alphabet.
  2. Count pairs. Across the whole corpus, count every adjacent pair of symbols. Find the most frequent one.
  3. Merge it. Replace that pair everywhere with a new single token, and add the merge to the vocabulary. Every sequence gets a little shorter.
  4. Repeat for a fixed number of merges (e.g. ~50,000). Common words collapse to one token; rare words stay split into reusable pieces.
WHY SUB-WORDS WIN

Characters make sequences too long; whole words make the vocabulary huge and choke on anything new. BPE lands in between — frequent = one token, rare = a few pieces — so it's compact and never hits a word it can't represent.

Encoding a word, once trained

text  → "lowest"
chars → l o w e s t </w>      # start split

apply learned merges, in order:
  (l,o)   → lo w e s t         # merge #1
  (lo,w)  → low e s t          # merge #2
  (e,s)   → low es t           # ...
  (es,t)  → low est
tokens → [ low ][ est ]        # 2 tokens, not 6
TINY VOCABlong seqschar-level · model relearns spelling
HUGE VOCABrare tokensword-level · unknowns & sparsity

Solved by hand — BPE on a tiny corpus

Corpus: low ×5 · lower ×2 · newest ×6 · widest ×3 · wider ×2. Each row is one merge: the most frequent pair, and the new token it becomes. Watch the vocabulary grow and the token count fall.

⚠ Where it bites

Models miscount letters (the r's in strawberry) because they see tokens, not characters. Numbers, code, and rare names split into many tokens — more cost, less context.

↔ Its cousins

WordPiece (BERT) and Unigram (SentencePiece) are alternative sub-word schemes. Modern GPT-style models use byte-level BPE, which never hits an unknown byte.

★ Where you've met it

Every prompt you've ever sent. Token counts drive your bill, your context limit, and even multilingual fairness — some languages cost 2–3× the tokens for the same sentence.

STEP BY STEP

Tokenization, step by step

Byte-pair encoding trained by hand on the corpus from Act 3 (low, lower, newest, widest, wider), how a trained tokenizer encodes new text, and what the vocabulary size costs.

Training and encoding

  1. Count words. Tally each word's frequency, split into characters plus an end marker, and start the vocabulary at those symbols.
  2. Merge the top pair. Count adjacent pairs weighted by word frequency, merge the most common everywhere, and record the merge. Ties go to whichever pair was seen first, which is how this page breaks them.
  3. Stop at a target size. Vocabulary size is the base symbols plus the number of merges. Production tokenizers run tens of thousands of merges.
  4. Encode new text. Split into characters, then replay the merges in the order they were learned. An unseen word falls back to smaller pieces, never to an unknown token.
# one training step
pair = most_frequent_pair(words)
words = merge(words, pair)
vocab.add(pair[0] + pair[1])

Worked example: five merges

  1. Start. Frequencies low 5, lower 2, newest 6, widest 3, wider 2. With end markers that is 107 tokens and 11 symbols.
  2. Merge 1. e+s occurs 9 times (6 in newest, 3 in widest), tied with s+t and t+end; the first seen wins. 98 tokens, vocabulary 12.
  3. Merges 2 and 3. es+t, then est+end, each 9 times. Now 80 tokens, vocabulary 14, and "est" is one token.
  4. Merges 4 and 5. l+o, then lo+w, 7 times each (low 5 plus lower 2). 66 tokens, vocabulary 16, and "low" is one token.
  5. Next. n+e, ne+w and new+est</w> follow at 6 each, reaching 48 tokens at vocabulary 19. "newest" becomes a single token and "widest" splits as w, i, d, est.
  6. Encode "lowest". Its characters merge to low and est, so two tokens plus the end marker, though "lowest" was never in the corpus.

⚠ Vocabulary size is a trade

The embedding table has vocab × d_model entries: 100,000 × 4,096 is 409.6 million parameters, while GPT-2's 50,257 × 768 is 38.6 million. A larger vocabulary shortens sequences, which saves compute and context, but rare tokens get little training.

↔ Bytes and whitespace

Byte-level BPE starts from the 256 byte values, so any string encodes. Most tokenizers fold the leading space into the token, so "the" and " the" are different tokens, and long digit strings are often split into short groups.

★ In production

Count tokens with the exact tokenizer your model uses, since the same text can produce noticeably different counts between families, and non-English text usually costs more. Keep special tokens out of user text, and never mix tokenizers between training and serving.

RUN IT YOURSELF

Train BPE yourself

The lab above, in code: real Byte-Pair Encoding training on a small corpus — CPython in your browser. It repeatedly merges the most frequent pair. Change the number of merges and watch the vocabulary grow. Hit Run (or ⌘/Ctrl + Enter).

HOW TO READ THE CODE — 4 IDEAS
  1. Each word starts as a tuple of characters ending in </w>.
  2. Count every adjacent pair across the corpus, weighted by word frequency.
  3. Merge the most frequent pair into one symbol — that's one new vocab token.
  4. Repeat num_merges times: common sequences collapse into single tokens.
CPython · WebAssembly
THE PICTURE

The picture: eight merges on the Act 3 corpus

wordstart: charactersafter 8 mergestokens low ×5l o w </w> low </w>4→2 lower ×2l o w e r </w> low e r </w>6→4 newest ×6n e w e s t </w> newest</w>7→1 widest ×3w i d e s t </w> w i d est</w>7→4 wider ×2w i d e r </w> w i d e r </w>6→6 107 tokens, 11 symbols → 48 tokens, 19 symbols merges: e+s, es+t, est+</w>, l+o, lo+w, n+e, ne+w, new+est</w>
Each word is weighted by how often it appears, so a merge is worth its pair count times the word frequencies. newest (6 copies) collapses to one token because every one of its pairs was among the most frequent. wider (2 copies) has not been touched: none of its pairs has won yet. Run the 16 merges this corpus allows and the total falls to 18.
TRADE-OFFS

Cost and trade-offs: training, encoding, vocabulary

Let N be the symbols across the distinct training words, M the number of merges, n the length of one word being encoded and V the vocabulary size.

CaseTimeSpaceWhy
Training, naive (the page’s code)O(M × N)O(N) pair countsRecounts every pair after every merge. Fine for five words, slow for a real corpus.
Training, incrementalabout O(N + M log N)pair counts + pair→words indexUpdate counts only in words that contain the merged pair; a heap gives the next best pair.
Encoding one wordO(n²), or O(n log n) with a heapmerge-rank table, O(V)Repeatedly merge the adjacent pair with the lowest learned rank.
Encoding with a word cacheO(1) on a hitone entry per distinct wordWord frequencies are heavily skewed, so most lookups hit.
Vocabulary size Vshorter sequencesV × d_model embedding rowsEach merge saves less: on this corpus merges 1–4 save 34 tokens, merges 13–16 save 11.

Weighting by word frequency is what makes training affordable. The corpus here has 107 symbols in total but only 30 across its five distinct words, and pairs are counted once per distinct word and multiplied by its frequency. Real trainers split text into words first for the same reason: a corpus with billions of words has far fewer distinct ones. The last row is the real trade-off. Merges keep buying shorter sequences, but each buys less, and every token added is another embedding row that rarely gets trained.

WATCH FOR

Common mistakes

  • Merging with plain string replace

    Store a word as "x es t" and merge the pair (s, t) with .replace("s t", "st"): you get "x est", gluing half of es to t. Match whole symbols only (split into a list, or a regex that respects the spaces). The page’s code uses replace and happens to be safe on its corpus; the merge sequences match a symbol-safe version for 8, 10, 15 and 20 merges.

  • Encoding by longest match instead of merge order

    Say the merges are (b, c), then (a, b), then (ab, c). BPE on abc applies (b, c) first, giving a bc, and stops: ab never forms. A longest-match lookup finds abc in the vocabulary and returns one token the model never saw for this text. Replay merges by rank.

  • Leaving ties to hash order

    The first merge here was a three-way tie at 9 (e+s, s+t, t+</w>). Break ties by a fixed rule. If iteration order decides, as with randomised hash maps, two training runs can produce different vocabularies and different token IDs.

  • Cutting a token stream in the middle of a character

    Byte-level tokens can end partway through a multi-byte UTF-8 character. Decode a truncated list, or print streamed tokens one at a time, and you get broken bytes (�). Buffer until the bytes form whole characters.

  • Assuming a word has one token ID

    the, the and The are usually different tokens. Searching or counting by ID, or forcing a word with a logit bias, has to cover every variant the tokenizer produces.

QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. What does one BPE step do?

    Answer: Merges the most frequent adjacent pair into a new token — BPE repeatedly finds the most frequent adjacent pair of symbols and merges it into a single new token, adding that merge to the vocabulary.

  2. Why use sub-word tokens instead of whole words?

    Answer: They keep the vocabulary small yet never hit an unknown word — Sub-words are the sweet spot: common words become one token, rare words split into reusable pieces, so the vocabulary stays compact and nothing is ever truly unknown.

  3. Why does an LLM struggle to count the r's in "strawberry"?

    Answer: It sees tokens, not individual characters — The model never sees letters — the characters are hidden inside tokens, so counting them requires reasoning about spelling it cannot directly observe. It is a tokenization artifact.

  4. If the same idea uses more tokens, what happens?

    Answer: It costs more and uses more of the context window — LLMs are billed per token and their context window is measured in tokens, so more tokens for the same meaning means higher cost and less room.

FAQ

Tokenization, answered

What is tokenization in an LLM?

Turning raw text into tokens — usually sub-word chunks — each mapped to an integer ID. The model only ever sees those IDs. Context limits, cost, and some model quirks all trace back to it.

What is Byte-Pair Encoding (BPE)?

The algorithm behind most LLM tokenizers: start from characters, then repeatedly merge the most frequent adjacent pair into a new token. Common words end up as one token; rare words stay split into reusable pieces.

Why not just use words as tokens?

A word vocabulary is huge, chokes on typos, names, and new words (all become 'unknown'), and wastes capacity on run/runs/running. Sub-words are the sweet spot — compact and never truly unknown.

Why does token count matter?

You're billed per token and the context window is measured in tokens. Fewer tokens = cheaper and more room. Rare words, code, numbers, and many languages split into more tokens for the same meaning.

Why do LLMs miscount letters like the r's in 'strawberry'?

The model sees tokens, not letters. The characters are hidden inside tokens, so counting them means reasoning about spelling the model can't directly see — a tokenization artifact, not a reasoning failure.

RUN CARD

—

Next → these token IDs become vectors, and every token learns to look at every other one: that's attention.

Finished this one? 0 / 61 Labs done
NextThe Dice Loader: Sampling Next on the “Driving the model” ladder · rung 2 of 4

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs