Skip to content
Indus AI Academy

How Tokenization Works: Build a BPE Tokenizer From Scratch

Learn how tokenization works in AI by building a byte-pair-encoding tokenizer from scratch in plain Python, then see why it costs more for some languages.

· IIT Delhi alumnus

· 14 min read

A sign-making display board with the word 'light' spelled out in many different languages and scripts
Photo: Brecht Corbeel / Unsplash

Ask any large language model to count the letters in "strawberry" and it has sometimes gotten the answer wrong, badly enough to become a running joke online. The reason has nothing to do with the model being bad at spelling. It has never actually seen the letters s-t-r-a-w-b-e-r-r-y. It saw a short sequence of tokens, and some of those tokens bundle several letters together. If you want to understand how tokenization works in AI, the clearest way is not to read about it. It's to build a working tokenizer yourself, in about an hour, with nothing but the Python that already ships on your computer.

That's what this guide does. By the end you will have a from-scratch byte-pair-encoding (BPE) tokenizer, the same family of algorithm behind GPT, Claude, Gemini, Llama and nearly every other modern language model, trained on a small corpus, tested on words it has never seen, and pointed at text in three different scripts so you can see with your own eyes why the same sentence can cost very different numbers of tokens depending on what language it's written in.

Key takeaways

  • A token is not a word or a character. It's whatever chunk of text a tokenizer's vocabulary happens to contain, learned from data, not fixed by grammar.
  • Byte-pair encoding (BPE) learns its vocabulary by repeatedly merging the most frequent adjacent pair of symbols, starting from individual characters, until it hits a target vocabulary size.
  • You can build a working BPE tokenizer in well under 100 lines of plain Python, no libraries, no GPU, no API key, and no internet connection once you've downloaded the one file.
  • The same tokenizer handles unseen words gracefully, falling back to smaller known pieces instead of failing outright, which is the entire point of subword tokenization.
  • Tokenizers trained mostly on one language make text in other scripts measurably more expensive, and peer-reviewed research shows this gap persists even in tokenizers that are supposedly built for multiple languages.

What is a token, really?

A language model doesn't read raw text. Before any of your words reach the model, a tokenizer converts them into a sequence of integers, each one an index into a fixed vocabulary the model learned during training. Everything downstream, the attention mechanism that lets a transformer weigh every token against every other token, the model's price per request, and the size of its context window, is counted in these tokens, not in words or characters.

The oldest approach, splitting text on whitespace into whole words, breaks the moment it meets a word it didn't see during training: the vocabulary would need an entry for every word in every language, including every typo, every product name and every made-up word, which is an impossibly large list. The opposite approach, splitting into individual characters, never runs into an unknown symbol, but turns every sentence into a very long sequence, which is slow and expensive since models pay, in compute and in context budget, per token.

Byte-pair encoding is the practical middle ground almost every production tokenizer now uses: start from characters, then learn, from real data, which chunks of characters show up together often enough to deserve their own token. Common words and common pieces of words become single tokens. Rare combinations stay split into smaller pieces. Nothing is ever truly unknown.

How byte-pair encoding learns its vocabulary

BPE wasn't invented for language models. It started as a data-compression algorithm, and was adapted for text segmentation in a 2016 paper by Rico Sennrich, Barry Haddow and Alexandra Birch, Neural Machine Translation of Rare Words with Subword Units, to help translation systems handle rare and unseen words without falling back to a fixed dictionary. The training procedure they describe has four parts:

  1. Start from characters. Represent every word in your training corpus as a sequence of individual characters, with a marker for the end of the word.
  2. Count adjacent pairs. Across the whole corpus, count how often each pair of neighboring symbols appears, weighted by how often each word itself occurs.
  3. Merge the most frequent pair. Replace every occurrence of that single most common pair with one new, merged symbol, and add it to the vocabulary.
  4. Repeat. Keep counting and merging. The paper notes that "the final symbol vocabulary size is equal to the size of the initial vocabulary, plus the number of merge operations" — the number of merges is the one setting you choose.

At test time, applying a trained BPE tokenizer to a new word is just replaying the same merges, in the exact order they were learned, as Hugging Face's own tokenizer course describes it: split the new word into characters, then apply each learned merge rule in turn wherever it matches. Because the rules are just "if you see these two symbols next to each other, combine them," they apply to any word, including ones the tokenizer never saw during training.

Five-step flow showing byte-pair encoding: splitting words into characters, counting adjacent pairs, merging the most frequent pair, repeating until a target vocabulary size, then replaying the same merges on new text, with a worked example showing "tokenizer" shrinking from 8 characters to 2 tokens
How a byte-pair-encoding tokenizer learns its vocabulary

