Back to Tutorials
Deep Learning
Intermediate

Tokenization: How Language Models Read Text

Train a real tokenizer in your browser, see the numbers a model actually receives, and find out why the same sentence costs more in some languages than others.

10 minInteractive: drag, click and try things as you read


A language model never sees letters or words. Before your text reaches it, a tokenizer cuts the text into pieces called tokens and swaps each piece for a number. The model reads numbers, writes numbers, and the tokenizer turns them back into text. What you pay, how much fits in a prompt and some of the strangest mistakes models make all come down to how that cutting is done. Here you’ll train a real tokenizer in your browser, see what a model actually receives, and find out why the same sentence costs more in some languages than others.

Models read numbers#

A model has a fixed vocabulary: a list of tokens, each with an ID number. GPT-2’s vocabulary has 50,257 tokens; the one used by GPT-4o has about 200,000. Common words are usually a single token, often with the space in front of them included, so “ the” is one token. Rarer words are split into pieces. The model is trained to predict the next token’s ID, one at a time, which is why answers stream out in chunks.

Why not just use letters, or whole words? Letters make every text long: each one would be a separate step for the model, and the cost of attention grows quickly with length. Whole words make the vocabulary enormous and still fail on anything new, such as a name, a typo or a word in another language. Tokens sit in between: frequent strings get their own token, and anything else can still be spelled out from smaller pieces.

How a tokenizer learns its pieces#

Most tokenizers are built with byte-pair encoding (BPE). It began in 1994 as a compression trick by Philip Gage, was adapted for translation models by Rico Sennrich and colleagues in 2016, and has been used, in a byte-level form, by GPT models since GPT-2 in 2019. The recipe is short:

  1. Turn the training text into bytes. Every possible byte is a token to start with, so any text can be encoded.
  2. Count every pair of neighbouring tokens in the whole text.
  3. Make the most frequent pair into a new token, a merge, and replace it everywhere.
  4. Repeat until the vocabulary is the size you want.

Before counting, the text is split into words, numbers and punctuation, with a word’s leading space kept on the front, so merges never cross from one word into the next.

Predict first

Trained on ordinary English text, which pair do you think BPE merges first?

Try it
A real byte-level BPE tokenizer, trained in your browser on the text of the 33 explainers published on this site before this one: about 263,000 characters, 5,577 distinct words and symbols. Real tokenizers do exactly this on far more text, for 50,000 to 200,000 merges. Type anything into the box.

With no merges, every byte is its own token, so the sample sentence’s 46 characters are 46 tokens. After 50 merges, common fragments such as “en”, “on”, “ow” and “ re” are single tokens and it takes 33. By 3,000 merges whole words like “ language”, “ models” and “ read” are one token each and the sentence takes 13. Across the training text, that’s about 3.7 characters per token.

Now try the other samples. Words that are common in the training text, like “ embeddings” or “tokens”, are a single token. “ strawberry” never appears there, so it’s spelled out in five pieces. The typos take 11 tokens, where “the model is really great” takes 7. And the Hindi greeting can’t use a single merge: there’s no Hindi in the training text, so each letter falls back to its raw bytes, three tokens per letter. A tokenizer is a summary of the text it was trained on: what was common there is cheap, and everything else is spelled out.

What the model actually sees#

Switch the figure to “What the model sees”. That list of numbers is the model’s entire view of your text. Whatever it knows about the letters inside a token, it had to learn from how that token was used in training.

Predict first

Models have famously struggled to count the r’s in “strawberry”. Using GPT-4o’s tokenizer, what does the model receive for the word “ strawberry” in a sentence?

Put the word in quotation marks, as people often do when they ask that question, and it splits differently: GPT-4o gets “st”, “raw” and “berry”. That’s still not letters. Numbers have the same problem. GPT-2 splits “ 2026” into “ 20” and “26”, while GPT-4 and GPT-4o cut every number into groups of up to three digits from the left, so 2026 becomes “202” and “6”, and 12345 becomes “123” and “45”. Meta’s first LLaMA models went the other way and split every number into single digits.

