Tokenization & Byte-Pair Encoding

Generative & Agentic AI · AI Foundations · Intermediate · 20 min

See text the way an LLM does: as tokens. Train a tiny byte-pair encoding (BPE) tokenizer by hand, and explain why tokens decide cost, context limits and some famous model mistakes.

A box of letter magnets. Every round you find the two magnets that sit side by side most often, and glue them into one bigger magnet. After thousands of rounds, common words are single magnets and rare words are a few pieces.

The idea in everyday words

Think of texting shortcuts. Friends who text a lot invent short forms for the things they say most: "brb", "idk", "omw". Rare words still get spelled out letter by letter. A tokenizer does the same thing with statistics: the pieces of text that appear most often get their own single symbol, so common text is short and anything at all can still be written.

Models read tokens, not letters or words

An LLM never sees your text directly. A tokenizer first chops it into tokens (small pieces of text) and turns each piece into a number (its token ID). The model only ever works with those numbers.

Why not just use letters or whole words?

Unit Problem
Letters Sequences get very long. Attention cost grows with length, so the model is slower and sees less text at once.
Whole words Millions of words, names, typos and new slang. Any word not in the list becomes "unknown".
Subword tokens The middle ground: common words are one token, rare words are a few pieces, and nothing is ever unknown.

Rough rule for English: 1 token ≈ 4 characters ≈ 0.75 words. So a 1,000-word essay is about 1,300 tokens.

text = "Tokenization is unbelievably useful"
words = text.split()
print(len(text), "characters,", len(words), "words, about", round(len(words) / 0.75), "tokens")

How BPE learns its tokens

Byte-pair encoding (BPE) builds the vocabulary from data with one simple loop:

  1. Start with every word split into single characters (real tokenizers start from the 256 possible bytes, so any text in any language can be written).
  2. Count every pair of neighbouring tokens, inside each word only.
  3. Merge the most frequent pair into one new token, everywhere it appears.
  4. Repeat until the vocabulary is big enough (tens of thousands to a few hundred thousand tokens).

Tiny example on the words hug, pug, pun, bun, hugs:

Round Most frequent pair Why New token
1 u + g 3 times (hug, pug, hugs) ug
2 h + ug tied with u + n at 2; "h" comes first alphabetically hug
3 u + n 2 times (pun, bun) un
4 b + un four pairs tied at 1; alphabetically smallest bun

The ordered list of merges is the tokenizer. To encode new text, split it into characters and apply the merges in the order they were learned. "bugs" becomes [b, ug, s] even though "bugs" never appeared in training.

Why "inside each word"? Before BPE runs, real tokenizers pre-tokenize: a rule splits text at spaces and punctuation first. So merges never glue the end of one word to the start of the next. Many tokenizers attach the space to the word that follows, which is why " hello" (with a space) and "hello" are different tokens.

Vocabulary size is a trade-off

More merges means a bigger vocabulary. Bigger vocabulary → shorter sequences, but there is a price:

  • Pros of big: fewer tokens per request (cheaper, faster, more fits in the context window), especially for code and non-English text.
  • Cons of big: the embedding table and the final output layer grow with vocabulary size, and very rare tokens are seen too few times in training to be learned well.

Some reference points (approximate): GPT-2 used about 50,000 tokens. Newer models use roughly 100,000 to 200,000+. Bigger vocabularies became popular because they make multilingual text and code much cheaper.

