python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
phi-1 のデコーダ層を、論文 2.3 節と参照実装(Hugging Face transformers の Phi)に沿って小さく書いた例
- 1 つの LayerNorm の出力を、アテンションと MLP に並列に入れ、両方の出力と入力を足す
- RoPE は 1 ヘッド 64 次元のうち 32 次元(rotary_dim)だけにかける
- MLP は 2048 → 8192 → 2048 で、活性化関数は GELU(tanh 近似)
- 全結合層はバイアスあり
Dropout(論文では 0.1)があるので、model.train() と model.eval() で計算が変わる
"""
def rope_angles(rotary_dim, max_len, theta=10000.0):
freqs = 1.0 / (theta ** (torch.arange(0, rotary_dim, 2).float() / rotary_dim))
angles = torch.outer(torch.arange(max_len).float(), freqs) # [max_len, rotary_dim/2]
return torch.cos(angles), torch.sin(angles)
def apply_partial_rope(x, cos, sin, rotary_dim):
# x: [batch, heads, n, head_dim]。先頭の rotary_dim 次元だけを回転させ、残りはそのまま
x_rot, x_pass = x[..., :rotary_dim], x[..., rotary_dim:]
x1, x2 = x_rot[..., : rotary_dim // 2], x_rot[..., rotary_dim // 2 :]
rotated = torch.cat((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1)
return torch.cat((rotated, x_pass), dim=-1)
class ParallelDecoderLayer(nn.Module):
def __init__(self, dim=2048, n_heads=32, mlp_dim=8192, rotary_dim=32, dropout=0.1):
super().__init__()
self.n_heads, self.head_dim, self.rotary_dim = n_heads, dim // n_heads, rotary_dim
self.ln = nn.LayerNorm(dim) # アテンションと MLP で共有する
self.qkv = nn.Linear(dim, 3 * dim)
self.out = nn.Linear(dim, dim)
self.fc1 = nn.Linear(dim, mlp_dim)
self.fc2 = nn.Linear(mlp_dim, dim)
self.attn_dropout = dropout
self.resid_dropout = nn.Dropout(dropout)
def attention(self, h, cos, sin):
b, n, _ = h.shape
q, k, v = self.qkv(h).view(b, n, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)
q = apply_partial_rope(q, cos[:n], sin[:n], self.rotary_dim)
k = apply_partial_rope(k, cos[:n], sin[:n], self.rotary_dim)
out = F.scaled_dot_product_attention(
q, k, v, is_causal=True, # 先を隠す
dropout_p=self.attn_dropout if self.training else 0.0)
return self.out(out.transpose(1, 2).reshape(b, n, -1))
def mlp(self, h):
return self.fc2(F.gelu(self.fc1(h), approximate="tanh"))
def forward(self, x, cos, sin):
h = self.ln(x)
# 順に通すのではなく、同じ h から同時に計算して足す
return x + self.resid_dropout(self.attention(h, cos, sin)) + self.resid_dropout(self.mlp(h))
class TinyPhi1(nn.Module):
def __init__(self, vocab=51200, dim=2048, n_layers=24, n_heads=32, max_len=2048):
super().__init__()
self.embed = nn.Embedding(vocab, dim) # 位置の埋め込みはない(RoPE で入れる)
self.layers = nn.ModuleList(ParallelDecoderLayer(dim, n_heads, 4 * dim) for _ in range(n_layers))
self.final_ln = nn.LayerNorm(dim)
self.lm_head = nn.Linear(dim, vocab)
cos, sin = rope_angles(32, max_len)
self.register_buffer("cos", cos, persistent=False)
self.register_buffer("sin", sin, persistent=False)
def forward(self, tokens): # tokens: [batch, n]
x = self.embed(tokens)
for layer in self.layers:
x = layer(x, self.cos, self.sin)
return self.lm_head(self.final_ln(x)) # 次のトークンのロジット
# 動作の確認(小さい設定)
model = TinyPhi1(vocab=1000, dim=128, n_layers=2, n_heads=2, max_len=64)
tokens = torch.randint(0, 1000, (2, 16))
model.train()
logits = model(tokens)
loss = F.cross_entropy(logits[:, :-1].reshape(-1, 1000), tokens[:, 1:].reshape(-1))
model.eval()
with torch.no_grad():
print(model(tokens).shape) # torch.Size([2, 16, 1000])