Katkat

Tokenization: BPE, Vocabulary Size and Why Tokens Matter

By the Katkat team · Updated · 10 min read

Quick overview

Learn how byte-pair encoding builds a vocabulary, why vocab size trades sequence length against embedding cost, and how tokens drive multilingual cost.

Lesson 3 of 88 · AI Engineering Interview Course

After this lesson you will be able to explain how byte-pair encoding (BPE) builds a vocabulary from raw text, and why the vocabulary size is a real engineering trade-off rather than a detail. You will also be able to say why the same sentence can cost very different amounts in different languages, and list the token-counting mistakes that cause bugs and surprise bills in production.

Why models read tokens, not characters or words

A language model works on integers. A tokenizer converts text into a sequence of token IDs, and each ID indexes a row of the embedding matrix (see Embeddings). The model's output is a probability distribution over the same set of IDs.

The unit could be a character, a word or something in between:

  • Characters or bytes only: the vocabulary is tiny and nothing is ever unknown, but sequences get very long. Attention cost grows with sequence length, and every generated character costs a full forward pass.
  • Whole words: sequences are short, but the vocabulary explodes (names, typos, code identifiers, inflections). Any word not in the list becomes an "unknown" token and its meaning is lost.
  • Subwords: common strings get their own token, and rare strings are assembled from smaller pieces. This is the compromise nearly all modern LLMs use.

The tokenizer is trained separately from the model, before pretraining, and is then frozen. Changing it later means the embedding and output layers no longer line up with the weights.

How byte-pair encoding works

BPE training is a simple greedy loop:

  1. Start with a base vocabulary of single symbols (characters or bytes).
  2. Split the training corpus into words and count how often each word occurs.
  3. Count every adjacent pair of symbols, weighted by word frequency.
  4. Merge the most frequent pair into a new symbol and add it to the vocabulary.
  5. Repeat until the vocabulary reaches the target size.

The output is the vocabulary plus an ordered list of merges. Encoding new text means splitting it into base symbols and applying the merges in the order they were learned.

Worked example

Corpus word counts: tack ×5, tacks ×3, stack ×4, track ×2. The base vocabulary is t, a, c, k, s, r (6 symbols).

Pair counts, weighted by frequency:

PairWhere it occursCount
(a, c)tack 5 + tacks 3 + stack 4 + track 214
(c, k)same four words14
(t, a)tack 5 + tacks 3 + stack 412
(s, t)stack4
(k, s)tacks3

(a, c) and (c, k) tie at 14. Break the tie by first occurrence and merge (a, c) into ac. The next merges follow:

Merge #Pair mergedCount at that pointNew token
1a + c14ac
2ac + k14ack
3t + ack12 (tack 5, tacks 3, stack 4)tack
4s + tack4stack

The final vocabulary has 6 base symbols + 4 merges = 10 tokens.

Now encode an unseen word, tracks. Start from t r a c k s. Merge 1 gives t r ac k s. Merge 2 gives t r ack s. Merges 3 and 4 do not apply, because t and r are not adjacent to ack in a matching way. The result is [t, r, ack, s], which is 4 tokens for a 6-character word the tokenizer never saw. This is why BPE has no real "out of vocabulary" problem. The worst case is falling back to single symbols.

To implement this yourself, see Implement a Byte-Pair Encoding Tokenizer.

Byte-level BPE, special tokens and pre-tokenization

Modern LLM tokenizers usually run BPE over UTF-8 bytes rather than Unicode characters. The base vocabulary is exactly 256 byte values, so any string in any language, including emoji and malformed text, can be encoded with no unknown token.

The cost shows up in non-Latin scripts. In UTF-8, ASCII letters use 1 byte, accented Latin letters typically 2, most CJK characters 3, and emoji 4. If no merge covers a character, it costs as many tokens as it has bytes.

Two other pieces matter in practice:

  • Pre-tokenization: before merging, text is split by a rule (often a regex) into chunks such as words, numbers and punctuation. Merges never cross chunk boundaries. This stops the tokenizer from learning tokens like dog.The. Whitespace is usually attached to the following word, so " hello" and "hello" are different tokens.
  • Special tokens: reserved IDs such as end-of-sequence, and role markers used by chat templates. They are not produced by merging; they are inserted by the application or template.

Other tokenizer algorithms

AlgorithmHow the vocabulary is builtTypical note
BPEGreedily merge the most frequent pair, bottom upCommon in decoder-only LLMs; often byte-level
WordPieceMerge pairs chosen by a likelihood-based score instead of raw frequencyAssociated with BERT-style encoders
Unigram LMStart with a large candidate set, prune tokens that hurt corpus likelihoodOffered by SentencePiece; can output several segmentations

SentencePiece is a toolkit that treats text as a raw stream (spaces included) so it needs no language-specific pre-splitting. It can train either BPE or Unigram models. You do not need to memorise the scoring formulas for an interview. You do need to know that these are all subword methods that differ in how the vocabulary is chosen.

Vocabulary size trade-offs

The vocabulary size V is a hyperparameter fixed before training. Open models have used sizes from roughly 30,000 to over 250,000, and the numbers vary by model.

Arithmetic for a model with hidden size d = 4,096:

  • V = 32,000: embedding matrix = 32,000 × 4,096 = 131,072,000 ≈ 131M parameters
  • V = 128,000: 128,000 × 4,096 = 524,288,000 ≈ 524M parameters
  • If the output projection is not tied to the embedding, double each figure.
  • Per generated token, the output layer costs about 2 × d × V FLOPs. For V = 128,000 that is 2 × 4,096 × 128,000 ≈ 1.05 GFLOPs, and it produces 128,000 logits that sampling must process (see Decoding).
