kalekarnn commited on
Commit
379e46a
·
verified ·
1 Parent(s): a4e0286

Upload transformar.py

Browse files
Files changed (1) hide show
  1. transformar.py +346 -0
transformar.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Solving for residual std scaling issue
2
+ import os
3
+ import math
4
+ import time
5
+ from dataclasses import dataclass
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.nn import functional as F
9
+ from tqdm import tqdm # Import tqdm for progress bar
10
+ import torch.quantization # Import quantization module
11
+ import torch.nn.utils.prune as prune
12
+ import tiktoken
13
+
14
+
15
+ class CausalSelfAttention(nn.Module):
16
+
17
+ def __init__(self, config):
18
+ super().__init__()
19
+ assert config.n_embd % config.n_head == 0
20
+ # key, query, value projections for all heads, but in a batch
21
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
22
+ # output projection
23
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
24
+ self.c_proj.NANGPT_SCALE_INIT = 1
25
+ # regularization
26
+ self.n_head = config.n_head
27
+ self.n_embd = config.n_embd
28
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
29
+
30
+ def forward(self, x):
31
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
32
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
33
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
34
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
35
+ qkv = self.c_attn(x)
36
+ q, k, v = qkv.split(self.n_embd, dim=2)
37
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
38
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
39
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
40
+
41
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
42
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
43
+ att = F.softmax(att, dim=-1)
44
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
45
+
46
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
47
+ # output projection
48
+ y = self.c_proj(y)
49
+ return y
50
+
51
+
52
+ class MLP(nn.Module):
53
+
54
+ def __init__(self, config):
55
+ super().__init__()
56
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
57
+ self.gelu = nn.GELU(approximate='tanh')
58
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
59
+ self.c_proj.NANOGPT_SCALE_INIT = 1
60
+
61
+ def forward(self, x):
62
+ x = self.c_fc(x)
63
+ x = self.gelu(x)
64
+ x = self.c_proj(x)
65
+ return x
66
+
67
+ class Block(nn.Module):
68
+
69
+ def __init__(self, config):
70
+ super().__init__()
71
+ self.ln_1 = nn.LayerNorm(config.n_embd)
72
+ self.attn = CausalSelfAttention(config)
73
+ self.ln_2 = nn.LayerNorm(config.n_embd)
74
+ self.mlp = MLP(config)
75
+
76
+ def forward(self, x):
77
+ x = x + self.attn(self.ln_1(x))
78
+ x = x + self.mlp(self.ln_2(x))
79
+ return x
80
+
81
+
82
+ @dataclass
83
+ class GPTConfig:
84
+ block_size: int = 1024 # max sequence length
85
+ vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
86
+ n_layer: int = 12 # number of layers
87
+ n_head: int = 12 # number of heads
88
+ n_embd: int = 768 # embedding dimension
89
+
90
+
91
+ class GPT(nn.Module):
92
+
93
+ def __init__(self, config):
94
+ super().__init__()
95
+ self.config = config
96
+
97
+ self.transformer = nn.ModuleDict(dict(
98
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
99
+ wpe = nn.Embedding(config.block_size, config.n_embd),
100
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
101
+ ln_f = nn.LayerNorm(config.n_embd),
102
+ ))
103
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
104
+
105
+ # weight sharing
106
+ self.transformer.wte.weight = self.lm_head.weight
107
+
108
+ # weight initialization
109
+ self.apply(self._init_weights)
110
+
111
+ def _init_weights(self, module):
112
+ if isinstance(module, nn.Linear):
113
+ std = 0.02
114
+ if hasattr(module, 'NANGPT_SCALE_INIT'):
115
+ std *= (2 * self.config.n_layer) ** -0.5
116
+ torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
117
+ if module.bias is not None:
118
+ torch.nn.init.zeros_(module.bias)
119
+ elif isinstance(module, nn.Embedding):
120
+ torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
121
+
122
+ def print_num_parameters(self):
123
+ num_params = sum(p.numel() for p in self.parameters())
124
+ print(f"Number of model parameters: {num_params}")
125
+
126
+ def forward(self, idx, targets=None):
127
+ # idx is of shape (B, T)
128
+ B, T = idx.size()
129
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
130
+ # forward the token and posisition embeddings
131
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
132
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
133
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
134
+ x = tok_emb + pos_emb
135
+ # forward the blocks of the transformer
136
+ for block in self.transformer.h:
137
+ x = block(x)
138
+ # forward the final layernorm and the classifier
139
+ x = self.transformer.ln_f(x)
140
+ logits = self.lm_head(x) # (B, T, vocab_size)
141
+ loss = None
142
+ if targets is not None:
143
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
144
+ return logits, loss
145
+
146
+ @classmethod
147
+ def from_pretrained(cls, model_type):
148
+ """Loads pretrained GPT-2 model weights from huggingface"""
149
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
150
+ from transformers import GPT2LMHeadModel
151
+ print("loading weights from pretrained gpt: %s" % model_type)
152
+
153
+ # n_layer, n_head and n_embd are determined from model_type
154
+ config_args = {
155
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
156
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
157
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
158
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
159
+ }[model_type]
160
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
161
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
162
+ # create a from-scratch initialized minGPT model
163
+ config = GPTConfig(**config_args)
164
+ model = GPT(config)
165
+ sd = model.state_dict()
166
+ sd_keys = sd.keys()
167
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
168
+
169
+ # init a huggingface/transformers model
170
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
171
+ sd_hf = model_hf.state_dict()
172
+
173
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
174
+ sd_keys_hf = sd_hf.keys()
175
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
176
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
177
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
178
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
179
+ # this means that we have to transpose these weights when we import them
180
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
181
+ for k in sd_keys_hf:
182
+ if any(k.endswith(w) for w in transposed):
183
+ # special treatment for the Conv1D weights we need to transpose
184
+ assert sd_hf[k].shape[::-1] == sd[k].shape
185
+ with torch.no_grad():
186
+ sd[k].copy_(sd_hf[k].t())
187
+ else:
188
+ # vanilla copy over the other parameters
189
+ assert sd_hf[k].shape == sd[k].shape
190
+ with torch.no_grad():
191
+ sd[k].copy_(sd_hf[k])
192
+
193
+ return model
194
+
195
+
196
+ device = 'cpu'
197
+ if torch.cuda.is_available():
198
+ device = 'cuda'
199
+ elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
200
+ device = "mps"
201
+ print(f"using device: {device}")
202
+
203
+ # SEED
204
+ torch.manual_seed(1337)
205
+ if torch.cuda.is_available():
206
+ torch.cuda.manual_seed(1337)
207
+
208
+ class DataLoaderLite:
209
+ def __init__(self, B, T):
210
+ self.B = B
211
+ self.T = T
212
+
213
+ # at init load tokens from disk and store them in memory
214
+ with open('input.txt', 'r') as f:
215
+ text = f.read()
216
+ enc = tiktoken.get_encoding('gpt2')
217
+ tokens = enc.encode(text)
218
+ self.tokens = torch.tensor(tokens, device=device) # Move tokens to the correct device
219
+ print(f'loaded {len(self.tokens)} tokens')
220
+ print(f'1 epoch = {len(self.tokens)} batches')
221
+
222
+ # state
223
+ self.current_position = 0
224
+
225
+ def next_batch(self):
226
+ B, T = self.B, self.T
227
+ buf = self.tokens[self.current_position: self.current_position + B * T + 1]
228
+ x = (buf[:-1]).view(B, T) # inputs
229
+ y = (buf[1:]).view(B, T) # targets
230
+ # advance the position in the tensor
231
+ self.current_position += B*T
232
+ # if loading the next batch would be out of bounds, reset
233
+ if self.current_position + (B * T + 1) > len(self.tokens):
234
+ self.current_position = 0
235
+ return x, y
236
+
237
+
238
+ import os
239
+ import time
240
+ import torch
241
+
242
+ # Initialize the model and data loader
243
+ config = GPTConfig()
244
+ model = GPT(config).to(device) # Move model to the correct device
245
+
246
+ # Print the model architecture and number of parameters
247
+ print(model)
248
+ model.print_num_parameters()
249
+
250
+ train_loader = DataLoaderLite(B=4, T=1024)
251
+
252
+ # Define the optimizer
253
+ optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
254
+
255
+ # Function to load the most recent checkpoint
256
+ def load_latest_checkpoint(model):
257
+ checkpoint_file = 'checkpoint.pt'
258
+ if not os.path.exists(checkpoint_file):
259
+ return 0 # No checkpoint found, start from epoch 0
260
+
261
+ print(f'Loading checkpoint from {checkpoint_file}')
262
+ checkpoint = torch.load(checkpoint_file, map_location=device) # Load checkpoint to the correct device
263
+ model.load_state_dict(checkpoint['model_state_dict'])
264
+ return checkpoint['epoch']
265
+
266
+ # Load the latest checkpoint if available
267
+ start_epoch = load_latest_checkpoint(model)
268
+
269
+ # Training loop
270
+ num_epochs = 100
271
+
272
+ # Start time tracking
273
+ start_time = time.time()
274
+
275
+ for epoch in range(start_epoch, num_epochs): # Start from the loaded epoch
276
+ epoch_loss = 0.0 # Initialize epoch loss
277
+ num_steps = 0 # Initialize step counter for the epoch
278
+ last_loss = None # Variable to store the last loss
279
+
280
+ # Calculate total steps for the progress bar
281
+ total_steps = len(train_loader.tokens) // (train_loader.B * train_loader.T)
282
+
283
+ # Use tqdm to create a progress bar
284
+ with tqdm(total=total_steps, desc=f'Epoch {epoch + 1}/{num_epochs}') as pbar:
285
+ for step in range(total_steps): # Iterate over the number of steps
286
+ x, y = train_loader.next_batch()
287
+ x, y = x.to(device), y.to(device)
288
+ optimizer.zero_grad()
289
+ logits, loss = model(x, y)
290
+ loss.backward()
291
+ optimizer.step()
292
+
293
+ epoch_loss += loss.item() # Accumulate loss
294
+ num_steps += 1 # Increment step counter
295
+ last_loss = loss.item() # Store the last loss
296
+ pbar.update(1) # Update progress bar
297
+
298
+ # Check if the loss is below the threshold
299
+ if last_loss < 0.099999:
300
+ print(f'Loss below threshold: {last_loss:.6f}') # Print loss before breaking
301
+ break # Exit the loop if the loss condition is met
302
+
303
+ # Print the loss at the end of the epoch
304
+ print(f'Epoch {epoch + 1}/{num_epochs}, Loss: {last_loss:.6f}')
305
+
306
+ # Check if the loss condition was met to break out of the epoch loop
307
+ if last_loss < 0.099999:
308
+ print(f'Early stopping at epoch {epoch + 1} due to loss condition met.')
309
+ break # Exit the epoch loop if the loss condition is met
310
+
311
+ # Checkpointing: Save the model and the current epoch after each epoch
312
+ checkpoint_path = 'checkpoint.pt' # Save to a single checkpoint file
313
+ torch.save({
314
+ 'epoch': epoch + 1, # Save the current epoch number
315
+ 'model_state_dict': model.state_dict(), # Save the model state
316
+ }, checkpoint_path)
317
+
318
+ # End time tracking
319
+ end_time = time.time()
320
+ training_duration = end_time - start_time
321
+
322
+ # Convert training duration to minutes and seconds
323
+ minutes = int(training_duration // 60)
324
+ seconds = int(training_duration % 60)
325
+
326
+ # Print the total training time in minute:second format
327
+ print(f'Total training time: {minutes} minutes and {seconds} seconds')
328
+
329
+ # After training your model, apply quantization and save it with compression
330
+ def save_model_with_quantization(model, file_path):
331
+ # Switch model to evaluation mode
332
+ model.eval()
333
+
334
+ # Apply dynamic quantization
335
+ quantized_model = torch.quantization.quantize_dynamic(
336
+ model, # the model to be quantized
337
+ {nn.Linear}, # layers to quantize
338
+ dtype=torch.qint8 # quantization type
339
+ )
340
+
341
+ # Save the quantized model with compression
342
+ torch.save(quantized_model.state_dict(), file_path, _use_new_zipfile_serialization=True)
343
+ print(f'Model saved to {file_path} with quantization and compression.')
344
+
345
+ # Call this function after training your model
346
+ save_model_with_quantization(model, 'trained_model_quantized.pt')