Positional Encoding in Transformer Models
Medium · Machine Learning · Machine Learning Engineer · Technical Screen
Prompt
Standard self-attention evaluates every token against every other token in parallel rather than stepping sequentially like a recurrent network or applying local spatial filters like a convolutional network. Because raw Query-Key dot products only compare token representations, an unmodified self-attention layer cannot tell one ordering of tokens apart from another.
Walk through how Transformers represent sequence order:
- Order blindness in raw self-attention: Show why unaugmented self-attention is invariant to token order from a token's perspective (and permutation-equivariant across rows), and explain why that fails on order-sensitive tasks such as translation between languages.
- Sinusoidal vs. trainable position vectors: Compare fixed multi-frequency sine/cosine encodings against learned positional lookup tables. In the sinusoidal scheme, coordinate pairs
(2i, 2i + 1)at slotposare defined as:PE(pos, 2i) = sin(pos / 10000^(2i / d_model))-
PE(pos, 2i + 1) = cos(pos / 10000^(2i / d_model))Explain why pairing sine and cosine across geometrically spaced wavelengths lets linear projections represent fixed relative offsets
pos + k. 3. Relative positional representations and context extrapolation: Explain how relative position methods inject pairwise token distance directly into attention and why they generalize better to sequence lengths exceeding those seen during training.
Scope & Expectations
- Demonstrate mathematically or via matrix notation why permuting input rows leaves self-attention blind to sequence order, with concrete linguistic examples where meaning flips under reordering.
- Derive or explain the trigonometric shift property of sinusoidal pairs alongside the parameter, memory, and context-limit trade-offs of learned positional tables.
- Contrast absolute slot indexing against pairwise relative offset mechanisms when extrapolating beyond the training context window.
Step-by-step walkthrough
Why raw self-attention treats tokens as an unordered set
In a recurrent network, hidden states advance one token at a time from left to right, so sequence order is wired directly into the recurrence. A Transformer instead scores all
Ltokens simultaneously via self-attention, projecting each token into a Query vector (q, what it searches for), a Key vector (k, what it advertises), and a Value vector (v, the payload it contributes).Given an input matrix
Xof shapeL x d_model(one row per token), a single attention head computes:Q = X Wq, K = X Wk, V = X Wv scores = (Q K^T) / sqrt(d_k) # entry (i, j) is (q_i · k_j) / sqrt(d_k) weights = softmax_rows(scores) # each row sums to 1.0 out = weights V # weighted combination of Value rowsInspect entry
(i, j)ofscores: the inner productq_i · k_jdepends solely on the two token embeddings, with zero dependence on indicesiandj:Order A: [ "chef", "praised", "critic" ] ---> "chef" attends over {"chef", "praised", "critic"} -> v_chef Order B: [ "critic", "praised", "chef" ] ---> "chef" attends over {"critic", "praised", "chef"} -> identical v_chef!Formally, multiply
Xon the left by anyL x Lpermutation matrixP(one1per row and column, zeros elsewhere, soP^T P = I):Q' = (P X) Wq = P Q, K' = P K, V' = P V Q' K'^T = P (Q K^T) P^T # rows and columns reorder identically weights' = softmax_rows(P scores P^T) = P weights P^T out' = (P weights P^T) (P V) = P weights (P^T P) V = P outTwo complementary terms capture this symmetry: - Permutation equivariance (across the matrix): reordering input rows reorders output rows in lockstep (
out' = P out). Because position-wise MLPs and layer normalization also act independently on each row, an entire unmasked encoder stack is permutation-equivariant. - Permutation invariance (per token or after mean/sum pooling): each token sees its context as an unordered multiset, so any pooled sentence representation is completely unchanged when words are scrambled.A short NumPy check confirms this property directly:
import numpy as np def self_attention(X, Wq, Wk, Wv): Q = X @ Wq K = X @ Wk V = X @ Wv scores = (Q @ K.T) / np.sqrt(K.shape[1]) shifted = np.exp(scores - scores.max(axis=1, keepdims=True)) weights = shifted / shifted.sum(axis=1, keepdims=True) return weights @ V rng = np.random.default_rng(0) X = rng.normal(size=(3, 4)) # 3 token vectors, d_model = 4 Wq, Wk, Wv = rng.normal(size=(3, 4, 4)) perm = [2, 0, 1] # reorder token slots out_original = self_attention(X, Wq, Wk, Wv) out_shuffled = self_attention(X[perm], Wq, Wk, Wv) print(np.allclose(out_original[perm], out_shuffled)) # True: identical per-token outputs!Why losing token order breaks translation and how position signals restore it
Natural language, math, and code rely heavily on sequential order: - Subject vs. object roles:
"The chef praised the critic"and"The critic praised the chef"share the exact same vocabulary items yet express opposite meanings — requiring different word orders or grammatical case markers when translated into target languages. - Negation and modifier attachment:"Only Maya solved problem two"vs."Maya solved only problem two"changes truth conditions without changing a single word. - Non-commutative operations:a - bvs.b - aorx / yvs.y / x.Without positional cues, an encoder emits the exact same bag of Key/Value vectors for both sentences, leaving a translation decoder unable to tell who praised whom.
Adding a slot-specific position vector
P[pos]to slotposbreaks that symmetry because slot coordinates stay anchored when words swap places:Order A + positions: [ e("chef") + P[0], e("praised") + P[1], e("critic") + P[2] ] Order B + positions: [ e("critic") + P[0], e("praised") + P[1], e("chef") + P[2] ] ^ "chef" now receives P[2] rather than P[0], producing distinct representations!One subtle interview bonus: in autoregressive decoders with a causal mask (where slot
ionly attends to slots0 .. i), slot0averages 1 vector while slotiaveragesi + 1vectors, leaking weak implicit position information even with zero explicit encoding. Bidirectional encoders and encoder-decoder cross-attention lack causal masks, so without positional signals they are completely blind to order.Sinusoidal positional encoding: the multi-dial clock intuition
Why not simply add raw integer indices
pos = 0, 1, 2, ..., 8000to embeddings? Unbounded integers would overwhelm unit-scale token embeddings (~[-1, 1]) and explode numerically on longer documents.Instead, the classic Transformer ("Attention Is All You Need") encodes each slot
posas ad_model-dimensional vector of bounded sines and cosines in[-1, 1], pairing channels intod_model / 22D planes(2i, 2i + 1):w_i = 1 / 10000^(2i / d_model) for pair index i = 0, 1, ..., (d_model / 2) - 1 PE(pos, 2i) = sin(pos * w_i) PE(pos, 2i+1) = cos(pos * w_i)Picture each
(sin, cos)pair as one dial on a multi-speed clock, rotating around the unit circle at angular ratew_i: - Pairi = 0advances atw_0 = 1radian per token, wrapping every2 * pi ≈ 6.28tokens — a fast dial that sharply separates adjacent slotsposandpos + 1. - The slowest pair (2i / d_model -> 1) advances at~1 / 10000radians per token, wrapping every2 * pi * 10000 ≈ 62,832tokens — a slow calendar dial that prevents distant positions from aliasing onto the same coordinates.Why space wavelengths geometrically? In
w_i = 10000^(-2i / d_model), incrementingiscales the wavelength2 * pi / w_iby a constant factor10000^(2 / d_model)(analogous to place values1, 10, 100, 1000). A single fast wave would repeat every ~6 tokens, whereas a single ultra-slow wave would barely budge (0.0001) between neighbors. Geometric spacing covers every distance scale — 1 token, 10 tokens, 100 tokens, 10,000 tokens — cleanly using onlyd_model / 2pairs.Concrete values for
d_model = 4(w_0 = 1.0,w_1 = 1 / 10000^(2/4) = 0.01):pos pair 0: sin(1*pos), cos(1*pos) pair 1: sin(0.01*pos), cos(0.01*pos) 0 0.0000, 1.0000 0.0000, 1.0000 1 0.8415, 0.5403 0.0100, 1.0000 2 0.9093, -0.4161 0.0200, 0.9998import numpy as np def sinusoidal_encoding(num_positions, d_model): pe = np.zeros((num_positions, d_model)) for pos in range(num_positions): for i in range(d_model // 2): speed = 1.0 / (10000.0 ** (2 * i / d_model)) angle = pos * speed pe[pos, 2 * i] = np.sin(angle) pe[pos, 2 * i + 1] = np.cos(angle) return pe print(np.round(sinusoidal_encoding(3, 4), 4))How sin/cos pairs turn relative offsets into linear rotations
In language modeling, relative offset (
ktokens earlier or later, like an adjective immediately preceding its noun) matters far more than whether a phrase begins at index12or412. Why can linear projectionsWqandWkaddress a fixed shift+kindependent ofpos?Apply standard angle-sum identities (
sin(a + b) = sin(a)cos(b) + cos(a)sin(b)andcos(a + b) = cos(a)cos(b) - sin(a)sin(b)) to pairiatpos + k:sin(w * (pos + k)) = cos(w * k) * sin(w * pos) + sin(w * k) * cos(w * pos) cos(w * (pos + k)) = -sin(w * k) * sin(w * pos) + cos(w * k) * cos(w * pos)In 2x2 matrix form:
[ sin(w * (pos + k)) ] [ cos(w * k) sin(w * k) ] [ sin(w * pos) ] [ cos(w * (pos + k)) ] = [ -sin(w * k) cos(w * k) ] [ cos(w * pos) ] \__________ ___________/ \/ 2x2 rotation R_i(k) — depends ONLY on k, NEVER on pos!Placing all
d_model / 22x2 rotation blocks along the diagonal of ad_model x d_modelblock-diagonal matrixM_kyields:PE(pos + k) = M_k PE(pos) for EVERY slot pos!Two immediate insights follow: 1. Why every frequency needs both
sinandcos: Computingsin(w * (pos + k))requires bothsin(w * pos)andcos(w * pos). Dropping cosine would destroy the fixed linear mapM_k. 2. Translation-invariant inner products: Bysin(a)sin(b) + cos(a)cos(b) = cos(a - b), the dot product of two sinusoidal vectors depends strictly onk:PE(pos) · PE(pos + k) = sum over i of [ sin(w_i*pos)*sin(w_i*(pos+k)) + cos(w_i*pos)*cos(w_i*(pos+k)) ] = sum over i of cos(w_i * k) Check for d_model = 4 (w_0 = 1, w_1 = 0.01): offset k = 1: PE(0)·PE(1) = PE(5)·PE(6) = cos(1) + cos(0.01) = 0.5403 + 1.0000 = 1.5403 offset k = 2: PE(1)·PE(3) = PE(8)·PE(10)= cos(2) + cos(0.02) = -0.4161 + 0.9998 = 0.5837Two important caveats round out the math: first,
cos(w_i * k) = cos(-w_i * k)is even, so unprojected dot products treat-kand+ksymmetrically until asymmetric matricesWqandWkbreak directionality; second, addingPEtoXcreates mixed content-position cross terms inside(x_i + p_i) Wq Wk^T (x_j + p_j)^Trather than enforcing pure relative attention.Sinusoidal waves vs. trainable lookup tables
Architectures such as BERT (
L_max = 512) and GPT-2 (L_max = 1,024) replace fixed waves with a learned positional embedding matrixPof shapeL_max x d_model— a standard parameter table optimized via backpropagation where rowposis added to slotpos.Aspect Sinusoidal Encoding Trainable Positional Table Parameter count 0(closed-form waves)L_max * d_modelweightsIn-distribution quality Matches learned tables on standard benchmarks Adapts freely to special slot roles (e.g., [CLS]at index 0)Memory cost Negligible; computed on the fly or cached small Grows linearly with maximum context window L_maxInputs exceeding L_maxFormula evaluates at any integer pos(though unseen phase combinations still degrade accuracy)Out-of-bounds failure: no row exists past L_max - 1without interpolation and fine-tuningTraining coverage Requires zero gradient updates High-index rows receive sparse updates if most training documents are short Concrete sizing shows how context scaling affects memory: - In GPT-2 small (
L_max = 1,024,d_model = 768),1,024 * 768 = 786,432floats (~1.5 MBin fp16) — trivial. - At long-context LLM scale (L_max = 131,072,d_model = 4,096), a learned table demands131,072 * 4,096 = 536,870,912parameters (~1.07 GBin fp16 solely for position vectors!), and any slot beyond the longest training example remains untrained random weights.Also note a practical subtlety: although sinusoidal formulas can emit vectors at
pos = 20,000after training up to2,048, downstream attention and MLP weights have never encountered those joint multi-frequency phase states, so language-modeling perplexity still spikes past the training horizon without relative mechanisms.Relative positional schemes and extrapolating to longer contexts
Relative positional encodings abandon global slot numbers and instead inject the pairwise offset
d = i - jdirectly into attention between query slotiand key slotj:Absolute scheme: score(i, j) = f(x_i + P[i], x_j + P[j]) <- depends on global indices i and j Relative scheme: score(i, j) = g(x_i, x_j, i - j) <- depends strictly on offset (i - j)!Four milestone designs illustrate how this works in practice: 1. Clipped relative vectors (Shaw et al.): Injects a learned vector
r_{clip(j - i, -K, K)}into Key/Value projections so distances beyondKsaturate cleanly to a trained boundary vector. 2. Log-bucketed scalar biases (T5): Adds a learned per-head scalarb[bucket(i - j)]toq_i · k_j / sqrt(d_k), using exact buckets nearby (0..15) and logarithmically wider buckets farther out. 3. ALiBi (Attention with Linear Biases): Subtracts a fixed per-head distance penaltym_h * |i - j|from raw logits (with slopem = 0.5, query10adds0.0at key10,-0.5at key9,-1.0at key8, and-5.0at key0). 4. RoPE (Rotary Position Embeddings): Rotates each 2D plane ofq_ibyi * thetaandk_jbyj * thetasoq_i · k_jdepends directly on(j - i) * theta.Why relative position mechanisms extrapolate to longer test sequences far better than absolute embeddings: - Shift-invariant rule sharing: Resolving a pronoun
4tokens back uses the exact same offseti - j = 4whether the sentence appears at token40or token40,000, whereas absolute models must re-discover that rule across every coordinate range. - Dense supervision on local offsets: Every512-token training sequence observes absolute index511at most once, but observes relative offset1511 times! On a4,096-token test document, the vast majority of syntactic and local semantic links still fall on heavily trained offsets. - Bounded behavior at unseen distances: Clipped/bucketed biases map extra-long distances onto their outermost trained bucket, and ALiBi smoothly decays distant logits rather than feeding unseen vectors into residual streams. (When extending RoPE models from4kto128k, frequency-rescaling techniques like Position Interpolation, NTK-aware scaling, or YaRN compress unseen rotation angles back into the trained angular domain.)Concise interview wrap-up
Structure a spoken answer around four crisp beats: 1. Symmetry problem: Raw
Q K^Tdot products ignore slot indices, making self-attention permutation-equivariant across rows and order-blind per token ("chef praised critic"=="critic praised chef"). 2. Sinusoidal geometry: Pairingsin(pos * w_i)andcos(pos * w_i)across geometrically spaced wavelengths (2*pito2*pi * 10000) creates bounded multi-scale coordinates where any step+kis a constant linear rotationPE(pos + k) = M_k PE(pos). 3. Fixed vs. learned tables: LearnedL_max x d_modelmatrices match sinusoidal quality insideL_max, but costO(L_max * d_model)memory and cannot index pastL_max - 1. 4. Relative advantage on long inputs: Conditioning attention directly oni - j(T5 buckets, ALiBi slopes, RoPE rotations) makes attention translation-invariant so short-context training transfers cleanly to longer sequences.
Intuition & how it works
Imagine handing a translator three unnumbered slips of paper reading "chef", "praised", and "critic": every slip can compare its word meaning against the others, yet nobody can tell who praised whom. Unaugmented self-attention (where every token scores every other token via a Query-Key dot product and averages Value vectors) behaves just like those loose slips — it compares token content in parallel without ever seeing token slots. Positional encoding breaks that symmetry either by stamping each slot with a structured coordinate vector or by adjusting pairwise attention scores as a function of slot separation.
Obvious shortcuts break down fast. Adding raw slot numbers 0, 1, 2, ..., 8000 swamps unit-scale word embeddings and blows up on longer documents, while learning one lookup row per slot (L_max x d_model) hits an out-of-bounds wall at L_max and consumes over a gigabyte at 128k context windows. Instead, the classic Transformer uses sinusoidal encoding — (sin, cos) pairs whose wavelengths follow a geometric progression (each pair ticks a constant factor slower than the previous one, like fast and slow dials on a clock) — while modern architectures inject relative offsets (i - j) directly into attention so "two tokens earlier" uses identical math at index 10 and index 50,000.
Walk through a tiny sinusoidal setup with d_model = 4 (two (sin, cos) pairs at angular rates w_0 = 1 and w_1 = 0.01):
- Slot 0: [sin(0), cos(0), sin(0), cos(0)] = [0.0000, 1.0000, 0.0000, 1.0000].
- Slot 1: [sin(1), cos(1), sin(0.01), cos(0.01)] = [0.8415, 0.5403, 0.0100, 1.0000].
- Slot 2: [sin(2), cos(2), sin(0.02), cos(0.02)] = [0.9093, -0.4161, 0.0200, 0.9998].
Pair (0, 1) turns rapidly to separate immediate neighbors, pair (2, 3) drifts slowly to avoid wrapping around across long spans, and the inner product at lag k = 1 is PE(0) · PE(1) = cos(1) + cos(0.01) = 1.5403 — identical to PE(5) · PE(6) = 1.5403 anywhere in the text.
Key points
- Equivariance vs. invariance in self-attention: Reordering input rows with a permutation matrix
Preorders output rows identically (out' = P out, permutation equivariance), whereas any single token's view of its context — or a pooled sequence vector — ignores word order completely (permutation invariance). - Why
sinandcospairs unlock linear relative shifts: Angle-addition identities turn a+ktoken shift on(sin(w_i * pos), cos(w_i * pos))into a constant 2x2 rotationR_i(k)independent ofpos, givingPE(pos + k) = M_k PE(pos)and translation-invariant inner productsPE(pos) · PE(pos + k) = sum_i cos(w_i * k). - Why wavelengths grow geometrically: Choosing
w_i = 1 / 10000^(2i / d_model)spans wavelengths from2 * pi ≈ 6.28tokens up to2 * pi * 10000 ≈ 62,832tokens at uniform multiplicative spacing, resolving adjacent words with fast waves and preventing periodic wrap-around collisions with slow waves. - Sinusoidal vs. trainable absolute tables: Learned tables (
L_max x d_model, e.g.,1,024 x 768 = 786,432weights in GPT-2 small vs.~537Mweights at131,072 x 4,096) adapt flexibly withinL_maxbut fail hard beyondL_maxand get sparse updates near the tail of variable-length batches. - Why relative attention generalizes past training length: Conditioning scores directly on
i - j(via T5 log buckets, ALiBi linear slopes, or RoPE rotations) makes attention shift-invariant across sequence index so local and mid-range dependencies trained on short sequences transfer directly to longer contexts.
Common mistakes
- Blurring permutation equivariance and invariance: Claiming the unpooled output matrix stays unchanged under row shuffling is imprecise — its rows permute in lockstep (
P out), while pooled outputs and per-token context multisets are strictly invariant. - Treating additive sinusoidal vectors as purely relative: Adding
PEat the input layer makes offsets linearly accessible, but expanding(x_i + p_i) Wq Wk^T (x_j + p_j)^Tstill introduces absolute position-content cross terms unless relative structure lives inside attention. - Expecting zero-shot infinite length generalization from raw sinusoids: Even though
sinandcosare well defined atpos = 50,000, weights trained up to2,048face unseen cross-frequency phase combinations past2,048and still lose perplexity without relative biases or frequency scaling. - Indexing
2iand2i + 1with different exponents: Hereiindexes pairs (0 .. d_model/2 - 1), so channels2iand2i + 1must share the exact same angular speed1 / 10000^(2i / d_model)for the 2x2 rotation identity to hold. - Applying RoPE rotations to Value vectors (
V): Position signals control routing (QandK), whereasVcarries semantic payload unless relative values are explicitly parameterized.
Follow-up questions
- How do Rotary Position Embeddings (RoPE) modify the classic sinusoidal scheme, and why do modern decoder LLMs favor them? Rather than adding a position vector once to bottom-layer embeddings, RoPE multiplies each 2D coordinate pair of Query
q_mand Keyk_nby 2D rotation matrices of anglesm * theta_iandn * theta_iinside every attention layer. Because orthogonal rotations preserve vector norms and satisfy(R(m * theta) q) · (R(n * theta) k) = q · (R((n - m) * theta) k), pre-softmax logits depend exclusively on content vectors and relative lagn - mwith zero additive cross terms. RoPE introduces zero trainable weights, costsO(L * d)elementwise ops per layer, plays cleanly with autoregressive KV caches (past Keys are rotated once by their fixed indexnand stored), and supports context extension through frequency scaling (Position Interpolation, NTK-aware scaling, YaRN).
```python import numpy as np
def rotate_2d(vec, angle): c, s = np.cos(angle), np.sin(angle) return np.array([c * vec[0] - s * vec[1], s * vec[0] + c * vec[1]])
q, k = np.array([0.6, 0.8]), np.array([1.0, 0.5]) print(round(float(rotate_2d(q, 2.0) @ rotate_2d(k, 3.0)), 4)) # 0.961 (slots 2 and 3, lag +1) print(round(float(rotate_2d(q, 7.0) @ rotate_2d(k, 8.0)), 4)) # 0.961 (slots 7 and 8, same lag +1) ```
- How would you generalize 1D positional representations to a 2D patch grid in a vision model? A Vision Transformer (ViT) slices an image into a regular
H x Wgrid of square patches (such as14 x 14 = 196tokens): the simplest baseline flattens the grid into 1D and learns a table, reshaping back toH x Wfor 2D bilinear interpolation whenever inference resolution changes. To preserve explicit 2D geometry, 2D axial sinusoidal encoding (used in DETR and Masked Autoencoders) dedicates half ofd_modelto row indexyand half to column indexx. For multi-scale detection and arbitrary aspect ratios, 2D axial RoPE (rotating half the Query/Key pairs byyand half byxso attention depends on(delta_y, delta_x)) or 2D relative window bias tables (used in Swin Transformer, learning(2M - 1) x (2M - 1)per-head offsets insideM x Mwindows) give true 2D translation invariance. - What compute and memory trade-offs arise between static absolute position vectors and per-pair dynamic relative biases? Static absolute vectors add one
L x d_modeltensor at the input layer —O(L * d_model)work and zero modifications to fused attention kernels (GPU kernels such as FlashAttention that tile softmax in fast SRAM without writing theL x Lscore matrix to HBM). Dynamic scalar biases (T5 buckets or ALiBi) add a per-headH x L x Lterm to attention logits: whileO(H * L^2)matches attention FLOPs asymptotically, materializing an explicit fp16 bias tensor atL = 8,192andH = 32burns32 * 8192^2 * 2 bytes ≈ 4.29 GBof HBM traffic unless fused directly into the kernel (straightforward for ALiBi's-m * |i - j|, trickier for irregular lookup tables). Vector relative embeddings (Shaw et al.) are costliest, requiringq_i · r_{j - i}products that takeO(L^2 * d_model)memory naively orO(L * d_model)with index-skewing — explaining why modern LLMs strongly prefer RoPE (O(L * d_model)compute, zeroL x Lbias tensor, native FlashAttention support).
Follow-up questions
- How do Rotary Position Embeddings (RoPE) modify the classic sinusoidal scheme, and why do modern decoder LLMs favor them?
- How would you generalize 1D positional representations to a 2D patch grid in a vision model?
- What compute and memory trade-offs arise between static absolute position vectors and per-pair dynamic relative biases?
Similar questions
- Depth-First Graph Traversal
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning
- Correlation Bounds, Equicorrelated Variables, and Box-Muller Sampling
More Cadence interview questions
- Depth-First Graph Traversal Medium