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
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Stage 2: MODEL ARCHITECTURE.
|
| 3 |
+
|
| 4 |
+
A from-scratch GPT-style decoder-only transformer, built directly in PyTorch
|
| 5 |
+
(no pretrained weights, no transformers.AutoModel -- this is the part that
|
| 6 |
+
makes "built an LLM from scratch" an honest claim):
|
| 7 |
+
- token + positional embeddings
|
| 8 |
+
- N transformer blocks, each with: multi-head causal self-attention,
|
| 9 |
+
a feed-forward MLP, and layer norm (pre-norm, like GPT-2)
|
| 10 |
+
- a final layer norm + linear head tied to the token embedding weights
|
| 11 |
+
|
| 12 |
+
Sizes (see PRESETS below):
|
| 13 |
+
- "tiny" ~ a few M params -> for a fast CPU dry-run / sanity check
|
| 14 |
+
- "small" ~ 30M params -> trains in well under an hour on an RTX 3060
|
| 15 |
+
- "medium" ~ 125M params -> GPT-1 scale, still fits an RTX 3060 12GB
|
| 16 |
+
"""
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn as nn
|
| 22 |
+
from torch.nn import functional as F
|
| 23 |
+
|
| 24 |
+
PRESETS = {
|
| 25 |
+
"tiny": dict(n_layer=4, n_head=4, n_embd=128, block_size=128), # CPU dry-run
|
| 26 |
+
"small": dict(n_layer=6, n_head=6, n_embd=384, block_size=256), # ~30M params
|
| 27 |
+
"medium": dict(n_layer=12, n_head=12, n_embd=768, block_size=512), # ~125M params
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class GPTConfig:
|
| 33 |
+
vocab_size: int = 8000
|
| 34 |
+
block_size: int = 256
|
| 35 |
+
n_layer: int = 6
|
| 36 |
+
n_head: int = 6
|
| 37 |
+
n_embd: int = 384
|
| 38 |
+
dropout: float = 0.1
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CausalSelfAttention(nn.Module):
|
| 42 |
+
def __init__(self, config: GPTConfig):
|
| 43 |
+
super().__init__()
|
| 44 |
+
assert config.n_embd % config.n_head == 0
|
| 45 |
+
self.n_head = config.n_head
|
| 46 |
+
self.head_dim = config.n_embd // config.n_head
|
| 47 |
+
self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 48 |
+
self.proj = nn.Linear(config.n_embd, config.n_embd)
|
| 49 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
| 50 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
| 51 |
+
mask = torch.tril(torch.ones(config.block_size, config.block_size))
|
| 52 |
+
self.register_buffer("mask", mask.view(1, 1, config.block_size, config.block_size))
|
| 53 |
+
|
| 54 |
+
def forward(self, x):
|
| 55 |
+
B, T, C = x.shape
|
| 56 |
+
qkv = self.qkv(x)
|
| 57 |
+
q, k, v = qkv.split(C, dim=2)
|
| 58 |
+
q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
|
| 59 |
+
k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
|
| 60 |
+
v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
|
| 61 |
+
|
| 62 |
+
att = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 63 |
+
att = att.masked_fill(self.mask[:, :, :T, :T] == 0, float("-inf"))
|
| 64 |
+
att = F.softmax(att, dim=-1)
|
| 65 |
+
att = self.attn_dropout(att)
|
| 66 |
+
y = att @ v
|
| 67 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 68 |
+
return self.resid_dropout(self.proj(y))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class MLP(nn.Module):
|
| 72 |
+
def __init__(self, config: GPTConfig):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
| 75 |
+
self.proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
| 76 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 77 |
+
|
| 78 |
+
def forward(self, x):
|
| 79 |
+
return self.dropout(self.proj(F.gelu(self.fc(x))))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class Block(nn.Module):
|
| 83 |
+
def __init__(self, config: GPTConfig):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.ln1 = nn.LayerNorm(config.n_embd)
|
| 86 |
+
self.attn = CausalSelfAttention(config)
|
| 87 |
+
self.ln2 = nn.LayerNorm(config.n_embd)
|
| 88 |
+
self.mlp = MLP(config)
|
| 89 |
+
|
| 90 |
+
def forward(self, x):
|
| 91 |
+
x = x + self.attn(self.ln1(x))
|
| 92 |
+
x = x + self.mlp(self.ln2(x))
|
| 93 |
+
return x
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class GPT(nn.Module):
|
| 97 |
+
def __init__(self, config: GPTConfig):
|
| 98 |
+
super().__init__()
|
| 99 |
+
self.config = config
|
| 100 |
+
self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
|
| 101 |
+
self.pos_emb = nn.Embedding(config.block_size, config.n_embd)
|
| 102 |
+
self.drop = nn.Dropout(config.dropout)
|
| 103 |
+
self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
|
| 104 |
+
self.ln_f = nn.LayerNorm(config.n_embd)
|
| 105 |
+
self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 106 |
+
self.head.weight = self.tok_emb.weight # weight tying
|
| 107 |
+
|
| 108 |
+
self.apply(self._init_weights)
|
| 109 |
+
n_params = sum(p.numel() for p in self.parameters())
|
| 110 |
+
print(f"GPT initialized: {n_params/1e6:.2f}M parameters "
|
| 111 |
+
f"(n_layer={config.n_layer}, n_head={config.n_head}, "
|
| 112 |
+
f"n_embd={config.n_embd}, vocab_size={config.vocab_size}, "
|
| 113 |
+
f"block_size={config.block_size})")
|
| 114 |
+
|
| 115 |
+
def _init_weights(self, module):
|
| 116 |
+
if isinstance(module, nn.Linear):
|
| 117 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 118 |
+
if module.bias is not None:
|
| 119 |
+
nn.init.zeros_(module.bias)
|
| 120 |
+
elif isinstance(module, nn.Embedding):
|
| 121 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 122 |
+
|
| 123 |
+
def forward(self, idx, targets=None):
|
| 124 |
+
B, T = idx.shape
|
| 125 |
+
assert T <= self.config.block_size, "sequence longer than block_size"
|
| 126 |
+
pos = torch.arange(0, T, device=idx.device).unsqueeze(0)
|
| 127 |
+
x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))
|
| 128 |
+
for block in self.blocks:
|
| 129 |
+
x = block(x)
|
| 130 |
+
x = self.ln_f(x)
|
| 131 |
+
logits = self.head(x)
|
| 132 |
+
|
| 133 |
+
loss = None
|
| 134 |
+
if targets is not None:
|
| 135 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
| 136 |
+
return logits, loss
|
| 137 |
+
|
| 138 |
+
@torch.no_grad()
|
| 139 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None, top_p=None):
|
| 140 |
+
self.eval()
|
| 141 |
+
for _ in range(max_new_tokens):
|
| 142 |
+
idx_cond = idx[:, -self.config.block_size:]
|
| 143 |
+
logits, _ = self(idx_cond)
|
| 144 |
+
logits = logits[:, -1, :] / max(temperature, 1e-5)
|
| 145 |
+
|
| 146 |
+
if top_k is not None:
|
| 147 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 148 |
+
logits[logits < v[:, [-1]]] = float("-inf")
|
| 149 |
+
|
| 150 |
+
if top_p is not None:
|
| 151 |
+
sorted_logits, sorted_idx = torch.sort(logits, descending=True)
|
| 152 |
+
probs = F.softmax(sorted_logits, dim=-1)
|
| 153 |
+
cum_probs = torch.cumsum(probs, dim=-1)
|
| 154 |
+
remove = cum_probs > top_p
|
| 155 |
+
remove[:, 1:] = remove[:, :-1].clone()
|
| 156 |
+
remove[:, 0] = False
|
| 157 |
+
sorted_logits[remove] = float("-inf")
|
| 158 |
+
logits = torch.full_like(logits, float("-inf")).scatter(1, sorted_idx, sorted_logits)
|
| 159 |
+
|
| 160 |
+
probs = F.softmax(logits, dim=-1)
|
| 161 |
+
next_id = torch.multinomial(probs, num_samples=1)
|
| 162 |
+
idx = torch.cat([idx, next_id], dim=1)
|
| 163 |
+
return idx
|