Tokens

How a tokenizer splits text into tokens, how byte-pair encoding learns its vocabulary, and how tokens affect cost, limits and letter-level mistakes.

13 minLesson 2 of 6
On this page
  1. How text becomes token IDs
  2. How a tokenizer learns its vocabulary
  3. Why tokenization differs between texts
  4. How tokens count toward limits and cost
  5. Pitfalls and nuances
  6. What this changes in practice
  7. Check yourself
  8. What to practise next

A token is the unit of text that a language model reads and writes. A tokenizer cuts text into tokens taken from a fixed vocabulary, and the model only ever sees the numeric ID of each token, never the individual letters. This matters because context limits and prices are counted in tokens, because some kinds of text use many more tokens than others, and because tasks that depend on single characters are harder for a model than its fluent writing suggests.

If a model received raw letters, every sentence would be a very long sequence and the model would have to relearn common words from scratch. If it received whole words, the vocabulary would need an entry for every name, typo and number. Tokens sit between the two: frequent text becomes short sequences, and any text can still be built from smaller pieces. The previous lesson, What Is an LLM, described a model that predicts the next piece of text, and those pieces are tokens.

How text becomes token IDs

The tokenizer holds a list of pieces called the vocabulary. It splits the input into pieces from that list and replaces each piece with its position in the list. The model works on this sequence of numbers.

Text I'm unbelievably tired. Tokens I 'm ␣un believ ably ␣tired . 40 2389 517 30911 2088 11724 13 7 tokens
An illustrative split. Real tokenizers differ in where they cut and which IDs they use.

Common short words such as "tired" are a single token, while a long or rare word is split into several pieces. The leading space usually belongs to the token that follows it (shown as ␣ in the figure), so " tired" and "tired" are different tokens with different IDs.

How a tokenizer learns its vocabulary

Most current tokenizers use a method called byte-pair encoding, which builds the vocabulary from a large sample of text. It starts with every word split into single characters. It then counts every pair of neighbouring pieces across the whole sample, merges the most frequent pair into one new piece, and adds that piece to the vocabulary. It repeats this until the vocabulary reaches the size the designers want.

The trace below runs the method on six words: tea (twice), team, teams, steam and seat.

Learning tokens from six wordsUse the arrows or ← → keys
split every word into lettersrepeat k times:  count each pair of neighbouring pieces  best = the most frequent pair  glue best together everywhere  add best to the vocabulary
  1. tea ×2
    0t
    1e
    2a
    team
    0t
    1e
    2a
    3m
    teams
    0t
    1e
    2a
    3m
    4s
    steam
    0s
    1t
    2e
    3a
    4m
    seat
    0s
    1e
    2a
    3t
    tokens
    24

    1Every word starts as single letters, which gives 24 tokens in total.

  2. tea ×2
    0t
    1e
    2a
    team
    0t
    1e
    2a
    3m
    teams
    0t
    1e
    2a
    3m
    4s
    steam
    0s
    1t
    2e
    3a
    4m
    seat
    0s
    1e
    2a
    3t
    e a
    6
    t e
    5
    a m
    3

    2Count the pairs. The pair e a appears 6 times, once in every word occurrence, and t e appears 5 times because seat does not contain it. The pair e a wins.

  3. tea ×2
    0t
    1ea
    team
    0t
    1ea
    2m
    teams
    0t
    1ea
    2m
    3s
    steam
    0s
    1t
    2ea
    3m
    seat
    0s
    1ea
    2t
    vocabulary +
    ea
    tokens
    18

    3Merge e a into ea in all 6 places, which reduces the total from 24 to 18 tokens.

  4. tea ×2
    0tea
    team
    0tea
    1m
    teams
    0tea
    1m
    2s
    steam
    0s
    1tea
    2m
    seat
    0s
    1ea
    2t
    vocabulary +
    tea
    t ea
    5
    tokens
    13

    4The pair t ea now appears 5 times, which is the most, so it becomes the piece tea and the total drops to 13 tokens.

  5. tea ×2
    0tea
    team
    0team
    teams
    0team
    1s
    steam
    0s
    1team
    seat
    0s
    1ea
    2t
    vocabulary +
    team
    tea m
    3
    tokens
    10

    5The pair tea m appears 3 times, so it becomes the piece team and the total drops to 10 tokens.

  6. tea ×2
    0tea
    team
    0team
    teams
    0team
    1s
    steam
    0s
    1team
    seat
    0s
    1ea
    2t
    merges
    3
    tokens
    10
    letters
    24

    6Three merges were learned: ea, tea and team. The frequent words are one token each. The word seat is still three pieces, because its pairs s ea and ea t each appeared only once and never won a round.

1 / 6

Real tokenizers run this on enormous amounts of text, usually on raw bytes instead of letters so that any writing system can be represented, and they perform tens of thousands of merges. To tokenize new text, the tokenizer applies the learned merges in the order it learned them.

