LH-Tech-AI commited on
Commit
024ea70
·
verified ·
1 Parent(s): 76f0c9b

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +333 -0
model.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Credit: Andrej Karpathy - nanoGPT
3
+ Full definition of a GPT Language Model, all of it in this single file.
4
+ References:
5
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
6
+ https://github.com/openai/gpt-2/blob/master/src/model.py
7
+ 2) huggingface/transformers PyTorch implementation:
8
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
9
+ """
10
+
11
+ import math
12
+ import inspect
13
+ from dataclasses import dataclass
14
+
15
+ import torch
16
+ import torch.nn as nn
17
+ from torch.nn import functional as F
18
+
19
+ class LayerNorm(nn.Module):
20
+ """ LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False """
21
+
22
+ def __init__(self, ndim, bias):
23
+ super().__init__()
24
+ self.weight = nn.Parameter(torch.ones(ndim))
25
+ self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
26
+
27
+ def forward(self, input):
28
+ return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)
29
+
30
+ class CausalSelfAttention(nn.Module):
31
+
32
+ def __init__(self, config):
33
+ super().__init__()
34
+ assert config.n_embd % config.n_head == 0
35
+ # key, query, value projections for all heads, but in a batch
36
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
37
+ # output projection
38
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
39
+ # regularization
40
+ self.attn_dropout = nn.Dropout(config.dropout)
41
+ self.resid_dropout = nn.Dropout(config.dropout)
42
+ self.n_head = config.n_head
43
+ self.n_embd = config.n_embd
44
+ self.dropout = config.dropout
45
+ # flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0
46
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
47
+ if not self.flash:
48
+ print("WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0")
49
+ # causal mask to ensure that attention is only applied to the left in the input sequence
50
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
51
+ .view(1, 1, config.block_size, config.block_size))
52
+
53
+ def forward(self, x):
54
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
55
+
56
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
57
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
58
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
59
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
60
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
61
+
62
+ # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)
63
+ if self.flash:
64
+ # efficient attention using Flash Attention CUDA kernels
65
+ y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0, is_causal=True)
66
+ else:
67
+ # manual implementation of attention
68
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
69
+ att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
70
+ att = F.softmax(att, dim=-1)
71
+ att = self.attn_dropout(att)
72
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
73
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
74
+
75
+ # output projection
76
+ y = self.resid_dropout(self.c_proj(y))
77
+ return y
78
+
79
+ class MLP(nn.Module):
80
+
81
+ def __init__(self, config):
82
+ super().__init__()
83
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
84
+ self.gelu = nn.GELU()
85
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
86
+ self.dropout = nn.Dropout(config.dropout)
87
+
88
+ def forward(self, x):
89
+ x = self.c_fc(x)
90
+ x = self.gelu(x)
91
+ x = self.c_proj(x)
92
+ x = self.dropout(x)
93
+ return x
94
+
95
+ class Block(nn.Module):
96
+
97
+ def __init__(self, config):
98
+ super().__init__()
99
+ self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)
100
+ self.attn = CausalSelfAttention(config)
101
+ self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)
102
+ self.mlp = MLP(config)
103
+
104
+ def forward(self, x):
105
+ x = x + self.attn(self.ln_1(x))
106
+ x = x + self.mlp(self.ln_2(x))
107
+ return x
108
+
109
+ @dataclass
110
+ class GPTConfig:
111
+ block_size: int = 1024
112
+ vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
113
+ n_layer: int = 12
114
+ n_head: int = 12
115
+ n_embd: int = 768
116
+ dropout: float = 0.0
117
+ bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
118
+
119
+ class GPT(nn.Module):
120
+
121
+ def __init__(self, config):
122
+ super().__init__()
123
+ assert config.vocab_size is not None
124
+ assert config.block_size is not None
125
+ self.config = config
126
+
127
+ self.transformer = nn.ModuleDict(dict(
128
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
129
+ wpe = nn.Embedding(config.block_size, config.n_embd),
130
+ drop = nn.Dropout(config.dropout),
131
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
132
+ ln_f = LayerNorm(config.n_embd, bias=config.bias),
133
+ ))
134
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
135
+ # with weight tying when using torch.compile() some warnings get generated:
136
+ # "UserWarning: functional_call was passed multiple values for tied weights.
137
+ # This behavior is deprecated and will be an error in future versions"
138
+ # not 100% sure what this is, so far seems to be harmless. TODO investigate
139
+ self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
140
+
141
+ # init all weights
142
+ self.apply(self._init_weights)
143
+ # apply special scaled init to the residual projections, per GPT-2 paper
144
+ for pn, p in self.named_parameters():
145
+ if pn.endswith('c_proj.weight'):
146
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
147
+
148
+ # report number of parameters
149
+ print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
150
+
151
+ def get_num_params(self, non_embedding=True):
152
+ """
153
+ Return the number of parameters in the model.
154
+ For non-embedding count (default), the position embeddings get subtracted.
155
+ The token embeddings would too, except due to the parameter sharing these
156
+ params are actually used as weights in the final layer, so we include them.
157
+ """
158
+ n_params = sum(p.numel() for p in self.parameters())
159
+ if non_embedding:
160
+ n_params -= self.transformer.wpe.weight.numel()
161
+ return n_params
162
+
163
+ def _init_weights(self, module):
164
+ if isinstance(module, nn.Linear):
165
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
166
+ if module.bias is not None:
167
+ torch.nn.init.zeros_(module.bias)
168
+ elif isinstance(module, nn.Embedding):
169
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
170
+
171
+ def forward(self, idx, targets=None):
172
+ device = idx.device
173
+ b, t = idx.size()
174
+ assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
175
+ pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
176
+
177
+ # forward the GPT model itself
178
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
179
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
180
+ x = self.transformer.drop(tok_emb + pos_emb)
181
+ for block in self.transformer.h:
182
+ x = block(x)
183
+ x = self.transformer.ln_f(x)
184
+
185
+ if targets is not None:
186
+ # if we are given some desired targets also calculate the loss
187
+ logits = self.lm_head(x)
188
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
189
+ else:
190
+ # inference-time mini-optimization: only forward the lm_head on the very last position
191
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
192
+ loss = None
193
+
194
+ return logits, loss
195
+
196
+ def crop_block_size(self, block_size):
197
+ # model surgery to decrease the block size if necessary
198
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
199
+ # but want to use a smaller block size for some smaller, simpler model
200
+ assert block_size <= self.config.block_size
201
+ self.config.block_size = block_size
202
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
203
+ for block in self.transformer.h:
204
+ if hasattr(block.attn, 'bias'):
205
+ block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
206
+
207
+ @classmethod
208
+ def from_pretrained(cls, model_type, override_args=None):
209
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
210
+ override_args = override_args or {} # default to empty dict
211
+ # only dropout can be overridden see more notes below
212
+ assert all(k == 'dropout' for k in override_args)
213
+ from transformers import GPT2LMHeadModel
214
+ print("loading weights from pretrained gpt: %s" % model_type)
215
+
216
+ # n_layer, n_head and n_embd are determined from model_type
217
+ config_args = {
218
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
219
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
220
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
221
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
222
+ }[model_type]
223
+ print("forcing vocab_size=50257, block_size=1024, bias=True")
224
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
225
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
226
+ config_args['bias'] = True # always True for GPT model checkpoints
227
+ # we can override the dropout rate, if desired
228
+ if 'dropout' in override_args:
229
+ print(f"overriding dropout rate to {override_args['dropout']}")
230
+ config_args['dropout'] = override_args['dropout']
231
+ # create a from-scratch initialized minGPT model
232
+ config = GPTConfig(**config_args)
233
+ model = GPT(config)
234
+ sd = model.state_dict()
235
+ sd_keys = sd.keys()
236
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
237
+
238
+ # init a huggingface/transformers model
239
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
240
+ sd_hf = model_hf.state_dict()
241
+
242
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
243
+ sd_keys_hf = sd_hf.keys()
244
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
245
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
246
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
247
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
248
+ # this means that we have to transpose these weights when we import them
249
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
250
+ for k in sd_keys_hf:
251
+ if any(k.endswith(w) for w in transposed):
252
+ # special treatment for the Conv1D weights we need to transpose
253
+ assert sd_hf[k].shape[::-1] == sd[k].shape
254
+ with torch.no_grad():
255
+ sd[k].copy_(sd_hf[k].t())
256
+ else:
257
+ # vanilla copy over the other parameters
258
+ assert sd_hf[k].shape == sd[k].shape
259
+ with torch.no_grad():
260
+ sd[k].copy_(sd_hf[k])
261
+
262
+ return model
263
+
264
+ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
265
+ # start with all of the candidate parameters
266
+ param_dict = {pn: p for pn, p in self.named_parameters()}
267
+ # filter out those that do not require grad
268
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
269
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
270
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
271
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
272
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
273
+ optim_groups = [
274
+ {'params': decay_params, 'weight_decay': weight_decay},
275
+ {'params': nodecay_params, 'weight_decay': 0.0}
276
+ ]
277
+ num_decay_params = sum(p.numel() for p in decay_params)
278
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
279
+ print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
280
+ print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
281
+ # Create AdamW optimizer and use the fused version if it is available
282
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
283
+ use_fused = fused_available and device_type == 'cuda'
284
+ extra_args = dict(fused=True) if use_fused else dict()
285
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
286
+ print(f"using fused AdamW: {use_fused}")
287
+
288
+ return optimizer
289
+
290
+ def estimate_mfu(self, fwdbwd_per_iter, dt):
291
+ """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
292
+ # first estimate the number of flops we do per iteration.
293
+ # see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
294
+ N = self.get_num_params()
295
+ cfg = self.config
296
+ L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
297
+ flops_per_token = 6*N + 12*L*H*Q*T
298
+ flops_per_fwdbwd = flops_per_token * T
299
+ flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
300
+ # express our flops throughput as ratio of A100 bfloat16 peak flops
301
+ flops_achieved = flops_per_iter * (1.0/dt) # per second
302
+ flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
303
+ mfu = flops_achieved / flops_promised
304
+ return mfu
305
+
306
+ @torch.no_grad()
307
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
308
+ """
309
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
310
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
311
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
312
+ """
313
+ for _ in range(max_new_tokens):
314
+ # if the sequence context is growing too long we must crop it at block_size
315
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
316
+ # forward the model to get the logits for the index in the sequence
317
+ logits, _ = self(idx_cond)
318
+ # pluck the logits at the final step and scale by desired temperature
319
+ logits = logits[:, -1, :] / temperature
320
+ # optionally crop the logits to only the top k options
321
+ if top_k is not None:
322
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
323
+ logits[logits < v[:, [-1]]] = -float('Inf')
324
+ # apply softmax to convert logits to (normalized) probabilities
325
+ probs = F.softmax(logits, dim=-1)
326
+ # sample from the distribution
327
+ idx_next = torch.multinomial(probs, num_samples=1)
328
+ # New: Early stop at EOS
329
+ if idx_next.item() == 50256:
330
+ break
331
+ idx = torch.cat((idx, idx_next), dim=1)
332
+
333
+ return idx