python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
phi-3-mini のデコーダ層を、技術報告の 2 章と参照実装(Hugging Face transformers の Phi-3)に沿って小さく書いた例
- Llama 2 と同じ形:入力側の RMSNorm、Q・K に RoPE、SwiGLU のフィードフォワード、バイアスなし
- 参照実装と同じく、Q・K・V を 1 つの全結合層(qkv_proj)で、ゲートと up を 1 つの全結合層(gate_up_proj)で計算する
- phi-3-mini:d = 3072、32 ヘッド、中間 8192、32 層、語彙 32,064
ドロップアウトは使わない(設定は 0)ので、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))
def forward(self, x):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * 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) # [max_len, head_dim]
return torch.cos(angles), torch.sin(angles)
def apply_rope(x, cos, sin):
# 前半と後半を 1 組として回転させる(rotate_half の書き方)
x1, x2 = x.chunk(2, dim=-1)
return x * cos + torch.cat((-x2, x1), dim=-1) * sin
class Phi3DecoderLayer(nn.Module):
def __init__(self, dim=3072, n_heads=32, hidden=8192):
super().__init__()
self.n_heads, self.head_dim = n_heads, dim // n_heads
self.input_norm = RMSNorm(dim)
self.qkv_proj = nn.Linear(dim, 3 * dim, bias=False)
self.o_proj = nn.Linear(dim, dim, bias=False)
self.post_attn_norm = RMSNorm(dim)
self.gate_up_proj = nn.Linear(dim, 2 * hidden, bias=False)
self.down_proj = nn.Linear(hidden, dim, bias=False)
def attention(self, h, cos, sin):
b, n, _ = h.shape
q, k, v = self.qkv_proj(h).view(b, n, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
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.o_proj(out.transpose(1, 2).reshape(b, n, -1))
def ffn(self, h):
gate, up = self.gate_up_proj(h).chunk(2, dim=-1)
return self.down_proj(up * F.silu(gate)) # SwiGLU
def forward(self, x, cos, sin):
x = x + self.attention(self.input_norm(x), cos, sin)
return x + self.ffn(self.post_attn_norm(x))
class TinyPhi3(nn.Module):
def __init__(self, vocab=32064, dim=3072, n_layers=32, n_heads=32, hidden=8192, max_len=4096):
super().__init__()
self.embed = nn.Embedding(vocab, dim)
self.layers = nn.ModuleList(Phi3DecoderLayer(dim, n_heads, hidden) for _ in range(n_layers))
self.norm = RMSNorm(dim)
self.lm_head = 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):
x = self.embed(tokens)
for layer in self.layers:
x = layer(x, self.cos, self.sin)
return self.lm_head(self.norm(x))
# 動作の確認(小さい設定)
model = TinyPhi3(vocab=1000, dim=128, n_layers=2, n_heads=4, hidden=256, max_len=64).eval()
with torch.no_grad():
print(model(torch.randint(0, 1000, (2, 16))).shape) # torch.Size([2, 16, 1000])