llm-124m / code /model.py
alexander2323's picture
Upload folder using huggingface_hub
dc9424f verified
Raw History Blame Contribute Delete
6.74 kB
"""
model.py - the GPT-2 architecture in plain PyTorch.
A decoder-only transformer, laid out exactly as GPT-2:
token embedding + learned position embedding
N blocks of [LayerNorm -> causal self-attention -> add] [LayerNorm -> MLP -> add]
final LayerNorm
linear head over the vocabulary, weights tied to the token embedding
The size presets at the bottom match the published GPT-2 sizes, plus a tiny one
for testing on the Mac.
"""
import math
from dataclasses import dataclass
import torch
import torch.nn as nn
import torch.nn.functional as F
@dataclass
class GPTConfig:
block_size: int = 1024 # context length in tokens
vocab_size: int = 50304 # GPT-2 has 50257 tokens, padded up to a multiple of 64 for speed
n_layer: int = 12
n_head: int = 12
n_embd: int = 768
dropout: float = 0.0
bias: bool = True
class CausalSelfAttention(nn.Module):
def __init__(self, cfg):
super().__init__()
assert cfg.n_embd % cfg.n_head == 0
self.n_head = cfg.n_head
self.n_embd = cfg.n_embd
self.c_attn = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=cfg.bias) # q, k, v in one matmul
self.c_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=cfg.bias)
self.dropout = cfg.dropout
self.resid_drop = nn.Dropout(cfg.dropout)
def forward(self, x):
B, T, C = x.shape
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, heads, T, head_dim)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
# fused attention kernel (flash attention on CUDA); is_causal masks the future
y = F.scaled_dot_product_attention(
q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0)
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.resid_drop(self.c_proj(y))
class MLP(nn.Module):
def __init__(self, cfg):
super().__init__()
self.c_fc = nn.Linear(cfg.n_embd, 4 * cfg.n_embd, bias=cfg.bias)
self.c_proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd, bias=cfg.bias)
self.drop = nn.Dropout(cfg.dropout)
def forward(self, x):
return self.drop(self.c_proj(F.gelu(self.c_fc(x), approximate="tanh")))
class Block(nn.Module):
def __init__(self, cfg):
super().__init__()
self.ln_1 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
self.attn = CausalSelfAttention(cfg)
self.ln_2 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias)
self.mlp = MLP(cfg)
def forward(self, x):
x = x + self.attn(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
class GPT(nn.Module):
def __init__(self, cfg: GPTConfig):
super().__init__()
self.cfg = cfg
self.transformer = nn.ModuleDict(dict(
wte=nn.Embedding(cfg.vocab_size, cfg.n_embd),
wpe=nn.Embedding(cfg.block_size, cfg.n_embd),
drop=nn.Dropout(cfg.dropout),
h=nn.ModuleList([Block(cfg) for _ in range(cfg.n_layer)]),
ln_f=nn.LayerNorm(cfg.n_embd, bias=cfg.bias),
))
self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False)
self.transformer.wte.weight = self.lm_head.weight # weight tying, as in GPT-2
self.apply(self._init_weights)
# GPT-2 scales the residual projections down with depth so activations stay bounded
for name, p in self.named_parameters():
if name.endswith("c_proj.weight"):
nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer))
def _init_weights(self, module):
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=0.0, std=0.02)
def num_params(self, non_embedding=True):
n = sum(p.numel() for p in self.parameters())
if non_embedding:
n -= self.transformer.wpe.weight.numel()
return n
def forward(self, idx, targets=None):
B, T = idx.shape
assert T <= self.cfg.block_size, f"sequence of {T} tokens exceeds block size {self.cfg.block_size}"
pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
x = self.transformer.drop(self.transformer.wte(idx) + self.transformer.wpe(pos))
for block in self.transformer.h:
x = block(x)
x = self.transformer.ln_f(x)
if targets is not None:
logits = self.lm_head(x)
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
return logits, loss
# inference: only the last position is needed for the next token
logits = self.lm_head(x[:, [-1], :])
return logits, None
def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
# weight decay on matrices and embeddings, none on biases and LayerNorm gains
params = [p for p in self.parameters() if p.requires_grad]
decay = [p for p in params if p.dim() >= 2]
no_decay = [p for p in params if p.dim() < 2]
groups = [
{"params": decay, "weight_decay": weight_decay},
{"params": no_decay, "weight_decay": 0.0},
]
return torch.optim.AdamW(groups, lr=learning_rate, betas=betas, fused=(device_type == "cuda"))
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
"""Yields one new token id at a time, so the caller can print as it goes."""
for _ in range(max_new_tokens):
idx_cond = idx if idx.size(1) <= self.cfg.block_size else idx[:, -self.cfg.block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :] / max(temperature, 1e-5)
if top_k is not None:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = -float("inf")
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
idx = torch.cat((idx, idx_next), dim=1)
yield idx_next.item()
# published GPT-2 sizes, plus a tiny one for the Mac
PRESETS = {
"tiny": dict(n_layer=4, n_head=4, n_embd=128),
"124M": dict(n_layer=12, n_head=12, n_embd=768),
"350M": dict(n_layer=24, n_head=16, n_embd=1024),
"774M": dict(n_layer=36, n_head=20, n_embd=1280),
"1.5B": dict(n_layer=48, n_head=25, n_embd=1600),
}