Tokenization and embeddings
- Beginner
- 25 min
- Lesson 2 of 3 in LLM foundations
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:How LLMs work
You will be able to
- Explain how byte-pair encoding builds a subword vocabulary and why that lets a model handle words it never saw whole.
- Explain why token count is not word count, and how language, code and numbers change the count and therefore cost and context budget.
- Describe how token IDs become learned embedding vectors, and the vocabulary-size trade-off.
- Choose the correct tokenizer to count tokens for a given model, and say why a count from another model family is only an estimate.
Ananya opens the usage report for the support assistant. A short word like “refund” is billed as one piece. A long town name like “Kancheepuram” is billed as several.
The same name is cut into the same pieces every time. Nobody told the system where to cut.
Why does a common word cost one piece and a rare one many, and how does a machine decide what counts as a piece?
Concept
A model cannot read letters. It computes on numbers. Tokenization is the step that turns text into a sequence of integer IDs, and it happens before anything in How LLMs work runs.
Modern tokenizersTokenizerThe component that splits text into tokens and maps them to integer ids, and back. Each model family has its own, so count tokens with the tokenizer of the model you call.Open the glossary entry split text into subword pieces. The most common recipe is Byte-Pair Encoding (BPE)Byte-pair encoding (BPE)A way to build a subword vocabulary by repeatedly merging the most frequent adjacent pair of symbols. Any text, even an unseen word, can then be written from a fixed set of pieces.Open the glossary entry (a data-compression algorithm that Sennrich et al., 2015 adapted to handle rare words in machine translation); WordPiece and Unigram are other subword algorithms, and SentencePiece is a library that can run BPE or Unigram. Each token ID is then looked up in a learned embedding tableEmbedding tableThe learned matrix with one row per token in the vocabulary. Looking up a token id returns its row, and the table is trained together with the rest of the model.Open the glossary entry, which returns a dense vector. Position informationPositional encodingExtra information that tells the model where each token sits in the sequence. Attention alone has no sense of order, so position must be injected.Open the glossary entry is added, and that sequence of vectors is the input to the transformer stack.
Here is that pipeline for one short input. The IDs and vector values are made up to show the shape; real ones come from the model’s own tokenizer and table.
| Stage | What it holds for refund policy |
|---|---|
| Raw text | refund policy |
| Tokens | refund · policy |
| Token IDs | [4821, 9137] |
| Embedding lookup | row 4821 → [0.12, -0.80, 0.33, …], row 9137 → [-0.41, 0.07, 0.65, …] |
| Plus position | each vector gets position 0 or 1 mixed in |
| Transformer input | two vectors, each the full embedding width (often thousands of numbers) |
Why It Matters
Everything you pay for and everything that limits you is counted in tokens: price, context window, rate limits, and latency. If you estimate in words or characters you will be wrong, sometimes by a lot, and the error is not the same for every language. Interviewers ask “how does the model handle a word it has never seen” and “why is token count not word count” because the answers show whether you understand the system underneath the API.
Mental Model
Tokenization is a LEGO set. The set holds a fixed number of pieces, from single bytes up to whole common words. Any text can be built from those pieces, even a word that never appeared in training, because worst case you build it from small pieces. Common words come as one big brick. Rare words, other scripts and unusual strings come as many small bricks, and you pay per brick.
Example
The word “unbelievable” might split into ["un", "believ", "able"]. The exact split depends on the tokenizer, so treat that as illustrative. A rare proper noun may split into many small pieces. Text in some non-English scripts needs many more tokens than the same sentence in English. Petrov et al. (2023) found that the same text translated into different languages can differ in tokenized length by up to 15 times in some cases.
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.
Technical Deep Dive
- BPE training: start from bytes or characters, repeatedly merge the most frequent adjacent pair in a training corpus, and record each merge. The final merge list is the vocabularyVocabularyThe fixed set of tokens a model can read and produce. A bigger vocabulary gives fewer tokens per text but a larger embedding table and output layer.Open the glossary entry. At run time the tokenizer applies the merges to new text, so unseen words fall back to smaller pieces.
- Different models, different vocabularies: each model family trains its own tokenizer. Examples from public sources: OpenAI’s tiktoken defines
gpt2with 50,257 tokens,cl100k_basewith a top token ID near 100k, ando200k_basenear 200k (tiktoken source, checked 2026-10-09). 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 vary and change, so always check the model you use. - Vocabulary-size trade-off: a bigger vocabulary means fewer tokens per text (cheaper and shorter sequences), but a bigger embedding table and a bigger output layer.
- Embeddings are learned: the embedding table is a matrix with one row per token. Its rows are trained jointly with the rest of the model, they are not hand-designed. The vector length is a model-specific number, typically in the thousands.
- Numbers and code: digits and symbols may be split in ways that do not line up with place value or syntax. That is a main reason models make spelling and arithmetic slips, and why tools (code or a calculator) are the robust fix.
Watching BPE learn: a tiny worked trace
Take a toy training corpus of four words and their counts: low ×5, lower ×2, newest ×6, widest ×3. Start with every word split into single characters. Each round, find the most frequent adjacent pair and merge it into one symbol.
| Round | Most frequent pair (count) | New symbol | newest is now | widest is now |
|---|---|---|---|---|
| 0 | start | none | n e w e s t | w i d e s t |
| 1 | e + s (9) | es | n e w es t | w i d es t |
| 2 | es + t (9) | est | n e w est | w i d est |
| 3 | l + o (7) | lo | n e w est | w i d est |
| 4 | lo + w (7) | low | n e w est | w i d est |
Two pairs were tied at 9 in round 1 and two at 7 in round 3; the tie is broken arbitrarily, here by first appearance. The recorded merge list is the tokenizer. Now feed it a word it never saw in training, lowest:
| 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 |
The unseen word is built from two pieces the tokenizer already knows. That is why byte-level BPE never meets an “unknown word”, and why a word made of rare pieces costs more tokens.
Vocabulary size, side by side
| 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 |
How big is the table? Illustrative arithmetic
A 128,000-token vocabulary with 4,096-dimension vectors has values in the embedding table alone. These numbers are illustrative, not a specific model. The point is that vocabulary size shows up directly in model size.
Code
# Counting with the tokenizer that matches your model (OpenAI-family example).
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]) # run it: the split is tokenizer-specificThe same string through another model family’s tokenizer can give a different count. For billing and context budgets, use the tokenizer or token-counting tool your provider documents for that exact model (check the provider’s docs), and compare with the usage numbers returned in real responses.
Real-World Application
Token counting drives cost estimation and context-window budgeting in every production LLM app. Teams pricing a feature must account for non-English users often paying more tokens, and so more cost and latency, for the same amount of text. A common safe workflow: sample real traffic in each language you support, count with the production model’s tokenizer, and budget from those measurements instead of a global “4 characters per token” rule of thumb. When you switch models, re-measure, because the tokenizer can change too. For example, Anthropic’s Claude Sonnet 5.5 migration guide says the same text produces about 30% more tokens than on Claude Sonnet 4.6, depending on content, and tells you to recount and revisit max_tokens and cost (Anthropic docs, checked 2026-10-09).
Interview Perspective
Expect: “difference between a token and a word”, “why does token count matter for cost”, “explain BPE at a high level”. The mistakes to avoid are assuming 1 token = 1 word, or that tokenization is language-neutral.
Provenance: Common industry pattern. Standard topics for ML and GenAI roles, not a verified list for any named company.
Practice Questions
- Basic: What problem does subword tokenization solve that word-level tokenization does not?
- Intermediate: Why would a bigger vocabulary reduce token count but increase model size?
- Advanced: Why might the same sentence cost more tokens in Hindi than in English?
- Product-Company: You are billing customers per API call, not per token. Why is that a risky pricing model, and how would you fix it?
Activity
Guess how a BPE tokenizer might split "internationalization", then run it through a real tokenizer (for example with the code above) and compare. Explain any difference by thinking about which pieces would be frequent in training text.
Homework
Take one paragraph and its translation in a non-Latin script. Count tokens for both with your chosen model’s tokenizer. Compute the ratio and write two sentences on the cost implication for a global product. Use the rough “4 characters per token for English” rule only as a sanity check and label it as an estimate.
Quick Revision
- Tokenization = text to subword tokens (BPE) to IDs to learned embedding vectors.
- Vocabularies differ per model family and change over time; recent ones are often 100k or more (some above 200k), and some older ones are about 50k.
- Vocab size trades tokens-per-text against embedding-table size.
- Non-English text, code and numbers often cost more tokens.
- Count with the tokenizer of the model you will call.
Check yourself
- Walk-through: Why does the same sentence cost different token counts across model families, and what follows for cost and context budgeting?
- Variation: A user pastes 20 pages of Hindi text. Why might cost and latency surprise you, and how would you budget?
- Common misconception: Treating a token as a word, or as a fixed 4 characters for every language.
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
Byte-Pair Encoding tokenization (opens in a new tab)Essential
Walks through BPE training and tokenization with code, so you can repeat the toy trace in this lesson on a bigger corpus.
Educational videos
Let's build the GPT Tokenizer (opens in a new tab)
A long lecture that builds a GPT-style tokenizer from scratch and explains why tokenization causes odd behaviour with spelling, numbers and code.
Hands-on
minbpe: minimal, clean code for byte-level BPE (opens in a new tab)
A small readable BPE implementation with exercises; reading the training loop makes the merge list in this lesson concrete.
More for this module: LLM foundations resources
Practice
Test what you just read. Quizzes and cards are grouped by module: LLM foundations.
Check yourself10 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.