Slides · LLM foundations
Tokenization and embeddings
1 / 27
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
Worked example
One input through the pipeline
The IDs and vector values are made up to show the shape.
| Stage | What it holds for refund policy |
|---|---|
| Tokens | refund and policy |
| Token IDs | [4821, 9137] |
| Lookup | row 4821, row 9137 of the table |
| Plus position | position 0 and 1 mixed in |
| Transformer input | two 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.
Sources[1] Neural Machine Translation of Rare Words with Subword Units[2] Tokenization algorithms
Process
How BPE is trained
- Start with every word split into single characters (or bytes).
- Count every adjacent pair across the training corpus.
- Merge the most frequent pair into one new symbol and record the merge.
- 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.
| Round | Most frequent pair (count) | New symbol | newest is now |
|---|---|---|---|
| 0 | start | none | n e w e s t |
| 1 | e + s (9) | es | n e w es t |
| 2 | es + t (9) | est | n e w est |
| 3 | l + o (7) | lo | n e w est |
| 4 | lo + w (7) | low | n e w est |
Counts: e+s appears in newest (6) and widest (3), so 6+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.
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 applying | lowest 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.
Compare
Tokens are not words
| Input | Typical effect on token count |
|---|---|
| Common English word | often one token |
| Rare word or proper noun | several small pieces |
| Some non-English scripts | many more tokens than the English equivalent |
| Code and numbers | digits 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.
Source[3] 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=200600=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| Variable | Meaning | Illustrative value |
|---|---|---|
| vocabulary size | number of rows, one per token | 128,000 |
| embedding width | numbers per vector | 4,096 |
Illustrative, not a specific model. Vocabulary size shows up directly in model size.
Compare
Vocabulary size trade-off
| Aspect | Small vocabulary | Large vocabulary |
|---|---|---|
| Tokens for the same text | more | fewer |
| Sequence length and attention cost | longer | shorter |
| Embedding table and output layer | smaller | larger |
| Rare words and scripts | split into many pieces | more 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
gpt2with 50,257 tokens,cl100k_base(special-token IDs from 100,257 to 100,276) ando200k_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.
Sources[4] 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
Even a provider counting tool describes its result as an estimate that can differ by a small amount.
Source[6] 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_encodingchooses a vocabulary. The name must match the model.encodereturns the token IDs;decodeon 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.
Sources[7] tiktoken: a fast BPE tokeniser for use with OpenAI's models[4] 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,000 tokens a day, before any price change.
Rule: re-measure on every model switch, because the tokenizer can change too.
Compare
Common mistakes
| Mistake | Better practice |
|---|---|
| 1 token = 1 word | Count with a tokenizer; words and tokens differ |
| 4 characters per token for every language | Sample real traffic per language and measure |
| Reusing a count from another model family | Recount with the model you will call |
| Pricing per API call when users send different amounts of text | Meter or bound tokens |
| Assuming the tokenizer is language-neutral | Budget 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)
Neural Machine Translation of Rare Words with Subword Units (opens in a new tab)
Rico Sennrich, Barry Haddow, Alexandra Birch2016ACL 2016Paper
arXiv 1508.07909 (opens in a new tab)https://arxiv.org/abs/1508.07909
Used for Byte-pair encoding was adapted to represent rare and unseen words as sequences of subword units.
Tokenization algorithms (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/transformers/en/tokenizer_summary
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.
Language Model Tokenizers Introduce Unfairness Between Languages (opens in a new tab)
Aleksandar Petrov, Emanuele La Malfa, Philip H.S. Torr, Adel Bibi2023NeurIPS 2023Paper
arXiv 2305.15425 (opens in a new tab)https://arxiv.org/abs/2305.15425
Used for The same text translated into different languages can differ in tokenized length by up to 15 times in some cases.
tiktoken_ext/openai_public.py (encoding definitions) (opens in a new tab)
OpenAI2026Repository
https://raw.githubusercontent.com/openai/tiktoken/main/tiktoken_ext/openai_public.py
Used for OpenAI's public encodings (gpt2 with 50,257 tokens, cl100k_base, o200k_base) are separate vocabularies.
Introducing Meta Llama 3: The most capable openly available LLM to date (opens in a new tab)
Meta AI2024Article
https://ai.meta.com/blog/meta-llama-3/
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)
Token counting (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/build-with-claude/token-counting
Used for Provider token counting is per model, and the returned count is an estimate.
tiktoken: a fast BPE tokeniser for use with OpenAI's models (opens in a new tab)
OpenAI2026Repository
https://github.com/openai/tiktoken
Used for get_encoding("o200k_base") selects an OpenAI encoding for counting.
Claude Sonnet 5.5 migration guide (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/models/sonnet-5-5/migration-guide
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.
Keys: ← → move, Home End first and last, F full screen.