Upload 4 files
Browse files- GPT2_TinyShakespeare1.pt +3 -0
- app.py +93 -0
- model.py +159 -0
- requirements.txt +2 -0
GPT2_TinyShakespeare1.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a4034c8816050f8c3179c282399bdc3de05d9f4fb56014669df2b08a49a73f0d
|
| 3 |
+
size 1544230233
|
app.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tiktoken
|
| 2 |
+
import os
|
| 3 |
+
import torch
|
| 4 |
+
from torch.nn import functional as F
|
| 5 |
+
|
| 6 |
+
from model import GPTConfig, GPT
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
device = 'cpu'
|
| 10 |
+
if torch.cuda.is_available():
|
| 11 |
+
device = 'cuda'
|
| 12 |
+
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
|
| 13 |
+
device = "mps"
|
| 14 |
+
print(f"using device: {device}")
|
| 15 |
+
|
| 16 |
+
modelpath = '.'
|
| 17 |
+
|
| 18 |
+
# STOP
|
| 19 |
+
max_length = 500
|
| 20 |
+
|
| 21 |
+
enc = tiktoken.get_encoding('gpt2')
|
| 22 |
+
|
| 23 |
+
# CHANGES IN CURRENT CODE
|
| 24 |
+
ckpt_path = os.path.join(modelpath, 'GPT2_TinyShakespeare1.pt')
|
| 25 |
+
print(ckpt_path)
|
| 26 |
+
checkpoint = torch.load(ckpt_path, map_location=device)
|
| 27 |
+
gptconf = GPTConfig(**checkpoint['model_args'])
|
| 28 |
+
model = GPT(gptconf)
|
| 29 |
+
state_dict = checkpoint['model']
|
| 30 |
+
unwanted_prefix = '_orig_mod.'
|
| 31 |
+
for k,v in list(state_dict.items()):
|
| 32 |
+
if k.startswith(unwanted_prefix):
|
| 33 |
+
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
|
| 34 |
+
model.load_state_dict(state_dict)
|
| 35 |
+
|
| 36 |
+
model.to(device)
|
| 37 |
+
model = torch.compile(model)
|
| 38 |
+
|
| 39 |
+
def generateText(inputText, num_tokens=500):
|
| 40 |
+
start_tokens = enc.encode(inputText)
|
| 41 |
+
# print(start_tokens, len(start_tokens))
|
| 42 |
+
start_tokens = torch.tensor(start_tokens)
|
| 43 |
+
x = start_tokens.view(1, len(start_tokens))
|
| 44 |
+
x = x.to(device)
|
| 45 |
+
|
| 46 |
+
while x.size(1) < max_length:
|
| 47 |
+
# forward the model to get the logits
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
logits = model(x)[0] # (B, T, vocab_size)
|
| 50 |
+
# take the logits at the last position
|
| 51 |
+
logits = logits[:, -1, :] # (B, vocab_size)
|
| 52 |
+
# get the probabilities
|
| 53 |
+
probs = F.softmax(logits, dim=-1)
|
| 54 |
+
# do top-k sampling of 50 (huggingface pipeline default)
|
| 55 |
+
# topk_probs here becomes (5, 50), topk_indices is (5, 50)
|
| 56 |
+
topk_probs, topk_indices = torch.topk(probs, 50, dim=-1)
|
| 57 |
+
# select a token from the top-k probabilities
|
| 58 |
+
# note: multinomial does not demand the input to sum to 1
|
| 59 |
+
ix = torch.multinomial(topk_probs, 1) # (B, 1)
|
| 60 |
+
# gather the corresponding indices
|
| 61 |
+
xcol = torch.gather(topk_indices, -1, ix) # (B, 1)
|
| 62 |
+
# append to the sequence
|
| 63 |
+
x = torch.cat((x, xcol), dim=1)
|
| 64 |
+
# print(x.size(1))
|
| 65 |
+
|
| 66 |
+
tokens = x[0, :max_length].tolist()
|
| 67 |
+
decoded = enc.decode(tokens)
|
| 68 |
+
return decoded
|
| 69 |
+
|
| 70 |
+
title = "GPT-2 Trained from Scratch"
|
| 71 |
+
description = "GPT-2 trained on scratch on TinyShakespeare dataset"
|
| 72 |
+
examples = [["ROMEO:\nWith love's light wings did I o'er-perch these walls;\nFor stony limits cannot hold love out,\nAnd what love can do that dares love attempt;\nTherefore thy kinsmen are no let to me.\n", 500],
|
| 73 |
+
["CAPULET:\nWhy, how now, kinsman! wherefore storm you so?\n", 500],
|
| 74 |
+
["KING RICHARD II:\nAy, hand from hand, my love, and heart from heart.\nAnd", 500],
|
| 75 |
+
["QUEEN:\nBanish us both and send the king with me.\nAnd", 500],
|
| 76 |
+
["CORIOLANUS:\n", 500]
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
demo = gr.Interface(
|
| 80 |
+
generateText,
|
| 81 |
+
inputs = [
|
| 82 |
+
gr.Textbox(label="Starting text"),
|
| 83 |
+
gr.Slider(100, 2000, value = 500, step=100, label="Number of chars that you want in your output"),
|
| 84 |
+
],
|
| 85 |
+
outputs = [
|
| 86 |
+
gr.Text(),
|
| 87 |
+
],
|
| 88 |
+
title = title,
|
| 89 |
+
description = description,
|
| 90 |
+
examples = examples,
|
| 91 |
+
cache_examples=False
|
| 92 |
+
)
|
| 93 |
+
demo.launch()
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ect
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from torch.nn import functional as F
|
| 6 |
+
|
| 7 |
+
class CausalSelfAttention(nn.Module):
|
| 8 |
+
""" multiple heads of self-attention in parallel """
|
| 9 |
+
|
| 10 |
+
def __init__(self, config):
|
| 11 |
+
super().__init__()
|
| 12 |
+
assert config.n_embd % config.n_head ==0
|
| 13 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
|
| 14 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd)
|
| 15 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
| 16 |
+
self.n_head = config.n_head
|
| 17 |
+
self.n_embd = config.n_embd
|
| 18 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
| 19 |
+
.view(1, 1, config.block_size, config.block_size))
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
| 23 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 24 |
+
# nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
|
| 25 |
+
# e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
|
| 26 |
+
qkv = self.c_attn(x)
|
| 27 |
+
q, k, v = qkv.split(self.n_embd, dim=2)
|
| 28 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 29 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 30 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
|
| 31 |
+
|
| 32 |
+
# att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 33 |
+
# att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
|
| 34 |
+
# att = F.softmax(att, dim=-1)
|
| 35 |
+
# y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
| 36 |
+
|
| 37 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal = True) # Flash attention
|
| 38 |
+
|
| 39 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
|
| 40 |
+
# output projection
|
| 41 |
+
y = self.c_proj(y)
|
| 42 |
+
return y
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class MLP(nn.Module):
|
| 46 |
+
""" a simple linear layer followed by a non-linearity """
|
| 47 |
+
|
| 48 |
+
def __init__(self, config):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.c_fc = nn.Linear(config.n_embd, 4*config.n_embd)
|
| 51 |
+
self.gelu = nn.GELU(approximate='tanh')
|
| 52 |
+
self.c_proj = nn.Linear(4*config.n_embd, config.n_embd)
|
| 53 |
+
self.c_proj.NANOGPT_SCALE_INIT = 1
|
| 54 |
+
|
| 55 |
+
def forward(self, x):
|
| 56 |
+
x = self.c_fc(x)
|
| 57 |
+
x = self.gelu(x)
|
| 58 |
+
x = self.c_proj(x)
|
| 59 |
+
return x
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Block(nn.Module):
|
| 63 |
+
|
| 64 |
+
def __init__(self, config):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.ln_1 = nn.LayerNorm(config.n_embd)
|
| 67 |
+
self.attn = CausalSelfAttention(config)
|
| 68 |
+
self.ln_2 = nn.LayerNorm(config.n_embd)
|
| 69 |
+
self.mlp = MLP(config)
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
x = x + self.attn(self.ln_1(x))
|
| 73 |
+
x = x + self.mlp(self.ln_2(x))
|
| 74 |
+
return x
|
| 75 |
+
|
| 76 |
+
@dataclass
|
| 77 |
+
class GPTConfig:
|
| 78 |
+
block_size: int = 1024 # max sequence length
|
| 79 |
+
vocab_size: int = 50304 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
|
| 80 |
+
n_layer: int = 12 # number of layers
|
| 81 |
+
n_head: int = 12 # number of heads
|
| 82 |
+
n_embd: int = 768 # embedding dimension
|
| 83 |
+
|
| 84 |
+
class GPT(nn.Module):
|
| 85 |
+
|
| 86 |
+
def __init__(self, config):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.config = config
|
| 89 |
+
|
| 90 |
+
self.transformer = nn.ModuleDict(dict(
|
| 91 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
| 92 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
| 93 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 94 |
+
ln_f = nn.LayerNorm(config.n_embd),
|
| 95 |
+
))
|
| 96 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 97 |
+
|
| 98 |
+
# weight sharing
|
| 99 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 100 |
+
|
| 101 |
+
# weight initialization
|
| 102 |
+
self.apply(self._init_weights)
|
| 103 |
+
|
| 104 |
+
def _init_weights(self, module):
|
| 105 |
+
if isinstance(module, nn.Linear):
|
| 106 |
+
std = 0.02
|
| 107 |
+
if hasattr(module, 'NANOGPT_SCALE_INIT'):
|
| 108 |
+
std *= (2 * self.config.n_layer) ** -0.5
|
| 109 |
+
torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
|
| 110 |
+
if module.bias is not None:
|
| 111 |
+
torch.nn.init.zeros_(module.bias)
|
| 112 |
+
elif isinstance(module, nn.Embedding):
|
| 113 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def forward(self, idx, targets=None):
|
| 117 |
+
# idx is of shape (B, T)
|
| 118 |
+
B, T = idx.size()
|
| 119 |
+
assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
|
| 120 |
+
# forward the token and posisition embeddings
|
| 121 |
+
pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
|
| 122 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
|
| 123 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
|
| 124 |
+
x = tok_emb + pos_emb
|
| 125 |
+
# forward the blocks of the transformer
|
| 126 |
+
for block in self.transformer.h:
|
| 127 |
+
x = block(x)
|
| 128 |
+
# forward the final layernorm and the classifier
|
| 129 |
+
x = self.transformer.ln_f(x)
|
| 130 |
+
logits = self.lm_head(x) # (B, T, vocab_size)
|
| 131 |
+
loss = None
|
| 132 |
+
if targets is not None:
|
| 133 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
|
| 134 |
+
return logits, loss
|
| 135 |
+
|
| 136 |
+
def configure_optimizers(self, weight_decay, learning_rate, device_type):
|
| 137 |
+
# start with all of the candidate parameters (that require grad)
|
| 138 |
+
param_dict = {pn: p for pn, p in self.named_parameters()}
|
| 139 |
+
param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
|
| 140 |
+
# create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
|
| 141 |
+
# i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
|
| 142 |
+
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
|
| 143 |
+
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
|
| 144 |
+
optim_groups = [
|
| 145 |
+
{'params': decay_params, 'weight_decay': weight_decay},
|
| 146 |
+
{'params': nodecay_params, 'weight_decay': 0.0}
|
| 147 |
+
]
|
| 148 |
+
num_decay_params = sum(p.numel() for p in decay_params)
|
| 149 |
+
num_nodecay_params = sum(p.numel() for p in nodecay_params)
|
| 150 |
+
|
| 151 |
+
print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
|
| 152 |
+
print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
|
| 153 |
+
# Create AdamW optimizer and use the fused version if it is available
|
| 154 |
+
fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
|
| 155 |
+
use_fused = fused_available and device_type == "cuda"
|
| 156 |
+
|
| 157 |
+
print(f"using fused AdamW: {use_fused}")
|
| 158 |
+
optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=(0.9, 0.95), eps=1e-8, fused=use_fused)
|
| 159 |
+
return optimizer
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
tiktoken
|