python コピー
import torch
def rope_cos_sin(seq_len: int, d: int, base: float = 10000.0, scale: float = 1.0):
"""位置 m の代わりに m * scale(位置補間では scale = L / L')で cos・sin を計算する"""
theta = base ** (-torch.arange(0, d, 2).float() / d) # θ_j = 10000^(-2j/d)
pos = torch.arange(seq_len).float() * scale # 位置補間:m → m L / L'(小数になる)
angle = pos[:, None] * theta # [seq_len, d/2]
cos = angle.cos().repeat_interleave(2, dim=-1) # 隣り合う 2 次元で同じ角度
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) を回転させる(RoPE と同じ)"""
x1, x2 = x[..., 0::2], x[..., 1::2]
rotated = torch.stack((-x2, x1), dim=-1).flatten(-2)
return x * cos + rotated * sin
L, L_new = 2048, 8192 # 事前学習の長さと、延ばしたい長さ
scale = L / L_new # 1/4
B, h, d = 1, 8, 128
n = 4096 # 事前学習より長い入力
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
cos, sin = rope_cos_sin(n, d, scale=scale)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
print(out.shape) # torch.Size([1, 8, 4096, 128])
# RoPE に渡る最大の位置は、学習した範囲に収まる
print((n - 1) * scale < L) # True(4095 / 4 = 1023.75)
# Hugging Face Transformers の LLaMA では、設定だけで同じことができる(このあと短くファインチューニングする)
# from transformers import AutoModelForCausalLM
# model = AutoModelForCausalLM.from_pretrained(name, rope_scaling={"type": "linear", "factor": L_new / L})