sosier commited on
Commit
bcfd3d7
1 Parent(s): 5bdba26

Upload NanoGPT

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