4.2.4Tokenization & Language Modeling

Vocabulary size tradeoffs

2,819 words13 min readdifficulty · medium

Why vocabulary size matters

When we tokenize text, we're making a compression-granularity tradeoff. A small vocabulary (say, 256 tokens for byte-level) treats every character separately. A large vocabulary (100K+ tokens) can represent entire common words or phrases as single tokens.

WHY this matters:

  1. Sequence length directly impacts transformer compute: O(n2d)O(n^2 d) for self-attention where nn is sequence length
  2. Embedding table size is V×dV \times d parameters where VV is vocabulary size
  3. Token granularity affects how well the model can generalize to rare/unseen words

The mathematics of the tradeoff

Let's derive the resource costs from first principles.

Embedding table cost

For vocabulary size VV and embedding dimension dd:

Embedding params=V×d\text{Embedding params} = V \times d

WHY: Each of the VV tokens needs a dd-dimensional dense vector representation.

WHAT this means: If V=5000V = 5000 and d=768d = 768 (BERT-base), that's 5000×768=3.84M5000 \times 768 = 3.84M parameters just for the embedding table. (If instead V=50000V = 50000, that's 50000×768=38.4M50000 \times 768 = 38.4M.) This grows linearly with VV.

Sequence processing cost

For sequence length nn, embedding dimension dd, and LL transformer layers:

Self-attention cost per layer: Attention cost=O(n2d)\text{Attention cost} = O(n^2 d)

WHY: The attention mechanism computes QKTQ K^T which is (n×d)×(d×n)=n×n(n \times d) \times (d \times n) = n \times n. Then attention-weighted values: (n×n)×(n×d)=n×d(n \times n) \times (n \times d) = n \times d. The n2n^2 term dominates.

Total forward pass cost: Total costLn2d+Lnd2\text{Total cost} \approx L \cdot n^2 d + L \cdot n d^2

The n2dn^2 d term (attention) and nd2n d^2 term (feedforward) both scale with sequence length.

WHAT this means: Doubling sequence length nn quadruples attention cost but only doubles feedforward cost. For long documents, attention dominates.

The breakeven analysis

When does a larger vocabulary save resources overall?

Memory cost comparison:

  • Small vocab (VsV_s): Embedding cost VsdV_s d, sequence length nsn_s, attention cost ns2d\propto n_s^2 d
  • Large vocab (VlV_l): Embedding cost VldV_l d, sequence length nln_l, attention cost nl2d\propto n_l^2 d

Large vocab wins if: (VlVs)dextra embedding params<(ns2nl2)dbatch countattention memory savings\underbrace{(V_l - V_s) d}_{\text{extra embedding params}} < \underbrace{(n_s^2 - n_l^2) d \cdot \text{batch count}}_{\text{attention memory savings}}

WHY this formula: The left side is the permanent parameter overhead of the larger vocabulary. The right side is the per-batch activation memory savings from shorter sequences. If you process many batches (training, high-throughput inference), the right side accumulates and can outweigh the left.

Figure — Vocabulary size tradeoffs

Common vocabulary size choices

Vocabulary Size Typical Use Case Pros Cons
256–512 Byte-level, multilingual Universal, no UNK tokens Very long sequences
8K-16K Early neural MT, smaller models Balanced, manageable embedding size Some rare words split
32K-50K GPT-2, BERT, RoBERTa Standard tradeoff, proven Struggles with rare technical terms
100K-250K Newer LMs, code models Short sequences, domain coverage Large embedding tables

Practical guidelines

Choosing vocabulary size for your use case:

  1. General-domain text (web, books): 32K-50K subword vocab (BPE/WordPiece)

    • WHY: Balances common word compression with rare word splitting
  2. Code models: 50K-100K vocab

    • WHY: Code has many unique identifiers, API names. Larger vocab reduces splitting of function names like get_user_profileget, _user, _profile
  3. Multilingual (100+ languages): 250K+ vocab OR byte-level

    • WHY: Each language needs its own frequent tokens. Byte-level avoids the explosion but pays sequence-length cost.
  4. Domain-specific (medical, legal): Train domain-specific vocab at 50K-100K

    • WHY: "Myocardial infarction" should be 1-2 tokens, not 6. Improves both efficiency and performance.
  5. Extremely long context (100K+ tokens): Smaller vocab (16K-32K) or hierarchical tokenization

    • WHY: With n2n^2 attention, every token counts. Better to have shorter sequences and split rare words.

Connections

  • 4.2.02-Byte-pair-encoding — BPE training produces different vocab sizes depending on number of merges
  • 4.2.03-WordPiece-and-SentencePiece — SentencePiece allows direct control of vocab size hyperparameter
  • 4.3.01-Transformer-attention-complexity — The O(n2)O(n^2) cost that vocabulary size indirectly impacts
  • 4.5.02-Embedding-layer-design — How embedding tables are implemented and optimized
  • 5.1.03-Memory-optimization-techniques — Flash Attention, gradient checkpointing reduce n2n^2 cost
  • 6.2.01-Multilingual-models — Why massive vocab sizes are needed for 100+ languages

Flashcards

#flashcards/ai-ml

