Mechanics of Positional Encodings in Transformer Architectures
Machine LearningModel answerLast updated
Understand Transformer positional encodings, including self-attention permutation properties, sinusoidal vs. learned schemes, linear shift derivations, and relative methods.
Transformer architectures replace classical sequential recurrence with parallel self-attention. Because self-attention evaluates pairs of vectors without an inherent sense of temporal or spatial order, models require explicit positional information.
Objectives
- Permutation Properties: Explain mathematically why scaled dot-product self-attention is permutation-equivariant (and how pooling leads to permutation invariance). Describe why this behavior breaks natural language processing tasks without explicit positional inputs.
- Absolute Encoding Methods: Compare fixed sinusoidal encodings with learned absolute positional embeddings. Discuss parameter overhead, inductive biases, and behavior when encountering sequence lengths longer than those seen during training.
- Trigonometric Shift Derivation: For the sinusoidal formulation: $$\text{PE}{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d{\text{model}}}}\right), \quad \text{PE}{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d{\text{model}}}}\right)$$ Show how the encoding vector at position $pos + k$ can be expressed as a linear transformation of the vector at position $pos$. Then, analyze the inner product $(E_i + P_i)^\top W_Q^\top W_K (E_j + P_j)$ to explain why adding encodings to token embeddings introduces cross-term entanglements.
- Relative Encodings & Context Extension: Explain why modern large language models favor relative positional techniques (e.g., RoPE, ALiBi) over absolute additive encodings when scaling context window lengths.
Hints
Hint 1
Multiply the input matrix X by a permutation matrix P and track it through the scaled dot-product attention formulation.
Hint 2
Use the angle addition formulas sin(a + b) = sin(a)cos(b) + cos(a)sin(b) and cos(a + b) = cos(a)cos(b) - sin(a)sin(b) to form a 2x2 rotation matrix.
Hint 3
Expand the dot product of (E_i + P_i) W_Q and (E_j + P_j) W_K into four separate terms to observe how content and position interact.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Permutation Mechanics of Self-Attention
Given an input matrix $X \in \mathbb{R}^{n \times d}$, standard scaled dot-product attention computes projections using weight matrices $W_Q, W_K \in \mathbb{R}^{d \times d_k}$ and $W_V \in \mathbb{R}^{d \times d_v}$:
$$\text{Attention}(X) = \text{softmax}\left(\frac{X W_Q W_K^\top X^\top}{\sqrt{d_k}}\right) X W_V$$
Let $P \in \mathbb{R}^{n \times n}$ be an arbitrary permutation matrix (a binary matrix where each row and column contains exactly one $1$). Permuting the input sequence rows gives $\tilde{X} = P X$:
$$\text{Attention}(P X) = \text{softmax}\left(\frac{P X W_Q W_K^\top X^\top P^\top}{\sqrt{d_k}}\right) P X W_V$$
Because row-wise softmax commutes with row permutations and distributes across column permutations:
$$\text{softmax}\left(P A P^\top\right) = P ,\text{softmax}(A), P^\top$$
Substituting this identity back into the attention formula yields:
$$\text{Attention}(P X) = P ,\text{softmax}\left(\frac{X W_Q W_K^\top X^\top}{\sqrt{d_k}}\right) P^\top P X W_V = P \cdot \text{Attention}(X)$$
Because $\text{Attention}(P X) = P \cdot \text{Attention}(X)$, scaled dot-product self-attention is permutation-equivariant. Reordering the inputs produces the identical output vectors, permuted in the exact same order. If sequence-level pooling (such as mean pooling) is subsequently applied, the output becomes completely permutation-invariant.
Consequence for Sequence Tasks
Natural language syntax depends heavily on word order:
- "The chef prepared the meal" vs. "The meal prepared the chef"
- "Not standard, highly effective" vs. "Highly standard, not effective"
Without positional signals, self-attention treats these inputs as identical bags of token vectors, preventing the model from resolving syntactic roles or semantic dependencies.
2. Sinusoidal vs. Learned Absolute Embeddings
Absolute positional techniques inject spatial information by adding a position-specific vector $P_{pos} \in \mathbb{R}^d$ to the content embedding $E_{pos} \in \mathbb{R}^d$:
$$Z_{pos} = E_{pos} + P_{pos}$$
+-------------------------+
| Combined Vector Z |
+-------------------------+
^
| (Element-wise Addition)
+---------+---------+
| |
+------------------+ +------------------+
| Content Vector E | | Position Vector P|
+------------------+ +------------------+
Sinusoidal Encodings (Vaswani et al., 2017)
Deterministic functions operating across predefined frequency bands:
$$\text{PE}{(pos, 2i)} = \sin(\omega_i \cdot pos), \quad \text{PE}{(pos, 2i+1)} = \cos(\omega_i \cdot pos) \quad \text{where } \omega_i = \frac{1}{10000^{2i/d_{\text{model}}}}$$
- Parameter Count: $0$ trainable parameters.
- Wavelengths: Scale geometrically from $2\pi$ at $i=0$ to $10000 \cdot 2\pi$ at $i = d_{\text{model}}/2 - 1$.
- Inductive Bias: Smooth multi-resolution signal. High frequencies capture immediate local ordering, while low frequencies preserve global offsets across long sequences.
Learned Absolute Embeddings (e.g., BERT, GPT-2)
A trainable matrix $M_{\text{pos}} \in \mathbb{R}^{L_{\text{max}} \times d}$ updated during pre-training.
- Parameter Count: $L_{\text{max}} \cdot d$ parameters.
- Inductive Bias: Unconstrained; relationships are learned purely from training data distributions.
- Extrapolation Limit: Cannot process indices beyond $L_{\text{max}}$ without modifying the architecture, as no embedding vectors exist for positions $pos > L_{\text{max}}$.
| Feature | Sinusoidal Encodings | Learned Absolute Embeddings |
|---|---|---|
| Parameters | $0$ | $L_{\text{max}} \times d$ |
| Context Limit | Mathematically infinite | Hard limit at $L_{\text{max}}$ |
| Extrapolation | Generates vectors, but quality degrades out-of-distribution | Fails directly without architecture modifications |
| Inductive Bias | Multi-frequency geometric smoothness | Minimal explicit structural bias |
3. Linear Shift Derivations & Content Cross-Terms
For a given frequency channel $\omega_i$, the sinusoidal encoding vector at position $pos$ is:
$$\mathbf{u}(pos) = \begin{bmatrix} \sin(\omega_i \cdot pos) \ \cos(\omega_i \cdot pos) \end{bmatrix}$$
Using the angle addition formulas:
- $\sin(\alpha + \beta) = \sin\alpha \cos\beta + \cos\alpha \sin\beta$
- $\cos(\alpha + \beta) = \cos\alpha \cos\beta - \sin\alpha \sin\beta$
Evaluating $\mathbf{u}(pos + k)$:
$$\sin(\omega_i (pos + k)) = \sin(\omega_i \cdot pos)\cos(\omega_i k) + \cos(\omega_i \cdot pos)\sin(\omega_i k)$$ $$\cos(\omega_i (pos + k)) = \cos(\omega_i \cdot pos)\cos(\omega_i k) - \sin(\omega_i \cdot pos)\sin(\omega_i k)$$
In matrix format:
$$\begin{bmatrix} \sin(\omega_i (pos + k)) \ \cos(\omega_i (pos + k)) \end{bmatrix} = \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix} \begin{bmatrix} \sin(\omega_i \cdot pos) \ \cos(\omega_i \cdot pos) \end{bmatrix}$$
Defining $R_i(k)$ as the 2D rotation matrix:
$$R_i(k) = \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix}$$
Stacking these 2D blocks across all $d_{\text{model}} / 2$ channels creates a block-diagonal transition matrix $M_k \in \mathbb{R}^{d \times d}$:
$$\text{PE}{pos + k} = M_k \cdot \text{PE}{pos}$$
Because $M_k$ depends only on offset $k$, linear transformations can project position encodings to evaluate relative shifts.
Content-Position Cross-Term Entanglement
Adding position encodings directly to content embeddings ($Z_i = E_i + P_i$) causes content and position to intermingle inside the scaled query-key dot product:
$$q_i^\top k_j = (E_i + P_i)^\top W_Q^\top W_K (E_j + P_j)$$ $$q_i^\top k_j = \underbrace{E_i^\top W_Q^\top W_K E_j}{\text{Content-Content}} + \underbrace{E_i^\top W_Q^\top W_K P_j + P_i^\top W_Q^\top W_K E_j}{\text{Content-Position Cross Terms}} + \underbrace{P_i^\top W_Q^\top W_K P_j}_{\text{Position-Position}}$$
The cross-terms ($E_i^\top W_Q^\top W_K P_j$ and $P_i^\top W_Q^\top W_K E_j$) entangle raw content vectors with absolute position vectors, preventing the attention score from isolating purely relative distance terms.
4. Relative Positional Representations and Context Extrapolation
To avoid cross-term interference and support sequence length scaling, modern models implement relative positional mechanisms.
Prominent Relative Mechanisms
- Rotary Position Embedding (RoPE): Multiplies query and key vectors by complex rotation matrices corresponding to absolute positions: $$\tilde{q}i = R{\Theta, i}^d q_i, \quad \tilde{k}j = R{\Theta, j}^d k_j$$ Their inner product simplifies to a function of relative distance: $$\langle \tilde{q}_i, \tilde{k}j \rangle = q_i^\top R{\Theta, j-i}^d k_j$$
- Attention with Linear Biases (ALiBi): Adds a static, non-learnable negative penalty directly to attention logits based on distance $|i - j|$: $$A_{ij} = \frac{q_i^\top k_j}{\sqrt{d_k}} - m \cdot |i - j|$$
- Relative Position Biases (T5): Adds learned scalar values representing binned relative distance buckets to the attention scores.
Out-of-Distribution Length Generalization
Relative approaches extrapolate better to longer context windows during inference for three primary reasons:
- Translation Invariance: Local grammatical patterns (e.g., modifier-noun relationships) behave consistently regardless of whether they appear at token position 20 or position 2,000.
- Frequency Distribution Stability: Absolute position encodings produce unseen vector values when evaluated beyond training lengths. Relative distances—especially short-range offsets that dominate attention weight—remain within familiar distributions seen during training.
- Distance Binning and Decay: Techniques like ALiBi apply monotonic distance penalties, preventing long-distance tokens from artificially dominating attention weights when contexts expand.