SysDesignAtlas

Tokens — the Unit of Everything

Why models see subword fragments rather than characters or words, how BPE builds a vocabulary, and why the token is simultaneously the unit of cost, latency, memory, and context.

CoreEasy10 min readaitokenizationllmcost
Confidence

#Why this is the first page

A language model does not process text. It processes a sequence of integers, and everything downstream — how much GPU memory a request consumes, how long it takes, what it costs, whether it fits in the context window — is measured in those integers.

Get the token count wrong by 3× and every capacity estimate you make is wrong by 3×. This page exists so that doesn't happen.

#Why not characters or words?

Both obvious options fail, in opposite directions.

Characters (~100 symbols) • Tiny vocabulary, no unknown inputs ever • Sequences 4-5× longer • Attention is quadratic → 16-25× the cost • Model wastes capacity relearning spelling Whole words (500K+) • Short sequences, semantically clean units • Enormous embedding and output layers • Any unseen word becomes <UNK> — data loss • Typos, code, and morphology all break it
Both extremes fail. Subwords are the compromise that stuck.

Subword tokenization takes the middle: common words stay whole, rare words split into fragments, and any input can be represented as some sequence of pieces. Nothing is ever unrepresentable, and the sequences stay short.

   "The unhappiest tokenization"

   character:  T h e   u n h a p p i e s t   t o k e n i z a t i o n
               → 28 tokens

   subword:    "The" " un" "happiest" " token" "ization"
               → 5 tokens

   word:       "The" "unhappiest" "tokenization"
               → 3 tokens, but "unhappiest" is probably <UNK>

#How BPE builds the vocabulary

Byte-Pair Encoding (BPE) is the dominant algorithm, and its idea is one sentence: repeatedly glue together whichever two neighbouring pieces occur together most often, and keep the result as a new piece.

Run over a large body of text, that discovers common fragments on its own — "ing", "tion", " the" — without anyone writing rules. It happens once, before the model is trained, and produces a fixed, ordered list of merges. Encoding (text → token IDs) replays that list on new text; decoding (token IDs → text) just looks each ID up.

   1. Start with every byte as its own token (256 base tokens)
      → guarantees ANY input is representable, in any language,
        including emoji and malformed UTF-8

   2. Count every adjacent pair in the training corpus

   3. Merge the most frequent pair into a new token
        "t" + "h"  →  "th"        (very common in English)

   4. Repeat until you hit the target vocabulary size
        typically 32,000 - 200,000 tokens

   Result: an ordered list of merges. Encoding replays them
   greedily; decoding is a lookup. Both are deterministic.

The consequence: the vocabulary reflects the training corpus. A tokenizer trained mostly on English web text spends most of its vocabulary on English fragments. Everything else — other languages, code, unusual formats — gets fewer dedicated pieces, so the same content gets chopped into more, smaller tokens.

#Where tokenization leaks into behaviour

Tokenization explains a surprising number of otherwise-baffling model behaviours.

Arithmetic and digits. If 1234 tokenizes as 123 + 4 while 1235 tokenizes as 1 + 235, the model sees inconsistent structure for adjacent numbers. Newer tokenizers deliberately split digits individually to fix this, at the cost of longer sequences.

Character-level tasks. "How many r's in strawberry?" is hard because the model sees str + aw + berry, not letters. It has to have memorised the spelling rather than being able to look.

Trailing whitespace. "Hello" and "Hello " are different tokens with different continuations. Most word tokens carry their leading space with them ( world, not world). So a prompt ending in a space can measurably degrade output: the space is already used up, and the model must continue with a space-less token it rarely saw in that position during training.

Glitch tokens. Each token ID maps to an embedding — a learned vector of numbers the model uses as that token's meaning. Tokens that appeared in the tokenizer's training corpus but were rare or absent in the model's training data end up with essentially untrained embeddings: the model never learned what they mean. Feeding one produces bizarre, sometimes deranged output. The famous examples from GPT-2/3 era vocabularies came from Reddit usernames and scraping artifacts.

