wang-sy commited on
Commit
da763fd
·
1 Parent(s): b464613

Upload model.py

Browse files
Files changed (1) hide show
  1. model.py +385 -0
model.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Full definition of a GPT Language Model, all of it in this single file.
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
+ import math
11
+ import inspect
12
+ from dataclasses import dataclass
13
+
14
+ import torch
15
+ import torch.nn as nn
16
+ from torch.nn import functional as F
17
+
18
+ from transformers import PreTrainedModel, PretrainedConfig
19
+
20
+ # @torch.jit.script # good to enable when not using torch.compile, disable when using (our default)
21
+ def new_gelu(x):
22
+ """
23
+ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
24
+ Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
25
+ """
26
+ return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
27
+
28
+ class LayerNorm(nn.Module):
29
+ """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
30
+
31
+ def __init__(self, ndim, bias):
32
+ super().__init__()
33
+ self.weight = nn.Parameter(torch.ones(ndim))
34
+ self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
35
+
36
+ def forward(self, input):
37
+ return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
38
+
39
+ class CausalSelfAttention(nn.Module):
40
+
41
+ def __init__(self, config):
42
+ super().__init__()
43
+ assert config.n_embd % config.n_head == 0
44
+ # key, query, value projections for all heads, but in a batch
45
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
46
+ # output projection
47
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
48
+ # regularization
49
+ self.attn_dropout = nn.Dropout(config.dropout)
50
+ self.resid_dropout = nn.Dropout(config.dropout)
51
+ self.n_head = config.n_head
52
+ self.n_embd = config.n_embd
53
+ self.dropout = config.dropout
54
+ # flash attention make GPU go brrrrr but support is only in PyTorch nightly and still a bit scary
55
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention') and self.dropout == 0.0
56
+ if not self.flash:
57
+ print("WARNING: using slow attention. Flash Attention atm needs PyTorch nightly and dropout=0.0")
58
+ # causal mask to ensure that attention is only applied to the left in the input sequence
59
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
60
+ .view(1, 1, config.block_size, config.block_size))
61
+
62
+ def forward(self, x):
63
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
64
+
65
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
66
+ q, k ,v = self.c_attn(x).split(self.n_embd, dim=2)
67
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
68
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
69
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
70
+
71
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
72
+ if self.flash:
73
+ # efficient attention using Flash Attention CUDA kernels
74
+ y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout, is_causal=True)
75
+ else:
76
+ # manual implementation of attention
77
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
78
+ att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
79
+ att = F.softmax(att, dim=-1)
80
+ att = self.attn_dropout(att)
81
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
82
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
83
+
84
+ # output projection
85
+ y = self.resid_dropout(self.c_proj(y))
86
+ return y
87
+
88
+ class MLP(nn.Module):
89
+
90
+ def __init__(self, config):
91
+ super().__init__()
92
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
93
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
94
+ self.dropout = nn.Dropout(config.dropout)
95
+
96
+ def forward(self, x):
97
+ x = self.c_fc(x)
98
+ x = new_gelu(x)
99
+ x = self.c_proj(x)
100
+ x = self.dropout(x)
101
+ return x
102
+
103
+ class Block(nn.Module):
104
+
105
+ def __init__(self, config):
106
+ super().__init__()
107
+ self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
108
+ self.attn = CausalSelfAttention(config)
109
+ self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
110
+ self.mlp = MLP(config)
111
+
112
+ def forward(self, x):
113
+ x = x + self.attn(self.ln_1(x))
114
+ x = x + self.mlp(self.ln_2(x))
115
+ return x
116
+
117
+ @dataclass
118
+ # class GPTConfig:
119
+ class GPTConfig(PretrainedConfig):
120
+ def __init__(
121
+ self,
122
+ block_size: int = 1024,
123
+ vocab_size: int = 50304, # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
124
+ n_layer: int = 12,
125
+ n_head: int = 12,
126
+ n_embd: int = 768,
127
+ dropout: float = 0.0,
128
+ bias: bool = True, # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
129
+ **kwargs
130
+ ):
131
+
132
+ self.block_size = block_size
133
+ self.vocab_size = vocab_size # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
134
+ self.n_layer = n_layer
135
+ self.n_head = n_head
136
+ self.n_embd = n_embd
137
+ self.dropout = dropout
138
+ self.bias = bias # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
139
+ super().__init__(**kwargs)
140
+
141
+ # class GPT(nn.Module):
142
+ class GPT(PreTrainedModel):
143
+
144
+ def __init__(self, config):
145
+ super().__init__(config)
146
+ assert config.vocab_size is not None
147
+ assert config.block_size is not None
148
+ self.config = config
149
+
150
+ self.transformer = nn.ModuleDict(dict(
151
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
152
+ wpe = nn.Embedding(config.block_size, config.n_embd),
153
+ drop = nn.Dropout(config.dropout),
154
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
155
+ ln_f = LayerNorm(config.n_embd, bias=config.bias),
156
+ ))
157
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
158
+ # with weight tying when using torch.compile() some warnings get generated:
159
+ # "UserWarning: functional_call was passed multiple values for tied weights.
160
+ # This behavior is deprecated and will be an error in future versions"
161
+ # not 100% sure what this is, so far seems to be harmless. TODO investigate
162
+ self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
163
+
164
+ # init all weights
165
+ self.apply(self._init_weights)
166
+ # apply special scaled init to the residual projections, per GPT-2 paper
167
+ for pn, p in self.named_parameters():
168
+ if pn.endswith('c_proj.weight'):
169
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
170
+
171
+ # report number of parameters
172
+ print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
173
+
174
+ def get_num_params(self, non_embedding=True):
175
+ """
176
+ Return the number of parameters in the model.
177
+ For non-embedding count (default), the position embeddings get subtracted.
178
+ The token embeddings would too, except due to the parameter sharing these
179
+ params are actually used as weights in the final layer, so we include them.
180
+ """
181
+ n_params = sum(p.numel() for p in self.parameters())
182
+ if non_embedding:
183
+ n_params -= self.transformer.wpe.weight.numel()
184
+ return n_params
185
+
186
+ def _init_weights(self, module):
187
+ if isinstance(module, nn.Linear):
188
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
189
+ if module.bias is not None:
190
+ torch.nn.init.zeros_(module.bias)
191
+ elif isinstance(module, nn.Embedding):
192
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
193
+
194
+ def forward(self, idx, targets=None):
195
+ device = idx.device
196
+ b, t = idx.size()
197
+ assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
198
+ pos = torch.arange(0, t, dtype=torch.long, device=device).unsqueeze(0) # shape (1, t)
199
+
200
+ # forward the GPT model itself
201
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
202
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (1, t, n_embd)
203
+ x = self.transformer.drop(tok_emb + pos_emb)
204
+ for block in self.transformer.h:
205
+ x = block(x)
206
+ x = self.transformer.ln_f(x)
207
+
208
+ if targets is not None:
209
+ # if we are given some desired targets also calculate the loss
210
+ logits = self.lm_head(x)
211
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
212
+ else:
213
+ # inference-time mini-optimization: only forward the lm_head on the very last position
214
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
215
+ loss = None
216
+
217
+ return logits, loss
218
+
219
+ def crop_block_size(self, block_size):
220
+ # model surgery to decrease the block size if necessary
221
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
222
+ # but want to use a smaller block size for some smaller, simpler model
223
+ assert block_size <= self.config.block_size
224
+ self.config.block_size = block_size
225
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
226
+ for block in self.transformer.h:
227
+ block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
228
+
229
+ @classmethod
230
+ def from_pretrained(cls, model_type, override_args=None):
231
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
232
+ override_args = override_args or {} # default to empty dict
233
+ # only dropout can be overridden see more notes below
234
+ assert all(k == 'dropout' for k in override_args)
235
+ from transformers import GPT2LMHeadModel
236
+ print("loading weights from pretrained gpt: %s" % model_type)
237
+
238
+ # n_layer, n_head and n_embd are determined from model_type
239
+ config_args = {
240
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
241
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
242
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
243
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
244
+ }[model_type]
245
+ print("forcing vocab_size=50257, block_size=1024, bias=True")
246
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
247
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
248
+ config_args['bias'] = True # always True for GPT model checkpoints
249
+ # we can override the dropout rate, if desired
250
+ if 'dropout' in override_args:
251
+ print(f"overriding dropout rate to {override_args['dropout']}")
252
+ config_args['dropout'] = override_args['dropout']
253
+ # create a from-scratch initialized minGPT model
254
+ config = GPTConfig(**config_args)
255
+ model = GPT(config)
256
+ sd = model.state_dict()
257
+ sd_keys = sd.keys()
258
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
259
+
260
+ # init a huggingface/transformers model
261
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
262
+ sd_hf = model_hf.state_dict()
263
+
264
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
265
+ sd_keys_hf = sd_hf.keys()
266
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
267
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
268
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
269
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
270
+ # this means that we have to transpose these weights when we import them
271
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
272
+ for k in sd_keys_hf:
273
+ if any(k.endswith(w) for w in transposed):
274
+ # special treatment for the Conv1D weights we need to transpose
275
+ assert sd_hf[k].shape[::-1] == sd[k].shape
276
+ with torch.no_grad():
277
+ sd[k].copy_(sd_hf[k].t())
278
+ else:
279
+ # vanilla copy over the other parameters
280
+ assert sd_hf[k].shape == sd[k].shape
281
+ with torch.no_grad():
282
+ sd[k].copy_(sd_hf[k])
283
+
284
+ return model
285
+
286
+ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
287
+ """
288
+ This long function is unfortunately doing something very simple and is being very defensive:
289
+ We are separating out all parameters of the model into two buckets: those that will experience
290
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
291
+ We are then returning the PyTorch optimizer object.
292
+ """
293
+
294
+ # separate out all parameters to those that will and won't experience regularizing weight decay
295
+ decay = set()
296
+ no_decay = set()
297
+ whitelist_weight_modules = (torch.nn.Linear, )
298
+ blacklist_weight_modules = (torch.nn.LayerNorm, LayerNorm, torch.nn.Embedding)
299
+ for mn, m in self.named_modules():
300
+ for pn, p in m.named_parameters():
301
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
302
+ # random note: because named_modules and named_parameters are recursive
303
+ # we will see the same tensors p many many times. but doing it this way
304
+ # allows us to know which parent module any tensor p belongs to...
305
+ if pn.endswith('bias'):
306
+ # all biases will not be decayed
307
+ no_decay.add(fpn)
308
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
309
+ # weights of whitelist modules will be weight decayed
310
+ decay.add(fpn)
311
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
312
+ # weights of blacklist modules will NOT be weight decayed
313
+ no_decay.add(fpn)
314
+
315
+ # subtle: 'transformer.wte.weight' and 'lm_head.weight' are tied, so they
316
+ # will appear in the no_decay and decay sets respectively after the above.
317
+ # In addition, because named_parameters() doesn't return duplicates, it
318
+ # will only return the first occurence, key'd by 'transformer.wte.weight', below.
319
+ # so let's manually remove 'lm_head.weight' from decay set. This will include
320
+ # this tensor into optimization via transformer.wte.weight only, and not decayed.
321
+ decay.remove('lm_head.weight')
322
+
323
+ # validate that we considered every parameter
324
+ param_dict = {pn: p for pn, p in self.named_parameters()}
325
+ inter_params = decay & no_decay
326
+ union_params = decay | no_decay
327
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
328
+ assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
329
+ % (str(param_dict.keys() - union_params), )
330
+
331
+ # create the pytorch optimizer object
332
+ optim_groups = [
333
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": weight_decay},
334
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
335
+ ]
336
+ # new PyTorch nightly has a new 'fused' option for AdamW that is much faster
337
+ use_fused = (device_type == 'cuda') and ('fused' in inspect.signature(torch.optim.AdamW).parameters)
338
+ print(f"using fused AdamW: {use_fused}")
339
+ extra_args = dict(fused=True) if use_fused else dict()
340
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
341
+
342
+ return optimizer
343
+
344
+ def estimate_mfu(self, fwdbwd_per_iter, dt):
345
+ """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
346
+ # first estimate the number of flops we do per iteration.
347
+ # see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
348
+ N = self.get_num_params()
349
+ cfg = self.config
350
+ L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
351
+ flops_per_token = 6*N + 12*L*H*Q*T
352
+ flops_per_fwdbwd = flops_per_token * T
353
+ flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
354
+ # express our flops throughput as ratio of A100 bfloat16 peak flops
355
+ flops_achieved = flops_per_iter * (1.0/dt) # per second
356
+ flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
357
+ mfu = flops_achieved / flops_promised
358
+ return mfu
359
+
360
+ @torch.no_grad()
361
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
362
+ """
363
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
364
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
365
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
366
+ """
367
+ for _ in range(max_new_tokens):
368
+ # if the sequence context is growing too long we must crop it at block_size
369
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
370
+ # forward the model to get the logits for the index in the sequence
371
+ logits, _ = self(idx_cond)
372
+ # pluck the logits at the final step and scale by desired temperature
373
+ logits = logits[:, -1, :] / temperature
374
+ # optionally crop the logits to only the top k options
375
+ if top_k is not None:
376
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
377
+ logits[logits < v[:, [-1]]] = -float('Inf')
378
+ # apply softmax to convert logits to (normalized) probabilities
379
+ probs = F.softmax(logits, dim=-1)
380
+ # sample from the distribution
381
+ idx_next = torch.multinomial(probs, num_samples=1)
382
+ # append sampled index to the running sequence and continue
383
+ idx = torch.cat((idx, idx_next), dim=1)
384
+
385
+ return idx