Tokenization and Embeddings
How raw text becomes tokens with byte-level BPE, how tokens become vectors, and how rotary position embeddings (RoPE) tell a model where each token sits.
In Module 6 (Deep Learning) you saw why attention replaced recurrence. Before we can build attention, we need to answer a more basic question: a neural network operates on vectors of numbers, so how does a sentence like "Tokenization isn't trivial!" become something a Transformer can process? The answer has three stages: split text into tokens, map each token to a learned vector (an embedding), and inject information about position. Every one of these choices affects model quality, cost and failure modes, so they are worth understanding precisely.
The pipeline above is what happens to every prompt you send to an LLM. Text becomes integer IDs, IDs become vectors, position is applied inside attention, and the model's output is a score for every token in the vocabulary.
Why not words or characters?
| Approach | Vocabulary | Sequence length | Problem |
|---|---|---|---|
| Words | Hundreds of thousands, still incomplete | Short | Unknown words, typos, new names; huge embedding table |
| Characters or bytes | Around 100 to 256 | Very long | Attention cost grows with length; the model must learn spelling from scratch |
| Subwords | Tens of thousands to a few hundred thousand | Moderate | The practical sweet spot |
Subword tokenization keeps frequent strings ("the", " transformer") as single tokens while breaking rare strings into reusable pieces ("Tokenization" might become "Token" + "ization"). As a rule of thumb, English text averages around 4 characters, or three-quarters of a word, per token for GPT-style tokenizers. The exact ratio depends on the tokenizer and the text.
Byte Pair Encoding, step by step
Byte Pair Encoding (BPE), adapted for neural machine translation by Sennrich, Haddow and Birch (2015), builds a vocabulary bottom-up:
- Start with a base vocabulary of single symbols (characters, or all 256 bytes).
- Count every adjacent pair of symbols in the training corpus.
- Merge the most frequent pair into a new symbol and add it to the vocabulary.
- Repeat until the vocabulary reaches the target size.
To tokenize new text, apply the learned merges in the order they were learned. Here is a complete, runnable BPE trainer:
from collections import Counter
def get_pair_counts(words):
"""words: dict mapping a tuple of symbols to its corpus frequency."""
pairs = Counter()
for symbols, freq in words.items():
for a, b in zip(symbols, symbols[1:]):
pairs[(a, b)] += freq
return pairs
def merge(words, pair):
merged = {}
for symbols, freq in words.items():
out, i = [], 0
while i < len(symbols):
if i < len(symbols) - 1 and (symbols[i], symbols[i + 1]) == pair:
out.append(symbols[i] + symbols[i + 1]); i += 2
else:
out.append(symbols[i]); i += 1
merged[tuple(out)] = merged.get(tuple(out), 0) + freq
return merged
corpus = "low low low low low lower lower newest newest newest newest newest newest widest widest widest"
# start from characters; "_" marks the start of a word, like the leading space in GPT-style tokenizers
words = Counter(tuple("_" + w) for w in corpus.split())
merges = []
for step in range(8):
pairs = get_pair_counts(words)
best = max(pairs, key=pairs.get)
merges.append(best)
words = merge(words, best)
print(f"merge {step + 1}: {best[0]!r} + {best[1]!r} (count {pairs[best]})")
print("\nfinal segmentation:")
for symbols, freq in words.items():
print(f" {freq} x {' '.join(symbols)}")
def encode(word, merges):
symbols = list("_" + word)
for a, b in merges: # apply merges in the order they were learned
i = 0
while i < len(symbols) - 1:
if symbols[i] == a and symbols[i + 1] == b:
symbols[i:i + 2] = [a + b]
else:
i += 1
return symbols
print("\nunseen word 'lowest' ->", encode("lowest", merges))
The first merges are e+s and then es+t, because "est" appears in both "newest" and "widest". After eight merges, the unseen word "lowest" is encoded as ['_low', 'est']: two meaningful pieces, even though the word never appeared in training. That is the core benefit of subwords.
What production tokenizers add
- Byte-level base vocabulary. GPT-2 introduced BPE over raw UTF-8 bytes. Any string, including emoji, code and unseen scripts, can be encoded, so there is no "unknown token".
- Pre-tokenization. A regular expression first splits text into chunks (words, numbers, punctuation, whitespace) so that merges never cross those boundaries. Many tokenizers split numbers into individual digits or groups of up to three digits, which helps arithmetic.
- Special tokens such as end-of-text and the role markers of chat templates (for example, tokens that delimit system, user and assistant turns). These are how a chat model knows who is speaking.
- Vocabulary size has grown from about 32,000 (early Llama models) and 50,257 (GPT-2) to 100,000 to 256,000 in many recent models. Larger vocabularies shorten sequences, especially for code and non-English text, at the cost of a bigger embedding table.
Related algorithms include WordPiece (BERT) and Unigram LM (often via the SentencePiece library, used by T5 and many multilingual models). They differ in how they choose merges or prune a vocabulary, but the result is the same kind of subword vocabulary.
Try typing different kinds of text below. Notice how common English words stay whole while rare words, numbers and other scripts fragment:
Tokenization causes real failures
Many puzzling LLM behaviours trace back to tokens:
- Spelling and counting letters. "How many r's in strawberry?" is hard when the model sees
straw+berryrather than ten letters. - Arithmetic. If "1234" and "1235" are tokenized inconsistently, digit-level patterns are harder to learn.
- Cost and context in other languages. Under-represented languages split into more tokens, so the same content costs more and fills the context window faster. That is a fairness and affordability issue, revisited in Module 12 (AI Cost Optimization).
- Whitespace and formatting.
" hello"and"hello"are different tokens; trailing spaces in a prompt can subtly change outputs. - Glitch tokens. Strings that were frequent in the tokenizer's training data but rare in the model's training data can produce bizarre behaviour, because their embeddings were barely trained.
Research on tokenizer-free models that operate on bytes and learn their own groupings (for example "Byte Latent Transformer: Patches Scale Better Than Tokens", 2024) is active, but subword tokenizers remain the norm.
From token IDs to embeddings
The tokenizer outputs integers. The model's first layer is an embedding matrix , one row per vocabulary entry. Token ID simply selects row , which is mathematically the same as multiplying a one-hot vector by the matrix:
These vectors are learned by backpropagation along with every other weight. Nothing about them is hand-designed: through training, tokens that appear in similar contexts end up with similar vectors.
Worked example: a model with a 128,000-token vocabulary and has million embedding parameters. At the output, the model needs the reverse map: a matrix that turns the final hidden vector into one logit per vocabulary entry. Some models tie the input and output matrices (reusing E transposed), which saves those parameters and is common in smaller models; many large models keep them separate.
Geometry of embeddings
The idea that meaning can live in vector geometry was popularized by word2vec (Mikolov et al., 2013), with the famous approximate analogy . LLM input embeddings are a starting point: the real contextual meaning of a token is built up layer by layer, so the vector for "bank" in "river bank" and "bank account" diverges after a few layers. Hover over the map below to see static neighbours:
Specialized embedding models, trained so that whole sentences or documents with similar meaning map to nearby vectors, power semantic search and retrieval. You will use them in Module 10 (Building AI Applications).
Position: attention has no sense of order
Self-attention, which you will build in the next lesson, treats its input as a set: shuffle the tokens and each token's output is the same, just shuffled. "Dog bites man" and "man bites dog" would look identical. Position must be injected explicitly.
| Method | How it works | Used by |
|---|---|---|
| Sinusoidal (2017) | Add fixed sine and cosine waves of different frequencies to each embedding | Original Transformer |
| Learned absolute | Add a trained vector per position | GPT-2, BERT |
| ALiBi (2021) | Subtract a penalty proportional to distance from attention scores | Some models aimed at length extrapolation |
| RoPE (2021) | Rotate query and key vectors by position-dependent angles | Most current open LLMs |
Rotary position embeddings (RoPE)
RoPE ("RoFormer: Enhanced Transformer with Rotary Position Embedding", Su et al., 2021) does not add anything to the embedding. Instead, inside each attention layer, it splits each -dimensional query and key vector into pairs of dimensions and rotates pair at position by angle :
The base is typically 10,000, and is often raised (for example to 500,000) for long-context models. Pair 0 rotates by one radian per position; the last pairs rotate extremely slowly.
Rotation has a beautiful property. Write for the block-diagonal matrix that applies all these rotations at position . Rotation matrices are orthogonal and compose by adding angles, so , and therefore:
The score depends on the content of and and only on their relative offset , not on where they sit absolutely.
import numpy as np
def rope(x, pos, base=10000.0):
"""Rotate consecutive pairs of dimensions of x by angles pos * theta_i."""
d = x.shape[-1]
theta = base ** (-np.arange(0, d, 2) / d) # one frequency per pair: fast ... slow
angle = pos * theta
cos, sin = np.cos(angle), np.sin(angle)
x1, x2 = x[..., 0::2], x[..., 1::2] # the two coordinates of each pair
out = np.empty_like(x)
out[..., 0::2] = x1 * cos - x2 * sin # 2-D rotation of each pair
out[..., 1::2] = x1 * sin + x2 * cos
return out
rng = np.random.default_rng(0)
q, k = rng.normal(size=64), rng.normal(size=64)
# the score depends only on the OFFSET between positions, not on absolute position
for m, n in [(5, 2), (105, 102), (1005, 1002)]:
print(f"q at {m:4d}, k at {n:4d}: score = {rope(q, m) @ rope(k, n):.6f}")
print("norm preserved:", np.allclose(np.linalg.norm(rope(q, 37)), np.linalg.norm(q)))
All three scores are identical, because the offset is 3 each time. Why RoPE won:
- Relative position for free, with no extra parameters.
- Multiple frequencies. Fast-rotating pairs distinguish nearby positions; slow-rotating pairs encode coarse, long-range position, like the hands of a clock.
- Norm-preserving. Rotations do not change vector lengths, so they do not disturb the scale of attention scores.
- Compatible with the KV cache (lesson 8): each key is rotated once, at its own position, and never needs updating.
Extending context length
A model trained on 4,096-token sequences has never seen the rotation angles that positions beyond 4,096 produce in its slow dimensions. With and , the slowest pair has , a period of about 54,000 positions, so during 4K training it only ever sweeps a small arc of its circle. Feed it longer text and quality collapses. Practical fixes rescale positions or frequencies so long sequences map back into familiar angles, followed by a short fine-tune on long documents:
- Position interpolation (2023) linearly squeezes positions, replacing with for a scale factor , for example to go from 4K to 32K.
- NTK-aware scaling and YaRN ("YaRN: Efficient Context Window Extension of Large Language Models", 2023) scale different frequencies differently, preserving the fast dimensions that encode local order.
A long advertised context does not guarantee the model uses it well. You will see how to test that in lesson 7.
Common pitfalls
- Estimating cost in words. APIs bill tokens. Count with the model's actual tokenizer.
- Mixing tokenizers. A model only works with the exact tokenizer it was trained with; IDs mean nothing across models.
- Ignoring chat templates. Fine-tuned chat models expect their special role tokens. Formatting a prompt by hand without them degrades quality.
- Assuming embeddings are fixed word meanings. Input embeddings are context-free; meaning is built in later layers.
Hands-on exercise
- Train BPE. Run the trainer above with 20 merges on a paragraph of your own text. Which merges appear first, and why? Encode three words that do not appear in your paragraph.
- Real tokenizer (needs internet).
pip install tiktoken, then runenc = tiktoken.get_encoding("cl100k_base")and print[enc.decode([t]) for t in enc.encode(text)]for an English sentence, the same sentence in another language, a number like1234567, and a line of Python. Compute characters per token for each. Expected outcome: English and code are most compact; other scripts and long numbers fragment more. - RoPE experiment. Using
rope, setq = k(the same random vector) and plot the scorerope(q, 0) @ rope(k, n)fornfrom 0 to 200. Expected outcome: the score is highest at offset 0 and tends to decay, with oscillations, as distance grows. That is a soft recency bias built into RoPE. - Embedding parameters. For vocabulary sizes 32K, 128K and 256K at
d_model = 4,096, compute embedding parameters with and without weight tying. What fraction of a 1-billion-parameter model is each?
Key takeaways
- LLMs see tokens, not characters or words. Byte-level BPE learns merges from corpus frequencies and can encode any string.
- Tokenization explains many oddities: spelling, arithmetic, whitespace sensitivity, and higher cost for under-represented languages.
- An embedding layer is a learned lookup table of shape ; meaning emerges from training, and context is added by later layers.
- Attention is order-blind, so position must be injected. RoPE rotates queries and keys so scores depend on relative offset, and is the default in current open models.
- Context extension (position interpolation, YaRN) rescales RoPE so long positions stay in the range the model learned.
Next, in The Attention Mechanism, you will build scaled dot-product attention, multi-head attention, and the grouped-query variants that modern models use, and see how FlashAttention makes it fast.
Further reading
- Sennrich, Haddow and Birch, "Neural Machine Translation of Rare Words with Subword Units" (2015): BPE for neural models.
- Su et al., "RoFormer: Enhanced Transformer with Rotary Position Embedding" (2021): RoPE.
- Peng et al., "YaRN: Efficient Context Window Extension of Large Language Models" (2023).
- Andrej Karpathy, "Let's build the GPT Tokenizer" (video lecture, 2024) and the minbpe repository (github.com/karpathy/minbpe).
Save your progress and earn XP
Create a free account to take the quiz, track progress and unlock badges.