Upload 3 files
Browse files- model.pt +3 -0
- model.py +634 -0
- tokenizer.json +0 -0
model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9106b9257c78cbc2136e9dd70614932f3ec6ba7ead5bdbdc9ddbdc4001b55d5a
|
| 3 |
+
size 70036687
|
model.py
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 3 |
+
References:
|
| 4 |
+
1) the official GPT-2 TensorFlow implementation released by OpenAI:
|
| 5 |
+
https://github.com/openai/gpt-2/blob/master/src/model.py
|
| 6 |
+
2) huggingface/transformers PyTorch implementation:
|
| 7 |
+
https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import math
|
| 12 |
+
import inspect
|
| 13 |
+
import os
|
| 14 |
+
import uuid
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
from pydantic import BaseModel, ConfigDict
|
| 18 |
+
import torch
|
| 19 |
+
import torch.nn as nn
|
| 20 |
+
from torch.nn import functional as F
|
| 21 |
+
from transformers import PreTrainedTokenizerFast
|
| 22 |
+
from typing import Callable
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class LayerNorm(nn.Module):
|
| 26 |
+
"""LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False"""
|
| 27 |
+
|
| 28 |
+
def __init__(self, ndim, bias):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.weight = nn.Parameter(torch.ones(ndim))
|
| 31 |
+
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
| 32 |
+
|
| 33 |
+
def forward(self, input):
|
| 34 |
+
return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CausalSelfAttention(nn.Module):
|
| 38 |
+
def __init__(self, config):
|
| 39 |
+
super().__init__()
|
| 40 |
+
assert config.n_embd % config.n_head == 0
|
| 41 |
+
# key, query, value projections for all heads, but in a batch
|
| 42 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
| 43 |
+
# output projection
|
| 44 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
| 45 |
+
# regularization
|
| 46 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
| 47 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
| 48 |
+
self.n_head = config.n_head
|
| 49 |
+
self.n_embd = config.n_embd
|
| 50 |
+
self.dropout = config.dropout
|
| 51 |
+
# flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
|
| 52 |
+
self.flash = hasattr(torch.nn.functional, "scaled_dot_product_attention")
|
| 53 |
+
if not self.flash:
|
| 54 |
+
print(
|
| 55 |
+
"WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0"
|
| 56 |
+
)
|
| 57 |
+
# causal mask to ensure that attention is only applied to the left in the input sequence
|
| 58 |
+
self.register_buffer(
|
| 59 |
+
"bias",
|
| 60 |
+
torch.tril(torch.ones(config.block_size, config.block_size)).view(
|
| 61 |
+
1, 1, config.block_size, config.block_size
|
| 62 |
+
),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def forward(self, x):
|
| 66 |
+
(
|
| 67 |
+
B,
|
| 68 |
+
T,
|
| 69 |
+
C,
|
| 70 |
+
) = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
| 71 |
+
|
| 72 |
+
# calculate query, key, values for all heads in batch and move head forward to be the batch dim
|
| 73 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
| 74 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(
|
| 75 |
+
1, 2
|
| 76 |
+
) # (B, nh, T, hs)
|
| 77 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(
|
| 78 |
+
1, 2
|
| 79 |
+
) # (B, nh, T, hs)
|
| 80 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(
|
| 81 |
+
1, 2
|
| 82 |
+
) # (B, nh, T, hs)
|
| 83 |
+
|
| 84 |
+
# causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
|
| 85 |
+
if self.flash:
|
| 86 |
+
# efficient attention using Flash Attention CUDA kernels
|
| 87 |
+
y = torch.nn.functional.scaled_dot_product_attention(
|
| 88 |
+
q,
|
| 89 |
+
k,
|
| 90 |
+
v,
|
| 91 |
+
attn_mask=None,
|
| 92 |
+
dropout_p=self.dropout if self.training else 0,
|
| 93 |
+
is_causal=True,
|
| 94 |
+
)
|
| 95 |
+
else:
|
| 96 |
+
# manual implementation of attention
|
| 97 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
|
| 98 |
+
att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float("-inf"))
|
| 99 |
+
att = F.softmax(att, dim=-1)
|
| 100 |
+
att = self.attn_dropout(att)
|
| 101 |
+
y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
|
| 102 |
+
y = (
|
| 103 |
+
y.transpose(1, 2).contiguous().view(B, T, C)
|
| 104 |
+
) # re-assemble all head outputs side by side
|
| 105 |
+
|
| 106 |
+
# output projection
|
| 107 |
+
y = self.resid_dropout(self.c_proj(y))
|
| 108 |
+
return y
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class MLP(nn.Module):
|
| 112 |
+
def __init__(self, config):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
|
| 115 |
+
self.gelu = nn.GELU()
|
| 116 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
|
| 117 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 118 |
+
|
| 119 |
+
def forward(self, x):
|
| 120 |
+
x = self.c_fc(x)
|
| 121 |
+
x = self.gelu(x)
|
| 122 |
+
x = self.c_proj(x)
|
| 123 |
+
x = self.dropout(x)
|
| 124 |
+
return x
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Block(nn.Module):
|
| 128 |
+
def __init__(self, config):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
|
| 131 |
+
self.attn = CausalSelfAttention(config)
|
| 132 |
+
self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
|
| 133 |
+
self.mlp = MLP(config)
|
| 134 |
+
|
| 135 |
+
def forward(self, x):
|
| 136 |
+
x = x + self.attn(self.ln_1(x))
|
| 137 |
+
x = x + self.mlp(self.ln_2(x))
|
| 138 |
+
return x
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class GPTConfig(BaseModel):
|
| 142 |
+
block_size: int = 1024
|
| 143 |
+
vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
|
| 144 |
+
n_layer: int = 12
|
| 145 |
+
n_head: int = 12
|
| 146 |
+
n_embd: int = 768
|
| 147 |
+
dropout: float = 0.0
|
| 148 |
+
bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
|
| 149 |
+
tokenizer_file: str = 'resources/tokenizer.json'
|
| 150 |
+
|
| 151 |
+
model_config = ConfigDict(extra='ignore')
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class GPT(nn.Module):
|
| 155 |
+
def __init__(self, config: GPTConfig):
|
| 156 |
+
super().__init__()
|
| 157 |
+
assert config.vocab_size is not None
|
| 158 |
+
assert config.block_size is not None
|
| 159 |
+
self.config = config
|
| 160 |
+
self.tokenizer = PreTrainedTokenizerFast(tokenizer_file=config.tokenizer_file)
|
| 161 |
+
self.end_token = self.tokenizer('[END]')['input_ids'][0]
|
| 162 |
+
self.comma_token = self.tokenizer(',')['input_ids'][0]
|
| 163 |
+
|
| 164 |
+
self.transformer = nn.ModuleDict(
|
| 165 |
+
dict(
|
| 166 |
+
wte=nn.Embedding(config.vocab_size, config.n_embd),
|
| 167 |
+
wpe=nn.Embedding(config.block_size, config.n_embd),
|
| 168 |
+
drop=nn.Dropout(config.dropout),
|
| 169 |
+
h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 170 |
+
ln_f=LayerNorm(config.n_embd, bias=config.bias),
|
| 171 |
+
)
|
| 172 |
+
)
|
| 173 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 174 |
+
# with weight tying when using torch.compile() some warnings get generated:
|
| 175 |
+
# "UserWarning: functional_call was passed multiple values for tied weights.
|
| 176 |
+
# This behavior is deprecated and will be an error in future versions"
|
| 177 |
+
# not 100% sure what this is, so far seems to be harmless. TODO investigate
|
| 178 |
+
self.transformer.wte.weight = (
|
| 179 |
+
self.lm_head.weight
|
| 180 |
+
) # https://paperswithcode.com/method/weight-tying
|
| 181 |
+
|
| 182 |
+
# init all weights
|
| 183 |
+
self.apply(self._init_weights)
|
| 184 |
+
# apply special scaled init to the residual projections, per GPT-2 paper
|
| 185 |
+
for pn, p in self.named_parameters():
|
| 186 |
+
if pn.endswith("c_proj.weight"):
|
| 187 |
+
torch.nn.init.normal_(
|
| 188 |
+
p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer)
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# report number of parameters
|
| 192 |
+
# print("number of parameters: %.2fM" % (self.get_num_params() / 1e6,))
|
| 193 |
+
|
| 194 |
+
def get_num_params(self, non_embedding=True):
|
| 195 |
+
"""
|
| 196 |
+
Return the number of parameters in the model.
|
| 197 |
+
For non-embedding count (default), the position embeddings get subtracted.
|
| 198 |
+
The token embeddings would too, except due to the parameter sharing these
|
| 199 |
+
params are actually used as weights in the final layer, so we include them.
|
| 200 |
+
"""
|
| 201 |
+
n_params = sum(p.numel() for p in self.parameters())
|
| 202 |
+
if non_embedding:
|
| 203 |
+
n_params -= self.transformer.wpe.weight.numel()
|
| 204 |
+
return n_params
|
| 205 |
+
|
| 206 |
+
def _init_weights(self, module):
|
| 207 |
+
if isinstance(module, nn.Linear):
|
| 208 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 209 |
+
if module.bias is not None:
|
| 210 |
+
torch.nn.init.zeros_(module.bias)
|
| 211 |
+
elif isinstance(module, nn.Embedding):
|
| 212 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 213 |
+
|
| 214 |
+
def forward(self, idx, targets=None):
|
| 215 |
+
# with torch.autograd.detect_anomaly():
|
| 216 |
+
# if torch.isnan(idx).any():
|
| 217 |
+
# print(f'NAN found!: {idx}')
|
| 218 |
+
|
| 219 |
+
device = idx.device
|
| 220 |
+
b, t = idx.size()
|
| 221 |
+
assert (
|
| 222 |
+
t <= self.config.block_size
|
| 223 |
+
), f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
|
| 224 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
|
| 225 |
+
|
| 226 |
+
# forward the GPT model itself
|
| 227 |
+
tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
|
| 228 |
+
pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
|
| 229 |
+
x = self.transformer.drop(tok_emb + pos_emb)
|
| 230 |
+
for block in self.transformer.h:
|
| 231 |
+
x = block(x)
|
| 232 |
+
x = self.transformer.ln_f(x)
|
| 233 |
+
|
| 234 |
+
if targets is not None:
|
| 235 |
+
# if we are given some desired targets also calculate the loss
|
| 236 |
+
logits = self.lm_head(x)
|
| 237 |
+
loss = F.cross_entropy(
|
| 238 |
+
logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1
|
| 239 |
+
)
|
| 240 |
+
else:
|
| 241 |
+
# inference-time mini-optimization: only forward the lm_head on the very last position
|
| 242 |
+
logits = self.lm_head(
|
| 243 |
+
x[:, [-1], :]
|
| 244 |
+
) # note: using list [-1] to preserve the time dim
|
| 245 |
+
loss = None
|
| 246 |
+
|
| 247 |
+
return logits, loss
|
| 248 |
+
|
| 249 |
+
def crop_block_size(self, block_size):
|
| 250 |
+
# model surgery to decrease the block size if necessary
|
| 251 |
+
# e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
|
| 252 |
+
# but want to use a smaller block size for some smaller, simpler model
|
| 253 |
+
assert block_size <= self.config.block_size
|
| 254 |
+
self.config.block_size = block_size
|
| 255 |
+
self.transformer.wpe.weight = nn.Parameter(
|
| 256 |
+
self.transformer.wpe.weight[:block_size]
|
| 257 |
+
)
|
| 258 |
+
for block in self.transformer.h:
|
| 259 |
+
if hasattr(block.attn, "bias"):
|
| 260 |
+
block.attn.bias = block.attn.bias[:, :, :block_size, :block_size]
|
| 261 |
+
|
| 262 |
+
@classmethod
|
| 263 |
+
def from_pretrained(cls, model_type, override_args=None):
|
| 264 |
+
assert model_type in {"gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl"}
|
| 265 |
+
override_args = override_args or {} # default to empty dict
|
| 266 |
+
# only dropout can be overridden see more notes below
|
| 267 |
+
assert all(k == "dropout" for k in override_args)
|
| 268 |
+
from transformers import GPT2LMHeadModel
|
| 269 |
+
|
| 270 |
+
print("loading weights from pretrained gpt: %s" % model_type)
|
| 271 |
+
|
| 272 |
+
# n_layer, n_head and n_embd are determined from model_type
|
| 273 |
+
config_args = {
|
| 274 |
+
"gpt2": dict(n_layer=12, n_head=12, n_embd=768), # 124M params
|
| 275 |
+
"gpt2-medium": dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
|
| 276 |
+
"gpt2-large": dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
|
| 277 |
+
"gpt2-xl": dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
|
| 278 |
+
}[model_type]
|
| 279 |
+
print("forcing vocab_size=50257, block_size=1024, bias=True")
|
| 280 |
+
config_args["vocab_size"] = 50257 # always 50257 for GPT model checkpoints
|
| 281 |
+
config_args["block_size"] = 1024 # always 1024 for GPT model checkpoints
|
| 282 |
+
config_args["bias"] = True # always True for GPT model checkpoints
|
| 283 |
+
# we can override the dropout rate, if desired
|
| 284 |
+
if "dropout" in override_args:
|
| 285 |
+
print(f"overriding dropout rate to {override_args['dropout']}")
|
| 286 |
+
config_args["dropout"] = override_args["dropout"]
|
| 287 |
+
# create a from-scratch initialized minGPT model
|
| 288 |
+
config = GPTConfig(**config_args)
|
| 289 |
+
model = GPT(config)
|
| 290 |
+
sd = model.state_dict()
|
| 291 |
+
sd_keys = sd.keys()
|
| 292 |
+
sd_keys = [
|
| 293 |
+
k for k in sd_keys if not k.endswith(".attn.bias")
|
| 294 |
+
] # discard this mask / buffer, not a param
|
| 295 |
+
|
| 296 |
+
# init a huggingface/transformers model
|
| 297 |
+
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
|
| 298 |
+
sd_hf = model_hf.state_dict()
|
| 299 |
+
|
| 300 |
+
# copy while ensuring all of the parameters are aligned and match in names and shapes
|
| 301 |
+
sd_keys_hf = sd_hf.keys()
|
| 302 |
+
sd_keys_hf = [
|
| 303 |
+
k for k in sd_keys_hf if not k.endswith(".attn.masked_bias")
|
| 304 |
+
] # ignore these, just a buffer
|
| 305 |
+
sd_keys_hf = [
|
| 306 |
+
k for k in sd_keys_hf if not k.endswith(".attn.bias")
|
| 307 |
+
] # same, just the mask (buffer)
|
| 308 |
+
transposed = [
|
| 309 |
+
"attn.c_attn.weight",
|
| 310 |
+
"attn.c_proj.weight",
|
| 311 |
+
"mlp.c_fc.weight",
|
| 312 |
+
"mlp.c_proj.weight",
|
| 313 |
+
]
|
| 314 |
+
# basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
|
| 315 |
+
# this means that we have to transpose these weights when we import them
|
| 316 |
+
assert len(sd_keys_hf) == len(
|
| 317 |
+
sd_keys
|
| 318 |
+
), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
|
| 319 |
+
for k in sd_keys_hf:
|
| 320 |
+
if any(k.endswith(w) for w in transposed):
|
| 321 |
+
# special treatment for the Conv1D weights we need to transpose
|
| 322 |
+
assert sd_hf[k].shape[::-1] == sd[k].shape
|
| 323 |
+
with torch.no_grad():
|
| 324 |
+
sd[k].copy_(sd_hf[k].t())
|
| 325 |
+
else:
|
| 326 |
+
# vanilla copy over the other parameters
|
| 327 |
+
assert sd_hf[k].shape == sd[k].shape
|
| 328 |
+
with torch.no_grad():
|
| 329 |
+
sd[k].copy_(sd_hf[k])
|
| 330 |
+
|
| 331 |
+
return model
|
| 332 |
+
|
| 333 |
+
def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
|
| 334 |
+
# start with all of the candidate parameters
|
| 335 |
+
param_dict = {pn: p for pn, p in self.named_parameters()}
|
| 336 |
+
# filter out those that do not require grad
|
| 337 |
+
param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
|
| 338 |
+
# create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
|
| 339 |
+
# i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
|
| 340 |
+
decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
|
| 341 |
+
nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
|
| 342 |
+
optim_groups = [
|
| 343 |
+
{"params": decay_params, "weight_decay": weight_decay},
|
| 344 |
+
{"params": nodecay_params, "weight_decay": 0.0},
|
| 345 |
+
]
|
| 346 |
+
num_decay_params = sum(p.numel() for p in decay_params)
|
| 347 |
+
num_nodecay_params = sum(p.numel() for p in nodecay_params)
|
| 348 |
+
print(
|
| 349 |
+
f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters"
|
| 350 |
+
)
|
| 351 |
+
print(
|
| 352 |
+
f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters"
|
| 353 |
+
)
|
| 354 |
+
# Create AdamW optimizer and use the fused version if it is available
|
| 355 |
+
fused_available = "fused" in inspect.signature(torch.optim.AdamW).parameters
|
| 356 |
+
use_fused = fused_available and device_type == "cuda"
|
| 357 |
+
extra_args = dict(fused=True) if use_fused else dict()
|
| 358 |
+
optimizer = torch.optim.AdamW(
|
| 359 |
+
optim_groups, lr=learning_rate, betas=betas, **extra_args
|
| 360 |
+
)
|
| 361 |
+
print(f"using fused AdamW: {use_fused}")
|
| 362 |
+
|
| 363 |
+
return optimizer
|
| 364 |
+
|
| 365 |
+
def estimate_mfu(self, fwdbwd_per_iter, dt):
|
| 366 |
+
"""estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS"""
|
| 367 |
+
# first estimate the number of flops we do per iteration.
|
| 368 |
+
# see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
|
| 369 |
+
N = self.get_num_params()
|
| 370 |
+
cfg = self.config
|
| 371 |
+
L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd // cfg.n_head, cfg.block_size
|
| 372 |
+
flops_per_token = 6 * N + 12 * L * H * Q * T
|
| 373 |
+
flops_per_fwdbwd = flops_per_token * T
|
| 374 |
+
flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
|
| 375 |
+
# express our flops throughput as ratio of A100 bfloat16 peak flops
|
| 376 |
+
flops_achieved = flops_per_iter * (1.0 / dt) # per second
|
| 377 |
+
flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
|
| 378 |
+
mfu = flops_achieved / flops_promised
|
| 379 |
+
return mfu
|
| 380 |
+
|
| 381 |
+
@property
|
| 382 |
+
def device(self) -> str:
|
| 383 |
+
# assign model inputs to the right device
|
| 384 |
+
return next(self.lm_head.parameters()).device.type
|
| 385 |
+
|
| 386 |
+
@torch.no_grad()
|
| 387 |
+
def generate(
|
| 388 |
+
self,
|
| 389 |
+
idx: torch.Tensor,
|
| 390 |
+
max_new_tokens: int = 12,
|
| 391 |
+
temperature: float = 0.0,
|
| 392 |
+
topn: int = 100,
|
| 393 |
+
pruning_ratio: float = 4,
|
| 394 |
+
pruning_offset: float = 5,
|
| 395 |
+
log_file: str | None = None,
|
| 396 |
+
on_iteration: Callable = None,
|
| 397 |
+
) -> torch.Tensor:
|
| 398 |
+
|
| 399 |
+
if topn <= 0:
|
| 400 |
+
raise ValueError('topn should be greater than 0')
|
| 401 |
+
|
| 402 |
+
if not 0 < max_new_tokens <= 20:
|
| 403 |
+
raise ValueError('max_new_tokens should be in (0, 20]')
|
| 404 |
+
|
| 405 |
+
run_uuid = uuid.uuid4()
|
| 406 |
+
|
| 407 |
+
idx = idx.to(self.device)
|
| 408 |
+
sequences = idx.unsqueeze(0)
|
| 409 |
+
|
| 410 |
+
probabilities = torch.tensor([1.], device=self.device)
|
| 411 |
+
|
| 412 |
+
finished_sequences = torch.tensor([], device=self.device)
|
| 413 |
+
finished_probs = torch.tensor([], device=self.device)
|
| 414 |
+
|
| 415 |
+
# compute number of sequences to pass to each iteration
|
| 416 |
+
sequences_per_iter = round(pruning_offset + topn / pruning_ratio)
|
| 417 |
+
|
| 418 |
+
for i in range(max_new_tokens):
|
| 419 |
+
if on_iteration is not None:
|
| 420 |
+
on_iteration()
|
| 421 |
+
|
| 422 |
+
# trim the sequences down to block size
|
| 423 |
+
sequences = sequences[:, -self.config.block_size:]
|
| 424 |
+
|
| 425 |
+
# inference the model
|
| 426 |
+
logits, _ = self(sequences)
|
| 427 |
+
logits = logits.squeeze(1)
|
| 428 |
+
|
| 429 |
+
# take N most probable next tokens for each sequence
|
| 430 |
+
output_probs = F.softmax(logits, dim=-1)
|
| 431 |
+
new_sequence_probs = output_probs * probabilities.unsqueeze(1)
|
| 432 |
+
|
| 433 |
+
# remove finished sequences (after end token) and cache their probs
|
| 434 |
+
if i > 0:
|
| 435 |
+
# feature to add: we should not add subdomain in input to the finished sequences
|
| 436 |
+
comma_token_probs = new_sequence_probs[:, self.comma_token]
|
| 437 |
+
end_token_probs = new_sequence_probs[:, self.end_token]
|
| 438 |
+
_finish_probs = end_token_probs + comma_token_probs
|
| 439 |
+
|
| 440 |
+
finished_sequences = torch.cat((finished_sequences, sequences))
|
| 441 |
+
finished_probs = torch.cat((finished_probs, _finish_probs), dim=-1)
|
| 442 |
+
|
| 443 |
+
# remove sequences and tokens with a probability that is too low
|
| 444 |
+
if len(finished_sequences) > topn:
|
| 445 |
+
# torch.kthvalue is not implemented on MPS, so we use topk
|
| 446 |
+
lowest_viable_probability = torch.topk(finished_probs, topn).values[-1]
|
| 447 |
+
viable_sequences = probabilities > lowest_viable_probability
|
| 448 |
+
|
| 449 |
+
if viable_sequences.sum() == 0:
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
# remove sequences with a too low probability
|
| 453 |
+
sequences = sequences[viable_sequences]
|
| 454 |
+
probabilities = probabilities[viable_sequences]
|
| 455 |
+
logits = logits[viable_sequences]
|
| 456 |
+
new_sequence_probs = new_sequence_probs[viable_sequences]
|
| 457 |
+
|
| 458 |
+
# remove tokens that would generate sequences with too low probability
|
| 459 |
+
token_mask = new_sequence_probs < lowest_viable_probability
|
| 460 |
+
if token_mask.sum() == 0:
|
| 461 |
+
break
|
| 462 |
+
|
| 463 |
+
new_sequence_probs[token_mask] = 0
|
| 464 |
+
logits[token_mask] = 0
|
| 465 |
+
|
| 466 |
+
# do not sample the end token or comma token for the next iter
|
| 467 |
+
new_sequence_probs[:, self.end_token] = 0
|
| 468 |
+
new_sequence_probs[:, self.comma_token] = 0
|
| 469 |
+
|
| 470 |
+
# number of sequences to pass to next iteration
|
| 471 |
+
num_nonzero_probs = torch.count_nonzero(new_sequence_probs).item()
|
| 472 |
+
num_seqs_next_iter = min(sequences_per_iter, num_nonzero_probs)
|
| 473 |
+
|
| 474 |
+
if num_seqs_next_iter == 0:
|
| 475 |
+
break
|
| 476 |
+
|
| 477 |
+
if temperature == 0: # select most likely tokens for next iteration
|
| 478 |
+
new_sequence_probs = new_sequence_probs.flatten()
|
| 479 |
+
_, idx_next = torch.topk(new_sequence_probs, num_seqs_next_iter)
|
| 480 |
+
|
| 481 |
+
else: # sample tokens for next iteration
|
| 482 |
+
# recalculate probabilities using temperature
|
| 483 |
+
scaled_logits = logits / (temperature+1e-1)
|
| 484 |
+
probs_with_temp = F.softmax(scaled_logits, dim=-1)
|
| 485 |
+
probs_with_temp = probs_with_temp * probabilities.unsqueeze(1)
|
| 486 |
+
|
| 487 |
+
probs_with_temp[:, self.end_token] = 0
|
| 488 |
+
probs_with_temp[:, self.comma_token] = 0
|
| 489 |
+
|
| 490 |
+
# sample tokens for next iteration
|
| 491 |
+
probs_with_temp = probs_with_temp.flatten()
|
| 492 |
+
probs_with_temp[probs_with_temp < 0] = 0
|
| 493 |
+
idx_next = torch.multinomial(probs_with_temp, num_seqs_next_iter)
|
| 494 |
+
|
| 495 |
+
# add the sampled tokens to the end of each sequence
|
| 496 |
+
sequence_idx = idx_next // self.config.vocab_size
|
| 497 |
+
token_values = idx_next % self.config.vocab_size
|
| 498 |
+
|
| 499 |
+
sequences = sequences[sequence_idx]
|
| 500 |
+
sequences = torch.cat([sequences, token_values.unsqueeze(1)], dim=-1)
|
| 501 |
+
probabilities = new_sequence_probs.flatten()[idx_next]
|
| 502 |
+
|
| 503 |
+
if log_file is not None:
|
| 504 |
+
_, current_best_idx = torch.topk(finished_probs, min(topn, len(finished_probs)))
|
| 505 |
+
current_best = finished_sequences[current_best_idx]
|
| 506 |
+
self.log_generation_data(
|
| 507 |
+
log_file=log_file,
|
| 508 |
+
run_id=run_uuid,
|
| 509 |
+
topn=topn,
|
| 510 |
+
x=idx,
|
| 511 |
+
iteration=i,
|
| 512 |
+
probabilities=probabilities,
|
| 513 |
+
current_preds=current_best,
|
| 514 |
+
finished_probs=finished_probs,
|
| 515 |
+
)
|
| 516 |
+
|
| 517 |
+
# take the highest scoring sequences for the next iteration
|
| 518 |
+
_, final_indices = torch.topk(finished_probs, topn)
|
| 519 |
+
final_sequences = finished_sequences[final_indices]
|
| 520 |
+
|
| 521 |
+
return final_sequences
|
| 522 |
+
|
| 523 |
+
def log_generation_data(
|
| 524 |
+
self,
|
| 525 |
+
log_file: str,
|
| 526 |
+
run_id: uuid.UUID,
|
| 527 |
+
iteration: int,
|
| 528 |
+
topn: int,
|
| 529 |
+
x: torch.Tensor,
|
| 530 |
+
probabilities: torch.Tensor,
|
| 531 |
+
current_preds: torch.Tensor,
|
| 532 |
+
finished_probs: torch.Tensor,
|
| 533 |
+
):
|
| 534 |
+
# use this in every iteration of the generate method to collect data for analysis
|
| 535 |
+
|
| 536 |
+
# # turn into list of ints
|
| 537 |
+
# current_preds = current_preds.int().tolist()
|
| 538 |
+
#
|
| 539 |
+
# # turn into list of strings
|
| 540 |
+
# current_preds = [
|
| 541 |
+
# self.tokenizer.decode(pred)
|
| 542 |
+
# .replace(" ", "")
|
| 543 |
+
# .rsplit("[DELIM]", 1)[1]
|
| 544 |
+
# for pred in current_preds
|
| 545 |
+
# ]
|
| 546 |
+
#
|
| 547 |
+
# # turn into comma separated strings
|
| 548 |
+
# current_preds = ','.join(current_preds)
|
| 549 |
+
#
|
| 550 |
+
# x = x.int().tolist()
|
| 551 |
+
# x = self.tokenizer.decode(x).replace('[PAD]', '').replace(' ', '')
|
| 552 |
+
|
| 553 |
+
if len(finished_probs) > topn:
|
| 554 |
+
topnth_finished_prob = torch.topk(finished_probs, topn).values[-1].item()
|
| 555 |
+
else:
|
| 556 |
+
topnth_finished_prob = 0
|
| 557 |
+
|
| 558 |
+
largest_prob = probabilities.max().item()
|
| 559 |
+
|
| 560 |
+
new_row = [{
|
| 561 |
+
'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'),
|
| 562 |
+
'run_id': str(run_id),
|
| 563 |
+
'topn': topn,
|
| 564 |
+
'iteration': iteration,
|
| 565 |
+
'largest_prob': largest_prob,
|
| 566 |
+
'topnth_finished_prob': topnth_finished_prob,
|
| 567 |
+
# 'x': x,
|
| 568 |
+
# 'probabilities': probabilities.sum().item(),
|
| 569 |
+
# 'finished_probabilities': finished_probs.sum().item(),
|
| 570 |
+
# 'finished_sequences': current_preds,
|
| 571 |
+
}]
|
| 572 |
+
df_new_row = pd.DataFrame(new_row)
|
| 573 |
+
|
| 574 |
+
if os.path.exists(log_file):
|
| 575 |
+
df = pd.read_csv(log_file, index_col=0)
|
| 576 |
+
df = pd.concat([df, df_new_row], ignore_index=True)
|
| 577 |
+
else:
|
| 578 |
+
df = df_new_row
|
| 579 |
+
|
| 580 |
+
df.to_csv(log_file)
|
| 581 |
+
|
| 582 |
+
def save_checkpoint(
|
| 583 |
+
self, path, optimizer=None, iter_num=None, best_val_loss=None, config=None
|
| 584 |
+
):
|
| 585 |
+
optimizer = {} if not optimizer else optimizer.state_dict()
|
| 586 |
+
iter_num = {} if not iter_num else {"iter_num": iter_num}
|
| 587 |
+
best_val_loss = {} if not best_val_loss else {"best_val_loss": best_val_loss}
|
| 588 |
+
config = {} if not config else {"config": config}
|
| 589 |
+
checkpoint = {
|
| 590 |
+
"model": self.state_dict(),
|
| 591 |
+
"model_args": dict(self.config),
|
| 592 |
+
**optimizer,
|
| 593 |
+
**iter_num,
|
| 594 |
+
**best_val_loss,
|
| 595 |
+
**config,
|
| 596 |
+
}
|
| 597 |
+
torch.save(checkpoint, path)
|
| 598 |
+
|
| 599 |
+
@staticmethod
|
| 600 |
+
def from_checkpoint(
|
| 601 |
+
path: str,
|
| 602 |
+
return_train_params: bool = False,
|
| 603 |
+
device: str = 'cpu',
|
| 604 |
+
tokenizer_path: str | None = None,
|
| 605 |
+
):
|
| 606 |
+
checkpoint = torch.load(path, map_location=device, weights_only=True)
|
| 607 |
+
|
| 608 |
+
config = GPTConfig(**checkpoint["model_args"])
|
| 609 |
+
if tokenizer_path:
|
| 610 |
+
config.tokenizer_file = tokenizer_path
|
| 611 |
+
model = GPT(config)
|
| 612 |
+
state_dict = checkpoint["model"]
|
| 613 |
+
|
| 614 |
+
# fix the keys of the state dictionary :(
|
| 615 |
+
# honestly no idea how checkpoints sometimes get this prefix, have to debug more
|
| 616 |
+
unwanted_prefix = "_orig_mod."
|
| 617 |
+
for k, v in list(state_dict.items()):
|
| 618 |
+
if k.startswith(unwanted_prefix):
|
| 619 |
+
state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
|
| 620 |
+
model.load_state_dict(state_dict)
|
| 621 |
+
model.to(device)
|
| 622 |
+
|
| 623 |
+
if not return_train_params:
|
| 624 |
+
return model
|
| 625 |
+
|
| 626 |
+
iter_num = checkpoint["iter_num"]
|
| 627 |
+
best_val_loss = checkpoint["best_val_loss"]
|
| 628 |
+
optim_state = checkpoint["optimizer"]
|
| 629 |
+
|
| 630 |
+
assert isinstance(iter_num, int)
|
| 631 |
+
assert isinstance(best_val_loss, torch.Tensor)
|
| 632 |
+
assert isinstance(optim_state, dict)
|
| 633 |
+
|
| 634 |
+
return model, iter_num, best_val_loss, optim_state
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|