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
| Method | Type | Length Generalization | Used In |
|---|---|---|---|
| Sinusoidal | Fixed | Moderate | Original Transformer |
| Learned | Trainable | ❌ Fixed max length | GPT-2, BERT |
| RoPE | Rotary | ✅ Good (with scaling) | LLaMA, Mistral |
| ALiBi | Bias-based | ✅ Excellent | BLOOM |
Sinusoidal (Original)
Fixed sin/cos at different frequencies:
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: . 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.
Related questions
- Explain the self-attention mechanism in detail. What are Q, K, V and why do we use scaled dot-product attention?
- Explain FlashAttention. How does it achieve sub-quadratic memory while maintaining exact attention?
- What are Large Language Models (LLMs) and how do they work?
- How does multi-head attention differ from single-head attention? Why use multiple heads?
- Explain the difference between LoRA, full fine-tuning, and prompt tuning. When would you use each?