Create mini_codegpt.py
Browse files- mini_codegpt.py +91 -0
mini_codegpt.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse, os, time
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
torch.set_num_threads(min(4, os.cpu_count() or 1))
|
| 8 |
+
ROOT = Path(__file__).resolve().parent
|
| 9 |
+
CORPUS = ROOT / 'data' / 'corpus.txt'
|
| 10 |
+
CHECKPOINT = ROOT / 'mini_codegpt.pt'
|
| 11 |
+
|
| 12 |
+
class Tokenizer:
|
| 13 |
+
def __init__(self, text):
|
| 14 |
+
self.chars = sorted(set(text)) or [' ']
|
| 15 |
+
self.stoi = {ch: i for i, ch in enumerate(self.chars)}
|
| 16 |
+
self.itos = {i: ch for ch, i in self.stoi.items()}
|
| 17 |
+
def encode(self, text):
|
| 18 |
+
return [self.stoi.get(ch, 0) for ch in text]
|
| 19 |
+
def decode(self, ids):
|
| 20 |
+
return ''.join(self.itos.get(int(i), '') for i in ids)
|
| 21 |
+
|
| 22 |
+
class MiniCodeGPT(nn.Module):
|
| 23 |
+
def __init__(self, vocab_size, d_model=64, heads=4, layers=2, block_size=128):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.block_size = block_size
|
| 26 |
+
self.token_emb = nn.Embedding(vocab_size, d_model)
|
| 27 |
+
self.pos_emb = nn.Embedding(block_size, d_model)
|
| 28 |
+
layer = nn.TransformerEncoderLayer(d_model, heads, 4*d_model, dropout=0.0, batch_first=True, activation='gelu')
|
| 29 |
+
self.transformer = nn.TransformerEncoder(layer, layers)
|
| 30 |
+
self.norm = nn.LayerNorm(d_model)
|
| 31 |
+
self.head = nn.Linear(d_model, vocab_size, bias=False)
|
| 32 |
+
self.register_buffer('mask', torch.triu(torch.ones(block_size, block_size, dtype=torch.bool), diagonal=1))
|
| 33 |
+
def forward(self, x, targets=None):
|
| 34 |
+
_, t = x.shape
|
| 35 |
+
x = self.token_emb(x) + self.pos_emb(torch.arange(t, device=x.device))[None, :, :]
|
| 36 |
+
logits = self.head(self.norm(self.transformer(x, mask=self.mask[:t, :t])))
|
| 37 |
+
loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.reshape(-1)) if targets is not None else None
|
| 38 |
+
return logits, loss
|
| 39 |
+
|
| 40 |
+
def main():
|
| 41 |
+
parser = argparse.ArgumentParser(description='Mini-CodeGPT educativo')
|
| 42 |
+
parser.add_argument('--retrain', action='store_true')
|
| 43 |
+
parser.add_argument('--no-chat', action='store_true')
|
| 44 |
+
parser.add_argument('--steps', type=int, default=1000)
|
| 45 |
+
args = parser.parse_args()
|
| 46 |
+
text = CORPUS.read_text(encoding='utf-8')
|
| 47 |
+
tokenizer = Tokenizer(text)
|
| 48 |
+
config = {'d_model': 64, 'heads': 4, 'layers': 2, 'block_size': 128}
|
| 49 |
+
if CHECKPOINT.exists() and not args.retrain:
|
| 50 |
+
saved = torch.load(CHECKPOINT, map_location='cpu', weights_only=True)
|
| 51 |
+
tokenizer.chars = saved['chars']
|
| 52 |
+
tokenizer.stoi = {ch: i for i, ch in enumerate(tokenizer.chars)}
|
| 53 |
+
tokenizer.itos = {i: ch for ch, i in tokenizer.stoi.items()}
|
| 54 |
+
config = saved['config']
|
| 55 |
+
model = MiniCodeGPT(len(tokenizer.chars), **config)
|
| 56 |
+
model.load_state_dict(saved['model'])
|
| 57 |
+
print('Checkpoint cargado.')
|
| 58 |
+
else:
|
| 59 |
+
data = torch.tensor(tokenizer.encode(text), dtype=torch.long)
|
| 60 |
+
if len(data) < 130:
|
| 61 |
+
data = data.repeat(130 // max(1, len(data)) + 1)
|
| 62 |
+
model = MiniCodeGPT(len(tokenizer.chars), **config)
|
| 63 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-3)
|
| 64 |
+
model.train(); start = time.time()
|
| 65 |
+
for step in range(args.steps):
|
| 66 |
+
starts = torch.randint(0, len(data)-129, (16,))
|
| 67 |
+
x = torch.stack([data[i:i+128] for i in starts])
|
| 68 |
+
y = torch.stack([data[i+1:i+129] for i in starts])
|
| 69 |
+
_, loss = model(x, y)
|
| 70 |
+
optimizer.zero_grad(set_to_none=True); loss.backward()
|
| 71 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); optimizer.step()
|
| 72 |
+
if step == 0 or (step+1) % 100 == 0: print(f'Paso {step+1}/{args.steps} | pérdida {loss.item():.4f}')
|
| 73 |
+
torch.save({'model': model.state_dict(), 'chars': tokenizer.chars, 'config': config}, CHECKPOINT)
|
| 74 |
+
print(f'Entrenamiento terminado en {time.time()-start:.1f}s')
|
| 75 |
+
if args.no_chat: return
|
| 76 |
+
@torch.inference_mode()
|
| 77 |
+
def generate(prompt, max_new_tokens=200):
|
| 78 |
+
model.eval(); ids = tokenizer.encode(prompt) or [0]; idx = torch.tensor([ids])
|
| 79 |
+
for _ in range(max_new_tokens):
|
| 80 |
+
logits, _ = model(idx[:, -config['block_size']:])
|
| 81 |
+
probs = F.softmax(logits[0, -1] / 0.8, dim=-1)
|
| 82 |
+
idx = torch.cat([idx, torch.multinomial(probs, 1).view(1, 1)], dim=1)
|
| 83 |
+
return tokenizer.decode(idx[0].tolist())
|
| 84 |
+
print('OpenZenit — escribe /quit para salir')
|
| 85 |
+
while True:
|
| 86 |
+
try: prompt = input('\nTú> ')
|
| 87 |
+
except (EOFError, KeyboardInterrupt): break
|
| 88 |
+
if prompt.strip() == '/quit': break
|
| 89 |
+
print('\nOpenZenit> ' + generate(prompt))
|
| 90 |
+
|
| 91 |
+
if __name__ == '__main__': main()
|