Slides · LLM foundations

Tokenization and embeddings

Tokenization and embeddings

How text becomes numbers a model can compute on, and why that decides your cost and context budget.

By the end you can explain BPE, explain why tokens are not words, describe the embedding lookup, and pick the right tokenizer for counting.

Concept

Why this matters

  • Price, context window, rate limits and latency are all counted in tokens.
  • Estimating in words or characters is wrong, and wrong by a different amount per language.
  • Opening question: why does “refund” cost one piece and “Kancheepuram” several, when nobody told the system where to cut?

Concept

Mental model: a LEGO set

  • The set has a fixed number of pieces, from single bytes up to whole common words.
  • Any text can be built from the pieces, even a word never seen before.
  • Common words come as one big brick; rare words and other scripts come as many small bricks.
  • You pay per brick.

Diagram

From text to transformer input

Diagram: Raw text goes through the tokenizer, which applies its learned merges to produce integer token IDs.

Raw text

BPE tokenizer
(apply learned merges)

Token IDs

Embedding table lookup

Token vectors

+ positional encoding

Input to transformer

Diagram summary: Raw text goes through the tokenizer, which applies its learned merges to produce integer token IDs. Each ID selects a row of the embedding table, giving one vector per token. Position information is added, and the resulting vectors are the input to the transformer.

Worked example

One input through the pipeline

The IDs and vector values are made up to show the shape.

StageWhat it holds for refund policy
Tokensrefund and policy
Token IDs[4821, 9137]
Lookuprow 4821, row 9137 of the table
Plus positionposition 0 and 1 mixed in
Transformer inputtwo vectors, each the full embedding width

The tokenizer attaches the space to the word that follows it, so the second token is policy with a leading space. That is why policy and policy are different tokens.

Concept

Why subwords, not words

  • A word-level vocabulary is fixed, so every unseen word becomes “unknown”.
  • Sennrich et al. fixed this for translation by encoding rare words as sequences of subword units.
  • Byte-pair encoding (BPE) is the common recipe. WordPiece and Unigram are other algorithms; SentencePiece is a library that runs BPE or Unigram on raw text.
  • Result: common words stay whole and rare words fall back to smaller pieces.
  • Plain character-based BPE can still map a character outside its base vocabulary to an unknown token. Byte-level BPE starts from the 256 byte values, so every string can be tokenized.

Sources1 Neural Machine Translation of Rare Words with Subword Units2 Tokenization algorithms

Process

How BPE is trained

  1. Start with every word split into single characters (or bytes).
  2. Count every adjacent pair across the training corpus.
  3. Merge the most frequent pair into one new symbol and record the merge.
  4. Repeat until the vocabulary reaches the target size.

The ordered merge list is the tokenizer.

Worked example

Worked trace: four rounds

Toy corpus: low x5, lower x2, newest x6, widest x3.

RoundMost frequent pair (count)New symbolnewest is now
0startnonen e w e s t
1e + s (9)esn e w es t
2es + t (9)estn e w est
3l + o (7)lon e w est
4lo + w (7)lown e w est

Counts: e+s appears in newest (6) and widest (3), so 6+3=96 + 3 = 9. After round 2, est appears in the same two words, so es+t is also 9. l+o appears in low (5) and lower (2), so 7. Ties (9 and 9 in round 1, 7 and 7 in round 3) are broken here by first appearance.

Diagram

Try it: what changes when you add a space?

This demo uses a different toy merge list from the worked trace. Try low, then low low. Look for the leading space marker in the token list. Compare the result with lowlow and explain why the token counts differ.

A toy tokenizer

Text summary

This is a toy tokenizer, not the tokenizer of any real model. Its small vocabulary and its merge list were written by hand to show the idea, so the counts it gives say nothing about real token counts.

You type some text and the tool shows the pieces it splits into, each with a number called an id, plus a count of tokens. It works like byte-pair encoding. It starts from single characters, then joins neighbouring pairs in a fixed order, so a common word such as “the” ends up as one piece and a rarer word ends up as several smaller ones. A word like “unbelievable” splits into a handful of pieces here.

The toy only knows lowercase letters, digits and a few punctuation marks. Any other character, such as a capital letter or “é”, is not dropped. Real tokenizers do include capitals, so do not read a capital letter as extra cost in a real model. It is replaced by its raw bytes, one token per byte, and those tokens are labelled “byte fallback”. That is why a short word with an accent can cost more tokens than a longer plain one.

Without JavaScript you see only this summary. With it you can type your own text, try the examples, and read the count in the status line under the tokens.

The interactive version needs JavaScript. The text summary above says what it shows.

Worked example

