3. Positional Encoding
The Necessity of Positional Awareness
The Transformer architecture, unlike RNNs or LSTMs, processes input sequences in parallel rather than sequentially. The core mechanism, self-attention, is inherently permutation-invariant. This means that if you shuffle the input tokens, the output vectors would simply be shuffled accordingly, as the attention weights depend only on the content similarity (dot product) and not on the spatial distance between tokens. Without explicit positional information, a Transformer treats the input as a 'bag of words'.
To restore the sense of order, we must inject positional signals into the input embeddings. This is achieved by adding or concatenating vectors that encode the position index of each token. The design of these signals is critical, as they must allow the model to attend to relative positions and potentially generalize to sequence lengths not seen during training.
import torch # Demonstrating permutation invariance # If we swap positions, the sum of weighted values remains the same seq_len, d_model = 4, 8 x = torch.randn(seq_len, d_model) attention_scores = torch.softmax(torch.matmul(x, x.T), dim=-1) output = torch.matmul(attention_scores, x) # Swapping rows changes output in the exact same index order x_permuted = x[[1, 0, 3, 2]] # The network needs Positional Embeddings to distinguish these states
Sinusoidal and Learned Embeddings
The original 'Attention Is All You Need' paper introduced fixed sinusoidal positional encodings. By using sine and cosine functions of different frequencies, the model can represent relative positions as linear functions. Specifically, PE(pos, 2i) = sin(pos/10000^(2i/d_model)) and PE(pos, 2i+1) = cos(pos/10000^(2i/d_model)). This allows the network to learn to attend by relative positions, as any fixed offset k can be represented as a linear function of the position embedding.
In contrast, learned positional embeddings treat the position indices as embedding table entries, updated via backpropagation. While learned embeddings are simple and effective for fixed-length tasks, they fail to extrapolate to sequences longer than those encountered during training, as there is no defined parameter for unseen index positions.
import numpy as np def get_sinusoidal_pe(pos, d_model): pe = np.zeros((pos, d_model)) for i in range(d_model // 2): div = 10000 ** (2 * i / d_model) pe[:, 2*i] = np.sin(np.arange(pos) / div) pe[:, 2*i+1] = np.cos(np.arange(pos) / div) return pe pe_matrix = get_sinusoidal_pe(10, 16)
Relative Positional Embeddings and RoPE
Rotary Positional Embeddings (RoPE) represent a paradigm shift. Rather than adding an embedding to the input, RoPE applies a rotation matrix to the Query and Key vectors in the complex space. The rotation angle is proportional to the position index. This encodes relative positional information directly into the attention mechanism, as the dot product between a query and key effectively becomes a function of their relative distance.
RoPE is widely used in modern LLMs like Llama 3 and Mistral because it preserves the length of the vectors and naturally integrates with efficient linear attention. Furthermore, it allows for context window extension through techniques like NTK-aware interpolation or yarn-scaling, where frequency bases are modified to accommodate longer sequence lengths without full fine-tuning.
import torch # Concept of RoPE rotation for 2D vectors def rotate_half(x): x1, x2 = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:] return torch.cat([-x2, x1], dim=-1) # Simplified RoPE application def apply_rotary_pos_emb(q, cos, sin): return (q * cos) + (rotate_half(q) * sin)
Knowledge Check
Ready to test your understanding of 3. Positional Encoding?