Smaller vocabularyLarger vocabulary
Tokens per textMoreFewer
Attention and KV cache per textLarger (more tokens)Smaller
Decode steps per answerMoreFewer
Embedding and output parametersFewerMore
Softmax cost per stepLowerHigher
Rare tokensFew, well trainedMany, seen rarely, so weaker embeddings
Multilingual coveragePoor for under-represented scriptsBetter, if the training mix includes them

The sweet spot depends on model size. For a small model, a huge vocabulary makes the embedding table a large fraction of all parameters. For a very large model, that table is a small fraction, so a bigger vocabulary is cheap and the shorter sequences pay off. Also, the tokenizer's training data should resemble the model's real traffic. A tokenizer trained mostly on English prose will fragment code or other languages.

Multilingual cost

Because merges are learned from frequency, languages and scripts that are rare in the tokenizer's training data get fewer merges and split into more tokens. The same meaning can therefore cost more.

Illustrative example (the ratio is hypothetical; measure with your own tokenizer): suppose a customer message is 20 tokens in English and 50 tokens in another language with the same meaning, a 2.5× ratio. With a price of $3 per million input tokens:

  • English: 1,000,000 messages × 20 tokens = 20M tokens → $60
  • Other language: 1,000,000 × 50 = 50M tokens → $150

The effects go beyond price:

  • A context window of 8,000 tokens holds 8,000 / 20 = 400 such messages in English but 8,000 / 50 = 160 in the other language.
  • Output also costs more and takes longer, since decoding is one step per token.
  • Self-attention compute scales roughly with the square of sequence length, so a 2.5× longer sequence means about 2.5² = 6.25× more attention compute for that part.
  • Token-based rate limits (see Token Rate Limits, Quotas and Backpressure) are hit sooner.

Mitigations: choose a model whose tokenizer covers your languages well, compare tokens per request across candidate models, and budget per language rather than using one average.

Token counting pitfalls

  • Different models, different tokenizers. A count from one model's tokenizer is only an estimate for another. Even versions within a model family may differ. Use the tokenizer or counting endpoint the provider documents for the exact model.
  • Rules of thumb are English-only. About 4 characters or 0.75 words per token is a rough figure for English prose. It fails for code, numbers, non-Latin scripts and text with unusual whitespace.
  • Hidden overhead. Chat templates add role markers and special tokens. Tool or function schemas, system prompts and retrieved context are all counted as input. Some providers also bill internal reasoning tokens as output.
  • Input and output share the window. The context window limit covers prompt plus generated tokens. A max_tokens setting that ignores the prompt size can cause truncated answers or errors (see Context Windows).
  • Whitespace and case change tokens. "Hello", " Hello" and "hello" can be three different tokens. A trailing space at the end of a prompt can slightly change generation.
  • Character-level tasks are hard. Counting letters, reversing strings or exact spelling are difficult because the model sees token chunks, not letters. Numbers may be split in inconsistent ways, which affects arithmetic.
  • Streaming chunks are not tokens. A streamed event can carry part of a token or several tokens. Do not count tokens by counting events.
  • Truncating by characters can cut in the middle of a token or a multi-byte character. Truncate by tokens, and decode cleanly.
  • Cached or multimodal inputs. Images and audio are converted to tokens by the model, using provider-specific rules.

For cost work, see How Would You Cut LLM Costs by 10x? and Numbers Every AI Engineer Should Know.

How does this come up in interviews?

1. Walk me through how BPE builds a vocabulary. Start with single bytes or characters, count adjacent pairs weighted by word frequency, merge the most frequent pair into a new token, and repeat until the target vocabulary size is reached. Keep the ordered merge list, because encoding applies the merges in that order. Mention that byte-level BPE guarantees no unknown tokens.

2. Why not just use a huge vocabulary so every word is one token? A larger vocabulary shortens sequences, which reduces attention and KV-cache cost and the number of decode steps. But the embedding and output matrices grow as V × d, the softmax gets more expensive, and rare tokens are seen too few times to learn good embeddings. The right size depends on model scale and on the languages and domains it must cover.

3. A product launches in a new language and the LLM bill per user is 2× higher. What do you check first? Check tokens per request in that language, since a tokenizer with weak coverage fragments the text into more tokens, raising input cost, output cost, latency and rate-limit usage. Compare candidate models' tokenizers on a sample of real traffic, and shorten prompts and context where possible. Do not assume the English tokens-per-word ratio.

4. Your token estimate for a prompt was 3,900 but the API rejected it for exceeding a 4,096 limit. Why? The estimate likely ignored template tokens, role markers, tool schemas, or used the wrong tokenizer. Reserve room for output tokens too, since they share the window. Count with the exact model's tokenizer, include everything sent, and leave a safety margin.

5. Why can a model struggle to count the letters in a word? The model sees token IDs, which are chunks of characters, not individual letters, so character-level structure is not directly visible. It has to infer spelling from training patterns. Tools such as code execution handle such tasks more reliably.

Common mistakes

  • Describing BPE as splitting by words or syllables rather than by frequency-driven merges.
  • Forgetting that the tokenizer is fixed before pretraining and tied to the model's weights.
  • Using one tokenizer's count to budget for a different model.
  • Applying the English "0.75 words per token" figure to code or other languages.
  • Ignoring chat-template, system-prompt and tool-schema tokens when computing context use.
  • Treating vocabulary size as "bigger is always better" and forgetting the V × d parameters and softmax cost.
  • Counting streamed chunks as tokens, or truncating text by characters.
  • Assuming byte-level BPE is free of cost for non-Latin scripts; it avoids unknown tokens but can still need many tokens per character.