Spaces:
Build error
Build error
Commit
·
2bb12cf
1
Parent(s):
40384fa
first commit to test the transformer in spaces
Browse files- app.py +74 -0
- requirements.txt +5 -0
- transformer-basic.py +335 -0
app.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import tiktoken
|
| 5 |
+
from huggingface_hub import hf_hub_download
|
| 6 |
+
from transformer-basic import GPT, GPTConfig # Import your model class
|
| 7 |
+
|
| 8 |
+
# Load the model from Hugging Face Hub
|
| 9 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 10 |
+
def load_model_from_hf():
|
| 11 |
+
# Replace with your Hugging Face model ID (username/model-name)
|
| 12 |
+
model_id = "satyanayak/transformer-basic"
|
| 13 |
+
checkpoint_path = hf_hub_download(repo_id=model_id, filename="trained_model.pt")
|
| 14 |
+
|
| 15 |
+
checkpoint = torch.load(checkpoint_path, map_location=device)
|
| 16 |
+
config = checkpoint['config']
|
| 17 |
+
model = GPT(config)
|
| 18 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
| 19 |
+
model.to(device)
|
| 20 |
+
model.eval()
|
| 21 |
+
return model
|
| 22 |
+
|
| 23 |
+
model = load_model_from_hf()
|
| 24 |
+
|
| 25 |
+
def generate_text(prompt, max_length=100, num_samples=1, temperature=0.8):
|
| 26 |
+
enc = tiktoken.get_encoding('gpt2')
|
| 27 |
+
tokens = enc.encode(prompt)
|
| 28 |
+
tokens = torch.tensor(tokens, dtype=torch.long)
|
| 29 |
+
tokens = tokens.unsqueeze(0).repeat(num_samples, 1)
|
| 30 |
+
tokens = tokens.to(device)
|
| 31 |
+
|
| 32 |
+
with torch.no_grad():
|
| 33 |
+
for _ in range(max_length):
|
| 34 |
+
if tokens.size(1) >= 1024: # GPT context length
|
| 35 |
+
break
|
| 36 |
+
|
| 37 |
+
logits = model(tokens)[0]
|
| 38 |
+
logits = logits[:, -1, :] / temperature
|
| 39 |
+
probs = F.softmax(logits, dim=-1)
|
| 40 |
+
|
| 41 |
+
# Top-k sampling
|
| 42 |
+
topk_probs, topk_indices = torch.topk(probs, 50, dim=-1)
|
| 43 |
+
ix = torch.multinomial(topk_probs, 1)
|
| 44 |
+
next_token = torch.gather(topk_indices, -1, ix)
|
| 45 |
+
|
| 46 |
+
tokens = torch.cat((tokens, next_token), dim=1)
|
| 47 |
+
|
| 48 |
+
# Check for end of text token
|
| 49 |
+
if next_token.item() == enc.encode('<|endoftext|>')[0]:
|
| 50 |
+
break
|
| 51 |
+
|
| 52 |
+
generated_texts = []
|
| 53 |
+
for i in range(num_samples):
|
| 54 |
+
text = enc.decode(tokens[i].tolist())
|
| 55 |
+
generated_texts.append(text)
|
| 56 |
+
|
| 57 |
+
return '\n\n---\n\n'.join(generated_texts)
|
| 58 |
+
|
| 59 |
+
# Create Gradio interface
|
| 60 |
+
iface = gr.Interface(
|
| 61 |
+
fn=generate_text,
|
| 62 |
+
inputs=[
|
| 63 |
+
gr.Textbox(label="Prompt", value="We are accounted poor citizens, the"),
|
| 64 |
+
gr.Slider(minimum=10, maximum=200, value=100, step=1, label="Max Length"),
|
| 65 |
+
gr.Slider(minimum=1, maximum=5, value=1, step=1, label="Number of Samples"),
|
| 66 |
+
gr.Slider(minimum=0.1, maximum=2.0, value=0.8, step=0.1, label="Temperature")
|
| 67 |
+
],
|
| 68 |
+
outputs=gr.Textbox(label="Generated Text"),
|
| 69 |
+
title="Shakespeare-style Text Generator",
|
| 70 |
+
description="Enter a prompt to generate Shakespeare-style text continuation"
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
if __name__ == "__main__":
|
| 74 |
+
iface.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
gradio
|
| 3 |
+
tiktoken
|
| 4 |
+
transformers
|
| 5 |
+
huggingface_hub
|
transformer-basic.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Solving for residual std scaling issue
|
| 2 |
+
import os
|
| 3 |
+
import math
|
| 4 |
+
import time
|
| 5 |
+
import inspect
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
from torch.nn import functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CausalSelfAttention(nn.Module):
|
| 13 |
+
|
| 14 |
+
def __init__(self, config):
|
| 15 |
+
super().__init__()
|
| 16 |
+
assert config.n_embd % config.n_head == 0
|
| 17 |
+
# key, query, value projections for all heads, but in a batch
|
| 18 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 19 |
+
# output projection
|
| 20 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 21 |
+
self.c_proj.NANGPT_SCALE_INIT = 1
|
| 22 |
+
# regularization
|
| 23 |
+
self.n_head = config.n_head
|
| 24 |
+
self.n_embd = config.n_embd
|
| 25 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
|
| 26 |
+
|
| 27 |
+
def forward(self, x):
|
| 28 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
| 29 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 30 |
+
# nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
|
| 31 |
+
# e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
|
| 32 |
+
qkv = self.c_attn(x)
|
| 33 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 34 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 35 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 36 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 37 |
+
|
| 38 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 39 |
+
att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
|
| 40 |
+
att = F.softmax(att, dim=-1)
|
| 41 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
| 42 |
+
|
| 43 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
| 44 |
+
# output projection
|
| 45 |
+
y = self.c_proj(y)
|
| 46 |
+
return y
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class MLP(nn.Module):
|
| 50 |
+
|
| 51 |
+
def __init__(self, config):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
|
| 54 |
+
self.gelu = nn.GELU(approximate='tanh')
|
| 55 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
|
| 56 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
| 57 |
+
|
| 58 |
+
def forward(self, x):
|
| 59 |
+
x = self.c_fc(x)
|
| 60 |
+
x = self.gelu(x)
|
| 61 |
+
x = self.c_proj(x)
|
| 62 |
+
return x
|
| 63 |
+
|
| 64 |
+
class Block(nn.Module):
|
| 65 |
+
|
| 66 |
+
def __init__(self, config):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
| 69 |
+
self.attn = CausalSelfAttention(config)
|
| 70 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
| 71 |
+
self.mlp = MLP(config)
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
x = x + self.attn(self.ln_1(x))
|
| 75 |
+
x = x + self.mlp(self.ln_2(x))
|
| 76 |
+
return x
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@dataclass
|
| 80 |
+
class GPTConfig:
|
| 81 |
+
block_size: int = 1024 # max sequence length
|
| 82 |
+
vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
| 83 |
+
n_layer: int = 12 # number of layers
|
| 84 |
+
n_head: int = 12 # number of heads
|
| 85 |
+
n_embd: int = 768 # embedding dimension
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class GPT(nn.Module):
|
| 89 |
+
|
| 90 |
+
def __init__(self, config):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.config = config
|
| 93 |
+
|
| 94 |
+
self.transformer = nn.ModuleDict(dict(
|
| 95 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
| 96 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
| 97 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 98 |
+
ln_f = nn.LayerNorm(config.n_embd),
|
| 99 |
+
))
|
| 100 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 101 |
+
|
| 102 |
+
# weight sharing
|
| 103 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 104 |
+
|
| 105 |
+
# weight initialization
|
| 106 |
+
self.apply(self._init_weights)
|
| 107 |
+
|
| 108 |
+
def _init_weights(self, module):
|
| 109 |
+
if isinstance(module, nn.Linear):
|
| 110 |
+
std = 0.02
|
| 111 |
+
if hasattr(module, 'NANGPT_SCALE_INIT'):
|
| 112 |
+
std *= (2 * self.config.n_layer) ** -0.5
|
| 113 |
+
torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
|
| 114 |
+
if module.bias is not None:
|
| 115 |
+
torch.nn.init.zeros_(module.bias)
|
| 116 |
+
elif isinstance(module, nn.Embedding):
|
| 117 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def forward(self, idx, targets=None):
|
| 122 |
+
# idx is of shape (B, T)
|
| 123 |
+
B, T = idx.size()
|
| 124 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
|
| 125 |
+
# forward the token and posisition embeddings
|
| 126 |
+
pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
|
| 127 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
|
| 128 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
|
| 129 |
+
x = tok_emb + pos_emb
|
| 130 |
+
# forward the blocks of the transformer
|
| 131 |
+
for block in self.transformer.h:
|
| 132 |
+
x = block(x)
|
| 133 |
+
# forward the final layernorm and the classifier
|
| 134 |
+
x = self.transformer.ln_f(x)
|
| 135 |
+
logits = self.lm_head(x) # (B, T, vocab_size)
|
| 136 |
+
loss = None
|
| 137 |
+
if targets is not None:
|
| 138 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 139 |
+
return logits, loss
|
| 140 |
+
|
| 141 |
+
@classmethod
|
| 142 |
+
def from_pretrained(cls, model_type):
|
| 143 |
+
"""Loads pretrained GPT-2 model weights from huggingface"""
|
| 144 |
+
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
|
| 145 |
+
from transformers import GPT2LMHeadModel
|
| 146 |
+
print("loading weights from pretrained gpt: %s" % model_type)
|
| 147 |
+
|
| 148 |
+
# n_layer, n_head and n_embd are determined from model_type
|
| 149 |
+
config_args = {
|
| 150 |
+
'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
| 151 |
+
'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
| 152 |
+
'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
| 153 |
+
'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
| 154 |
+
}[model_type]
|
| 155 |
+
config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
|
| 156 |
+
config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
|
| 157 |
+
# create a from-scratch initialized minGPT model
|
| 158 |
+
config = GPTConfig(**config_args)
|
| 159 |
+
model = GPT(config)
|
| 160 |
+
sd = model.state_dict()
|
| 161 |
+
sd_keys = sd.keys()
|
| 162 |
+
sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
|
| 163 |
+
|
| 164 |
+
# init a huggingface/transformers model
|
| 165 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
| 166 |
+
sd_hf = model_hf.state_dict()
|
| 167 |
+
|
| 168 |
+
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
| 169 |
+
sd_keys_hf = sd_hf.keys()
|
| 170 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
|
| 171 |
+
sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
|
| 172 |
+
transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
|
| 173 |
+
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
| 174 |
+
# this means that we have to transpose these weights when we import them
|
| 175 |
+
assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
| 176 |
+
for k in sd_keys_hf:
|
| 177 |
+
if any(k.endswith(w) for w in transposed):
|
| 178 |
+
# special treatment for the Conv1D weights we need to transpose
|
| 179 |
+
assert sd_hf[k].shape[::-1] == sd[k].shape
|
| 180 |
+
with torch.no_grad():
|
| 181 |
+
sd[k].copy_(sd_hf[k].t())
|
| 182 |
+
else:
|
| 183 |
+
# vanilla copy over the other parameters
|
| 184 |
+
assert sd_hf[k].shape == sd[k].shape
|
| 185 |
+
with torch.no_grad():
|
| 186 |
+
sd[k].copy_(sd_hf[k])
|
| 187 |
+
|
| 188 |
+
return model
|
| 189 |
+
|
| 190 |
+
# model = GPT.from_pretrained('gpt2')
|
| 191 |
+
|
| 192 |
+
device = 'cpu'
|
| 193 |
+
if torch.cuda.is_available():
|
| 194 |
+
device = 'cuda'
|
| 195 |
+
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 196 |
+
device = "mps"
|
| 197 |
+
print(f"using device: {device}")
|
| 198 |
+
|
| 199 |
+
# SEED
|
| 200 |
+
torch.manual_seed(1337)
|
| 201 |
+
if torch.cuda.is_available():
|
| 202 |
+
torch.cuda.manual_seed(1337)
|
| 203 |
+
|
| 204 |
+
# STOP
|
| 205 |
+
num_return_sequences = 5
|
| 206 |
+
max_length = 30
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
import tiktoken
|
| 211 |
+
|
| 212 |
+
class DataLoaderLite:
|
| 213 |
+
def __init__(self, B, T):
|
| 214 |
+
self.B = B
|
| 215 |
+
self.T = T
|
| 216 |
+
|
| 217 |
+
# at init load tokens from disk and store them in memory
|
| 218 |
+
with open('input.txt', 'r') as f:
|
| 219 |
+
text = f.read()
|
| 220 |
+
enc = tiktoken.get_encoding('gpt2')
|
| 221 |
+
tokens = enc.encode(text)
|
| 222 |
+
self.tokens = torch.tensor(tokens)
|
| 223 |
+
print(f'loaded {len(self.tokens)} tokens')
|
| 224 |
+
print(f'1 epoch = {len(self.tokens) // (B * T)} batches')
|
| 225 |
+
|
| 226 |
+
# state
|
| 227 |
+
self.current_position = 0
|
| 228 |
+
|
| 229 |
+
def next_batch(self):
|
| 230 |
+
B, T = self.B, self.T
|
| 231 |
+
buf = self.tokens[self.current_position: self.current_position + B * T + 1]
|
| 232 |
+
x = (buf[:-1]).view(B, T) # inputs
|
| 233 |
+
y = (buf[1:]).view(B, T) # targets
|
| 234 |
+
# advance the position in the tensor
|
| 235 |
+
self.current_position += B*T
|
| 236 |
+
# if loading the next batch would be out of bounds, reset
|
| 237 |
+
if self.current_position + (B * T + 1) > len(self.tokens):
|
| 238 |
+
self.current_position = 0
|
| 239 |
+
return x, y
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
model = GPT(GPTConfig())
|
| 243 |
+
model.to(device)
|
| 244 |
+
|
| 245 |
+
# Increase batch size slightly but keep it manageable
|
| 246 |
+
train_loader = DataLoaderLite(B=8, T=64)
|
| 247 |
+
|
| 248 |
+
# Calculate total steps for one cycle
|
| 249 |
+
total_steps = 10000
|
| 250 |
+
print(f"Training for {total_steps} steps")
|
| 251 |
+
|
| 252 |
+
# Initialize optimizer with more conservative parameters
|
| 253 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.1, betas=(0.9, 0.95))
|
| 254 |
+
|
| 255 |
+
# Use OneCycleLR scheduler
|
| 256 |
+
scheduler = torch.optim.lr_scheduler.OneCycleLR(
|
| 257 |
+
optimizer,
|
| 258 |
+
max_lr=3e-4,
|
| 259 |
+
total_steps=total_steps,
|
| 260 |
+
pct_start=0.1, # Warm up for 10% of steps
|
| 261 |
+
anneal_strategy='cos',
|
| 262 |
+
cycle_momentum=False,
|
| 263 |
+
div_factor=25.0, # Initial lr = max_lr/25
|
| 264 |
+
final_div_factor=10000.0, # Min lr = initial_lr/10000
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# Training loop
|
| 268 |
+
best_loss = float('inf')
|
| 269 |
+
step = 0
|
| 270 |
+
losses = [] # Keep track of losses for monitoring
|
| 271 |
+
last_time = time.time()
|
| 272 |
+
interval = 10 # Print every 10 steps
|
| 273 |
+
|
| 274 |
+
while step < total_steps and best_loss > 0.099999:
|
| 275 |
+
x, y = train_loader.next_batch()
|
| 276 |
+
x, y = x.to(device), y.to(device)
|
| 277 |
+
|
| 278 |
+
optimizer.zero_grad()
|
| 279 |
+
logits, loss = model(x, y)
|
| 280 |
+
loss.backward()
|
| 281 |
+
|
| 282 |
+
# Gradient clipping
|
| 283 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5) # Reduced from 1.0
|
| 284 |
+
|
| 285 |
+
optimizer.step()
|
| 286 |
+
scheduler.step()
|
| 287 |
+
|
| 288 |
+
# Update best loss
|
| 289 |
+
if loss.item() < best_loss:
|
| 290 |
+
best_loss = loss.item()
|
| 291 |
+
|
| 292 |
+
losses.append(loss.item())
|
| 293 |
+
|
| 294 |
+
# Print progress
|
| 295 |
+
if step % interval == 0:
|
| 296 |
+
current_time = time.time()
|
| 297 |
+
time_per_batch = (current_time - last_time) / interval if step > 0 else 0
|
| 298 |
+
last_time = current_time
|
| 299 |
+
|
| 300 |
+
# Calculate average loss over last 100 steps for stability
|
| 301 |
+
avg_loss = sum(losses[-100:]) / min(len(losses), 100)
|
| 302 |
+
|
| 303 |
+
print(f'step {step}, '
|
| 304 |
+
f'loss: {loss.item():.4f}, '
|
| 305 |
+
f'avg_loss: {avg_loss:.4f}, '
|
| 306 |
+
f'best_loss: {best_loss:.4f}, '
|
| 307 |
+
f'lr: {scheduler.get_last_lr()[0]:.2e}, '
|
| 308 |
+
f'time/batch: {time_per_batch:.3f}s')
|
| 309 |
+
|
| 310 |
+
step += 1
|
| 311 |
+
|
| 312 |
+
print(f'Final loss: {loss.item():.6f}')
|
| 313 |
+
print(f'Best loss: {best_loss:.6f}')
|
| 314 |
+
print(f'Average of last 100 losses: {sum(losses[-100:]) / min(len(losses), 100):.6f}')
|
| 315 |
+
|
| 316 |
+
# Save the trained model
|
| 317 |
+
save_path = 'trained_model.pt'
|
| 318 |
+
torch.save({
|
| 319 |
+
'model_state_dict': model.state_dict(),
|
| 320 |
+
'optimizer_state_dict': optimizer.state_dict(),
|
| 321 |
+
'scheduler_state_dict': scheduler.state_dict(),
|
| 322 |
+
'best_loss': best_loss,
|
| 323 |
+
'config': model.config,
|
| 324 |
+
}, save_path)
|
| 325 |
+
print(f"Model saved to {save_path}")
|
| 326 |
+
|
| 327 |
+
# Generation code
|
| 328 |
+
enc = tiktoken.get_encoding('gpt2')
|
| 329 |
+
prompt = "We are accounted poor citizens, the"
|
| 330 |
+
tokens = enc.encode(prompt)
|
| 331 |
+
tokens = torch.tensor(tokens, dtype=torch.long)
|
| 332 |
+
tokens = tokens.unsqueeze(0).repeat(num_return_sequences, 1)
|
| 333 |
+
x = tokens.to(device)
|
| 334 |
+
|
| 335 |
+
# Rest of generation code remains same...
|