satyanayak commited on
Commit
51ffa64
·
1 Parent(s): 4d50f71

model file updated

Browse files
Files changed (1) hide show
  1. transformer.py +21 -241
transformer.py CHANGED
@@ -1,53 +1,37 @@
1
- # Solving for residual std scaling issue
2
- import os
3
  import math
4
- import time
5
- import inspect
6
- from dataclasses import dataclass
7
  import torch
8
  import torch.nn as nn
9
  from torch.nn import functional as F
10
-
11
 
12
  class CausalSelfAttention(nn.Module):
13
-
14
  def __init__(self, config):
15
  super().__init__()
16
  assert config.n_embd % config.n_head == 0
17
- # key, query, value projections for all heads, but in a batch
18
  self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
19
- # output projection
20
  self.c_proj = nn.Linear(config.n_embd, config.n_embd)
21
  self.c_proj.NANGPT_SCALE_INIT = 1
22
- # regularization
23
  self.n_head = config.n_head
24
  self.n_embd = config.n_embd
25
  self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
26
 
27
  def forward(self, x):
28
- B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
29
- # calculate query, key, values for all heads in batch and move head forward to be the batch dim
30
- # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
31
- # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
32
  qkv = self.c_attn(x)
33
  q, k, v = qkv.split(self.n_embd, dim=2)
34
- k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
35
- q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
36
- v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
37
 
38
  att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
39
  att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
40
  att = F.softmax(att, dim=-1)
41
- y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
42
-
43
- y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
44
- # output projection
45
  y = self.c_proj(y)
46
  return y
47
 
48
-
49
  class MLP(nn.Module):
50
-
51
  def __init__(self, config):
52
  super().__init__()
53
  self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
@@ -62,7 +46,6 @@ class MLP(nn.Module):
62
  return x
63
 
64
  class Block(nn.Module):
65
-
66
  def __init__(self, config):
67
  super().__init__()
68
  self.ln_1 = nn.LayerNorm(config.n_embd)
@@ -75,18 +58,15 @@ class Block(nn.Module):
75
  x = x + self.mlp(self.ln_2(x))
76
  return x
77
 
78
-
79
  @dataclass
80
  class GPTConfig:
81
- block_size: int = 1024 # max sequence length
82
- vocab_size: int = 50257 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
83
- n_layer: int = 12 # number of layers
84
- n_head: int = 12 # number of heads
85
- n_embd: int = 768 # embedding dimension
86
-
87
 
88
  class GPT(nn.Module):
89
-
90
  def __init__(self, config):
91
  super().__init__()
92
  self.config = config
@@ -98,11 +78,7 @@ class GPT(nn.Module):
98
  ln_f = nn.LayerNorm(config.n_embd),
99
  ))
100
  self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
101
-
102
- # weight sharing
103
  self.transformer.wte.weight = self.lm_head.weight
104
-
105
- # weight initialization
106
  self.apply(self._init_weights)
107
 
108
  def _init_weights(self, module):
@@ -116,218 +92,22 @@ class GPT(nn.Module):
116
  elif isinstance(module, nn.Embedding):
117
  torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
118
 
119
-
120
-
121
  def forward(self, idx, targets=None):
122
- # idx is of shape (B, T)
123
  B, T = idx.size()
124
  assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
125
- # forward the token and posisition embeddings
126
- pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
127
- pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
128
- tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
129
  x = tok_emb + pos_emb
130
- # forward the blocks of the transformer
131
  for block in self.transformer.h:
132
  x = block(x)
133
- # forward the final layernorm and the classifier
134
  x = self.transformer.ln_f(x)
135
- logits = self.lm_head(x) # (B, T, vocab_size)
 
136
  loss = None
137
  if targets is not None:
138
  loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
