-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
113 lines (92 loc) · 4.5 KB
/
Copy pathmodel.py
File metadata and controls
113 lines (92 loc) · 4.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import torch
import torch.nn as nn
from dataclasses import dataclass
@dataclass
class GPTConfig:
"""Hyperparameters that fully describe a GPT model's architecture."""
n_head: int # number of attention heads
n_embd: int # embedding dimension
n_layer: int # number of transformer blocks
vocab_size: int # character-level: 65 unique chars in Shakespeare
block_size: int # max sequence length (context window)
class CausalSelfAttention(nn.Module):
"""Multi-head causal self-attention with a single fused QKV projection."""
def __init__(self, config:GPTConfig):
super().__init__()
assert config.n_embd % config.n_head == 0
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd) # Q, K, V projections
self.c_proj = nn.Linear(config.n_embd, config.n_embd) # output projection
self.n_head = config.n_head
self.n_embd = config.n_embd
def forward(self, x):
"""Project input to Q/K/V, apply scaled dot-product attention with causal mask, return output projection."""
B, T, C = x.shape
qkv = self.c_attn(x)
q, k, v = qkv.split(self.n_embd, dim=2)
# reshape for multi-head: (B, T, C) -> (B, n_head, T, head_dim)
head_dim = C // self.n_head
q = q.view(B, T, self.n_head, head_dim).transpose(1, 2)
k = k.view(B, T, self.n_head, head_dim).transpose(1, 2)
v = v.view(B, T, self.n_head, head_dim).transpose(1, 2)
# attention with causal mask (each token can only attend to previous tokens)
y = torch.nn.functional.scaled_dot_product_attention(
q, k, v, is_causal=True
)
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.c_proj(y)
class MLP(nn.Module):
"""Position-wise feed-forward network: linear up-projection → GELU → linear down-projection."""
def __init__(self, config:GPTConfig):
super().__init__()
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
self.gelu = nn.GELU(approximate='tanh')
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
def forward(self, x):
"""Apply up-projection, GELU activation, and down-projection."""
x = self.c_fc(x) # project up: 384 -> 1536
x = self.gelu(x) # non-linearity
return self.c_proj(x) # project back down: 1536 -> 384
class Block(nn.Module):
"""Transformer block: pre-norm causal self-attention and pre-norm MLP, each with a residual connection."""
def __init__(self, config:GPTConfig):
super().__init__()
self.ln_1 = nn.LayerNorm(config.n_embd)
self.attn = CausalSelfAttention(config)
self.ln_2 = nn.LayerNorm(config.n_embd)
self.mlp = MLP(config)
def forward(self, x):
"""Apply LayerNorm → attention → residual, then LayerNorm → MLP → residual."""
x = x + self.attn(self.ln_1(x)) # attention with residual connection
x = x + self.mlp(self.ln_2(x)) # MLP with residual connection
return x
class GPT(nn.Module):
"""Character-level GPT with token and positional embeddings, transformer blocks, and a weight-tied output head."""
def __init__(self, config: GPTConfig):
super().__init__()
self.config = config
self.transformer = nn.ModuleDict(dict(
wte = nn.Embedding(config.vocab_size, config.n_embd), # token embeddings
wpe = nn.Embedding(config.block_size, config.n_embd), # position embeddings
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
ln_f = nn.LayerNorm(config.n_embd),
))
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
self.transformer.wte.weight = self.lm_head.weight
def forward(self, idx, targets=None):
"""Run the full forward pass; return (logits, loss) where loss is cross-entropy if targets are provided."""
B, T = idx.shape
pos = torch.arange(0, T, device=idx.device)
tok_emb = self.transformer.wte(idx) # (B, T, n_embd)
pos_emb = self.transformer.wpe(pos) # (T, n_embd)
x = tok_emb + pos_emb # (B, T, n_embd) — broadcasting adds position info
for block in self.transformer.h:
x = block(x)
x = self.transformer.ln_f(x)
logits = self.lm_head(x)
loss = None
if targets is not None:
loss = nn.functional.cross_entropy(
logits.view(-1, logits.size(-1)),
targets.view(-1)
)
return logits, loss