function learnMerges(words, numMerges) {
  let pieces = words.map((w) => w.split("")); // start from single letters
  const merges = [];
  for (let m = 0; m < numMerges; m++) {
    const counts = new Map(); // count every pair of neighbouring pieces
    for (const word of pieces) {
      for (let i = 0; i + 1 < word.length; i++) {
        const pair = word[i] + "|" + word[i + 1];
        counts.set(pair, (counts.get(pair) || 0) + 1);
      }
    }
    let best = null; // most frequent pair; the first one seen wins a tie
    for (const [pair, c] of counts) if (best === null || c > counts.get(best)) best = pair;
    if (best === null) break; // every word is already one piece
    const [a, b] = best.split("|");
    merges.push(a + b);
    pieces = pieces.map((word) => {
      const out = [];
      for (let i = 0; i < word.length; i++) {
        if (word[i] === a && word[i + 1] === b) { out.push(a + b); i++; }
        else out.push(word[i]);
      }
      return out;
    });
  }
  return { merges, pieces };
}
 
learnMerges(["tea", "tea", "team", "teams", "steam", "seat"], 3).merges;
// ["ea", "tea", "team"]
def learn_merges(words, num_merges):
    pieces = [list(w) for w in words]  # start from single letters
    merges = []
    for _ in range(num_merges):
        counts = {}  # count every pair of neighbouring pieces
        for word in pieces:
            for a, b in zip(word, word[1:]):
                counts[(a, b)] = counts.get((a, b), 0) + 1
        if not counts:
            break  # every word is already one piece
        best = max(counts, key=counts.get)  # the first one seen wins a tie
        merges.append(best[0] + best[1])
        new_pieces = []
        for word in pieces:
            out, i = [], 0
            while i < len(word):
                if i + 1 < len(word) and (word[i], word[i + 1]) == best:
                    out.append(word[i] + word[i + 1])
                    i += 2
                else:
                    out.append(word[i])
                    i += 1
            new_pieces.append(out)
        pieces = new_pieces
    return merges, pieces
 
learn_merges(["tea", "tea", "team", "teams", "steam", "seat"], 3)[0]
# ['ea', 'tea', 'team']

Each merge scans all the text once, so k merges over n characters cost O(k · n) in this simple version. Production tokenizers use better bookkeeping to get the same vocabulary faster.

Why tokenization differs between texts

Common and rare text

The merges reflect whatever was frequent in the sample the tokenizer learned from. English prose and popular programming languages therefore pack into few tokens. Languages that were rare in the sample, unusual names, long identifiers and random strings such as hashes break into many small pieces. The same message can cost several times as many tokens in one language as in another, and it also uses up more of the context limit.

Numbers

A number such as 2847 might be one token, or "284" followed by "7", or four separate digits, depending on the tokenizer. When the chunks do not line up with place value, the model cannot easily match units with units, which is one reason long arithmetic is unreliable unless the model uses a calculator or code.

Letters inside words

The model receives the ID for "␣tired", not the letters t, i, r, e, d. It can often spell a word because it has seen the spelling in many places, but counting or reversing letters asks it to recover information that was never directly shown to it. This is why a model can write a fluent paragraph and still miscount the letters in a single word.

How tokens count toward limits and cost

The context limit applies to everything the model handles in one request: your instructions, any documents you attach, the earlier messages of the conversation, and the reply the model writes. Input and output tokens both count against the limit. If a request fills most of the limit with input, little room remains for the answer, and a reply that hits the limit is cut off in the middle of a sentence.

Providers usually charge per token, and often charge a different rate for input tokens and output tokens. In a chat application the whole conversation so far is sent again with each new message, so the input grows with every turn and a long conversation costs more per message than a short one. For this reason, trimming old messages or summarising them is a cost decision as well as a limit decision.

Counts also include text you did not type, such as a system prompt, tool descriptions and the formatting that marks where each message starts and ends. A request that looks short can therefore be larger than the text you wrote suggests.

Pitfalls and nuances

What this changes in practice

Measure inputs in tokens when you budget for cost or context, and measure them on the kind of text you will really send, because a sample in one language or format does not predict another. Put work that depends on exact characters, such as counting, sorting letters, exact string comparison and long arithmetic, into code instead of asking the model to do it in its head. When you must have the model do it, make it write the characters out step by step so that each one becomes its own token. The embeddings lesson covers how each token ID is turned into a vector the model can compute with.

Try it: Make letter counting reliable

This prompt sometimes gets a confident wrong count. Rewrite it so the model works with letters instead of tokens.

Show a sample answer
Rewritten promptIllustrative example. Real replies vary.
You
Spell the word "possessiveness" one letter per line, numbering each line. Then list the line numbers that contain the letter "s". Finally, give the count.
Model
1. p 2. o 3. s 4. s 5. e 6. s 7. s 8. i 9. v 10. e 11. n 12. e 13. s 14. s Lines with "s": 3, 4, 6, 7, 13, 14 Count: 6

Writing one letter per line makes each letter its own token in the output, so counting becomes a matter of looking back at separate tokens instead of looking inside a chunk. You can also check every line yourself. When a wrong answer would matter, ask the model to write code for the count instead.

Check yourself

Quick check

In the six-word example, why did seat stay as three pieces?

The same paragraph, translated into a language that was rare in the tokenizer's training sample, will usually use...

Why can a model write fluent sentences but miscount the letters in a word?

What to practise next

Build a tokenizer yourself in Knitting Pattern Shorthand, which learns merges, and Sign Shop Letter Blocks, which cuts text into known pieces. After that, Attention and Transformers shows how the model combines token vectors so that each token can use information from the others.