-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
291 lines (237 loc) · 8.7 KB
/
Copy pathmain.py
File metadata and controls
291 lines (237 loc) · 8.7 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import torch
import torch.nn as nn
from torch.nn import functional as F
import time
import sys
import os
from pathlib import Path
import tiktoken
SCRIPT_DIR = Path(__file__).resolve().parent
print("[llm]")
print()
print(f"Device: {'CUDA' if torch.cuda.is_available() else 'CPU'}")
print(f"PyTorch: {torch.__version__}")
start = time.time()
cleaned_path = Path(os.environ.get("data", SCRIPT_DIR / "input.txt"))
train_split = 0.9
seed = 1337
batch_size = 2
block_size = 20
max_iters = 10000
eval_interval = 1
learning_rate = 3e-4
device = 'cuda' if torch.cuda.is_available() else 'cpu'
eval_iters = 1
n_embd = 6
n_head = 4
n_layer = 4
dropout = 0.0
torch.manual_seed(seed)
def get_miniq_tokenizer(encoding_name="o200k_base"):
miniq_tokenizer = tiktoken.get_encoding(encoding_name)
miniq_vocab_size = miniq_tokenizer.n_vocab
return miniq_tokenizer, miniq_vocab_size
def miniq_encode(text, tokenizer): return tokenizer.encode(text)
def miniq_decode(tokens, tokenizer): return tokenizer.decode(tokens)
with open(cleaned_path, 'r', encoding='utf-8') as f:
text = f.read()
miniq_tokenizer, vocab_size = get_miniq_tokenizer("o200k_base")
encoded_data = miniq_encode(text, miniq_tokenizer)
data = torch.tensor(encoded_data, dtype=torch.long)
n = int(train_split * len(data))
train_data = data[:n]
val_data = data[n:]
def get_batch(split):
data_split = train_data if split == 'train' else val_data
ix = torch.randint(len(data_split) - block_size, (batch_size,))
x = torch.stack([data_split[i:i + block_size] for i in ix])
y = torch.stack([data_split[i + 1:i + block_size + 1] for i in ix])
x, y = x.to(device), y.to(device)
return x, y
@torch.no_grad()
def estimate_loss():
out = {}
miniq_model.eval()
for split in ['train', 'val']:
losses = torch.zeros(eval_iters)
for k in range(eval_iters):
X, Y = get_batch(split)
_, loss = miniq_model(X, Y)
losses[k] = loss.item()
out[split] = losses.mean()
miniq_model.train()
return out
class MiniQuadtrixHead(nn.Module):
def __init__(self, head_size):
super().__init__()
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(
torch.ones(block_size, block_size)))
self.dropout = nn.Dropout(dropout)
def forward(self, x):
B, T, C = x.shape
k = self.key(x)
q = self.query(x)
wei = q @ k.transpose(-2, -1) * k.shape[-1] ** -0.5
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf'))
wei = F.softmax(wei, dim=-1)
wei = self.dropout(wei)
return wei @ self.value(x)
class MiniQuadtrixMHA(nn.Module):
def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList(
[MiniQuadtrixHead(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(head_size * num_heads, n_embd)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1)
return self.dropout(self.proj(out))
class MiniQuadtrixFFN(nn.Module):
def __init__(self, n_embd):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd),
nn.ReLU(),
nn.Linear(4 * n_embd, n_embd),
nn.Dropout(dropout),
)
def forward(self, x):
return self.net(x)
class MiniQuadtrixBlock(nn.Module):
def __init__(self, n_embd, n_head):
super().__init__()
head_size = n_embd // n_head
self.sa = MiniQuadtrixMHA(n_head, head_size)
self.ffwd = MiniQuadtrixFFN(n_embd)
self.ln1 = nn.LayerNorm(n_embd)
self.ln2 = nn.LayerNorm(n_embd)
def forward(self, x):
x = x + self.sa(self.ln1(x))
x = x + self.ffwd(self.ln2(x))
return x
class MiniQuadtrix(nn.Module):
def __init__(self):
super().__init__()
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
self.position_embedding_table = nn.Embedding(block_size, n_embd)
self.blocks = nn.Sequential(
*[MiniQuadtrixBlock(n_embd, n_head=n_head) for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd)
self.lm_head = nn.Linear(n_embd, vocab_size)
self.apply(self._init_weights)
def _init_weights(self, module):
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, targets=None):
B, T = idx.shape
tok_emb = self.token_embedding_table(idx)
pos_emb = self.position_embedding_table(torch.arange(T, device=device))
x = tok_emb + pos_emb
x = self.blocks(x)
x = self.ln_f(x)
logits = self.lm_head(x)
if targets is None:
loss = None
else:
B, T, C = logits.shape
logits = logits.view(B * T, C)
targets = targets.view(B * T)
loss = F.cross_entropy(logits, targets)
return logits, loss
def generate(self, idx, max_new_tokens):
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :]
probs = F.softmax(logits, dim=-1)
idx_next = torch.multinomial(probs, num_samples=1)
idx = torch.cat((idx, idx_next), dim=1)
return idx
miniq_model = MiniQuadtrix().to(device)
miniq_n_params = sum(p.numel() for p in miniq_model.parameters())
miniq_optimizer = torch.optim.AdamW(miniq_model.parameters(), lr=learning_rate)
print("CONFIG")
print(f"Seed: {seed}")
print(f"Batch size: {batch_size}")
print(f"Block size: {block_size}")
print(f"Learning rate: {learning_rate}")
print(f"Layers: {n_layer}")
print(f"Heads: {n_head}")
print(f"Embedding dim: {n_embd}")
print(f"Dropout: {dropout}")
print(f"Parameters: {miniq_n_params:,}")
print(f"Train tokens: {len(train_data):,}")
print(f"Val tokens: {len(val_data):,}")
print(f"Data file: {str(cleaned_path)}")
print()
best_val_loss = float('inf')
train_start = time.time()
prev_loss = None
for iter in range(max_iters):
if iter % eval_interval == 0 or iter == max_iters - 1:
losses = estimate_loss()
elapsed = time.time() - train_start
total_norm = 0
for p in miniq_model.parameters():
if p.grad is not None:
param_norm = p.grad.detach().data.norm(2)
total_norm += param_norm.item() ** 2
total_norm = total_norm ** 0.5
tokens_per_sec = (iter + 1) * batch_size * \
block_size / elapsed if elapsed > 0 else 0
is_best = losses['val'] < best_val_loss
if is_best:
best_val_loss = losses['val']
torch.save(miniq_model.state_dict(), 'llm.pt')
print(
f"step {iter} | loss: {losses['train']:.6f} | lr {learning_rate:.4e} | norm: {total_norm:.4f} | dt: {elapsed*1000:.2f}ms | tok/sec: {tokens_per_sec:.2f}")
sys.stdout.flush()
xb, yb = get_batch('train')
logits, loss = miniq_model(xb, yb)
miniq_optimizer.zero_grad(set_to_none=True)
loss.backward()
miniq_optimizer.step()
total_time = time.time() - train_start
print()
print(f"Duration: {int(total_time // 60)}m {int(total_time % 60):02d}s")
print(f"Best val loss: {best_val_loss:.4f}")
print()
miniq_model.load_state_dict(torch.load(
'mini-quadtrix.pt', map_location=device, weights_only=True))
miniq_model.eval()
print("INFERENCE")
print()
try:
while True:
prompt = input("user > ").strip()
if prompt.lower() in ("quit", "exit", "q"):
print()
print("Session ended.")
break
if not prompt:
continue
encoded_prompt = miniq_encode(prompt, miniq_tokenizer)
context = torch.tensor(
[encoded_prompt], dtype=torch.long, device=device)
with torch.no_grad():
output_ids = miniq_model.generate(context, max_new_tokens=200)
new_tokens = output_ids[0][len(encoded_prompt):].tolist()
response = miniq_decode(new_tokens, miniq_tokenizer).strip()
print()
print(f"Model > {response}")
print()
except KeyboardInterrupt:
print()
print("Interrupted.")
wall_clock = time.time() - start
print()
print(f"Training: {int(total_time // 60)}m {int(total_time % 60):02d}s")
print(f"Total: {int(wall_clock // 60)}m {int(wall_clock % 60):02d}s")
print()