Applying the merges to an unseen word

lowest was never in the corpus. Replay the merges in order.

After applyinglowest becomes
nothing (characters)l o w e s t
merge 1 (e + s)l o w es t
merge 2 (es + t)l o w est
merge 3 (l + o)lo w est
merge 4 (lo + w)low est

Two known pieces build the new word. A word made of rare pieces would need more tokens.

Check yourself

Check: the unseen word

Using the four merges above, how would lower be split, and what happens to a word with no learned merges at all, such as a string of unusual symbols?

Answer

lower becomes low + e + r: merges 3 and 4 apply, and nothing merges e or r with a neighbour. A string with no applicable merges stays as single base symbols, so it still encodes, just with many tokens. This is guaranteed for byte-level BPE, whose base vocabulary is the 256 byte values. A plain character-level BPE can map a character missing from its base vocabulary to an unknown token.

Source2 Tokenization algorithms

Compare

Tokens are not words

InputTypical effect on token count
Common English wordoften one token
Rare word or proper nounseveral small pieces
Some non-English scriptsmany more tokens than the English equivalent
Code and numbersdigits and symbols split in ways that ignore place value or syntax

Petrov et al. (2023) found the same text translated into different languages can differ in tokenized length by up to 15 times in some cases. The split of “unbelievable” into un, believ, able is illustrative; it depends on the tokenizer.

Source3 Language Model Tokenizers Introduce Unfairness Between Languages

Worked example

Worked example: what the ratio means for cost

Illustrative numbers, not measured: one English paragraph counts 200 tokens and its translation in a non-Latin script counts 600 tokens.

ratio=600200=3.0\text{ratio} = \frac{600}{200} = 3.0
  • The same message costs about three times as many input tokens.
  • It also uses about three times as much of the context window, and takes more time to process.
  • Budget from counts you measure on real traffic in each language, not from a global “4 characters per token” rule.

Homework asks you to measure this on a real paragraph and label any rule of thumb as an estimate.

Concept

Numbers and code

  • Digits and symbols may split in ways that do not match place value or syntax.
  • That is one reason models can slip on spelling and arithmetic.
  • The robust fix is a tool: run code or a calculator instead of asking the model to do digit work.

Concept

Token IDs become vectors

  • The embedding table is a matrix with one row per token in the vocabulary.
  • Looking up ID 4821 means reading row 4821: a dense vector.
  • The rows are learned together with the rest of the model, not hand-designed.
  • Vector length is model-specific, typically in the thousands.

Math

How big is the table?

table values=vocabulary size×embedding width\text{table values} = \text{vocabulary size} \times \text{embedding width}
VariableMeaningIllustrative value
vocabulary sizenumber of rows, one per token128,000
embedding widthnumbers per vector4,096
128,000×4,096=524,288,000 values128{,}000 \times 4{,}096 = 524{,}288{,}000\ \text{values}

Illustrative, not a specific model. Vocabulary size shows up directly in model size.

Compare

Vocabulary size trade-off

AspectSmall vocabularyLarge vocabulary
Tokens for the same textmorefewer
Sequence length and attention costlongershorter
Embedding table and output layersmallerlarger
Rare words and scriptssplit into many piecesmore likely to get their own piece

No free lunch: fewer tokens per text is paid for with a bigger table.

Concept

Vocabularies differ by model family

  • OpenAI’s tiktoken defines gpt2 with 50,257 tokens, cl100k_base (special-token IDs from 100,257 to 100,276) and o200k_base (special-token IDs 199,999 and 200,018).
  • Meta’s Llama 3 uses a 128K-token vocabulary and reports up to 15% fewer tokens than Llama 2 (Meta, 2024-04-18).
  • Newer models trend toward larger vocabularies, but sizes change. Check the model you use.

Sources4 tiktoken_ext/openai_public.py (encoding definitions)5 Introducing Meta Llama 3: The most capable openly available LLM to date

Diagram

Choosing the tokenizer to count with

Diagram: Start by asking which model you will call.

Own tokenizer or provider tool available

Only a different family's tokenizer

Need a token count

Which model will you call?

Use that model's tokenizer or the provider's counting tool

Exact enough for budgets

Only another family's tokenizer available

Treat the count as an estimate

Compare with usage numbers in real responses

Diagram summary: Start by asking which model you will call. If you can use that model’s own tokenizer or its provider’s token-counting tool, the count is dependable for budgets. If you only have another family’s tokenizer, the number is an estimate. In both cases, compare with the usage numbers returned in real responses.

Even a provider counting tool describes its result as an estimate that can differ by a small amount.

Source6 Token counting

Code

Counting with tiktoken

Python

