KatInterview

Mechanics of Positional Encodings in Transformer Architectures

Machine LearningModel answer
MediumModel answerMachine Learningtransformerspositional-encodingattention

Last 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

  1. 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.
  2. 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.
  3. 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.
  4. 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.