MLCrack

    LLMS & TRANSFORMERS · INTERVIEW QUESTION

    Explain positional encoding in Transformers. Compare sinusoidal, learned, RoPE, and ALiBi.

    🔴 advanced · Transformer Architecture

    Hint: Without position signals or order-dependent masks, self-attention is permutation-equivariant; how can we represent order?

    Answer

    Without positional information or order-dependent masking, self-attention is permutation-equivariant: permuting input tokens permutes their outputs. Therefore, we must inject position information explicitly.

    Comparison

    MethodTypeLength GeneralizationUsed In
    SinusoidalFixedModerateOriginal Transformer
    LearnedTrainable❌ Fixed max lengthGPT-2, BERT
    RoPERotary✅ Good (with scaling)LLaMA, Mistral
    ALiBiBias-based✅ ExcellentBLOOM

    Sinusoidal (Original)

    Fixed sin/cos at different frequencies: PE(pos,2i)=sin⁡(pos/100002i/d)PE(pos, 2i) = \sin(pos / 10000^{2i/d})

    RoPE (Rotary Position Embedding)

    Applies rotation matrices to Q and K, encoding relative positions directly in the attention dot product. Most popular in modern LLMs.

    ALiBi

    No positional embeddings — adds a linear bias to attention scores based on token distance: score−=m⋅∣i−j∣\text{score} -= m \cdot |i - j|. Excellent extrapolation.

    Modern trend: RoPE dominates for its balance of expressiveness and length generalization. With NTK scaling or YaRN, RoPE models extend from 4K to 128K+ context.