anjikum commited on
Commit
503d665
·
verified ·
1 Parent(s): dbb4d61

Upload 2 files

Browse files
Files changed (2) hide show
  1. requirements.txt +5 -1
  2. train.py +365 -0
requirements.txt CHANGED
@@ -1 +1,5 @@
1
-
 
 
 
 
 
1
+ torch
2
+ gradio
3
+ tiktoken
4
+ numpy
5
+ huggingface-hub
train.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ import time
4
+ import inspect
5
+ from dataclasses import dataclass
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.nn import functional as F
9
+ import tiktoken
10
+ import numpy as np
11
+ from huggingface_hub import HfApi, Repository
12
+ import gradio as gr
13
+ from tqdm import tqdm
14
+
15
+
16
+ class CausalSelfAttention(nn.Module):
17
+
18
+ def __init__(self, config):
19
+ super().__init__()
20
+ assert config.n_embd % config.n_head == 0
21
+ # key, query, value projections for all heads, but in a batch
22
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
23
+ # output projection
24
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
25
+ self.c_proj.NANGPT_SCALE_INIT = 1
26
+ # regularization
27
+ self.n_head = config.n_head
28
+ self.n_embd = config.n_embd
29
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
30
+
31
+ def forward(self, x):
32
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
33
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
34
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
35
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
36
+ qkv = self.c_attn(x)
37
+ q, k, v = qkv.split(self.n_embd, dim=2)
38
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
39
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
40
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
41
+
42
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
43
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
44
+ att = F.softmax(att, dim=-1)
45
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
46
+
47
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
48
+ # output projection
49
+ y = self.c_proj(y)
50
+ return y
51
+
52
+
53
+ class MLP(nn.Module):
54
+
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
58
+ self.gelu = nn.GELU(approximate='tanh')
59
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
60
+ self.c_proj.NANOGPT_SCALE_INIT = 1
61
+
62
+ def forward(self, x):
63
+ x = self.c_fc(x)
64
+ x = self.gelu(x)
65
+ x = self.c_proj(x)
66
+ return x
67
+
68
+ class Block(nn.Module):
69
+
70
+ def __init__(self, config):
71
+ super().__init__()
72
+ self.ln_1 = nn.LayerNorm(config.n_embd)
73
+ self.attn = CausalSelfAttention(config)
74
+ self.ln_2 = nn.LayerNorm(config.n_embd)
75
+ self.mlp = MLP(config)
76
+
77
+ def forward(self, x):
78
+ x = x + self.attn(self.ln_1(x))
79
+ x = x + self.mlp(self.ln_2(x))
80
+ return x
81
+
82
+
83
+ @dataclass
84
+ class GPTConfig:
85
+ block_size: int = 1024 # max sequence length
86
+ vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
87
+ n_layer: int = 12 # number of layers
88
+ n_head: int = 12 # number of heads
89
+ n_embd: int = 768 # embedding dimension
90
+
91
+
92
+ class GPT(nn.Module):
93
+
94
+ def __init__(self, config):
95
+ super().__init__()
96
+ self.config = config
97
+
98
+ self.transformer = nn.ModuleDict(dict(
99
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
100
+ wpe = nn.Embedding(config.block_size, config.n_embd),
101
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
102
+ ln_f = nn.LayerNorm(config.n_embd),
103
+ ))
104
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
105
+
106
+ # weight sharing
107
+ self.transformer.wte.weight = self.lm_head.weight
108
+
109
+ # weight initialization
110
+ self.apply(self._init_weights)
111
+
112
+ def generate(self, idx, max_new_tokens):
113
+ # idx is (B, T) array of indices in the current context
114
+ for _ in range(max_new_tokens):
115
+ # crop idx to the last block_size tokens
116
+ idx_cond = idx[:, -self.config.block_size:]
117
+ # get the predictions
118
+ logits, loss = self(idx_cond)
119
+ # focus only on the last time step
120
+ logits = logits[:, -1, :] # becomes (B, C)
121
+ # apply softmax to get probabilities
122
+ probs = F.softmax(logits, dim=-1) # (B, C)
123
+ # sample from the distribution
124
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
125
+ # append sampled index to the running sequence
126
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
127
+ return idx
128
+
129
+ def _init_weights(self, module):
130
+ if isinstance(module, nn.Linear):
131
+ std = 0.02
132
+ if hasattr(module, 'NANGPT_SCALE_INIT'):
133
+ std *= (2 * self.config.n_layer) ** -0.5
134
+ torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
135
+ if module.bias is not None:
136
+ torch.nn.init.zeros_(module.bias)
137
+ elif isinstance(module, nn.Embedding):
138
+ torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
139
+
140
+
141
+
142
+ def forward(self, idx, targets=None):
143
+ # idx is of shape (B, T)
144
+ B, T = idx.size()
145
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
146
+ # forward the token and posisition embeddings
147
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
148
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
149
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
150
+ x = tok_emb + pos_emb
151
+ # forward the blocks of the transformer
152
+ for block in self.transformer.h:
153
+ x = block(x)
154
+ # forward the final layernorm and the classifier
155
+ x = self.transformer.ln_f(x)
156
+ logits = self.lm_head(x) # (B, T, vocab_size)
157
+ loss = None
158
+ if targets is not None:
159
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
160
+ return logits, loss
161
+
162
+ @classmethod
163
+ def from_pretrained(cls, model_type):
164
+ """Loads pretrained GPT-2 model weights from huggingface"""
165
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
166
+ from transformers import GPT2LMHeadModel
167
+ print("loading weights from pretrained gpt: %s" % model_type)
168
+
169
+ # n_layer, n_head and n_embd are determined from model_type
170
+ config_args = {
171
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
172
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
173
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
174
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
175
+ }[model_type]
176
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
177
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
178
+ # create a from-scratch initialized minGPT model
179
+ config = GPTConfig(**config_args)
180
+ model = GPT(config)
181
+ sd = model.state_dict()
182
+ sd_keys = sd.keys()
183
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
184
+
185
+ # init a huggingface/transformers model
186
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
187
+ sd_hf = model_hf.state_dict()
188
+
189
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
190
+ sd_keys_hf = sd_hf.keys()
191
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
192
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
193
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
194
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
195
+ # this means that we have to transpose these weights when we import them
196
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
197
+ for k in sd_keys_hf:
198
+ if any(k.endswith(w) for w in transposed):
199
+ # special treatment for the Conv1D weights we need to transpose
200
+ assert sd_hf[k].shape[::-1] == sd[k].shape
201
+ with torch.no_grad():
202
+ sd[k].copy_(sd_hf[k].t())
203
+ else:
204
+ # vanilla copy over the other parameters
205
+ assert sd_hf[k].shape == sd[k].shape
206
+ with torch.no_grad():
207
+ sd[k].copy_(sd_hf[k])
208
+
209
+ return model
210
+
211
+ # model = GPT.from_pretrained('gpt2')
212
+
213
+ device = 'cpu'
214
+ if torch.cuda.is_available():
215
+ device = 'cuda'
216
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
217
+ device = "mps"
218
+ print(f"using device: {device}")
219
+
220
+ # SEED
221
+ torch.manual_seed(1337)
222
+ if torch.cuda.is_available():
223
+ torch.cuda.manual_seed(1337)
224
+
225
+ # STOP
226
+ num_return_sequences = 5
227
+ max_length = 30
228
+
229
+
230
+ class DataLoaderLite:
231
+ def __init__(self, B, T):
232
+ self.B = B
233
+ self.T = T
234
+
235
+ # at init load tokens from disk and store them in memory
236
+ with open('/content/drive/My Drive/ERAV3/Assign12/input.txt', 'r') as f:
237
+ text = f.read()
238
+ enc = tiktoken.get_encoding('gpt2')
239
+ tokens = enc.encode(text)
240
+ self.tokens = torch.tensor(tokens)
241
+ print(f'loaded {len(self.tokens)} tokens')
242
+ print(f'1 epoch = {len(self.tokens) // (B * T)} batches')
243
+
244
+ # state
245
+ self.current_position = 0
246
+
247
+ def next_batch(self):
248
+ B, T = self.B, self.T
249
+ buf = self.tokens[self.current_position: self.current_position + B * T + 1]
250
+ x = (buf[:-1]).view(B, T) # inputs
251
+ y = (buf[1:]).view(B, T) # targets
252
+ # advance the position in the tensor
253
+ self.current_position += B*T
254
+ # if loading the next batch would be out of bounds, reset
255
+ if self.current_position + (B * T + 1) > len(self.tokens):
256
+ self.current_position = 0
257
+ return x, y
258
+
259
+
260
+ model = GPT(GPTConfig())
261
+ model.to(device)
262
+
263
+ train_loader = DataLoaderLite(B = 4, T = 32)
264
+
265
+ # Calculate number of epochs
266
+ total_tokens = len(train_loader.tokens)
267
+ batches_per_epoch = total_tokens // (4 * 32)
268
+ total_epochs = 5000 / batches_per_epoch
269
+ print(f'\nTraining for approximately {total_epochs:.2f} epochs')
270
+ print(f'Total tokens: {total_tokens:,}')
271
+ print(f'Batches per epoch: {batches_per_epoch}')
272
+ print(f'Total steps: 5,000\n')
273
+
274
+ # Continue with training loop
275
+ optimizer = torch.optim.AdamW(model.parameters(), lr = 3e-4)
276
+
277
+ # Calculate total epochs and steps per epoch
278
+ total_steps = 5000
279
+ steps_per_epoch = batches_per_epoch
280
+ num_epochs = total_steps // steps_per_epoch
281
+ remaining_steps = total_steps % steps_per_epoch
282
+
283
+ print(f"Training for {num_epochs} full epochs plus {remaining_steps} steps")
284
+ print(f"Steps per epoch: {steps_per_epoch}\n")
285
+
286
+ step = 0
287
+ for epoch in range(num_epochs + 1):
288
+ # Determine steps for this epoch
289
+ if epoch == num_epochs:
290
+ if remaining_steps == 0:
291
+ break
292
+ current_steps = remaining_steps
293
+ else:
294
+ current_steps = steps_per_epoch
295
+
296
+ print(f"\nEpoch {epoch+1}/{num_epochs + (1 if remaining_steps > 0 else 0)}")
297
+ epoch_loss = 0
298
+
299
+ # Use tqdm for progress bar
300
+ pbar = tqdm(range(current_steps), desc=f'Training',
301
+ leave=True, ncols=100)
302
+
303
+ for i in pbar:
304
+ x, y = train_loader.next_batch()
305
+ x, y = x.to(device), y.to(device)
306
+
307
+ optimizer.zero_grad()
308
+ logits, loss = model(x, y)
309
+ loss.backward()
310
+ optimizer.step()
311
+
312
+ epoch_loss += loss.item()
313
+ step += 1
314
+
315
+ # Update progress bar description with current loss
316
+ pbar.set_description(f'Loss: {loss.item():.4f}')
317
+
318
+ # Print epoch summary
319
+ avg_epoch_loss = epoch_loss / current_steps
320
+ print(f'\nEpoch {epoch+1} completed. Average Loss: {avg_epoch_loss:.4f}')
321
+ print(f'Total steps completed: {step}/{total_steps}')
322
+
323
+ # For even smaller file size, quantize the model to 8-bit
324
+ model_save_path = '/content/drive/My Drive/ERAV3/Assign12/gpt_model_quantized.pt'
325
+ try:
326
+ # Quantize weights to 8-bit
327
+ state_dict = model.state_dict()
328
+ quantized_dict = {}
329
+
330
+ for key, param in state_dict.items():
331
+ if param.dtype == torch.float32 or param.dtype == torch.float16:
332
+ # Quantize to 8-bit
333
+ param_np = param.cpu().numpy()
334
+ scale = np.max(np.abs(param_np)) / 127
335
+ quantized = np.round(param_np / scale).astype(np.int8)
336
+ quantized_dict[key] = {
337
+ 'data': quantized,
338
+ 'scale': scale
339
+ }
340
+ else:
341
+ quantized_dict[key] = param
342
+
343
+ # Save quantized weights
344
+ torch.save(quantized_dict, model_save_path)
345
+ print(f'\nQuantized model saved successfully to {model_save_path}')
346
+ except Exception as e:
347
+ print(f'\nError saving model: {e}')
348
+
349
+ # To load the quantized model:
350
+ # def dequantize_model(model, quantized_dict):
351
+ # state_dict = {}
352
+ # for key, value in quantized_dict.items():
353
+ # if isinstance(value, dict):
354
+ # # Dequantize
355
+ # state_dict[key] = torch.tensor(
356
+ # value['data'].astype(np.float32) * value['scale']
357
+ # )
358
+ # else:
359
+ # state_dict[key] = value
360
+ # model.load_state_dict(state_dict)
361
+ # return model
362
+
363
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
364
+ enc = tiktoken.get_encoding('gpt2')
365
+ print(enc.decode(model.generate(context, max_new_tokens=500)[0].tolist()))