Tokens, vocabulary and learned representations
easy 8 minThe input pipeline changes representation twice.
The typesetter cuts, numbers and sets the word.
A typesetter cuts a word into familiar pieces, reads the number on each drawer, then sets the matching blocks on the page.
Video lesson · Chapter 1 of 4
A label at the parts counter
Theory
Read or listen first. About 3 min.
What it is
The input pipeline changes representation twice. Segmentation turns text into vocabulary IDs. An embedding lookup turns those IDs into the vectors the model can transform. The first decision controls how many positions a string consumes; the second provides the learned starting values for those positions.
Why it exists
When the same part number costs more tokens in one model than another, inspect the segmentation. When a retriever confuses product meanings, inspect its learned representation. These problems occur at different boundaries and need different measurements.
Why one rare part number consumes three positions
Inside this chapter
Chapter sources- What is Tokenization?
- A tokenizer converts text into a sequence of vocabulary IDs and decodes those IDs back into text according to its rules. Words, spaces and punctuation can occupy different numbers of tokens. Count the actual prompt with the model’s tokenizer before enforcing a budget; counting visible words misses these differences.
Think of the tokenizer as a fixed dictionary plus a rulebook. Encoding walks the text and replaces each recognised piece with its dictionary number; decoding looks the numbers up and joins the pieces back together. Because the dictionary was learned from training text, common English words tend to be one piece while rare names, long numbers and other scripts break into several. A leading space is usually part of the piece, so
catat the start of a line andcatafter a word are different IDs.Example. Encode “42”, “ 42” and “0042” using the same tokenizer. Inspect the IDs rather than assuming every visible number occupies one position.
Another example. A support prompt that reads
Order #A-77193 failedlooks like four words, yet the order code alone can become five or six pieces once the hash, letter, hyphen and digit groups are split. Budget against the tokenizer's count, not the word count.Text in, IDs out, text back - 1Raw text
I can't wait - 2Split into pieces
I·can·'t·wait - 3Look up IDseach piece has one vocabulary number
- 4Model reads IDs4 positions in the context window
- 5DecodeIDs join back into the same string
Illustrative split. The deployed tokenizer decides the real pieces and IDs.
- BPE (Byte-Pair Encoding)
- Byte-pair encoding learns merge rules from frequent neighboring symbol pairs in training data. Encoding applies the learned ranking of merges to new input. A frequent prefix can become one unit while a rare identifier remains several pieces. Changing the vocabulary without retraining the model breaks the mapping between IDs and learned weights.
Training BPE is a counting loop: start from single bytes or characters, find the most frequent adjacent pair in the corpus, add the merged pair to the vocabulary as a new symbol, rewrite the corpus with it, and repeat until the vocabulary reaches its target size. Encoding new text replays the learned merges in rank order. Nothing about meaning is learned here; BPE only learns which fragments occur together often.
Example. With merge rules r+e→re and p+a→pa, applying them to r e p a yields re, pa. A further merge requires its own learned rule.
Watching merges build a token
Merge step Rule applied Pieces for repackPositions Start none repack6 1 r+e→rerepack5 2 p+a→parepack4 3 c+k→ckrepack3 Stop no rule joins re+parepack3 A teaching vocabulary with three learned rules. Each merge removes one position; a merge that was never learned cannot be applied. - SentencePiece & Unigram
- SentencePiece can train directly on raw text and supports more than one segmentation algorithm. Its unigram model scores alternative segmentations built from a learned vocabulary. Selecting a segmentation is a probabilistic modeling decision, distinct from greedily applying ranked BPE merges. Normalization choices affect the resulting token sequence.
Where BPE grows a vocabulary upwards by merging, the unigram model works downwards: it starts with a large candidate vocabulary, gives every piece a probability, and repeatedly drops the pieces whose removal hurts the likelihood of the training text least. At encoding time it considers every way to cut the string into known pieces and keeps the cut with the highest combined probability, usually found with a Viterbi search.
Example. “ab” may admit [ab] or [a,b]. Compare their products of piece probabilities under the unigram model to choose the higher-scoring segmentation.
Scoring two ways to cut the same string
Made-up probabilities for illustration. The unigram model compares whole segmentations; it does not apply merges greedily. - Vocabulary Size Impact
- A larger vocabulary may shorten sequences by representing common fragments as single tokens, but it also enlarges embedding and output tables. A vocabulary tuned on English prose can split product identifiers or other languages inefficiently. Compare token counts on representative traffic alongside model quality and memory use.
Vocabulary size is a trade between sequence length and table size. Every extra entry adds one row to the input embedding table and, in most decoder models, one row to the output projection as well, so the parameter cost is roughly twice vocabulary times width. The saving appears only on text that actually uses the new entries: a vocabulary grown on English web text may do little for log lines or Tamil support tickets.
Example. Doubling a vocabulary from 8,000 to 16,000 at width 256 adds 2,048,000 embedding parameters. Measure the corresponding length saving on real prompts.
Larger vocabulary
- Common fragments become single tokens
- Shorter sequences, so more evidence fits
- Fewer decoding steps per answer
What it costs
- Bigger embedding and output tables
- Rare entries get few training updates
- No gain on text the vocabulary was not tuned for
- Tiktoken in Practice
- Tiktoken maps text into the integer IDs used by particular OpenAI encodings. Inspect the IDs for leading spaces, punctuation and non-English strings. Choose the encoding for the actual model and distinguish local text counts from provider-reported usage, which can include message framing and tool definitions.
Local counting answers one question: how many tokens is this exact string under this encoding? The bill answers another: how many tokens did the provider process, including role markers, separators, system text, tool schemas and the reply. Keep both numbers and reconcile them on a sample of real requests before you set limits or forecast spend.
Example. Count tokens for the document text, then count again after wrapping the document in your complete message template. Explain the difference before estimating cost.
Why the local count and the bill differ
Count the fully rendered request, not just the user's text. - What are Embeddings?
- An embedding maps an item into a vector whose geometry reflects the training objective. A model trained for search should put questions near passages that answer them. Store the embedding model and normalization policy with each index. Equal dimensions alone do not make vectors from different models comparable.
An embedding is only meaningful relative to the model and objective that produced it. A search encoder is trained so that a question and the passage that answers it end up close together, typically measured by cosine similarity. Two different encoders can both output 768 numbers, yet their axes mean different things, so mixing them in one index silently breaks retrieval.
Example. A retrieval encoder should place “How do I cancel?” near the cancellation instructions. Compare that distance with an unrelated shipping passage.
Distances, not IDs, carry meaning
Illustrative scores from a retrieval encoder. Re-embed the whole index when the encoder or its normalisation changes. - Word2Vec to Modern Embeddings
- Word2vec learns word representations by predicting nearby words or a target given its context. A contextual encoder can represent “bank” differently in “river bank” and “bank account.” Sentence embedding models also need a way to pool token representations and a training objective that rewards useful sentence-level proximity.
Word2vec gives every word exactly one vector, so
bankcarries a blend of its river and money senses. Transformer encoders compute a fresh vector for every occurrence by attending to the surrounding words, then a pooling step (for example averaging, or a special summary token) turns the token vectors into one sentence vector. Sentence encoders are then trained with pairs or triplets so that useful neighbours end up close.Example. Encode “she deposited cash at the bank” and “they sat on the river bank.” The spelling matches while the supporting contexts differ.
One spelling, one or many vectors
Approach bankin a money sentencebankin a river sentenceSentence vector Word2vec (static) same vector same vector needs extra averaging Contextual encoder vector near deposit, cash vector near shore, water pooled from token vectors Sentence encoder contextual contextual trained so similar sentences sit close - Measuring tokenizer expansion
- Token costs and the usable space for evidence depend on the actual token IDs after template rendering. A fixed character allowance can systematically exclude users writing in a different script. Measure tokens for representative traffic in each supported language.
Expansion is the ratio of tokens to characters (or to tokens for a reference language) on the same content. Measure it per language and per content type from real traffic, then size context budgets and prices from the worst group you serve rather than the average. Otherwise the users writing in the most expensive script quietly get less evidence in every answer.
Example. If one translated manual needs 1,500 tokens and another needs 2,200, the same 2,000-token budget truncates only the latter. Record the lost evidence before comparing answer quality.
Same manual, same 2,000-token budget
Version Tokens needed Fits in 2,000? Evidence lost Manual A 1,500 yes none Manual B (translated) 2,200 no last 200 tokens cut The figures from the example above. The truncated version answers from less evidence, so compare quality only after fixing the budget.
How it works
Step through the idea, or press Play.
Part catalog. “repack”
Understand it
Worked example
Why one rare part number consumes three positions
- 1
“repack”
Use a teaching vocabulary with the pieces re, pa and ck. The real split depends on the deployed tokenizer and its learned merge rules.
- 2
[18, 54, 92]
The tokenizer emits three IDs for this example. Another encoding could give the entire word one ID, changing the sequence length before the model runs.
- 3
3 rows × d values
Each ID selects a learned row. After lookup, order and subsequent model layers help build contextual representations. An ID is an address, not a semantic distance.
Size of an embedding table
Follow the handoffs
- 1"repack"6 characters of catalogue text
- 2re · pa · ck3 learned pieces
- 3[18, 54, 92]3 vocabulary IDs
- 43 rows × d3 embedding vectors
Two changes of representation: segmentation sets the length, lookup sets the starting values.
Summary
The whole topic in one minute.
Vocabulary ordering is an implementation choice. Similarity depends on learned representations and the task used to train them.
When the same part number costs more tokens in one model than another, inspect the segmentation. When a retriever confuses product meanings, inspect its learned representation. These problems occur at different boundaries and need different measurements.