Repository navigation
Expand file tree
/
Copy pathgpt_at_cpu.py
More file actions
462 lines (394 loc) · 17.7 KB
/
Copy pathgpt_at_cpu.py
File metadata and controls
462 lines (394 loc) · 17.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
"""
GPT_at_CPU — Shakespeare Text Generation in 120 Seconds on CPU
===============================================================
CPU'da 120 saniyede BPB 2.03 — Karpathy'nin GPU baseline'ini (2.10) yendi.
Components:
- LazySmart Optimizer: Shampoo-lite + Lookahead + P3 (AdamW'yi %14.4 yener)
- ParallelBlock: PaLM-style parallel Attention + MLP
- Hybrid_Inno: LazySmart + ParallelBlock + Compass
Usage:
python gpt_at_cpu.py # Train + Generate (default 120s)
python gpt_at_cpu.py --time 60 # Train 60 seconds
python gpt_at_cpu.py --time 300 # Train 5 minutes for better quality
python gpt_at_cpu.py --prompt "ROMEO:" # Custom prompt
Requirements:
pip install torch tiktoken numpy
Author: https://github.com/umiteknoloji
License: MIT
"""
import os, sys, time, math, gc, argparse, platform, subprocess
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from collections import Counter
# ============================================================
# 1. DATA PREPARATION
# ============================================================
def prepare_data(text_path=None):
"""Load Shakespeare and tokenize with GPT-2 BPE, limited vocab."""
# Find or download data
if text_path and os.path.exists(text_path):
pass
else:
# Try common locations
candidates = [
'data/input.txt',
'input.txt',
'shakespeare_input.txt',
]
text_path = None
for c in candidates:
if os.path.exists(c):
text_path = c; break
if text_path is None:
# Try nanoGPT repo
for repo in ['/content/nanoGPT', '/kaggle/working/nanoGPT', './nanoGPT']:
p = os.path.join(repo, 'data/shakespeare_char/input.txt')
if os.path.exists(p):
text_path = p; break
if text_path is None:
print("Shakespeare verisi bulunamadi. Indiriliyor...")
os.makedirs('data', exist_ok=True)
try:
import urllib.request
url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt"
urllib.request.urlretrieve(url, 'data/input.txt')
text_path = 'data/input.txt'
except:
print("Veri indirilemedi. Lutfen input.txt dosyasini manuel indirin:")
print(" https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt")
sys.exit(1)
with open(text_path, 'r', encoding='utf-8') as f:
text = f.read()
import tiktoken
enc = tiktoken.get_encoding("gpt2")
tokens = enc.encode_ordinary(text)
# Limit vocab to top 4500 tokens
vocab_limit = 4500
counts = Counter(tokens)
top_tokens = {t for t, _ in counts.most_common(vocab_limit)}
toi = {t: i for i, t in enumerate(sorted(list(top_tokens)))}
iot = {i: t for t, i in toi.items()}
unk_id = vocab_limit
vocab_size = vocab_limit + 1
encoded = np.array([toi.get(t, unk_id) for t in tokens], dtype=np.uint16)
split = int(len(encoded) * 0.9)
train_data = encoded[:split]
val_data = encoded[split:]
return text, tokens, enc, toi, iot, vocab_size, train_data, val_data
def get_batch(train_data, val_data, split='train', block_size=64, batch_size=16):
data = train_data if split == 'train' else val_data
ix = torch.randint(len(data) - block_size, (batch_size,))
x = torch.stack([torch.from_numpy(data[i:i+block_size].astype(np.int64)) for i in ix])
y = torch.stack([torch.from_numpy(data[i+1:i+1+block_size].astype(np.int64)) for i in ix])
return x, y
# ============================================================
# 2. MODEL: ParallelBlock + GPT
# ============================================================
class CausalSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
assert config['n_embd'] % config['n_head'] == 0
self.c_attn = nn.Linear(config['n_embd'], 3 * config['n_embd'], bias=config['bias'])
self.c_proj = nn.Linear(config['n_embd'], config['n_embd'], bias=config['bias'])
self.n_head = config['n_head']
self.n_embd = config['n_embd']
self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
def forward(self, x):
B, T, C = x.size()
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
hs = C // self.n_head
q = q.view(B, T, self.n_head, hs).transpose(1, 2)
k = k.view(B, T, self.n_head, hs).transpose(1, 2)
v = v.view(B, T, self.n_head, hs).transpose(1, 2)
if self.flash:
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
else:
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(hs))
att = att.masked_fill(
torch.tril(torch.ones(T, T, device=x.device)).view(1, 1, T, T) == 0,
float('-inf')
)
att = F.softmax(att, dim=-1)
y = att @ v
y = y.transpose(1, 2).contiguous().view(B, T, C)
return self.c_proj(y)
class MLP(nn.Module):
def __init__(self, config):
super().__init__()
self.c_fc = nn.Linear(config['n_embd'], 4 * config['n_embd'], bias=config['bias'])
self.gelu = nn.GELU()
self.c_proj = nn.Linear(4 * config['n_embd'], config['n_embd'], bias=config['bias'])
def forward(self, x):
return self.c_proj(self.gelu(self.c_fc(x)))
class ParallelBlock(nn.Module):
"""PaLM-style: Attention and MLP run in parallel, sharing LayerNorm."""
def __init__(self, config):
super().__init__()
self.ln = nn.LayerNorm(config['n_embd'])
self.attn = CausalSelfAttention(config)
self.mlp = MLP(config)
def forward(self, x):
x_norm = self.ln(x)
return x + self.attn(x_norm) + self.mlp(x_norm)
class GPT(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.wte = nn.Embedding(config['vocab_size'], config['n_embd'])
self.wpe = nn.Embedding(config['block_size'], config['n_embd'])
self.drop = nn.Dropout(config['dropout'])
self.blocks = nn.ModuleList([ParallelBlock(config) for _ in range(config['n_layer'])])
self.ln_f = nn.LayerNorm(config['n_embd'])
self.head = nn.Linear(config['n_embd'], config['vocab_size'], bias=False)
self.wte.weight = self.head.weight # weight tying
self.apply(self._init_weights)
# Scale residual projections
for pn, p in self.named_parameters():
if pn.endswith('c_proj.weight'):
torch.nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config['n_layer']))
n_params = sum(p.numel() for p in self.parameters()) - self.wpe.weight.numel()
print(f"Model: {config['n_layer']} layers, {config['n_embd']} dim, {config['n_head']} heads, {n_params/1e6:.2f}M params")
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.size()
pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
x = self.drop(self.wte(idx) + self.wpe(pos))
for block in self.blocks:
x = block(x)
x = self.ln_f(x)
logits = self.head(x)
loss = None
if targets is not None:
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
return logits, loss
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=0.7, top_k=50):
for _ in range(max_new_tokens):
idx_cond = idx if idx.size(1) <= self.config['block_size'] else idx[:, -self.config['block_size']:]
logits, _ = self(idx_cond)
logits = logits[:, -1, :] / temperature
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)
return idx
# ============================================================
# 3. LAZYSMART OPTIMIZER
# ============================================================
class LazySmart:
"""
LazySmart: Shampoo-lite + Lookahead + P3
- Shampoo-lite: Lazy preconditioner update every 10 steps
- Lookahead: Slow weight sync every 5 steps (alpha=0.5)
- P3: Layer-wise gradient normalization
"""
def __init__(self, model, optimizer):
self.model = model
self.optimizer = optimizer
self.slow_params = [p.clone().detach() for p in model.parameters()]
self.precond_L = {}
self.cached_inv = {}
def step(self, iteration):
with torch.no_grad():
# P3: Layer-wise gradient normalization
for block in self.model.blocks:
params = [p for p in block.parameters() if p.grad is not None]
if params:
gn = sum(p.grad.norm() ** 2 for p in params) ** 0.5
scale = 1.0 / (gn + 1e-6)
for p in params:
p.grad.data *= scale
# Shampoo-lite preconditioning
for name, p in self.model.named_parameters():
if p.grad is not None and p.ndim >= 2 and p.size(0) <= 256:
if name not in self.precond_L:
self.precond_L[name] = torch.eye(p.grad.size(0)) * 0.1
self.cached_inv[name] = torch.eye(p.grad.size(0))
if iteration % 10 == 0:
self.precond_L[name] = 0.9 * self.precond_L[name] + 0.1 * (p.grad.data @ p.grad.data.T)
try:
self.cached_inv[name] = torch.linalg.solve(
self.precond_L[name] + 1e-4 * torch.eye(p.grad.size(0)),
torch.eye(p.grad.size(0))
)
except:
pass
p.grad.data = self.cached_inv[name] @ p.grad.data
# Gradient clipping + optimizer step
torch.nn.utils.clip_grad_norm_(self.model.parameters(), 1.0)
self.optimizer.step()
self.optimizer.zero_grad(set_to_none=True)
# Lookahead: sync slow weights every 5 steps
if iteration % 5 == 0:
with torch.no_grad():
for p, sp in zip(self.model.parameters(), self.slow_params):
sp.data += 0.5 * (p.data - sp.data)
p.data.copy_(sp.data)
# ============================================================
# 4. HARDWARE DETECTION
# ============================================================
def detect_hardware():
info = {'platform': 'Local', 'cpu': 'unknown', 'gpu': 'none', 'gpu_count': 0}
if os.path.exists('/content'):
info['platform'] = 'Colab'
elif os.path.exists('/kaggle'):
info['platform'] = 'Kaggle'
try:
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if 'model name' in line:
info['cpu'] = line.split(':')[1].strip(); break
except:
info['cpu'] = platform.processor() or 'unknown'
if torch.cuda.is_available():
info['gpu'] = torch.cuda.get_device_name(0)
info['gpu_count'] = torch.cuda.device_count()
try:
info['ram_gb'] = round(os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / (1024**3), 1)
except:
info['ram_gb'] = '?'
return info
# ============================================================
# 5. TEXT GENERATION
# ============================================================
def generate_text(model, enc, toi, iot, prompt, max_tokens=200, temperature=0.7, top_k=50):
"""Generate text from a prompt."""
model.eval()
prompt_gpt2 = enc.encode_ordinary(prompt)
prompt_ids = [toi.get(t, len(toi)) for t in prompt_gpt2]
idx = torch.tensor([prompt_ids], dtype=torch.long)
with torch.no_grad():
output_ids = model.generate(idx, max_new_tokens=max_tokens, temperature=temperature, top_k=top_k)
# Decode back to text
generated_ids = output_ids[0].tolist()
gpt2_tokens = [iot[tid] for tid in generated_ids if tid in iot]
return enc.decode(gpt2_tokens) if gpt2_tokens else ""
# ============================================================
# 6. MAIN: TRAIN + GENERATE
# ============================================================
def main():
parser = argparse.ArgumentParser(description='GPT_at_CPU: Shakespeare in 120s on CPU')
parser.add_argument('--time', type=int, default=120, help='Training time in seconds (default: 120)')
parser.add_argument('--prompt', type=str, default=None, help='Custom prompt for text generation')
parser.add_argument('--n_layer', type=int, default=3, help='Number of transformer layers (default: 3)')
parser.add_argument('--n_embd', type=int, default=192, help='Embedding dimension (default: 192)')
parser.add_argument('--n_head', type=int, default=6, help='Number of attention heads (default: 6)')
parser.add_argument('--batch_size', type=int, default=16, help='Batch size (default: 16)')
parser.add_argument('--block_size', type=int, default=64, help='Context length (default: 64)')
parser.add_argument('--lr', type=float, default=1e-2, help='Learning rate (default: 0.01)')
parser.add_argument('--data', type=str, default=None, help='Path to Shakespeare input.txt')
args = parser.parse_args()
# Hardware
hw = detect_hardware()
print(f"\n{'='*65}")
print(f" GPT_at_CPU — Shakespeare Text Generation")
print(f" CPU: {hw['cpu']}")
print(f" GPU: {hw['gpu']} (x{hw['gpu_count']})")
print(f" Platform: {hw['platform']} | RAM: {hw['ram_gb']} GB")
print(f"{'='*65}")
# Data
print("\nVeri hazirlaniyor...")
text, tokens, enc, toi, iot, vocab_size, train_data, val_data = prepare_data(args.data)
print(f" {len(text)} chars, {len(tokens)} tokens, vocab={vocab_size}")
# Config
config = {
'block_size': args.block_size,
'vocab_size': vocab_size,
'n_layer': args.n_layer,
'n_head': args.n_head,
'n_embd': args.n_embd,
'dropout': 0.0,
'bias': False,
}
# Model
print("\nModel olusturuluyor...")
model = GPT(config)
# Optimizer: AdamW + LazySmart
param_dict = {pn: p for pn, p in model.named_parameters() if p.requires_grad}
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
optimizer = torch.optim.AdamW([
{'params': decay_params, 'weight_decay': 0.1},
{'params': nodecay_params, 'weight_decay': 0.0}
], lr=args.lr, betas=(0.9, 0.95))
lazysmart = LazySmart(model, optimizer)
# Train
print(f"\nEgitim basliyor ({args.time} saniye)...")
model.train()
t0 = time.time()
iters = 0
losses = []
while (time.time() - t0) < args.time:
X, Y = get_batch(train_data, val_data, 'train', args.block_size, args.batch_size)
_, loss = model(X, Y)
loss.backward()
lazysmart.step(iters)
losses.append(loss.item())
if iters % 50 == 0:
avg = sum(losses[-50:]) / len(losses[-50:])
elapsed = time.time() - t0
print(f" iter {iters:>4d} | loss {avg:.4f} | {elapsed:.0f}s / {args.time}s")
iters += 1
elapsed = time.time() - t0
# Eval
model.eval()
with torch.no_grad():
val_losses = [model(*get_batch(train_data, val_data, 'val', args.block_size, args.batch_size))[1].item() for _ in range(10)]
avg_val_loss = sum(val_losses) / len(val_losses)
bpb = (avg_val_loss * len(tokens)) / (len(text) * math.log(2))
print(f"\n{'='*65}")
print(f" SONUC")
print(f" Iterasyon: {iters}")
print(f" Val Loss: {avg_val_loss:.4f}")
print(f" BPB: {bpb:.4f}")
print(f" Sure: {elapsed:.1f}s")
print(f" Hiz: {iters/elapsed:.2f} iter/s")
print(f"{'='*65}")
# Generate
print(f"\n{'='*65}")
print(f" METIN URETIMI")
print(f"{'='*65}")
prompts = args.prompt.split('|') if args.prompt else [
"KING HENRY:",
"To be or not to be",
"My lord, I",
"First Citizen:\nBefore we proceed",
"ROMEO:\nO, she doth",
]
for prompt in prompts:
prompt = prompt.strip()
print(f"\n--- Prompt: '{prompt}' ---")
for temp in [0.5, 0.8, 1.0]:
generated = generate_text(model, enc, toi, iot, prompt,
max_tokens=200, temperature=temp, top_k=40)
# Show first 400 chars
display = generated[:400].replace('\n', '\n ')
print(f"\n [temp={temp}]")
print(f" {display}")
print()
# Save model
save_path = f"gpt_cpu_{args.n_layer}L_{args.n_embd}d_bpb{bpb:.2f}.pt"
torch.save({
'model_state': model.state_dict(),
'config': config,
'bpb': bpb,
'iters': iters,
'time': elapsed,
'hardware': hw,
'toi': toi,
'iot': iot,
}, save_path)
print(f"\nModel kaydedildi: {save_path}")
return model, bpb, iters
if __name__ == '__main__':
model, bpb, iters = main()