Spaces:
Sleeping
Sleeping
Commit ·
2b9a831
1
Parent(s): f9f8ce6
bug due to file name issue fix
Browse files- app.py +1 -1
- transformer.py +161 -98
app.py
CHANGED
|
@@ -7,7 +7,7 @@ import gradio as gr
|
|
| 7 |
tokenizer = GPT2Tokenizer.from_pretrained("gpt2") # Using GPT-2 tokenizer for compatibility
|
| 8 |
|
| 9 |
# Load model
|
| 10 |
-
from
|
| 11 |
|
| 12 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 13 |
|
|
|
|
| 7 |
tokenizer = GPT2Tokenizer.from_pretrained("gpt2") # Using GPT-2 tokenizer for compatibility
|
| 8 |
|
| 9 |
# Load model
|
| 10 |
+
from transformer import GPT, GPTConfig
|
| 11 |
|
| 12 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 13 |
|
transformer.py
CHANGED
|
@@ -1,125 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
@dataclass
|
| 7 |
-
class Config:
|
| 8 |
-
vocab_size: int = 50257
|
| 9 |
-
max_seq_len: int = 2048
|
| 10 |
-
dim: int = 768
|
| 11 |
-
num_layers: int = 12
|
| 12 |
-
num_heads: int = 12
|
| 13 |
-
dropout: float = 0.1
|
| 14 |
-
|
| 15 |
-
class MultiHeadAttention(nn.Module):
|
| 16 |
def __init__(self, config):
|
| 17 |
super().__init__()
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
self.
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
self.
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
self.
|
| 27 |
-
self.
|
| 28 |
|
| 29 |
def forward(self, x):
|
| 30 |
-
B, T, C = x.size() #
|
| 31 |
-
|
| 32 |
-
#
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) #
|
| 37 |
-
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) #
|
| 38 |
-
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) #
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
att =
|
| 42 |
-
att = F.softmax(att, dim=-1)
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
#
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
# Reshape and project
|
| 49 |
-
y = y.transpose(1, 2).contiguous().view(B, T, C) # [B, T, n_embd]
|
| 50 |
-
y = self.c_proj(y) # [B, T, n_embd]
|
| 51 |
-
y = self.resid_dropout(y) # [B, T, n_embd]
|
| 52 |
-
|
| 53 |
return y
|
| 54 |
|
| 55 |
-
|
|
|
|
|
|
|
| 56 |
def __init__(self, config):
|
| 57 |
super().__init__()
|
| 58 |
-
self.c_fc
|
| 59 |
-
self.
|
| 60 |
-
self.
|
|
|
|
| 61 |
|
| 62 |
def forward(self, x):
|
| 63 |
-
x = self.c_fc(x)
|
| 64 |
-
x =
|
| 65 |
-
x = self.c_proj(x)
|
| 66 |
-
x = self.dropout(x) # [B, T, n_embd]
|
| 67 |
return x
|
| 68 |
|
| 69 |
-
class
|
|
|
|
| 70 |
def __init__(self, config):
|
| 71 |
super().__init__()
|
| 72 |
-
self.ln_1 = nn.LayerNorm(config.
|
| 73 |
-
self.attn =
|
| 74 |
-
self.ln_2 = nn.LayerNorm(config.
|
| 75 |
-
self.mlp =
|
| 76 |
|
| 77 |
def forward(self, x):
|
| 78 |
-
x = x + self.attn(self.ln_1(x))
|
| 79 |
-
x = x + self.mlp(self.ln_2(x))
|
| 80 |
return x
|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
def __init__(self, config):
|
| 84 |
super().__init__()
|
| 85 |
self.config = config
|
| 86 |
-
|
| 87 |
-
self.
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
self.apply(self._init_weights)
|
| 94 |
|
| 95 |
def _init_weights(self, module):
|
| 96 |
-
if isinstance(module,
|
| 97 |
-
|
| 98 |
-
if
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
module.bias
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
#
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
#
|
| 118 |
-
for block in self.
|
| 119 |
-
x = block(x)
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|