139
- return logits, loss
140
-
141
- @classmethod
142
- def from_pretrained(cls, model_type):
143
- """Loads pretrained GPT-2 model weights from huggingface"""
144
- assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
145
- from transformers import GPT2LMHeadModel
146
- print("loading weights from pretrained gpt: %s" % model_type)
147
-
148
- # n_layer, n_head and n_embd are determined from model_type
149
- config_args = {
150
- 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
151
- 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
152
- 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
153
- 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
154
- }[model_type]
155
- config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
156
- config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
157
- # create a from-scratch initialized minGPT model
158
- config = GPTConfig(**config_args)
159
- model = GPT(config)
160
- sd = model.state_dict()
161
- sd_keys = sd.keys()
162
- sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
163
-
164
- # init a huggingface/transformers model
165
- model_hf = GPT2LMHeadModel.from_pretrained(model_type)
166
- sd_hf = model_hf.state_dict()
167
-
168
- # copy while ensuring all of the parameters are aligned and match in names and shapes
169
- sd_keys_hf = sd_hf.keys()
170
- sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
171
- sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
172
- transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
173
- # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
174
- # this means that we have to transpose these weights when we import them
175
- assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
176
- for k in sd_keys_hf:
177
- if any(k.endswith(w) for w in transposed):
178
- # special treatment for the Conv1D weights we need to transpose
179
- assert sd_hf[k].shape[::-1] == sd[k].shape
180
- with torch.no_grad():
181
- sd[k].copy_(sd_hf[k].t())
182
- else:
183
- # vanilla copy over the other parameters
184
- assert sd_hf[k].shape == sd[k].shape
185
- with torch.no_grad():
186
- sd[k].copy_(sd_hf[k])
187
-
188
- return model
189
-
190
- # model = GPT.from_pretrained('gpt2')
191
-
192
- device = 'cpu'
193
- if torch.cuda.is_available():
194
- device = 'cuda'
195
- elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
196
- device = "mps"
197
- print(f"using device: {device}")
198
-
199
- # SEED
200
- torch.manual_seed(1337)
201
- if torch.cuda.is_available():
202
- torch.cuda.manual_seed(1337)
203
-
204
- # STOP
205
- num_return_sequences = 5
206
- max_length = 30
207
-
208
-
209
-
210
- import tiktoken
211
-
212
- class DataLoaderLite:
213
- def __init__(self, B, T):
214
- self.B = B
215
- self.T = T
216
-
217
- # at init load tokens from disk and store them in memory
218
- with open('input.txt', 'r') as f:
219
- text = f.read()
220
- enc = tiktoken.get_encoding('gpt2')
221
- tokens = enc.encode(text)
222
- self.tokens = torch.tensor(tokens)
223
- print(f'loaded {len(self.tokens)} tokens')
224
- print(f'1 epoch = {len(self.tokens) // (B * T)} batches')
225
-
226
- # state
227
- self.current_position = 0
228
-
229
- def next_batch(self):
230
- B, T = self.B, self.T
231
- buf = self.tokens[self.current_position: self.current_position + B * T + 1]
232
- x = (buf[:-1]).view(B, T) # inputs
233
- y = (buf[1:]).view(B, T) # targets
234
- # advance the position in the tensor
235
- self.current_position += B*T
236
- # if loading the next batch would be out of bounds, reset
237
- if self.current_position + (B * T + 1) > len(self.tokens):
238
- self.current_position = 0
239
- return x, y
240
-
241
-
242
- model = GPT(GPTConfig())
243
- model.to(device)
244
-
245
- # Increase batch size slightly but keep it manageable
246
- train_loader = DataLoaderLite(B=8, T=64)
247
-
248
- # Calculate total steps for one cycle
249
- total_steps = 10000
250
- print(f"Training for {total_steps} steps")
251
-
252
- # Initialize optimizer with more conservative parameters
253
- optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0.1, betas=(0.9, 0.95))
254
-
255
- # Use OneCycleLR scheduler
256
- scheduler = torch.optim.lr_scheduler.OneCycleLR(
257
- optimizer,
258
- max_lr=3e-4,
259
- total_steps=total_steps,
260
- pct_start=0.1, # Warm up for 10% of steps
261
- anneal_strategy='cos',
262
- cycle_momentum=False,
263
- div_factor=25.0, # Initial lr = max_lr/25
264
- final_div_factor=10000.0, # Min lr = initial_lr/10000
265
- )
266
-
267
- # Training loop
268
- best_loss = float('inf')
269
- step = 0
270
- losses = [] # Keep track of losses for monitoring
271
- last_time = time.time()
272
- interval = 2 # Print every 10 steps
273
-
274
- while step < total_steps and best_loss > 0.099999:
275
- x, y = train_loader.next_batch()
276
- x, y = x.to(device), y.to(device)
277
-
278
- optimizer.zero_grad()
279
- logits, loss = model(x, y)
280
- loss.backward()
281
-
282
- # Gradient clipping
283
- torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5) # Reduced from 1.0
284
-
285
- optimizer.step()
286
- scheduler.step()
287
-
288
- # Update best loss
289
- if loss.item() < best_loss:
290
- best_loss = loss.item()
291
-
292
- losses.append(loss.item())
293
-
294
- # Print progress
295
- if step % interval == 0:
296
- current_time = time.time()
297
- time_per_batch = (current_time - last_time) / interval if step > 0 else 0
298
- last_time = current_time
299
-
300
- # Calculate average loss over last 100 steps for stability
301
- avg_loss = sum(losses[-100:]) / min(len(losses), 100)
302
-
303
- print(f'step {step}, '
304
- f'loss: {loss.item():.4f}, '
305
- f'avg_loss: {avg_loss:.4f}, '
306
- f'best_loss: {best_loss:.4f}, '
307
- f'lr: {scheduler.get_last_lr()[0]:.2e}, '
308
- f'time/batch: {time_per_batch:.3f}s')
309
-
310
- step += 1
311
-
312
- print(f'Final loss: {loss.item():.6f}')
313
- print(f'Best loss: {best_loss:.6f}')
314
- print(f'Average of last 100 losses: {sum(losses[-100:]) / min(len(losses), 100):.6f}')
315
-
316
- # Save the trained model
317
- save_path = 'trained_model.pt'
318
- torch.save({
319
- 'model_state_dict': model.state_dict(),
320
- 'best_loss': best_loss,
321
- 'config': model.config,
322
- }, save_path)
323
- print(f"Model saved to {save_path}")
324
-
325
- # Generation code
326
- enc = tiktoken.get_encoding('gpt2')
327
- prompt = "We are accounted poor citizens, the"
328
- tokens = enc.encode(prompt)
329
- tokens = torch.tensor(tokens, dtype=torch.long)
330
- tokens = tokens.unsqueeze(0).repeat(num_return_sequences, 1)
331
- x = tokens.to(device)
332
-
333
- # Rest of generation code remains same...
 
 
 
