LH-Tech-AI commited on
Commit
94fe597
·
verified ·
1 Parent(s): 1f6dd77

Create use.py

Browse files
Files changed (1) hide show
  1. use.py +383 -0
use.py ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tiktoken
2
+ import os
3
+ """
4
+ Full definition of a GPT Language Model, all of it in this single file.
5
+ References:
6
+ 1) the official GPT-2 TensorFlow implementation released by OpenAI:
7
+ https://github.com/openai/gpt-2/blob/master/src/model.py
8
+ 2) huggingface/transformers PyTorch implementation:
9
+ https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py
10
+ """
11
+
12
+ import math
13
+ import inspect
14
+ from dataclasses import dataclass
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ from torch.nn import functional as F
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
+ @dataclass
111
+ class GPTConfig:
112
+ block_size: int = 1024
113
+ vocab_size: int = 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency
114
+ n_layer: int = 12
115
+ n_head: int = 12
116
+ n_embd: int = 768
117
+ dropout: float = 0.0
118
+ bias: bool = True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster
119
+
120
+ class GPT(nn.Module):
121
+
122
+ def __init__(self, config):
123
+ super().__init__()
124
+ assert config.vocab_size is not None
125
+ assert config.block_size is not None
126
+ self.config = config
127
+
128
+ self.transformer = nn.ModuleDict(dict(
129
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
130
+ wpe = nn.Embedding(config.block_size, config.n_embd),
131
+ drop = nn.Dropout(config.dropout),
132
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
133
+ ln_f = LayerNorm(config.n_embd, bias=config.bias),
134
+ ))
135
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
136
+ # with weight tying when using torch.compile() some warnings get generated:
137
+ # "UserWarning: functional_call was passed multiple values for tied weights.
138
+ # This behavior is deprecated and will be an error in future versions"
139
+ # not 100% sure what this is, so far seems to be harmless. TODO investigate
140
+ self.transformer.wte.weight = self.lm_head.weight # https://paperswithcode.com/method/weight-tying
141
+
142
+ # init all weights
143
+ self.apply(self._init_weights)
144
+ # apply special scaled init to the residual projections, per GPT-2 paper
145
+ for pn, p in self.named_parameters():
146
+ if pn.endswith('c_proj.weight'):
147
+ torch.nn.init.normal_(p, mean=0.0, std=0.02/math.sqrt(2 * config.n_layer))
148
+
149
+ # report number of parameters
150
+ print("number of parameters: %.2fM" % (self.get_num_params()/1e6,))
151
+
152
+ def get_num_params(self, non_embedding=True):
153
+ """
154
+ Return the number of parameters in the model.
155
+ For non-embedding count (default), the position embeddings get subtracted.
156
+ The token embeddings would too, except due to the parameter sharing these
157
+ params are actually used as weights in the final layer, so we include them.
158
+ """
159
+ n_params = sum(p.numel() for p in self.parameters())
160
+ if non_embedding:
161
+ n_params -= self.transformer.wpe.weight.numel()
162
+ return n_params
163
+
164
+ def _init_weights(self, module):
165
+ if isinstance(module, nn.Linear):
166
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
167
+ if module.bias is not None:
168
+ torch.nn.init.zeros_(module.bias)
169
+ elif isinstance(module, nn.Embedding):
170
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
171
+
172
+ def forward(self, idx, targets=None):
173
+ device = idx.device
174
+ b, t = idx.size()
175
+ assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
176
+ pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)
177
+
178
+ # forward the GPT model itself
179
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
180
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)
181
+ x = self.transformer.drop(tok_emb + pos_emb)
182
+ for block in self.transformer.h:
183
+ x = block(x)
184
+ x = self.transformer.ln_f(x)
185
+
186
+ if targets is not None:
187
+ # if we are given some desired targets also calculate the loss
188
+ logits = self.lm_head(x)
189
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
190
+ else:
191
+ # inference-time mini-optimization: only forward the lm_head on the very last position
192
+ logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
193
+ loss = None
194
+
195
+ return logits, loss
196
+
197
+ def crop_block_size(self, block_size):
198
+ # model surgery to decrease the block size if necessary
199
+ # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)
200
+ # but want to use a smaller block size for some smaller, simpler model
201
+ assert block_size <= self.config.block_size
202
+ self.config.block_size = block_size
203
+ self.transformer.wpe.weight = nn.Parameter(self.transformer.wpe.weight[:block_size])
204
+ for block in self.transformer.h:
205
+ if hasattr(block.attn, 'bias'):
206
+ block.attn.bias = block.attn.bias[:,:,:block_size,:block_size]
207
+
208
+ @classmethod
209
+ def from_pretrained(cls, model_type, override_args=None):
210
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
211
+ override_args = override_args or {} # default to empty dict
212
+ # only dropout can be overridden see more notes below
213
+ assert all(k == 'dropout' for k in override_args)
214
+ from transformers import GPT2LMHeadModel
215
+ print("loading weights from pretrained gpt: %s" % model_type)
216
+
217
+ # n_layer, n_head and n_embd are determined from model_type
218
+ config_args = {
219
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
220
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
221
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
222
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
223
+ }[model_type]
224
+ print("forcing vocab_size=50257, block_size=1024, bias=True")
225
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
226
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
227
+ config_args['bias'] = True # always True for GPT model checkpoints
228
+ # we can override the dropout rate, if desired
229
+ if 'dropout' in override_args:
230
+ print(f"overriding dropout rate to {override_args['dropout']}")
231
+ config_args['dropout'] = override_args['dropout']
232
+ # create a from-scratch initialized minGPT model
233
+ config = GPTConfig(**config_args)
234
+ model = GPT(config)
235
+ sd = model.state_dict()
236
+ sd_keys = sd.keys()
237
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
238
+
239
+ # init a huggingface/transformers model
240
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
241
+ sd_hf = model_hf.state_dict()
242
+
243
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
244
+ sd_keys_hf = sd_hf.keys()
245
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
246
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
247
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
248
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
249
+ # this means that we have to transpose these weights when we import them
250
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
251
+ for k in sd_keys_hf:
252
+ if any(k.endswith(w) for w in transposed):
253
+ # special treatment for the Conv1D weights we need to transpose
254
+ assert sd_hf[k].shape[::-1] == sd[k].shape
255
+ with torch.no_grad():
256
+ sd[k].copy_(sd_hf[k].t())
257
+ else:
258
+ # vanilla copy over the other parameters
259
+ assert sd_hf[k].shape == sd[k].shape
260
+ with torch.no_grad():
261
+ sd[k].copy_(sd_hf[k])
262
+
263
+ return model
264
+
265
+ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
266
+ # start with all of the candidate parameters
267
+ param_dict = {pn: p for pn, p in self.named_parameters()}
268
+ # filter out those that do not require grad
269
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
270
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
271
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
272
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
273
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
274
+ optim_groups = [
275
+ {'params': decay_params, 'weight_decay': weight_decay},
276
+ {'params': nodecay_params, 'weight_decay': 0.0}
277
+ ]
278
+ num_decay_params = sum(p.numel() for p in decay_params)
279
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
280
+ print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
281
+ print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
282
+ # Create AdamW optimizer and use the fused version if it is available
283
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
284
+ use_fused = fused_available and device_type == 'cuda'
285
+ extra_args = dict(fused=True) if use_fused else dict()
286
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
287
+ print(f"using fused AdamW: {use_fused}")
288
+
289
+ return optimizer
290
+
291
+ def estimate_mfu(self, fwdbwd_per_iter, dt):
292
+ """ estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS """
293
+ # first estimate the number of flops we do per iteration.
294
+ # see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311
295
+ N = self.get_num_params()
296
+ cfg = self.config
297
+ L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd//cfg.n_head, cfg.block_size
298
+ flops_per_token = 6*N + 12*L*H*Q*T
299
+ flops_per_fwdbwd = flops_per_token * T
300
+ flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter
301
+ # express our flops throughput as ratio of A100 bfloat16 peak flops
302
+ flops_achieved = flops_per_iter * (1.0/dt) # per second
303
+ flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS
304
+ mfu = flops_achieved / flops_promised
305
+ return mfu
306
+
307
+ @torch.no_grad()
308
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
309
+ """
310
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
311
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
312
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
313
+ """
314
+ for _ in range(max_new_tokens):
315
+ # if the sequence context is growing too long we must crop it at block_size
316
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
317
+ # forward the model to get the logits for the index in the sequence
318
+ logits, _ = self(idx_cond)
319
+ # pluck the logits at the final step and scale by desired temperature
320
+ logits = logits[:, -1, :] / temperature
321
+ # optionally crop the logits to only the top k options
322
+ if top_k is not None:
323
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
324
+ logits[logits < v[:, [-1]]] = -float('Inf')
325
+ # apply softmax to convert logits to (normalized) probabilities
326
+ probs = F.softmax(logits, dim=-1)
327
+ # sample from the distribution
328
+ idx_next = torch.multinomial(probs, num_samples=1)
329
+ # append sampled index to the running sequence and continue
330
+ idx = torch.cat((idx, idx_next), dim=1)
331
+
332
+ return idx
333
+
334
+ out_dir = 'out-emails-instr'
335
+ device = 'cuda'
336
+
337
+ print("Loading checkpoint...")
338
+ ckpt_path = os.path.join(out_dir, 'ckpt.pt')
339
+ checkpoint = torch.load(ckpt_path, map_location=device)
340
+ gptconf = GPTConfig(**checkpoint['model_args'])
341
+ model = GPT(gptconf)
342
+ state_dict = checkpoint['model']
343
+
344
+ unwanted_prefix = '_orig_mod.'
345
+ for k,v in list(state_dict.items()):
346
+ if k.startswith(unwanted_prefix):
347
+ state_dict[k[len(unwanted_prefix):]] = state_dict.pop(k)
348
+ model.load_state_dict(state_dict)
349
+
350
+ model.to(device)
351
+ model.eval()
352
+
353
+ enc = tiktoken.get_encoding("gpt2")
354
+
355
+ instruction = "Write a polite refusal email"
356
+ prompt = f"### Instruction:\n{instruction}\n\n### Response:\n"
357
+
358
+ start_ids = enc.encode(prompt, allowed_special={""})
359
+ x = torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...]
360
+
361
+ import json
362
+
363
+ print("\n--- Generating email ---")
364
+ with torch.no_grad():
365
+ y = model.generate(x, max_new_tokens=300, temperature=0.7, top_k=15)
366
+ full_output = enc.decode(y[0].tolist())
367
+
368
+ response_marker = "### Response:\n"
369
+ if response_marker in full_output:
370
+ json_part = full_output.split(response_marker)[1].split("<|endoftext|>")[0].strip()
371
+
372
+ try:
373
+ email_data = json.loads(json_part)
374
+
375
+ print(f"SUBJECT: {email_data.get('subject', 'No subject')}")
376
+ print("-" * 30)
377
+ print(f"BODY:\n{email_data.get('body', 'No body')}")
378
+
379
+ except json.JSONDecodeError:
380
+ print("Failed parsing JSON. Raw output:")
381
+ print(json_part)
382
+ else:
383
+ print("No response marker found!")