python コピー
import math
import torch
def yarn_inv_freq(d: int, L: int, s: float, base: float = 10000.0,
alpha: float = 1.0, beta: float = 32.0) -> torch.Tensor:
"""YaRN の回転の速さ h(θ_j)(論文の式 (8)・(10)・(11)・(13))"""
theta = base ** (-torch.arange(0, d, 2).float() / d) # θ_j = b^(-2j/|D|)
wavelength = 2 * math.pi / theta # λ_j
r = L / wavelength # 学習の長さ L の間に回る回数
gamma = ((r - alpha) / (beta - alpha)).clamp(0.0, 1.0) # r < α で 0、r > β で 1
return (1 - gamma) * theta / s + gamma * theta # 遅い組は θ/s、速い組は θ のまま
def yarn_cos_sin(seq_len: int, d: int, L: int, s: float):
inv_freq = yarn_inv_freq(d, L, s)
angle = torch.arange(seq_len).float()[:, None] * inv_freq # 位置の番号はそのまま(g(m) = m)
mscale = 0.1 * math.log(s) + 1.0 # √(1/t)(式 (15))
cos = angle.cos().repeat_interleave(2, dim=-1) * mscale # cos・sin にかけておくと q と k の両方にかかる
sin = angle.sin().repeat_interleave(2, dim=-1) * mscale
return cos, sin
def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
x1, x2 = x[..., 0::2], x[..., 1::2]
rotated = torch.stack((-x2, x1), dim=-1).flatten(-2)
return x * cos + rotated * sin
L, s, d = 2048, 16, 128 # LLaMA 7B を 16 倍(32k)に延ばす
ratio = yarn_inv_freq(d, L, s) / (10000.0 ** (-torch.arange(0, d, 2).float() / d))
print(ratio[:3], ratio[-3:]) # 速い組は 1.0、遅い組は 0.0625(= 1/16)
B, h, n = 1, 8, 4096
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
cos, sin = yarn_cos_sin(n, d, L, s)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) # スコアは 1/t 倍になる
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
print(out.shape) # torch.Size([1, 8, 4096, 128])
# Hugging Face Transformers では設定だけで使える(このあと短くファインチューニングする)
# model = AutoModelForCausalLM.from_pretrained(name, rope_scaling={"type": "yarn", "factor": 16.0})