import tiktoken

enc = tiktoken.get_encoding("o200k_base")   # pick the encoding for YOUR model
text = "unbelievable"
ids = enc.encode(text)
print(len(ids), [enc.decode([i]) for i in ids])
  • get_encoding chooses a vocabulary. The name must match the model.
  • encode returns the token IDs; decode on each ID shows its piece.
  • Run it: the split is tokenizer-specific.
  • This fits OpenAI-family models. For other families use the tokenizer or counting tool their provider documents.

Sources7 tiktoken: a fast BPE tokeniser for use with OpenAI's models4 tiktoken_ext/openai_public.py (encoding definitions)

Worked example

When the model changes, the count changes

Anthropic’s Claude Sonnet 5.5 migration guide says the same text produces about 30 percent more tokens than on Claude Sonnet 4.6, depending on content. It tells you to recount and to revisit max_tokens and cost.

Illustrative arithmetic: a prompt that counted 100,000 tokens a day on the old model becomes about 100,000×1.30=130,000100{,}000 \times 1.30 = 130{,}000 tokens a day, before any price change.

Rule: re-measure on every model switch, because the tokenizer can change too.

Source8 Claude Sonnet 5.5 migration guide

Compare

Common mistakes

MistakeBetter practice
1 token = 1 wordCount with a tokenizer; words and tokens differ
4 characters per token for every languageSample real traffic per language and measure
Reusing a count from another model familyRecount with the model you will call
Pricing per API call when users send different amounts of textMeter or bound tokens
Assuming the tokenizer is language-neutralBudget per language

Check yourself

Check: the Hindi paste

A user pastes 20 pages of Hindi text. Why might cost and latency surprise you, and how would you budget?

Answer

Non-English scripts often need many more tokens than English for the same content, so input cost, context use and processing time can all be higher than a word or character estimate suggests. Budget by sampling real traffic in that language, counting with the production model’s tokenizer, and re-measuring when the model changes.

Check yourself

Check: bigger vocabulary

Why does a bigger vocabulary reduce token count but increase model size?

Answer

More text is covered by whole-word or longer pieces, so the same text needs fewer tokens. But the embedding table has one row per token and the output layer scores every token, so both grow with vocabulary size.

Summary

Recap

  • Text becomes subword tokens (BPE merges), then IDs, then learned embedding vectors.
  • Unseen words are built from known pieces; byte-level BPE can encode any string, so it has no unknown word.
  • Tokens are not words: language, code and numbers change the count, and so cost and context use.
  • Vocabulary size trades tokens per text against table size.
  • Count with the tokenizer of the model you will call, and re-measure when the model changes.

References

References & Sources (1 of 2)

  1. Neural Machine Translation of Rare Words with Subword Units (opens in a new tab)

    Rico Sennrich, Barry Haddow, Alexandra Birch2016ACL 2016Paper

    Used for Byte-pair encoding was adapted to represent rare and unseen words as sequences of subword units.

  2. Tokenization algorithms (opens in a new tab)

    Hugging Face2026Documentation

    Used for Byte-level BPE uses 256 byte values as its base vocabulary so no <unk> is needed; SentencePiece is a library applying BPE or Unigram.

  3. Language Model Tokenizers Introduce Unfairness Between Languages (opens in a new tab)

    Aleksandar Petrov, Emanuele La Malfa, Philip H.S. Torr, Adel Bibi2023NeurIPS 2023Paper

    Used for The same text translated into different languages can differ in tokenized length by up to 15 times in some cases.

  4. tiktoken_ext/openai_public.py (encoding definitions) (opens in a new tab)

    OpenAI2026Repository

    Used for OpenAI's public encodings (gpt2 with 50,257 tokens, cl100k_base, o200k_base) are separate vocabularies.

  5. Introducing Meta Llama 3: The most capable openly available LLM to date (opens in a new tab)

    Meta AI2024Article

    Used for Llama 3 uses a 128K-token vocabulary and reports up to 15% fewer tokens than Llama 2.

References

References & Sources (2 of 2)

  1. Token counting (opens in a new tab)

    Anthropic2026Documentation

    Used for Provider token counting is per model, and the returned count is an estimate.

  2. tiktoken: a fast BPE tokeniser for use with OpenAI's models (opens in a new tab)

    OpenAI2026Repository

    Used for get_encoding("o200k_base") selects an OpenAI encoding for counting.

  3. Claude Sonnet 5.5 migration guide (opens in a new tab)

    Anthropic2026Documentation

    Used for Claude Sonnet 5.5 produces about 30 percent more tokens than Sonnet 4.6 for the same text, so recount and revisit max_tokens and cost.