Transformer cần cơ chế cho model biết thứ tự token (attention tự nó là permutation-invariant).
Các cách positional encoding:
- Sinusoidal (Transformer gốc) — cộng vector sin/cos cố định vào embedding. Extrapolate kém với seq dài hơn train.
- Learned (BERT, GPT-2) — embedding positional trainable. Giới hạn ở max length khi train, không extrapolate.
- RoPE (Su et al. 2021) — rotate Q và K bằng ma trận rotation phụ thuộc vị trí trước khi tính attention.
- ALiBi — thêm bias tuyến tính vào attention score theo khoảng cách; extrapolate tốt.
Cơ chế RoPE: với mỗi pair chiều của Q và K, áp dụng rotation 2D theo góc θ_i · pos (trong đó θ_i = 10000^(-2i/d)). Tính chất toán học quan trọng: <RoPE(q, m), RoPE(k, n)> = <q, k, m-n> — inner product chỉ phụ thuộc khoảng cách tương đối m-n, không phải vị trí tuyệt đối.
Ưu điểm:
- Relative position encoding tự nhiên, phù hợp ngôn ngữ.
- Không thêm parameters (không phải embedding trainable).
- Extrapolation tốt hơn learned position; với các trick như Position Interpolation, YaRN, NTK-aware scaling có thể mở rộng context 4-32x qua fine-tune nhẹ.
- Áp dụng trực tiếp vào Q, K (không modify toàn bộ pipeline).
Do đó RoPE là default của hầu hết LLM hiện đại: LLaMA 1/2/3, Mistral, Qwen, DeepSeek, GPT-NeoX, PaLM (variant). Các kỹ thuật context extension phổ biến đều dựa trên RoPE: PI (chia pos cho s), NTK (chia theta), YaRN (kết hợp), LongRoPE (tune theta từng pair) — cho phép mở context 128K, 1M+ từ model train 4K-8K.
Transformers need a mechanism to know token order (attention itself is permutation-invariant).
Positional encoding options:
- Sinusoidal (original Transformer) — add fixed sin/cos vectors to embeddings. Poor extrapolation beyond training length.
- Learned (BERT, GPT-2) — trainable position embeddings. Capped at training max length, no extrapolation.
- RoPE (Su et al. 2021) — rotate Q and K by a position-dependent rotation matrix before computing attention.
- ALiBi — add a linear bias to attention scores based on distance; extrapolates well.
RoPE mechanics: for each dim-pair in Q and K, apply a 2D rotation by angle θ_i · pos (where θ_i = 10000^(-2i/d)). Key math property: <RoPE(q, m), RoPE(k, n)> = <q, k, m-n> — the inner product depends only on relative position m-n, not absolute position.
Advantages:
- Natural relative position encoding, suitable for language.
- No extra parameters (not trainable embeddings).
- Better extrapolation than learned positions; with Position Interpolation, YaRN, NTK-aware scaling tricks, context extends 4–32x via lightweight fine-tuning.
- Applied directly to Q, K (no pipeline rewrite).
RoPE is the default in most modern LLMs: LLaMA 1/2/3, Mistral, Qwen, DeepSeek, GPT-NeoX, PaLM (variant). Popular context-extension techniques are RoPE-based: PI (divide pos by s), NTK (divide theta), YaRN (combined), LongRoPE (per-pair theta tuning) — extending 4K–8K-trained models to 128K, 1M+ context.