-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
178 lines (140 loc) · 5.74 KB
/
Copy pathmodel.py
File metadata and controls
178 lines (140 loc) · 5.74 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""A small GPT-style decoder-only transformer, from scratch in PyTorch."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiHeadSelfAttention(nn.Module):
def __init__(self, d_model: int, n_heads: int, dropout: float = 0.1):
super().__init__()
assert d_model % n_heads == 0
self.n_heads = n_heads
self.head_dim = d_model // n_heads
self.qkv = nn.Linear(d_model, 3 * d_model)
self.out_proj = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
B, T, C = x.shape
qkv = self.qkv(x) # (B, T, 3*C)
q, k, v = qkv.chunk(3, dim=-1)
# Reshape to (B, n_heads, T, head_dim)
q = q.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
k = k.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
v = v.view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
# Scaled dot-product attention with causal mask
scale = math.sqrt(self.head_dim)
attn = (q @ k.transpose(-2, -1)) / scale # (B, nh, T, T)
# Causal mask: prevent attending to future positions
mask = torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool()
attn = attn.masked_fill(mask, float("-inf"))
attn = F.softmax(attn, dim=-1)
attn = self.dropout(attn)
out = attn @ v # (B, nh, T, head_dim)
out = out.transpose(1, 2).contiguous().view(B, T, C)
return self.out_proj(out)
class FeedForward(nn.Module):
def __init__(self, d_model: int, d_ff: int, dropout: float = 0.1):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.GELU(),
nn.Linear(d_ff, d_model),
nn.Dropout(dropout),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
class TransformerBlock(nn.Module):
def __init__(self, d_model: int, n_heads: int, d_ff: int, dropout: float = 0.1):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = MultiHeadSelfAttention(d_model, n_heads, dropout)
self.ln2 = nn.LayerNorm(d_model)
self.ff = FeedForward(d_model, d_ff, dropout)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Pre-norm architecture (like GPT-2)
x = x + self.attn(self.ln1(x))
x = x + self.ff(self.ln2(x))
return x
class TinyLLM(nn.Module):
"""A small decoder-only transformer language model.
Architecture mirrors GPT-2 but much smaller:
- Token embeddings + learned positional embeddings
- N transformer blocks with pre-norm
- Final layer norm + linear head to vocab
"""
def __init__(
self,
vocab_size: int,
d_model: int = 256,
n_heads: int = 8,
n_layers: int = 6,
d_ff: int = 1024,
max_seq_len: int = 256,
dropout: float = 0.1,
):
super().__init__()
self.max_seq_len = max_seq_len
self.token_emb = nn.Embedding(vocab_size, d_model)
self.pos_emb = nn.Embedding(max_seq_len, d_model)
self.drop = nn.Dropout(dropout)
self.blocks = nn.ModuleList(
[TransformerBlock(d_model, n_heads, d_ff, dropout) for _ in range(n_layers)]
)
self.ln_f = nn.LayerNorm(d_model)
self.head = nn.Linear(d_model, vocab_size, bias=False)
# Weight tying: share token embedding weights with output head
self.head.weight = self.token_emb.weight
self._init_weights()
def _init_weights(self):
for module in self.modules():
if isinstance(module, nn.Linear):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
if module.bias is not None:
torch.nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
def forward(
self, idx: torch.Tensor, targets: torch.Tensor | None = None
) -> tuple[torch.Tensor, torch.Tensor | None]:
B, T = idx.shape
assert T <= self.max_seq_len, f"Sequence length {T} exceeds max {self.max_seq_len}"
# Embeddings
tok_emb = self.token_emb(idx) # (B, T, d_model)
pos = torch.arange(T, device=idx.device)
pos_emb = self.pos_emb(pos) # (T, d_model)
x = self.drop(tok_emb + pos_emb)
# Transformer blocks
for block in self.blocks:
x = block(x)
x = self.ln_f(x)
logits = self.head(x) # (B, T, vocab_size)
loss = None
if targets is not None:
loss = F.cross_entropy(
logits.view(-1, logits.size(-1)),
targets.view(-1),
)
return logits, loss
def param_count(self) -> int:
return sum(p.numel() for p in self.parameters() if p.requires_grad)
@torch.no_grad()
def generate(
self,
idx: torch.Tensor,
max_new_tokens: int = 200,
temperature: float = 0.8,
top_k: int = 40,
) -> torch.Tensor:
"""Autoregressive generation with temperature and top-k sampling."""
for _ in range(max_new_tokens):
# Crop to max_seq_len
idx_cond = idx[:, -self.max_seq_len :]
logits, _ = self(idx_cond)
logits = logits[:, -1, :] / temperature
# Top-k filtering
if top_k > 0:
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
logits[logits < v[:, [-1]]] = float("-inf")
probs = F.softmax(logits, dim=-1)
next_token = torch.multinomial(probs, num_samples=1)
idx = torch.cat([idx, next_token], dim=1)
return idx