python コピー
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
TinyLlama のデコーダ層を、論文 2.2 節・Table 1 と公式の設定(jzhang38/TinyLlama の tiny_LLaMA_1b)に沿って小さく書いた例
- Llama 2 と同じ部品:入力側の RMSNorm、Q・K に RoPE、SwiGLU のフィードフォワード、バイアスなし
- GQA:クエリ 32 ヘッド、キー・バリュー 4 ヘッド(8 個のクエリのヘッドで 1 組を共有)
- d = 2048、中間 5632、22 層、文脈 2048、語彙 32,000
ドロップアウトは使わないので、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)
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 GQAttention(nn.Module):
def __init__(self, dim=2048, n_heads=32, n_kv_heads=4):
super().__init__()
self.n_heads, self.n_kv_heads, self.head_dim = n_heads, n_kv_heads, dim // n_heads
self.wq = nn.Linear(dim, n_heads * self.head_dim, bias=False)
self.wk = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False) # K・V は 4 ヘッドだけ
self.wv = nn.Linear(dim, n_kv_heads * self.head_dim, bias=False)
self.wo = nn.Linear(dim, dim, bias=False)
def forward(self, x, cos, sin):
b, n, _ = x.shape
q = self.wq(x).view(b, n, self.n_heads, self.head_dim).transpose(1, 2)
k = self.wk(x).view(b, n, self.n_kv_heads, self.head_dim).transpose(1, 2)
v = self.wv(x).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 # 8 個のクエリのヘッドで同じ 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.wo(out.transpose(1, 2).reshape(b, n, -1))
class SwiGLU(nn.Module):
def __init__(self, dim=2048, hidden=5632):
super().__init__()
self.w1 = nn.Linear(dim, hidden, bias=False) # ゲート側(SiLU に通す)
self.w3 = nn.Linear(dim, hidden, bias=False)
self.w2 = nn.Linear(hidden, dim, bias=False)
def forward(self, x):
return self.w2(F.silu(self.w1(x)) * self.w3(x))
class DecoderLayer(nn.Module):
def __init__(self, dim, n_heads, n_kv_heads, hidden):
super().__init__()
self.attn_norm, self.attn = RMSNorm(dim), GQAttention(dim, n_heads, n_kv_heads)
self.ffn_norm, self.ffn = RMSNorm(dim), SwiGLU(dim, hidden)
def forward(self, x, cos, sin):
x = x + self.attn(self.attn_norm(x), cos, sin)
return x + self.ffn(self.ffn_norm(x))
class TinyLlama(nn.Module):
def __init__(self, vocab=32000, dim=2048, n_layers=22, n_heads=32, n_kv_heads=4, hidden=5632, max_len=2048):
super().__init__()
self.embed = nn.Embedding(vocab, dim)
self.layers = nn.ModuleList(DecoderLayer(dim, n_heads, n_kv_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 = TinyLlama(vocab=1000, dim=128, n_layers=2, n_heads=8, n_kv_heads=2, hidden=352, max_len=64).eval()
with torch.no_grad():
print(model(torch.randint(0, 1000, (2, 16))).shape) # torch.Size([2, 16, 1000])
# 公開の重みは Hugging Face transformers の Llama のクラスで読み込める
# from transformers import AutoModelForCausalLM
# model = AutoModelForCausalLM.from_pretrained("TinyLlama/TinyLlama_v1.1")