What a token is

Language models never see letters or words. They see tokens. What those are, how they are chosen, and why they explain some of AI’s strangest mistakes.

By · · 5 min read

For a while, one of the most reliable ways to trip up a chatbot was to ask how many r’s are in “strawberry.” Systems that could write passable sonnets and explain quantum tunneling would confidently answer two.

It looked like a lapse in basic intelligence. It was at least partly a window into how these systems read. A language model does not normally see the letters s-t-r-a-w-b-e-r-r-y. It sees the word as one chunk or a few, each replaced by a number, and the letters inside those chunks are hidden from it. Those chunks are called tokens, and once you understand them, a surprising amount of AI behavior starts to make sense.

Text in, numbers out

Neural networks only do arithmetic, so before a model can read anything, the text has to become numbers. That job belongs to a separate program called a tokenizer. It has a fixed list of text fragments, its vocabulary, and it chops your input into pieces from that list. Each piece has an ID number, and the model only ever receives the IDs.

Inside the model, each ID is swapped for an embedding, a long list of numbers that the model learned during training. From there on, everything the first essay described happens over tokens: attention connects tokens to other tokens, and the model’s output is a prediction of the next token’s ID, which the tokenizer turns back into text.

In English, a token averages roughly four characters, or about three-quarters of a word. Common words like “the” or “house” are usually a single token. Rarer words get split: “tokenization” might become “token” and “ization.”

Why not letters? Why not words?

Two obvious alternatives both fail. Reading letter by letter makes every sentence several times longer, and the cost of standard attention grows with the square of the length, since every position looks at every other position. Letters also carry little meaning on their own, so the model would spend much of its effort just reassembling words.

Reading whole words fails the other way. The list of possible words never ends: names, typos, slang, new coinages, “COVID,” every language on Earth. Any word missing from a fixed list would be unreadable.

Tokens are the compromise. Frequent words get a token of their own, and anything rarer is spelled out from smaller pieces, down to single characters if necessary. A vocabulary of tens of thousands of fragments can then express any text at all. GPT-2’s vocabulary had 50,257 tokens; more recent models typically use somewhere between about 100,000 and a few hundred thousand.

How the pieces are chosen

Nobody picks the fragments by hand. The most widely used method, byte-pair encoding, began life in 1994 as a data-compression trick1 and was adapted for machine translation in 2015.2 It is almost embarrassingly simple:

  1. Start with every text split into single characters.
  2. Count every pair of neighboring symbols across the training text.
  3. Glue the most frequent pair into a new symbol, and add it to the vocabulary.
  4. Repeat until the vocabulary is as big as you want.

Early merges capture common letter pairs like “h” + “e.” Later ones build up syllables, then whole frequent words. The figure below runs that exact procedure, live in your browser, using the paragraphs of this essay as its training text.

A toy tokenizer trained on this essay’s paragraphs. Drag the slider toward zero to undo its merges and watch the text fall apart into single characters. Dots mark spaces. Real tokenizers learn far more merges from far more text, so their pieces are longer, but the core procedure is the same.

Try a word that appears often in this essay, like “tokenization,” and then one it barely uses, like “photosynthesis.” The familiar word comes out in one or two pieces; the unfamiliar one shatters into fragments. Real models meet rare names and unusual spellings in much the same way.

Go deeper: byte-pair encoding in code

Training learns an ordered list of merges. This is a minimal version of what the figure runs:

from collections import Counter

def train_bpe(words, num_merges):
    # words: Counter mapping each word to how often it appears
    seqs = {w: list(w) for w in words}
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for w, syms in seqs.items():
            for a, b in zip(syms, syms[1:]):
                pairs[a, b] += words[w]
        if not pairs:
            break
        a, b = max(pairs, key=pairs.get)
        merges.append((a, b))
        for w, syms in seqs.items():
            out, i = [], 0
            while i < len(syms):
                if syms[i:i + 2] == [a, b]:
                    out.append(a + b); i += 2
                else:
                    out.append(syms[i]); i += 1
            seqs[w] = out
    return merges

To tokenize new text, start from characters again and keep applying whichever learned merge has the earliest rank among the pairs present, until none apply. Before any of this, text is first split on a simple pattern, roughly “runs of letters, runs of digits, runs of punctuation,” each keeping one leading space. That is why “ the” and “the” are different tokens.

Many production tokenizers, GPT-2’s among them, work on raw bytes rather than characters.3 The base vocabulary is then exactly 256 symbols, so any text in any language or encoding can be represented, and nothing is ever “unknown.”

What tokens explain

Counting letters. GPT-2’s tokenizer splits “strawberry” on its own into “st,” “raw” and “berry.” Put a space in front, as in the middle of a sentence, and the whole word is a single token. Either way, the model never directly sees how many r’s there are. It has to have learned the spelling of each chunk as a fact, the way you might know that “colonel” contains an l without hearing one. Models have since got much better at this, but tokens help explain why it was hard.

Arithmetic. Numbers get chopped up too. GPT-2’s tokenizer turns “1234567” into “123,” “45” and “67,” which is no help for lining up columns. The details matter: GPT-3.5 and GPT-4 read long numbers in three-digit chunks from the left, and researchers found that making them chunk from the right instead, the way commas do, greatly improved their addition.4 Some other models read every digit separately.

Spaces and capitals. “The,” “ the” and “ THE” are typically three unrelated tokens. A model has to learn from data that they mean the same thing, which it does well for common words and less well for rare ones.

Other languages. A tokenizer is most efficient on the kind of text it was built from, and English has usually been well represented. The same text in another language can take several times as many tokens, in extreme cases up to 15 times.5 Since usage is billed per token and a model’s memory is measured in tokens, those languages are slower, more expensive and fit less into a single conversation.

Glitch tokens. In 2023, researchers found tokens such as “SolidGoldMagikarp,” a Reddit username, that sat in GPT-3’s vocabulary but seemed to be nearly meaningless to the model. Asking it to repeat one could produce bizarre or evasive answers.6 Their suggested explanation: the vocabulary was built from scraped web text, while the model was trained on a more carefully filtered set in which those strings hardly appeared.

Why it matters to you

If you use these systems, tokens are the unit everything is measured in. Prices are quoted per million tokens. A model’s context window, how much it can consider at once, is a token count. When a model stumbles over spelling, digits or an unusual name, the tokenizer is a good first suspect.

There is also something quietly odd here. In most language models, the tokenizer is not trained along with the rest of the network. It is built beforehand, often by simple counting, then frozen. Much of what these models know, they know in terms of pieces chosen by a 1990s compression trick. Attention may be all you need, but first, you need tokens.

  1. Gage, “A New Algorithm for Data Compression” (1994). Published in C Users Journal. ↩
  2. Sennrich, Haddow and Birch, “Neural Machine Translation of Rare Words with Subword Units” (2015). ↩
  3. Radford et al., “Language Models are Unsupervised Multitask Learners” (2019). The GPT-2 paper, which describes its byte-level BPE. ↩
  4. Singh and Strouse, “Tokenization counts: the impact of tokenization on arithmetic in frontier LLMs” (2024). ↩
  5. Petrov et al., “Language Model Tokenizers Introduce Unfairness Between Languages” (2023). ↩
  6. Rumbelow and Watkins, “SolidGoldMagikarp (plus, prompt generation)” (2023). ↩
← All essays