What is the vocabulary size tradeoff in tokenization?
Smaller vocabulary → longer sequences (more attention cost) but fewer embedding parameters. Larger vocabulary → shorter sequences (less attention cost) but more embedding parameters. It's a resource allocation decision.
Why does sequence length matter more than vocab size for attention cost?
Attention cost is O(n2d)O(n^2 d) where nn is sequence length. Doubling sequence length quadruples attention cost. Embedding cost is only O(V×d)O(V \times d), linear in vocab size VV.
What is the embedding table parameter count formula?
Embedding parameters = V×dV \times d where VV is vocabulary size and dd is embedding dimension. For GPT-2 small (V=50257V=50257, d=768d=768), that's 38.6M parameters.
Why don't character-level models solve the vocabulary tradeoff?
They eliminate embedding table cost but explode sequence length (8-10x longer). Attention is O(n2)O(n^2), so this increases compute by ~64x. The tradeoff just moves from parameters to compute.
When does a larger vocabulary save resources?
When (VlVs)d<(ns2nl2)d×batch count(V_l - V_s) d < (n_s^2 - n_l^2) d \times \text{batch count}. The extra embedding params must be outweighed by accumulated attention memory savings over many batches.
What's a typical vocabulary size for code models vs. general text?
Code models use 50K-100K (many unique identifiers). General text uses 32K-50K. Code needs larger vocab to avoid splitting function/variable names into many tokens.
Why is the bottom 10% of vocabulary by frequency important?
Rare tokens (bottom 10%) should still appear 50-100+ times in training for good embeddings. Otherwise you waste parameters on noisy embeddings that don't generalize. This guides vocab size choice.
Recall Explain to a 12-year-old

Imagine you're texting a friend, but you only have a limited "dictionary" of pre-approved text shortcuts.

Small dictionary (256 shortcuts): You can only send individual letters like "h", "e", "l", "o". To say "hello" you send 5 messages. That's slow!

Medium dictionary (32,000 shortcuts): You have shortcuts for common words. "hello" is one shortcut, "how" is another, "are" is another. Now "hello how are you" is just 4 shortcuts. Much faster!

Huge dictionary (200,000 shortcuts): You have shortcuts for entire phrases like "hello how are you doing today". Super fast! But now your phone needs to store 200,000 shortcuts in memory. That takes up space.

The tradeoff: Small dictionary = send LOTS of messages (slow). Huge dictionary = your phone is full of shortcuts (eats memory). You want the "goldilocks" size: enough shortcuts to be fast, but not so many that your phone runs out of space.

For AI models, "sending messages" is like the computer processing each token. More tokens = more work (especially because the computer has to compare every token with every other token, which gets really slow). But storing shortcuts (the vocabulary) also takes memory. So we pick a size that's "just right" for the task!

Concept Map

larger V shortens

scales linearly

drives

quadratic with n

grows

affects

more per token

too large hurts

balanced by

balanced by

constrains

Vocabulary size V

Sequence length n

Embedding table V x d

Attention cost O n squared d

Rare word generalization

Information density per token

Goldilocks tradeoff

Inference compute

Parameter memory

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, is note ka core intuition ye hai ki vocabulary size choose karna ek "goldilocks problem" hai — na bahut chhota, na bahut bada, balki bilkul theek hona chahiye. Jab hum text ko tokenize karte hain, toh basically ek tradeoff kar rahe hote hain. Agar vocabulary chhoti rakhein (jaise 256 tokens byte-level ke liye), toh har character alag token banega, matlab sequence lambi ho jayegi — aur transformer ka self-attention cost O(n2d)O(n^2 d) hai, toh lambi sequence se compute bahut zyada badh jaata hai. Doosri taraf, agar vocabulary badi rakhein (100K+ tokens), toh sequence chhoti ho jayegi, par embedding table ka size V×dV \times d hone ki wajah se memory aur parameters bahut zyada kha jaate hain. Yahi fundamental tension hai.

Ab ye matter kyun karta hai? Kyunki resource allocation ki poori decision isi pe depend karti hai. Sochke dekho — V=5000V = 5000 aur d=768d = 768 pe embedding table sirf 3.84M parameters ka hai, par V=50000V = 50000 pe wahi 38.4M ho jaata hai, yaani seedha linear growth. Waise hi sequence length double karo toh attention cost 4 guna badh jaata hai (kyunki n2n^2 term dominate karta hai), jabki feedforward sirf double hota hai. Interesting baat ye hai ki jab vocabulary badhaate hain, toh average token length sublinear tarike se badhti hai — VV ko double karne se ˉ\bar{\ell} sirf 20-30% badhta hai, poore 2x nahi. Isiliye simple calculation se decide nahi hota.

Toh practically iska matlab ye hai ki bada vocabulary tabhi worthwhile hai jab uske extra embedding parameters ka permanent cost, shorter sequences se milne wale attention memory savings se kam ho. Real-world engineering mein — jaise koi model design karte time — yahi breakeven analysis batata hai ki apne use case ke hisaab se kaunsa vocabulary size lena chahiye. Agar tum long documents process kar rahe ho, toh attention cost dominate karega, isliye bada vocabulary faydemand ho sakta hai; par agar zyaadatar chhote texts hain, toh chhota vocabulary better hai. Ye samajhna important hai kyunki ye tumhe rattafication se aage le jaake, actual tradeoffs ke basis pe smart decisions lena sikhata hai.

Go deeper — visual, from zero

Test yourself — Tokenization & Language Modeling

Connections