1
  import math
 
 
 
2
  import torch
3
  import torch.nn as nn
4
  from torch.nn import functional as F
5
+ from dataclasses import dataclass
6
 
7
  class CausalSelfAttention(nn.Module):
 
8
  def __init__(self, config):
9
  super().__init__()
10
  assert config.n_embd % config.n_head == 0
 
11
  self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
 
12
  self.c_proj = nn.Linear(config.n_embd, config.n_embd)
13
  self.c_proj.NANGPT_SCALE_INIT = 1
 
14
  self.n_head = config.n_head
15
  self.n_embd = config.n_embd
16
  self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
17
 
18
  def forward(self, x):
19
+ B, T, C = x.size()
 
 
 
20
  qkv = self.c_attn(x)
21
  q, k, v = qkv.split(self.n_embd, dim=2)
22
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
23
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
24
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
25
 
26
  att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
27
  att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
28
  att = F.softmax(att, dim=-1)
29
+ y = att @ v
30
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
 
 
31
  y = self.c_proj(y)
32
  return y
33
 
 
34
  class MLP(nn.Module):
 
35
  def __init__(self, config):
36
  super().__init__()
37
  self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
 
46
  return x
47
 
48
  class Block(nn.Module):
 
49
  def __init__(self, config):
50
  super().__init__()
51
  self.ln_1 = nn.LayerNorm(config.n_embd)
 
58
  x = x + self.mlp(self.ln_2(x))
59
  return x
60
 
 
61
  @dataclass
62
  class GPTConfig:
63
+ block_size: int = 1024
64
+ vocab_size: int = 50257
65
+ n_layer: int = 12
66
+ n_head: int = 12
67
+ n_embd: int = 768
 
68
 
69
  class GPT(nn.Module):
 
70
  def __init__(self, config):
71
  super().__init__()
72
  self.config = config
 
78
  ln_f = nn.LayerNorm(config.n_embd),
79
  ))
80
  self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
 
 
81
  self.transformer.wte.weight = self.lm_head.weight
 
 
82
  self.apply(self._init_weights)
83
 
84
  def _init_weights(self, module):
 
92
  elif isinstance(module, nn.Embedding):
93
  torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
94
 
 
 
95
  def forward(self, idx, targets=None):
 
96
  B, T = idx.size()
97
  assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
98
+
99
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device)
100
+ pos_emb = self.transformer.wpe(pos)
101
+ tok_emb = self.transformer.wte(idx)
102
  x = tok_emb + pos_emb
103
+
104
  for block in self.transformer.h:
105
  x = block(x)
106
+
107
  x = self.transformer.ln_f(x)
108
+ logits = self.lm_head(x)
109
+
110
  loss = None
111
  if targets is not None:
112
  loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
113
+ return logits, loss