python
import torch
def rope_cos_sin(seq_len: int, d: int, base: float = 10000.0):
"""位置 m と組 i ごとの cos(m θ_i)、sin(m θ_i) を前もって計算する(θ_i = base^(-2(i-1)/d))"""
theta = base ** (-torch.arange(0, d, 2).float() / d) # [d/2]
angle = torch.arange(seq_len).float()[:, None] * theta # [seq_len, d/2] m θ_i
# 隣り合う 2 次元が同じ角度を使うので、各値を 2 回ずつ並べる(論文の式 (34))
cos = angle.cos().repeat_interleave(2, dim=-1) # [seq_len, d]
sin = angle.sin().repeat_interleave(2, dim=-1)
return cos, sin
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
"""x: [..., seq_len, d]。各組 (x1, x2) を角度 m θ_i だけ回転させる"""
x1, x2 = x[..., 0::2], x[..., 1::2]
rotated = torch.stack((-x2, x1), dim=-1).flatten(-2) # (-x2, x1, -x4, x3, ...)
return x * cos + rotated * sin
# アテンションの中で、クエリとキーだけを回転させる(バリューはそのまま)
B, h, n, d = 2, 8, 16, 64
q, k, v = torch.randn(B, h, n, d), torch.randn(B, h, n, d), torch.randn(B, h, n, d)
cos, sin = rope_cos_sin(n, d)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
attn = torch.softmax(q @ k.transpose(-2, -1) / d ** 0.5, dim=-1)
out = attn @ v
print(out.shape) # torch.Size([2, 8, 16, 64])
# 内積が距離だけで決まることを確かめる:同じ q と k を、位置 (1, 3) と (4, 6) に置く
q0, k0 = torch.randn(d), torch.randn(d)
cos, sin = rope_cos_sin(8, d)
dot = lambda m, n_: apply_rope(q0, cos[m], sin[m]) @ apply_rope(k0, cos[n_], sin[n_])
print(dot(1, 3).item(), dot(4, 6).item()) # 同じ値になる(距離はどちらも 2)