Build it yourself: a BPE tokenizer in plain Python

Everything below was actually run while writing this article, on Python 3.11.18, using only the standard library — no pip install needed at all. That makes this one of the simplest hands-on AI builds there is: open a terminal, paste in the code, and you have a real, working piece of the machinery behind every major language model.

Step 1: Count word frequencies and represent words as symbols

from collections import defaultdict
import re

END = "</w>"

def word_freqs_from_corpus(corpus: str) -> dict[tuple[str, ...], int]:
    """Lowercase, strip punctuation, split into words, count how often each occurs."""
    words = re.findall(r"[a-z]+", corpus.lower())
    freqs: dict[tuple[str, ...], int] = defaultdict(int)
    for w in words:
        freqs[tuple(w) + (END,)] += 1
    return freqs

Each word becomes a tuple of its characters, plus an end-of-word marker. That marker matters: without it, the tokenizer couldn't tell "er" at the end of "tokenizer" apart from "er" in the middle of a longer word.

Step 2: Count adjacent pairs and merge the most frequent one

def pair_counts(word_freqs: dict[tuple[str, ...], int]) -> dict[tuple[str, str], int]:
    """Count every adjacent symbol pair across the corpus, weighted by word frequency."""
    counts: dict[tuple[str, str], int] = defaultdict(int)
    for symbols, freq in word_freqs.items():
        for a, b in zip(symbols, symbols[1:]):
            counts[(a, b)] += freq
    return counts

def merge_pair(pair: tuple[str, str], word_freqs: dict[tuple[str, ...], int]) -> dict[tuple[str, ...], int]:
    """Replace every occurrence of `pair` with a single merged symbol."""
    a, b = pair
    merged = a + b
    new_freqs: dict[tuple[str, ...], int] = {}
    for symbols, freq in word_freqs.items():
        out, i = [], 0
        while i < len(symbols):
            if i < len(symbols) - 1 and symbols[i] == a and symbols[i + 1] == b:
                out.append(merged)
                i += 2
            else:
                out.append(symbols[i])
                i += 1
        new_freqs[tuple(out)] = new_freqs.get(tuple(out), 0) + freq
    return new_freqs

Step 3: Train, by repeating the merge loop

def train_bpe(corpus: str, num_merges: int) -> list[tuple[str, str]]:
    """Learn `num_merges` merge rules, most frequent pair first each round."""
    word_freqs = word_freqs_from_corpus(corpus)
    merges: list[tuple[str, str]] = []
    for _ in range(num_merges):
        counts = pair_counts(word_freqs)
        if not counts:
            break
        best = max(counts, key=counts.get)
        if counts[best] < 2:
            break
        merges.append(best)
        word_freqs = merge_pair(best, word_freqs)
    return merges

Step 4: Encode new text with the learned merges

def encode(word: str, merges: list[tuple[str, str]]) -> list[str]:
    """Apply learned merges, in the order learned, to a new (possibly unseen) word."""
    symbols = list(word.lower()) + [END]
    for a, b in merges:
        out, i = [], 0
        while i < len(symbols):
            if i < len(symbols) - 1 and symbols[i] == a and symbols[i + 1] == b:
                out.append(a + b)
                i += 2
            else:
                out.append(symbols[i])
                i += 1
        symbols = out
    return symbols

That's the whole tokenizer. No neural network, no training loop in the machine-learning sense, just counting and merging. Train it on a short corpus of AI-related sentences and ask for 60 merges:

merges = train_bpe(corpus, num_merges=60)

Running it prints the merges it chose, in order, most frequent pair first:

Learned 60 merges from a 171-word corpus.

First 15 merges learned, in order:
   1.    's' + '</w>' -> 's</w>'
   2.    'e' + 'n'    -> 'en'
   3.    't' + 'o'    -> 'to'
   4.    'a' + 'n'    -> 'an'
   5.    't' + '</w>' -> 't</w>'
   6.    'e' + 'r'    -> 'er'
   7.    'e' + '</w>' -> 'e</w>'
   8.    'i' + 'n'    -> 'in'
   9.    'a' + '</w>' -> 'a</w>'
  10.    'a' + 't'    -> 'at'
  11.   'to' + 'k'    -> 'tok'
  12.  'tok' + 'en'   -> 'token'
  13.    'd' + '</w>' -> 'd</w>'
  14.    't' + 'h'    -> 'th'
  15.    'c' + 'h'    -> 'ch'

