python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Gemma のデコーダ層を、技術報告の Model Architecture の節と公式の実装(google/gemma_pytorch)に沿って小さく書いた例
- 入力側の RMSNorm(ゲインは 1 + w)、Q・K に RoPE、GeGLU のフィードフォワード(GELU は tanh の近似)、バイアスなし
- n_kv_heads = 1 ならマルチクエリ(2B)、n_heads と同じならマルチヘッド(7B)
- 埋め込みに √d をかけ、出力の全結合層は埋め込みと重みを共有する
ドロップアウトは使わないので、model.train() と model.eval() で計算は変わらない
"""
class GemmaRMSNorm(nn.Module):
def __init__(self, dim, eps=1e-6):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.zeros(dim)) # 0 から学習し、(1 + w) をかける
def forward(self, x):
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
return x * (1 + self.weight)
def rope_angles(head_dim, max_len, theta=10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs)
angles = torch.cat((angles, angles), dim=-1)
return torch.cos(angles), torch.sin(angles)
def apply_rope(x, cos, sin):
x1, x2 = x.chunk(2, dim=-1)
return x * cos + torch.cat((-x2, x1), dim=-1) * sin
class GemmaDecoderLayer(nn.Module):
def __init__(self, dim, n_heads, n_kv_heads, head_dim, hidden):
super().__init__()
self.n_heads, self.n_kv_heads, self.head_dim = n_heads, n_kv_heads, head_dim
self.attn_norm = GemmaRMSNorm(dim)
self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False) # 7B は 16 × 256 = 4096(d = 3072 と違う)
self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
self.ffn_norm = GemmaRMSNorm(dim)
self.gate_proj = nn.Linear(dim, hidden, bias=False) # W(GELU に通す側)
self.up_proj = nn.Linear(dim, hidden, bias=False) # V
self.down_proj = nn.Linear(hidden, dim, bias=False) # W2
def attention(self, h, cos, sin):
b, n, _ = h.shape
q = self.q_proj(h).view(b, n, self.n_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(h).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(h).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
q, k = apply_rope(q, cos[:n], sin[:n]), apply_rope(k, cos[:n], sin[:n])
rep = self.n_heads // self.n_kv_heads # マルチクエリなら全ヘッドで同じ K・V を使う
k, v = k.repeat_interleave(rep, dim=1), v.repeat_interleave(rep, dim=1)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return self.o_proj(out.transpose(1, 2).reshape(b, n, -1))
def ffn(self, h):
return self.down_proj(F.gelu(self.gate_proj(h), approximate="tanh") * self.up_proj(h)) # GeGLU
def forward(self, x, cos, sin):
x = x + self.attention(self.attn_norm(x), cos, sin)
return x + self.ffn(self.ffn_norm(x))
class TinyGemma(nn.Module):
# 2B:dim=2048, n_layers=18, n_heads=8, n_kv_heads=1, head_dim=256, hidden=16384
# 7B:dim=3072, n_layers=28, n_heads=16, n_kv_heads=16, head_dim=256, hidden=24576
def __init__(self, vocab=256128, dim=2048, n_layers=18, n_heads=8, n_kv_heads=1, head_dim=256, hidden=16384, max_len=8192):
super().__init__()
self.dim = dim
self.embed = nn.Embedding(vocab, dim)
self.layers = nn.ModuleList(GemmaDecoderLayer(dim, n_heads, n_kv_heads, head_dim, hidden) for _ in range(n_layers))
self.norm = GemmaRMSNorm(dim)
cos, sin = rope_angles(head_dim, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens):
x = self.embed(tokens) * self.dim ** 0.5 # √d 倍してから入れる
for layer in self.layers:
x = layer(x, self.cos, self.sin)
return self.norm(x) @ self.embed.weight.T # 出力は埋め込みと同じ重み
# 動作の確認(小さい設定・マルチクエリ)
model = TinyGemma(vocab=1000, dim=128, n_layers=2, n_heads=4, n_kv_heads=1, head_dim=32, hidden=256, max_len=64).eval()
with torch.no_grad():
print(model(torch.randint(0, 1000, (2, 16))).shape) # torch.Size([2, 16, 1000])