python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
LLaMA の部品を、論文 2.2 節と公式の実装(facebookresearch/llama)に沿って小さく書いた例
- RMSNorm:平均を引かず、二乗平均平方根で割ってゲインをかける
- SwiGLU のフィードフォワード:(SiLU(xW) * xV) W2。中間の長さは (2/3)·4d を 256 の倍数に切り上げる
- RoPE:クエリとキーを位置に比例した角度で回転させる(バリューには使わない)
- デコーダ層:x + Attention(RMSNorm(x))、x + FFN(RMSNorm(x))。全結合層にバイアスはない
ドロップアウトを使わないので、model.train() と model.eval() で計算は変わらない
"""
class RMSNorm(nn.Module):
def __init__(self, dim, eps=1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(dim)) # ゲイン g(1 から始める)
def forward(self, x):
rms = torch.sqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x / rms * self.weight
class SwiGLUFeedForward(nn.Module):
def __init__(self, dim, multiple_of=256):
super().__init__()
hidden = int(2 * (4 * dim) / 3) # (2/3)·4d
hidden = multiple_of * ((hidden + multiple_of - 1) // multiple_of) # 7B(d=4096)なら 11008
self.w = nn.Linear(dim, hidden, bias=False) # ゲート側(SiLU に通す)
self.v = nn.Linear(dim, hidden, bias=False)
self.w2 = nn.Linear(hidden, dim, bias=False)
def forward(self, x):
return self.w2(F.silu(self.w(x)) * self.v(x))
def rope_angles(head_dim, max_len, theta=10000.0):
# 2 次元ずつの組ごとに回転の速さ θ_i = 10000^(-2(i-1)/d) を決め、位置 m の角度 m·θ_i を作る
freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs) # [max_len, head_dim/2]
return torch.cos(angles), torch.sin(angles)
def apply_rope(x, cos, sin):
# x: [batch, heads, n, head_dim]。隣り合う2つの値を1組として回転させる
x1, x2 = x[..., 0::2], x[..., 1::2]
out = torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
return out.flatten(-2)
class Attention(nn.Module):
def __init__(self, dim, n_heads):
super().__init__()
self.n_heads, self.head_dim = n_heads, dim // n_heads
self.wq = nn.Linear(dim, dim, bias=False)
self.wk = nn.Linear(dim, dim, bias=False)
self.wv = nn.Linear(dim, dim, bias=False)
self.wo = nn.Linear(dim, dim, bias=False)
def forward(self, x, cos, sin):
b, n, _ = x.shape
split = lambda t: t.view(b, n, self.n_heads, self.head_dim).transpose(1, 2)
q, k, v = split(self.wq(x)), split(self.wk(x)), split(self.wv(x))
q, k = apply_rope(q, cos[:n], sin[:n]), apply_rope(k, cos[:n], sin[:n])
out = F.scaled_dot_product_attention(q, k, v, is_causal=True) # 先を隠す
return self.wo(out.transpose(1, 2).reshape(b, n, -1))
class DecoderLayer(nn.Module):
def __init__(self, dim, n_heads):
super().__init__()
self.attn_norm, self.attn = RMSNorm(dim), Attention(dim, n_heads)
self.ffn_norm, self.ffn = RMSNorm(dim), SwiGLUFeedForward(dim)
def forward(self, x, cos, sin):
x = x + self.attn(self.attn_norm(x), cos, sin) # 入力側で正規化(Pre-LN)
return x + self.ffn(self.ffn_norm(x))
class TinyLLaMA(nn.Module):
def __init__(self, vocab=32000, dim=512, n_layers=4, n_heads=8, max_len=2048):
super().__init__()
self.embed = nn.Embedding(vocab, dim) # 位置の埋め込みはない
self.layers = nn.ModuleList(DecoderLayer(dim, n_heads) for _ in range(n_layers))
self.norm = RMSNorm(dim) # 最後に1つ
self.out = nn.Linear(dim, vocab, bias=False)
cos, sin = rope_angles(dim // n_heads, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens):
h = self.embed(tokens)
for layer in self.layers:
h = layer(h, self.cos, self.sin)
return self.out(self.norm(h)) # 次のトークンのロジット
model = TinyLLaMA()
tokens = torch.randint(0, 32000, (2, 16))
logits = model(tokens)
print(logits.shape) # torch.Size([2, 16, 32000])
# 学習済みの重みは Hugging Face transformers の LlamaForCausalLM で読み込める
# (配布元のライセンスに同意して入手した重みを、変換してから使う)