Notice the first merge is plural "s" at the end of a word, then common two-letter combinations, and only by merge 11 and 12 does the algorithm build up "tok" and then "token" on its own, purely because that corpus mentions tokens and tokenizers a lot. Nobody told it "token" was an important word. It found that out from frequency alone.

What happens when you feed it a word it has never seen

This is the part that matters most. Encode a handful of words, some seen during training, some not:

Encoding words with the 60 learned merges:
       'tokenizer' -> ['tokeniz', 'er</w>']  (2 tokens)
    'tokenization' -> ['tokeniz', 'ation</w>']  (2 tokens)
    'transformers' -> ['tr', 'ans', 'for', 'm', 'er', 's</w>']  (6 tokens)
      'detokenize' -> ['d', 'e', 'tokeniz', 'e</w>']  (4 tokens)
      'strawberry' -> ['s', 'tr', 'a', 'w', 'b', 'er', 'r', 'y</w>']  (8 tokens)
    'unbelievable' -> ['u', 'n', 'be', 'l', 'i', 'ev', 'a', 'b', 'l', 'e</w>']  (10 tokens)

A word never seen in training:
  'xenolinguistics' -> ['x', 'en', 'o', 'l', 'in', 'g', 'u', 'i', 's', 't', 'i', 'c', 's</w>']

"Tokenizer" and "tokenization" collapse into just two tokens each, because this corpus is full of sentences about tokenizers. "Strawberry" never appeared in training at all, so it falls apart into eight small pieces, mostly single letters, which is exactly why a model has to reconstruct the idea of "strawberry" from fragments rather than seeing it as one clean unit, and why asking it to count letters inside that fragmented representation is a harder task than it looks. "Xenolinguistics," a word this tokenizer has absolutely never encountered, still encodes into something, instead of erroring out. That graceful fallback to smaller, known pieces is the entire reason subword tokenization replaced whole-word vocabularies.

Why the same idea costs more tokens in some languages

Here's a demonstration worth running yourself. Take one short idea, translate it into three languages, and encode each with the exact same 60 merges, learned only from English text:

The same short idea in different scripts, run through the SAME merges learned only from English:
  English                               29 characters ->  14 tokens with this tokenizer
  Hindi (Devanagari script)             23 characters ->  24 tokens with this tokenizer
  Yoruba (Latin script, diacritics)     23 characters ->  24 tokens with this tokenizer

The English sentence needs roughly two characters per token. The Hindi and Yoruba sentences, despite being shorter in raw character count, need almost one token per character, because this toy tokenizer never learned any merges for Devanagari symbols or Yoruba diacritics. Every character in those scripts falls back to its own single-character token.

This tokenizer is small and only trained on English, so take the exact numbers as illustration, not as a benchmark of any real product. But the mechanism it demonstrates is real, and it doesn't disappear just because a production tokenizer is trained on many languages at once. A 2023 NeurIPS paper by Aleksandar Petrov, Emanuele La Malfa, Philip Torr and Adel Bibi, Language Model Tokenizers Introduce Unfairness Between Languages, measured this directly across real tokenizers and found that encoding the same text in different languages can take up to around 15 times as many tokens, and that even character-level and byte-level tokenizers built for multilingual use still showed more than a fourfold difference between some language pairs. The authors argue this creates real unfairness: higher cost per request, higher latency, and less room in the context window, for people writing and reading in some languages rather than others, not because the model understands those languages worse, but because the tokenizer was never built to treat them equally in the first place.

How production tokenizers differ from this toy version

Three differences matter if you want to go from this toy tokenizer to understanding what GPT, Claude or Gemini actually use:

  • Byte-level, not character-level. The GPT-2 paper explains why: a tokenizer that starts from Unicode code points needs a base vocabulary "over 130,000" symbols just to cover every character that might appear, which the authors call "prohibitively large." Starting from raw bytes instead keeps the starting alphabet at exactly 256 symbols, since any Unicode text can be represented as a sequence of bytes, and the paper reports GPT-2's final vocabulary, after merges, at 50,257. Nothing is ever truly out of vocabulary.
  • Far larger training corpora. Real tokenizers train their merges on billions of words across many languages and domains, not 171 words about AI concepts, which is exactly why they can represent "strawberry" or technical jargon in far fewer tokens than this toy version does.
  • Fast, production-grade implementations. OpenAI's tiktoken library implements the same core idea in a fast, well-tested package, reversible and lossless, so any token sequence can be converted back into the exact original text, which is a property any serious tokenizer needs.
