Chapter 2: Tokenization & Embeddings
Learn how raw text is converted into numerical representations that neural networks can process. Master the tokenization algorithms (BPE, WordPiece, SentencePiece) that determine a model's vocabulary, understand how word embeddings capture semantic meaning in vector space, and explore positional encodings that give transformers a sense of word order.
- Topics
- 5
- Demos
- 2
- Videos
- 3
- Min read
- 37
Chapter Overview
Before an LLM can process text, it must convert characters into numbers. This seemingly simple step---tokenization---has profound implications for model performance, multilingual capability, and computational efficiency.
Tokenization sits at the intersection of linguistics and engineering. Break words into too-small pieces (individual characters) and the model must learn spelling from scratch. Keep words whole and the vocabulary explodes, making the output layer impossibly large. Modern tokenizers like BPE find a middle ground: common words stay whole ("the", "and") while rare words are split into meaningful subwords ("unhappiness" -> "un", "happiness").
Once tokenized, each token is mapped to a dense vector---an embedding---that captures its semantic meaning. Words with similar meanings cluster together in this high-dimensional space. Finally, since transformers process all tokens in parallel (unlike sequential RNNs), we must inject positional information so the model knows word order.
This chapter covers:
- Byte Pair Encoding (BPE): The dominant tokenization algorithm used by GPT, Llama, and most modern LLMs
- WordPiece & SentencePiece: Alternative algorithms used by BERT and multilingual models
- Token Vocabularies: How vocabulary size affects model performance and efficiency
- Word Embeddings: Dense vector representations that capture semantic relationships
- Positional Encodings: How transformers understand token order without recurrence
Chapter Roadmap
Click any topic to jump in
Byte Pair Encoding
The dominant tokenization algorithm — iteratively merging frequent character pairs to build a subword vocabulary.
WordPiece & SentencePiece
Alternative tokenizers using likelihood-based merges and language-agnostic byte processing.
Token Vocabularies
How vocabulary size, special tokens, and byte fallback affect efficiency and multilingual fairness.
Tokens become dense vectors that encode meaning and position
Word Embeddings
Dense vector representations that capture semantic similarity — from Word2Vec to contextual embeddings.
Positional Encodings
Injecting order information into transformers — sinusoidal, learned, RoPE, and ALiBi approaches.
Topics
5 topics in this chapter
A neural network only accepts numbers, so text must first be cut into pieces and each piece given an ID. The obvious cuts both fail. With whole words as units, the vocabulary runs into millions and every typo or new name becomes an unknown token. With single characters, a sentence turns into hundreds of positions, and the model must learn spelling before it can learn meaning. What we want is a vocabulary in which common words are single units and rare words break into reusable parts.
The previous chapter, Introduction to LLMs, treated the token as the basic unit of prediction without saying where tokens come from. This topic answers that question with the algorithm used by GPT-2, GPT-4, Llama, and most modern LLMs.
We start with the BPE training loop, which repeatedly merges the most frequent adjacent pair. Then we cover byte-level BPE, which starts from the 256 byte values so no input is ever unknown. Next we measure how token counts drive compute cost. We finish with the artifacts BPE leaves behind, from split numbers to miscounted letters.
Definition
Byte Pair Encoding (BPE) is a subword tokenization algorithm. It starts from a base vocabulary of characters or bytes and repeatedly adds a new token by merging the most frequent adjacent pair in the training corpus, until the target vocabulary size is reached. New text is encoded by applying the learned merges in the order they were learned.
In this topic
- 1BPE Algorithm
- 2Byte-Level BPE
- 3Tokenization and Compute Cost
- 4Tokenization Artifacts
BPE Algorithm
BPE training is a greedy loop over a corpus of word frequencies. First, split every word into single symbols, which form the base vocabulary. Second, count every adjacent pair of symbols, weighting each by its word's frequency. Third, merge the most frequent pair everywhere it occurs and add the merged symbol to the vocabulary. Repeat until the vocabulary reaches its target size, often 32,000 to 200,000. The ordered merge list is the tokenizer, and encoding new text replays those merges in order. Ties between equally frequent pairs are broken by a fixed rule, and a greedy choice can leave awkward splits in rare words.
BPE greedily maximizes compression: at each step, merging the most frequent pair reduces total sequence length by tokens. After merges from base vocabulary , the vocabulary is . The algorithm approximates minimum description length (MDL): where is the encoded corpus length under vocabulary .
Given the corpus: "low lower lowest", trace the first 3 BPE merges.
Byte-Level BPE
Character-level BPE has a gap: a character never seen in training, such as a rare script or emoji, has no token and becomes [UNK], losing information. GPT-2 closed the gap by running BPE over bytes instead of characters. Text is first encoded as UTF-8, so the base vocabulary is exactly the 256 possible byte values, and merges are learned on top of those. Every string is a byte sequence, so every string can be encoded and decoded exactly. The cost falls on text the merges rarely covered, which splits into many small pieces. Each non-Latin character is 2 to 4 bytes, and that affects multilingual fairness.
Starting from 256 byte values guarantees universal coverage because any Unicode character encodes as 1-4 UTF-8 bytes. The worst-case expansion is 4x: a 4-byte character becomes 4 tokens. The expected expansion for English is approximately x (ASCII maps to single bytes), while CJK characters average x (3-byte UTF-8). This asymmetry is the root cause of tokenizer bias across languages.
Why does byte-level BPE never produce an "unknown token"?
Tokenization and Compute Cost
Every token is a position the model must process, so tokenizer efficiency is a compute question. Self-attention compares every pair of positions, so its cost grows with the square of sequence length, while the feedforward layers grow linearly. A tokenizer that packs the same text into fewer tokens therefore saves money in training and inference and fits more text into a fixed context window. For English, good BPE vocabularies average about 1.3 tokens per word, against roughly 5 or 6 characters per word for a character-level model. The failure mode is uneven compression: text unlike the training corpus gets many more tokens.
Self-attention cost scales as where is sequence length. A tokenizer that reduces by factor saves in attention compute. For example, BPE compressing 5000 characters to 1300 tokens: attention cost is of character-level cost. This quadratic saving is why tokenizer efficiency directly impacts training and inference budgets.
"International" is 1 token in GPT-4 but 3 tokens in a character-level model. What is the compute difference?
Tokenization Artifacts
Because BPE splits text by frequency rather than meaning, it leaves visible artifacts. Numbers are split into chunks that depend on which digit groups happened to be common, so the same digits can be grouped differently in different numbers. Leading spaces are part of the token in GPT-style tokenizers, so "hello" and " hello" have different IDs. Letters inside a token are invisible to the model, which sees only the token ID. These artifacts explain some odd failures, such as miscounting letters, fumbling arithmetic on long numbers, or behaving differently when a prompt has a trailing space.
BPE tokenization is context-dependent at boundaries: "123" might tokenize as ["123"] but "1234" as ["12", "34"] because the merge history creates different split points. The number of possible tokenizations of a string of length with vocabulary is exponential: up to segmentations. BPE's deterministic greedy approach selects just one, which may not be optimal for downstream tasks.
Why do LLMs sometimes struggle with counting letters in a word like "strawberry"?
Theory Exercise
Problem:
A BPE tokenizer with vocabulary size 32,000 tokenizes English at 1.3 tokens/word but Japanese at 3.5 tokens/word. Why? What are the implications?
Hints:
- Think about the training data distribution for BPE
- Consider what happens to languages underrepresented in training
- Think about cost implications for different languages
Related Problems on PixelBank
BPE merges whatever pair is most frequent, but frequency is not the only sensible rule. A pair can be common simply because both halves are common. The letters "e" and "s" meet constantly without forming a meaningful unit. BPE also assumes the text has already been split into words at spaces. Chinese, Japanese, and Thai do not put spaces between words, and a tokenizer that depends on a language-specific word splitter cannot be applied to a hundred languages at once.
The previous topic, Byte Pair Encoding (BPE), built a vocabulary bottom-up by frequency. This topic covers the alternatives used by BERT, T5, and many multilingual models, and shows how each changes one design choice.
We start with WordPiece, which scores a merge by how much more often the pair occurs than chance predicts. Then comes SentencePiece, a toolkit that treats raw text, spaces included, as the input, so it needs no pre-tokenizer. Next we cover the Unigram model, which prunes a large vocabulary down instead of building one up. We finish by comparing the three.
Definition
WordPiece is a merge-based subword algorithm that picks the pair whose merge most increases training-data likelihood, which amounts to a frequency ratio. SentencePiece is a language-independent toolkit that treats input as a raw character stream with whitespace as an ordinary symbol, and trains either BPE or Unigram models. Unigram tokenization prunes a large candidate vocabulary using a probabilistic segmentation model.
In this topic
- 1WordPiece Algorithm
- 2SentencePiece
- 3Unigram Language Model
- 4BPE vs WordPiece vs Unigram
WordPiece Algorithm
WordPiece (Schuster and Nakajima, 2012), later used for BERT, builds its vocabulary with merges like BPE but chooses them differently. The score of a candidate pair is the frequency of the merged unit divided by the product of the frequencies of and . A pair whose halves are individually common but rarely adjacent scores low. A pair that almost always occurs together scores high, even if it is rare overall. Pieces that continue a word carry a "##" prefix, so word-initial and word-internal pieces have different IDs. At encoding time WordPiece takes the longest matching vocabulary entry from the left.
WordPiece scores pairs by , which is the pointwise mutual information (PMI) without the log. High PMI means and co-occur much more than chance predicts. This favors merging rare but highly correlated pairs over common but weakly associated ones, producing more linguistically meaningful subwords.
How does BERT tokenize "unhappiness"?
SentencePiece
SentencePiece (Kudo and Richardson, 2018) is a toolkit rather than a new merge rule. It trains either a BPE or a Unigram model directly on raw text, without first splitting it into words. Whitespace is treated as an ordinary symbol, written as a special underscore-like character, so it becomes part of the pieces. That makes tokenization lossless: decoding the pieces reproduces the exact original string, spaces included. It also means one tokenizer works across languages that do not use spaces. T5, ALBERT, XLNet, and the original Llama all used SentencePiece models. Rare characters still need a fallback, which is covered in the next topic.
SentencePiece treats the input as a raw byte/character stream with no language-specific tokenization. The key mathematical property: the encoding is reversible — for any string . This is achieved by treating whitespace as a regular character (encoded as the Unicode underscore) rather than a delimiter, eliminating the information loss that occurs when pre-tokenizing on spaces.
Why is SentencePiece better for multilingual models than standard BPE?
Unigram Language Model
The Unigram model (Kudo, 2018) works in the opposite direction from BPE. It starts with a large candidate vocabulary and prunes it. Each token has an independent probability, and a segmentation of a word scores the product of its token probabilities. The best segmentation is found by dynamic programming (the Viterbi algorithm). Training alternates between estimating token probabilities with expectation-maximisation and deleting the tokens whose removal hurts corpus likelihood least, until the target size is reached. Because it scores every segmentation, it can also sample alternative splits during training, a technique called subword regularisation.
The Unigram model finds the segmentation using the Viterbi algorithm in time. Unlike BPE which builds vocabulary bottom-up, Unigram prunes top-down: starting from a large vocabulary, it iteratively removes the token whose removal least decreases summed over all training sentences. The EM algorithm alternates between finding optimal segmentations and updating token probabilities.
Unigram model has P("un") = 0.01, P("happi") = 0.005, P("ness") = 0.02, P("unhappiness") = 0.0001. Which segmentation is preferred?
BPE vs WordPiece vs Unigram
The three algorithms differ in the direction of training and in the scoring rule. BPE builds up by merging the most frequent pair. WordPiece builds up by merging the pair with the highest likelihood gain, a frequency ratio. Unigram prunes down from a large set using a probabilistic model. BPE and WordPiece encode deterministically, while Unigram can sample several segmentations, which acts as data augmentation. At large vocabularies the downstream quality differences are small. The bigger decisions are vocabulary size, byte fallback, and the language mix of the tokenizer's training data. BPE dominates today partly because GPT-2 and tiktoken popularised it.
BPE and WordPiece produce deterministic tokenizations. Unigram can sample from multiple valid segmentations weighted by probability, acting as a regularizer during training. This stochasticity has been shown to improve robustness by - on downstream tasks, analogous to dropout: the model cannot rely on a fixed tokenization and must learn representations robust to different subword boundaries.
Which tokenizer would you choose for a new multilingual LLM?
Theory Exercise
Problem:
Design a tokenizer for a multilingual model that must support English, Chinese, Arabic, and code. What algorithm, vocabulary size, and preprocessing choices would you make?
Hints:
- Consider that Chinese has no spaces between words
- Arabic is right-to-left with complex morphology
- Code has special characters and indentation
Related Problems on PixelBank
Once you have a tokenizer algorithm, you still have to decide how many tokens it should learn, and that single number pulls in opposite directions. A small vocabulary keeps the embedding table small but chops text into long sequences, which costs attention compute and context space. A large vocabulary shortens sequences but adds millions of parameters, and many of its rare tokens are seen too seldom to be learned well. The same number also decides which languages are cheap to process and which are expensive.
The previous topic, WordPiece & SentencePiece, compared the algorithms that build a vocabulary. This topic looks at what goes inside the vocabulary and what its size and makeup cost.
We start with the size trade-off, measured in embedding parameters and sequence length. Then we cover special tokens such as start, end, padding, and mask, which control model behaviour rather than carry text. Next comes fertility, the number of tokens per word, and the unequal price it sets across languages. We finish with byte fallback, the safety net that guarantees any character can be encoded.
Definition
A token vocabulary is the fixed set of units, text pieces plus special control tokens, that a model can read and emit. Each unit has its own row in the embedding matrix and in the output layer. Its size and training corpus set the model's parameter cost, its sequence lengths, and its fertility, meaning tokens per word, in each language.
In this topic
- 1Vocabulary Size Tradeoffs
- 2Special Tokens
- 3Vocabulary and Multilingual Efficiency
- 4Byte Fallback
Vocabulary Size Tradeoffs
Vocabulary size sets two costs that move in opposite directions. The input embedding matrix has parameters, where is the model width, and an untied output layer adds another , so doubling doubles both. A larger vocabulary, though, gives each text fewer tokens, which saves attention compute and context space. It also stores common multi-character strings as single units. The failure mode at the large end is undertrained rows: rare tokens get too few gradient updates to learn good embeddings. Modern LLMs settle between about 32,000 and 256,000 tokens, with the larger sizes common in multilingual models.
Embedding parameters scale as and the output softmax layer also has weights. For and : embedding + output = parameters, which is of a 7B model. The information-theoretic optimal vocabulary size minimizes total description length — too small wastes tokens on long sequences, too large wastes parameters on rarely-used entries.
Model A uses 32K vocabulary with . Model B uses 128K vocabulary. How do embedding sizes compare?
Special Tokens
Besides pieces of text, every vocabulary reserves a few special tokens that carry control signals. [BOS] marks the beginning of a sequence and [EOS] the end. [PAD] fills short sequences so a batch is rectangular, and the loss and attention mask ignore it. [MASK] is BERT's blank to fill in, [SEP] separates segments, and [CLS] collects a sequence-level summary. Chat models add role markers for system, user, and assistant turns. Each special token has an ordinary learned embedding. The failure modes are practical. A missing [EOS] in fine-tuning data teaches the model never to stop, and user text that imitates a special token can spoof the chat format.
Special tokens partition the token space into functional categories: [BOS] and [EOS] define sequence boundaries (the model learns to decide when to stop), [PAD] enables batching of variable-length sequences (masked out in loss computation), and [MASK] enables bidirectional pre-training objectives. Each special token occupies one slot in the vocabulary and has a learned embedding like any other token.
Why does GPT-4 need [BOS] and [EOS] tokens?
Vocabulary and Multilingual Efficiency
Fertility measures how many tokens a tokenizer needs per word of a language: tokens divided by words on a reference text. A vocabulary trained mostly on English gives English words dedicated tokens, so English fertility is about 1.2 to 1.5. Languages that were rare in the tokenizer's training data fall back to short fragments or single bytes, with fertility several times higher. High fertility has three costs for users of that language. They pay more per word under per-token pricing, fit fewer words into the context window, and often get lower quality. Petrov et al. (2023) measured length differences of up to 15 times for the same content across languages.
Fertility measures tokenizer efficiency for language . The cost ratio for language vs English is in attention compute and in context window utilization. For Bengali with vs English : compute cost is x and effective context is x. This is a structural inequality baked into the tokenizer.
Llama's tokenizer has fertility 1.3 for English but 4.2 for Bengali. A 4096-token context window holds how many words in each?
Byte Fallback
Byte fallback guarantees that any input can be encoded. When a character has no token in the vocabulary, the tokenizer emits its UTF-8 bytes instead, using 256 reserved byte tokens. This removes [UNK], so the model can always reproduce the exact input, which matters for code, names, and rare scripts. Llama's SentencePiece tokenizer uses this scheme, and fully byte-level BPE as in GPT-2 gets the same guarantee by construction. The cost is length. UTF-8 uses 1 byte for ASCII, 2 for most Latin and Cyrillic letters with accents, 3 for most Asian scripts, and 4 for emoji. Unseen text can therefore become 3 or 4 times longer.
UTF-8 encodes Unicode code points as 1-4 bytes: ASCII uses 1 byte ( characters), Latin/Cyrillic use 2 bytes (), CJK/most scripts use 3 bytes, and emoji/rare symbols use 4 bytes. With byte fallback, the worst case token-to-character ratio is 4:1. The expected ratio depends on the script distribution: .
An emoji like a smile face is 4 bytes in UTF-8. How many tokens does a byte-level tokenizer use?
Theory Exercise
Problem:
You are training a code-focused LLM. Should you use a standard text tokenizer or train a custom one on code? What special considerations apply to code tokenization?
Hints:
- Think about how code differs from natural language
- Consider indentation, operators, and variable names
- Think about the token efficiency of different approaches
Related Problems on PixelBank
A token ID such as 3290 is just an index, and the number itself means nothing. Token 3290 is no more similar to 3291 than to 17. If a network received raw IDs, it would try to learn from their arithmetic, and it could not use what it learns about "dog" when it later sees "puppy". What the model needs is a representation in which related words are close together, so that evidence about one generalises to the others.
The previous topic, Token Vocabularies, fixed the set of units the model reads. This topic turns each unit into a vector the network can compute with, and explains why the geometry of those vectors carries meaning.
We start by moving from sparse one-hot vectors to dense learned embeddings stored in a lookup table. Then we measure similarity with the cosine of the angle between vectors. Next come word analogies, where relations such as country to capital appear as consistent directions. We finish with contextual embeddings, where a Transformer adjusts each word's vector to fit its sentence, so "bank" by a river and "bank" in finance differ.
Definition
A word embedding is a learned dense vector that represents token . It is stored as row of an embedding matrix and trained so that tokens used in similar contexts get nearby vectors. Static embeddings give each token one vector. Contextual embeddings are recomputed by a network for each occurrence in its sentence.
In this topic
- 1From One-Hot to Dense Embeddings
- 2Semantic Similarity
- 3Word Analogies
- 4Contextual Embeddings
From One-Hot to Dense Embeddings
A one-hot vector represents token as a length- vector of zeros with a single 1 at position . It is huge, and every pair of distinct words is equally far apart, so it encodes no similarity. An embedding matrix replaces it. Multiplying by the one-hot vector simply selects row , so in practice the operation is a table lookup. Here is the embedding width, typically 768 to 8,192 in modern LLMs. The rows start random and are trained along with the rest of the network, so words that appear in similar contexts drift toward similar vectors.
A one-hot vector has dimensions but only 1 bit of information ( bits if we count the index). A dense embedding packs bits (float32) of information into dimensions. The embedding matrix is a lookup table: . This lookup is rather than the of a full matrix multiply.
Vocabulary: [cat, dog, car, truck]. One-hot for 'cat' vs embedding for 'cat'.
Semantic Similarity
Cosine similarity compares two embeddings and by the angle between them. It is their dot product divided by the product of their lengths and , which gives , between for opposite directions and for the same direction. Dividing by length removes magnitude, which often tracks word frequency rather than meaning. High similarity captures both synonyms, such as happy and joyful, and related words, such as king and queen. One pitfall: antonyms such as hot and cold appear in similar contexts, so they often score high. Similarity measures shared usage, not shared meaning.
Cosine similarity measures the angle between vectors, invariant to magnitude. In a -dimensional space, random unit vectors have expected cosine similarity with standard deviation . For : . So a cosine similarity of between "king" and "queen" is roughly standard deviations above random — an astronomically significant alignment.
cos(king, queen) = 0.85, cos(king, apple) = 0.12. Interpret these values.
Word Analogies
Trained static embeddings often encode relations as consistent directions. If the vector from man to woman is roughly the same as the vector from king to queen, then king minus man plus woman lands near queen, as in the formula. The same pattern appears for country to capital, verb tense, and singular to plural. To solve an analogy, compute the target vector and return the nearest word by cosine, excluding the three input words. That exclusion matters, because the nearest raw neighbour is often an input word itself. Analogies are a diagnostic of embedding structure, not a guarantee. Many relations are not linear, and the directions also encode social biases.
The analogy works because embeddings learn linear subspaces for semantic relations. Formally, if is the "gender" direction, then and . Subtracting cancels from one pair, adding reintroduces the female component. This linearity is not guaranteed — it emerges from the training objective's implicit low-rank factorization of the co-occurrence matrix.
Complete the analogy: Paris:France :: Tokyo:? using embedding arithmetic.
Contextual Embeddings
Static embeddings such as Word2Vec and GloVe give each word one vector, so "bank" gets a single vector that averages its river sense and its finance sense. Contextual embeddings fix this by letting the network recompute each token's vector from its surrounding sentence. ELMo did this with bidirectional LSTMs. BERT and GPT do it with self-attention, where each layer adds context-dependent updates to a residual stream that starts from the static lookup. The first layer's vector is still context-free. By the upper layers, the same word in different sentences has clearly different vectors. The cost is compute, since a static lookup is replaced by a full forward pass.
In a transformer, the embedding of token at layer is . The residual stream means each layer adds context-dependent modifications. For polysemous words, the initial embedding is the same regardless of context, but by layer , has been updated by attending to surrounding tokens. The cosine similarity between "bank" in financial vs. river contexts drops from (layer 0) to (final layer) in BERT.
How would BERT represent "bank" in "river bank" vs "investment bank"?
Theory Exercise
Problem:
Word2Vec training has two variants: CBOW (Continuous Bag of Words) and Skip-gram. CBOW predicts the center word from context; Skip-gram predicts context from the center word. Which works better for rare words and why?
Hints:
- Think about how often each word appears during training
- Consider which variant gives rare words more gradient updates
- Think about the effective number of training examples each word gets
Related Problems on PixelBank
Self-attention treats its input as a set. Shuffle the tokens and each token receives exactly the same attention output, just in a different slot. So without extra information, "dog bites man" and "man bites dog" look identical to the attention layers, although they mean opposite things. Recurrent networks never had this problem, because they read tokens in order. The Transformer gave up that order to gain parallelism, so position must be put back in explicitly.
The previous topic, Word Embeddings, gave each token a vector describing what it is. This topic adds where it is, and the method chosen decides how well a model copes with texts longer than those it was trained on.
We start with the sinusoidal encoding of the original Transformer, a fixed pattern of waves added to each embedding. Then come learned positional embeddings, one trained vector per position, which are simple but cannot go past their table. Next is RoPE, which rotates queries and keys so attention depends on relative distance. We finish with ALiBi, which skips encodings entirely and penalises attention by distance.
Definition
A positional encoding injects token order into a Transformer, whose self-attention is otherwise permutation-invariant. It either adds a position-dependent vector to each token embedding, sinusoidal or learned, or modifies attention directly. RoPE rotates query and key vectors by position-dependent angles, and ALiBi adds a distance-proportional bias to attention scores.
In this topic
- 1Sinusoidal Positional Encoding
- 2Learned Positional Embeddings
- 3Rotary Position Embedding (RoPE)
- 4ALiBi: Attention with Linear Biases
Sinusoidal Positional Encoding
The original Transformer adds a fixed vector to the embedding of the token at position . Dimension pair and holds the sine and cosine of divided by , where is the model width. Low dimensions oscillate quickly and high dimensions slowly, with wavelengths from up to nearly , so each position gets a distinct pattern, like the hands of a clock running at many speeds. Moving by a fixed offset is the same rotation of each sine-cosine pair wherever you start, so relative offsets are easy to learn. The encoding needs no parameters but extrapolates poorly in practice.
The frequencies create wavelengths from to . A key property: can be expressed as a linear transformation of , because . This means relative position information is accessible through a learned linear projection, even though the encoding itself is absolute.
Why use sinusoidal functions instead of simple position numbers (1, 2, 3...)?
Learned Positional Embeddings
Learned positional embeddings treat position like a second vocabulary. A matrix holds one trainable -dimensional vector per position, up to the maximum length . The input to the first layer is the token embedding plus the row of for that position. GPT-2 and BERT use this scheme, and it is simple and flexible, since the model learns whatever positional pattern helps. The hard limit is the table. Positions beyond have no row at all, and rows near the end of the table get less training, because fewer training sequences reach those positions.
Learned embeddings add parameters. For and : extra parameters. The embeddings are added to token embeddings: . Since is a lookup table, positions beyond have no embedding. Extrapolation fails because the model has never seen gradients for those positions during training.
A model trained with encounters a sequence of 3000 tokens. What happens?
Rotary Position Embedding (RoPE)
RoPE (Su et al., 2021) encodes position by rotating vectors instead of adding to them. Each query and key vector is split into pairs of dimensions, and the pair at position is rotated by angle , as in the formula, with a different frequency for each pair. The attention score is a dot product, and rotating a query by and a key by leaves a dot product that depends only on the difference . So attention sees relative distance, though each vector was rotated by absolute position. It adds no parameters and is used by Llama, Mistral, and most recent LLMs. Beyond the trained length it still needs scaling tricks.
RoPE applies rotation by angle to pairs of dimensions: . The attention score between positions and becomes , which depends only on the relative distance , making RoPE inherently relative despite being applied to absolute positions.
Why has RoPE become the standard for modern LLMs over sinusoidal or learned encodings?
ALiBi: Attention with Linear Biases
ALiBi (Press et al., 2022) adds no positional vectors at all. Instead, each attention score gets a penalty proportional to distance. A key positions back receives bias , so nearby tokens are favoured, as in the formula. Each head has its own fixed slope , a geometric sequence such as for 8 heads, so some heads focus locally and others look far back. There are no learned parameters, and because the penalty is defined for any distance, models trained on short sequences handle longer ones gracefully. The cost is a built-in bias toward recent tokens, which can hurt tasks that need precise long-range retrieval.
ALiBi adds a linear penalty to attention scores, where is a head-specific slope. The slopes are set geometrically: for head out of total. This creates a spectrum from sharp local attention (large , steep decay) to broad global attention (small , gentle decay). The bias is additional compute (no learnable parameters), and because it is a simple distance penalty, it extrapolates naturally to any sequence length.
In ALiBi, head 1 has slope and head 2 has . How do they differ?
Theory Exercise
Problem:
Compare RoPE and ALiBi for extending a model's context window from 4K to 32K tokens. What are the tradeoffs?
Hints:
- Think about what happens when you extrapolate beyond training length
- Consider computational overhead
- Think about what empirical results show