Other tokenizer families you should be able to name:

  • Byte-level BPE (GPT-2 onwards, and OpenAI's tiktoken library): BPE over bytes, so there is never an unknown token.
  • WordPiece (BERT): like BPE, but picks merges by how much they improve the likelihood of the data, not raw frequency.
  • SentencePiece (used by T5, Gemma and earlier Llama models): works on raw text, treats the space as a normal symbol (shown as ▁), and supports both BPE and the Unigram method, which starts big and prunes.

Why tokens explain cost, limits and odd mistakes

Tokens are the unit of almost everything in production:

  • Cost: Amazon Bedrock (and every other API) bills per input token and per output token. Every Bedrock Converse response includes a usage block with inputTokens and outputTokens: log it per request. Check the AWS pricing page for current rates.
  • Context window: limits like "200K tokens" count tokens, not words. Code, JSON, emoji and many non-English languages need more tokens per word, so they fill the window faster and cost more.
  • Latency: the model writes one token per step, so long answers take longer.

Famous quirks that come from tokenization:

  • "How many r's in strawberry?" The model may see something like [str, aw, berry], not ten letters, so counting letters is genuinely hard for it.
  • Arithmetic: numbers are split into odd chunks ("2024" may be one token, "2025" two). Some models split every digit separately, and many recent tokenizers split numbers into groups of up to 3 digits, to make maths more regular.
  • Spaces matter: " Paris" and "Paris" are different tokens, so a trailing space in a prompt can change the answer.
  • Glitch tokens: a few tokens that appeared in tokenizer training but almost never in model training made early GPT models behave strangely.

On AWS: Bedrock hosts models from several providers, and each model family has its own tokenizer, so the same prompt has a different token count on Claude, Llama, Mistral or Amazon Nova. Measure with the usage numbers from real calls rather than assuming. Open-source equivalent: inspect tokenizers with Hugging Face tokenizers / transformers or OpenAI's tiktoken.

Step by step

  1. Split into characters:

    Training words: hug, pug, pun, bun, hugs. Each starts as single letters: [h, u, g], [p, u, g], [p, u, n], [b, u, n], [h, u, g, s].

  2. Count pairs:

    Count neighbours inside each word: u+g = 3, h+u = 2, p+u = 2, u+n = 2, b+u = 1, g+s = 1. The winner is u+g.

  3. Merge #1: u + g → ug:

    Glue u and g everywhere: [h, ug], [p, ug], [p, u, n], [b, u, n], [h, ug, s]. 17 tokens became 14.

  4. Recount, break a tie:

    Now h+ug = 2 and u+n = 2 are tied. The rule says the alphabetically smallest pair wins (compare the left token first): "h" comes before "u", so merge #2 is h + ug → hug.

  5. Merge #3: u + n → un:

    Recount after every merge. u+n = 2 is now the clear winner, so pun → [p, un] and bun → [b, un].

  6. Merge #4: a four-way tie:

    Every remaining pair appears once: b+un, hug+s, p+ug, p+un. The smallest is b + un, so bun becomes a single token.

  7. Encode a new word:

    "bugs" was never in training. Start from [b, u, g, s] and apply the merges in order: u+g matches → [b, ug, s]; the other merges do not appear. Result: 3 tokens.

Code example

# Encode new words with merges learned on: hug, pug, pun, bun, hugs
merges = [("u", "g"), ("h", "ug"), ("u", "n"), ("b", "un")]
rank = {pair: i for i, pair in enumerate(merges)}   # lower rank = learned earlier

def encode(word):
    tokens = list(word)
    while True:
        # find the earliest-learned merge that appears in the word
        found = [(rank[p], i) for i, p in enumerate(zip(tokens, tokens[1:])) if p in rank]
        if not found:
            return tokens
        _, i = min(found)
        tokens[i:i + 2] = [tokens[i] + tokens[i + 1]]

for word in ["hugs", "bugs", "unhug", "bun", "zebra"]:
    print(word, "->", encode(word))

# Byte-level tokenizers start from bytes, so any text can be encoded.
for text in ["hi", "héllo", "日本"]:
    print(repr(text), len(text), "characters,", len(text.encode("utf-8")), "bytes")

Complexity

  • Time: O(k × N) for this simple trainer, where N is the total number of letters: every round recounts and rewrites every word. Production trainers update pair counts incrementally and use a priority queue.
  • Space: O(N) for the token lists plus the pair counts (at most N pairs at a time).

Interview tips

  • "Why do LLMs struggle to count letters or reverse words?" Because they see subword tokens, not characters. Mention that tool use (running code) is the reliable fix.

  • Be ready to implement BPE training on a whiteboard: count adjacent pairs, merge the most frequent, recount, with a clear tie-break. Then explain how encoding applies merges by rank.

  • Explain the vocabulary-size trade-off: shorter sequences and cheaper multilingual text versus bigger embedding and output layers and undertrained rare tokens.

  • Know why the same prompt costs different amounts on different models: each model family has its own tokenizer. Estimate with ~4 characters per token, but bill from the usage numbers the API returns.

  • Compare BPE, WordPiece and SentencePiece / Unigram in one sentence each, and say what byte-level BPE buys you (no unknown tokens).

Challenge: Train a BPE Tokenizer

Write bpe_merges(words, k) that learns up to k byte-pair merges and returns them in order.

  • Each word in words starts as a list of single characters. Words are lowercase letters only. A word that appears twice counts twice.
  • Each round: count every pair of neighbouring tokens inside each word (never across two words). Overlapping positions all count: "aaa" has the pair (a, a) twice.
  • Pick the pair with the highest count. Ties: the smallest pair comparing the left token first, then the right token, alphabetically.
  • Merge that pair in every word, scanning left to right with no overlaps: (a, a) turns "aaa" into [aa, a].
  • Record each merge as [left, right]. If no pairs are left, stop early.

Example:

bpe_merges(["hug", "pug", "pun", "bun", "hugs"], 4)
→ [["u", "g"], ["h", "ug"], ["u", "n"], ["b", "un"]]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in AI Foundations

Previous: What Is GenAI? LLMs & Tokens · Next: Transformers & Attention