Approach Vocabulary size Handles unseen words Typical sequence length
Whole words Enormous, open-ended No — fails on anything new Shortest, when it works
Single characters Tiny (dozens to hundreds) Always Longest
Byte-pair encoding (subwords) Chosen (commonly 32,000–100,000+) Always, falls back gracefully Balanced

What this means if you build with AI

Understanding tokenization isn't trivia. It changes decisions you make every time you build something on top of a language model:

  • Estimate cost and context budget realistically. If you're processing text heavy in code, rare technical terms, or a language a model's tokenizer wasn't trained heavily on, expect more tokens per sentence than a quick word count would suggest, and budget your context window and API costs accordingly.
  • Check token counts directly rather than guessing. Use the tokenizer library that matches the model you're actually calling, since tokenizers differ between model families.
  • Expect certain failure modes. Letter-counting, character-level puzzles, and precise spelling tasks are harder for a model when the relevant word is split into multiple tokens, because the model never saw the individual letters as separate units in the first place.
  • Be realistic about multilingual products. If you're building for users who write in a language your model's tokenizer handles poorly, expect higher latency and cost for identical requests, and test with real text in that language before you ship.

How to go deeper

Building this tokenizer teaches you the mechanics, but using that understanding well, alongside retrieval, agents and the rest of an AI system, is a different skill, one worth practicing with feedback rather than alone. The AI Automation & Agents Bootcamp is built for exactly this kind of hands-on work: live sessions you can join from anywhere, three production-grade agents you build and get reviewed during the course, and an Indus AI Academy certificate you can verify, backed by a capstone project rather than a quiz. The next cohort is open to join.

If you'd rather go deeper on the mechanism tokens feed into, read how transformers turn a sequence of tokens into attention-weighted meaning, or, if retrieval is more your interest, see how the same idea of turning text into numbers powers a RAG app's search step. And if you're mapping out which AI skills are actually worth your time generally, this guide to becoming an AI generalist is a reasonable next stop.

Frequently asked questions

What is a token in AI?

A token is the basic unit a language model actually processes, somewhere between a character and a word. It's whatever chunk of text a specific tokenizer's vocabulary happens to contain, which is learned from training data, not fixed by spelling or grammar rules. A common English word is often one token; a rare word or a word in an underrepresented language is usually split into several.

How does byte-pair encoding (BPE) work?

BPE starts by treating every character as its own token, then repeatedly finds the single most frequent pair of adjacent symbols in a training corpus and merges it into one new token. This repeats for a fixed number of merges, building up a vocabulary of common subwords. At encoding time, the same merge rules are replayed, in the order they were learned, on any new text.

Why do some languages need more tokens than others for the same sentence?

Because tokenizers learn their vocabulary from training data, and most training data is skewed toward a small number of languages, usually English. Text in a language or script the tokenizer saw less of during training falls back to smaller, less efficient pieces, sometimes close to one token per character. Peer-reviewed research has measured this gap at up to roughly 15 times as many tokens for the same meaning, even in tokenizers built for multilingual use.

Is the BPE tokenizer in this tutorial the same one GPT or Claude use?

The core idea, repeatedly merging frequent adjacent symbol pairs, is the same family of algorithm. Production tokenizers differ in scale: they typically work at the byte level rather than the character level, train on vastly larger and more diverse text, and run through fast, optimized libraries. This tutorial builds the same mechanism in miniature so you can see exactly how it works.

Do I need to understand tokenization to use AI tools well?

Not to use them casually, but it helps the moment you're building something, estimating cost, debugging a strange failure, or working with a language your tools don't support well. Knowing that a model sees tokens rather than words or letters explains a surprising number of its odd behaviors, including letter-counting mistakes and uneven performance across languages.

Found this useful?

Next cohort starts 2 Dec

AI Automation & Agents Bootcamp

Design, build and run AI agents and automations in production.

  • Mondays and Wednesdays, 7–10 PM IST
  • 6 weeks · 12 sessions · 36 live hours · Online
  • For: Operations, product and technical teams, developers and analysts
  • ₹44,999 per seat, taxes extra
Reserve your seat
Vivek Gupta

About the author

· IIT Delhi alumnus

Vivek Gupta is an IIT Delhi alumnus and PhD scholar, an AI researcher and serial entrepreneur with 14 years of building technology at MakeMyTrip, Goibibo, Wissen and Jubilant FoodWorks.

More articles by VivekConnect on LinkedIn

Discussion

No comments yet. Start the discussion.

Turn ideas into skills.

Live, hands-on AI programs for professionals and teams, with certificates issued by INDUS AI Private Limited.