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