#Why the token is the unit of everything

Once text becomes tokens, every quantity in the system is denominated in them.

QuantityRelationship to tokens
CostBilled per input and output token, usually at different rates
LatencyOutput is generated one token at a time, so output time ≈ tokens × time-per-token; output length dominates
GPU memoryThe KV cache (memory the model keeps for each token already processed, covered later) grows linearly with every token of every live request
Context limitA hard cap measured in tokens
Rate limitsMeaningfully expressed as tokens/minute, not requests/minute
Attention costQuadratic in sequence length — 2× the tokens is 4× the attention work

That second point is why chat products cap history length, summarise older turns, or charge by conversation rather than message. It is a direct consequence of tokens accumulating.

#The practical rules

Count with the real tokenizer. Every provider publishes theirs. Estimating is fine for a napkin, never for a limit check.

Budget the context window explicitly. System prompt + retrieved documents + history + user message + room for the response. That last term is the one people forget, and running out of room mid-generation truncates the answer.

Put the stable content first. Prefix caching means an unchanged prefix can be reused rather than recomputed. The cache only matches from the very first token onward, so one changed token early on invalidates everything after it. Putting the system prompt first and volatile content (the user's message, fresh documents) last turns most of every request into a cache hit. That saves a large fraction of both cost and time-to-first-token — how long the user waits before the first word of the answer appears. This gets developed properly in the KV cache material.

Rate limit on tokens, not requests. A request generating 4,000 tokens costs two hundred times one generating 20. A requests-per-second (RPS) limit counts both as "one request", so it does not describe this workload at all.

#Check yourself

Why do models use subword tokens?Show answer
Characters make sequences 4–5× longer (attention is quadratic); whole words need huge vocabularies and turn unseen words into <UNK>. Subwords keep common words whole, split rare ones, and can represent anything.
How does BPE build a vocabulary?Show answer
Start from 256 bytes, repeatedly merge the most frequent adjacent pair into a new token until the target size (32K–200K). Encoding replays the merges; decoding is a lookup.
What is the working token estimate for English, and where is it wrong?Show answer
1 token ≈ 4 characters ≈ 0.75 words. Code is ~1.5× worse, JSON ~2×, non-Latin scripts up to 4×, base64 and UUIDs near worst case — measure with the real tokenizer.
Why are cost and context language-dependent?Show answer
The vocabulary reflects a mostly-English training corpus, so other languages need 3–5× more tokens: they pay more, fit less in the window and hit rate limits sooner.
Name two behaviours tokenization explains.Show answer
Inconsistent arithmetic (numbers split unevenly), letter-counting failures (the model sees str + aw + berry), trailing-whitespace degradation, and glitch tokens with untrained embeddings.
Which system quantities are measured in tokens?Show answer
Cost (input and output priced separately), latency (output length dominates), KV-cache memory, the context limit, rate limits, and attention cost (quadratic in length).
Why does a chat conversation get more expensive each turn?Show answer
History is re-sent as input every turn, so input dominates (~6× output in the example) and later turns cost far more — hence summarising history and prefix caching.
Why put stable content first in a prompt?Show answer
Prefix caching reuses an unchanged prefix instead of recomputing it, so a fixed system prompt first and volatile content last makes most of each request a cache hit.

#What to carry forward

  • Subword tokenization is the compromise between unrepresentable words and unmanageable vocabularies.
  • English prose ≈ 4 chars/token. Code, JSON, and non-Latin scripts are all worse, sometimes several times worse.
  • The vocabulary reflects its training corpus, which makes cost and context language-dependent.
  • Tokenization explains arithmetic weirdness, character-counting failures, and glitch tokens.
  • Tokens are the unit of cost, latency, memory, context, and rate limiting. Denominate every estimate in them.
  • Stable content first in a prompt, so the prefix can be cached.
00:00
/ 10m