Positional Encoding
Positional Encoding
Encoding position information within a sequence as vectors. Lets the Transformer understand order.
Positional Encoding
Encoding position information within a sequence as vectors. Lets the Transformer understand order.
Positional Encoding is a key technique in the Transformer architecture that provides the model with information about the order of tokens in a sequence. Unlike RNNs or LSTMs, the Transformer processes all tokens simultaneously using the Self-Attention mechanism, so without separate positional information it cannot distinguish between "나는 사과를 먹었다" and "사과를 나는 먹었다". Positional Encoding solves this problem by adding positional information to the Embedding of each token.
Sine/cosine-based Positional Encoding, first proposed in the 2017 paper "Attention Is All You Need," assigns a unique vector to each position by combining sin and cos functions of different frequencies. It uses the formulas PE(pos, 2i) = sin(pos / 10000^(2i/d)) and PE(pos, 2i+1) = cos(pos / 10000^(2i/d)), and this approach has the advantages of being able to handle sequences of arbitrary length without training and of being able to express relative positional relationships as linear transformations.
As of 2024-2025, various variants have been developed. RoPE (Rotary Position Embedding) is used in LLaMA, Mistral, and others, and effectively encodes relative positional information. ALiBi (Attention with Linear Biases) adds a positional bias directly to Attention scores, giving it excellent extrapolation performance. Learnable position embeddings are used in BERT and GPT and learn the optimal positional representation from data. Recently, techniques such as YaRN and Streaming LLM have also emerged to extend the context length to 100K or more.
In practice, the choice of Positional Encoding has a direct impact on model performance. RoPE or ALiBi is preferred in RAG systems that need to process long documents, and Vision Transformers require a separate design to encode 2D coordinates. Recently, GPT-4 Turbo, Claude 3, and others support contexts of 128K or more, which is thanks to advances in efficient Positional Encoding techniques.
This is an example implementation of sine/cosine Positional Encoding and RoPE using PyTorch.
import torch
import torch.nn as nn
import math
class SinusoidalPositionalEncoding(nn.Module):
"""원본 Transformer 사인/코사인 포지셔널 인코딩"""
def __init__(self, d_model: int, max_len: int = 5000, dropout: float = 0.1):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
# 위치 인코딩 행렬 생성 [max_len, d_model]
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
# 10000^(2i/d_model) 계산
div_term = torch.exp(
torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)
)
# sin은 짝수 인덱스, cos은 홀수 인덱스
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0) # [1, max_len, d_model]
self.register_buffer('pe', pe)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: [batch_size, seq_len, d_model]"""
x = x + self.pe[:, :x.size(1), :]
return self.dropout(x)
class RotaryPositionalEncoding(nn.Module):
"""RoPE: Rotary Position Embedding (LLaMA, Mistral 등에서 사용)"""
def __init__(self, dim: int, max_len: int = 2048, base: int = 10000):
super().__init__()
self.dim = dim
self.max_len = max_len
# 주파수 계산
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
self.register_buffer('inv_freq', inv_freq)
# 캐시 생성
self._build_cache(max_len)
def _build_cache(self, seq_len: int):
t = torch.arange(seq_len, device=self.inv_freq.device)
freqs = torch.einsum('i,j->ij', t, self.inv_freq)
emb = torch.cat((freqs, freqs), dim=-1)
self.register_buffer('cos_cached', emb.cos())
self.register_buffer('sin_cached', emb.sin())
def forward(self, q: torch.Tensor, k: torch.Tensor) -> tuple:
"""Query와 Key에 회전 변환 적용"""
seq_len = q.shape[1]
cos = self.cos_cached[:seq_len].unsqueeze(0)
sin = self.sin_cached[:seq_len].unsqueeze(0)
q_embed = (q * cos) + (self._rotate_half(q) * sin)
k_embed = (k * cos) + (self._rotate_half(k) * sin)
return q_embed, k_embed
def _rotate_half(self, x: torch.Tensor) -> torch.Tensor:
x1, x2 = x[..., :x.shape[-1]//2], x[..., x.shape[-1]//2:]
return torch.cat((-x2, x1), dim=-1)
# 사용 예시
if __name__ == "__main__":
batch_size, seq_len, d_model = 2, 128, 512
# 사인/코사인 인코딩
sinusoidal_pe = SinusoidalPositionalEncoding(d_model)
x = torch.randn(batch_size, seq_len, d_model)
x_with_pos = sinusoidal_pe(x)
print(f"Sinusoidal PE 출력: {x_with_pos.shape}")
# RoPE
rope = RotaryPositionalEncoding(dim=64) # head_dim
q = torch.randn(batch_size, seq_len, 8, 64) # 8 heads
k = torch.randn(batch_size, seq_len, 8, 64)
q_rope, k_rope = rope(q, k)
print(f"RoPE 적용 후 Q: {q_rope.shape}, K: {k_rope.shape}")
| Method | Maximum context | Extrapolation Performance | Models Used |
|---|---|---|---|
| Sinusoidal (Absolute) | Length During Training | Moderate | Original Transformer |
| Learned Embedding | Length During Training | Low | BERT, GPT-2 |
| RoPE | 8K~128K+ | Excellent | LLaMA, Mistral, Qwen |
| ALiBi | Unlimited | Excellent | BLOOM, MPT |
| YaRN (RoPE Extension) | 128K+ | Excellent | LLaMA 2 Long |
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Models that use Learned Positional Embedding (BERT, GPT-2) suffer a sharp drop in performance when max_length from training is exceeded, because there are no position embeddings beyond it. Be sure to check the model's maximum context length.
The dimension of the Positional Encoding must exactly match the token Embedding dimension (d_model). If the addition operation cannot be performed, a runtime error occurs.
If you need to process long sequences such as document QA or code analysis, choose a RoPE-based model (LLaMA 3, Mistral, Claude) from the start. It is much more stable than extending the context later.