Same meaning, different bill#

A tokenizer trained mostly on English gets very good at English and much worse at everything else. To see how much, the next figure uses one sentence in 15 languages: Article 1 of the Universal Declaration of Human Rights, in the United Nations’ own translations. “All human beings are born free and equal in dignity and rights…”

Predict first

GPT-4’s tokenizer turns the English version into 33 tokens. About how many tokens does the Hindi translation take?

Try it
Article 1 of the Universal Declaration of Human Rights in 15 languages: the UN’s translations, as collected in the NLTK udhr2 corpus. Token counts for GPT-2, GPT-4 and GPT-4o come from OpenAI’s published tokenizers (counted with tiktoken); “Ours” is the tokenizer from the first figure, run in your browser. Tap a language to see how it’s cut up.

With GPT-2’s tokenizer, the same article costs 9 times as many tokens in Hindi as in English and 20 times as many in Tamil. GPT-4’s larger vocabulary brought Hindi down to 5.5 times and Tamil to 10. GPT-4o’s, with about 200,000 tokens drawn from more languages, gets most of them within about twice English: Hindi 1.7 times, Tamil 2.3, Spanish and Chinese close to English. But Amharic still takes 6.2 times as many tokens. Our little tokenizer, trained only on English, is worse than all of them: Hindi costs 10 times English, because every letter falls back to bytes.

This is a real unfairness, not a curiosity. In 2023 Aleksandar Petrov and colleagues at Oxford measured it across 200 languages and found that GPT-4’s tokenizer needed up to 15 times as many tokens for the same content in some languages. People writing in those languages pay more for the same answer, wait longer for it, and fit less into the same context window.

Why tokens matter in your app#

  • Cost. API prices are per million tokens, and output tokens usually cost several times as much as input tokens. A wordy system prompt is paid for on every single call.
  • Context windows are measured in tokens, and your prompt, any documents you add, the conversation so far and the reply all have to fit.
  • Speed and rate limits. Models write one token at a time, and rate limits count tokens per minute, so more tokens means slower answers and sooner throttling.
  • Every model counts differently. The common rule of thumb, about four characters of English per token, is only a rough guide for English prose. Code, numbers, tables and other languages can be far from it, and even one company’s models differ: Anthropic’s migration guide says Claude Sonnet 5 turns the same text into roughly 30% more tokens than Claude Sonnet 4.6. Count with the tokenizer of the model you actually use.

In code#

OpenAI publishes its tokenizers in the tiktoken library (pip install tiktoken):

import tiktoken

enc = tiktoken.get_encoding("o200k_base")   # GPT-4o's tokenizer

english = "All human beings are born free and equal in dignity and rights."
spanish = "Todos los seres humanos nacen libres e iguales en dignidad y derechos."
print(len(enc.encode(english)), len(enc.encode(spanish)))
# 13 15

for text in [" strawberry", '"strawberry"', " 12345"]:
    print([enc.decode([t]) for t in enc.encode(text)])
# [' strawberry']
# ['"', 'st', 'raw', 'berry', '"']
# [' ', '123', '45']

Open models ship their tokenizer with the model, so Hugging Face’s AutoTokenizer loads the right one. Claude’s tokenizer isn’t published; Anthropic’s API has a token-counting endpoint instead, called from Python as client.messages.count_tokens(model=..., messages=[...]), which returns input_tokens for exactly the model you name. Counting is free, so check a prompt before you rely on a rule of thumb.

What to remember

  • Models read token IDs, not letters or words; a tokenizer cuts text into tokens learned from its training data.
  • BPE merges the most frequent pair again and again, so common strings become single tokens and rare ones are spelled out in pieces.
  • Token counts differ by language, by content and by model: count with your model’s own tokenizer, and use code for exact counting and arithmetic.

Keep going

Sign in to save your place and keep a learning streak. Free, with Google.