Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model.py 16 KB

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

Press p or to see the previous file or, n or to see the next file

Comments

Loading...