Kartheekb7 commited on
Commit
b89f4f5
1 Parent(s): f285e0a

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +215 -0
model.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+
11
+ class CausalSelfAttention(nn.Module):
12
+
13
+ def __init__(self, config):
14
+ super().__init__()
15
+ assert config.n_embd % config.n_head == 0
16
+ # key, query, value projections for all heads, but in a batch
17
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
18
+ # output projection
19
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
20
+ self.c_proj.NANGPT_SCALE_INIT = 1
21
+ # regularization
22
+ self.n_head = config.n_head
23
+ self.n_embd = config.n_embd
24
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
25
+
26
+ def forward(self, x):
27
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
28
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
29
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
30
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
31
+ qkv = self.c_attn(x)
32
+ q, k, v = qkv.split(self.n_embd, dim=2)
33
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
34
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
35
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
36
+
37
+ # att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
38
+ # att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
39
+ # att = F.softmax(att, dim=-1)
40
+ # y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
41
+
42
+ y = F.scaled_dot_product_attention(q, k, v, is_causal = True) # Flash attention
43
+
44
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
45
+ # output projection
46
+ y = self.c_proj(y)
47
+ return y
48
+
49
+
50
+ class MLP(nn.Module):
51
+
52
+ def __init__(self, config):
53
+ super().__init__()
54
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
55
+ self.gelu = nn.GELU(approximate='tanh')
56
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
57
+ self.c_proj.NANOGPT_SCALE_INIT = 1
58
+
59
+ def forward(self, x):
60
+ x = self.c_fc(x)
61
+ x = self.gelu(x)
62
+ x = self.c_proj(x)
63
+ return x
64
+
65
+ class Block(nn.Module):
66
+
67
+ def __init__(self, config):
68
+ super().__init__()
69
+ self.ln_1 = nn.LayerNorm(config.n_embd)
70
+ self.attn = CausalSelfAttention(config)
71
+ self.ln_2 = nn.LayerNorm(config.n_embd)
72
+ self.mlp = MLP(config)
73
+
74
+ def forward(self, x):
75
+ x = x + self.attn(self.ln_1(x))
76
+ x = x + self.mlp(self.ln_2(x))
77
+ return x
78
+
79
+
80
+ @dataclass
81
+ class GPTConfig:
82
+ block_size: int = 1024 # max sequence length
83
+ vocab_size: int = 50304 # number of tokens: 50,000 BPE merges + 256 bytes tokens + 1 <|endoftext|> token
84
+ n_layer: int = 12 # number of layers
85
+ n_head: int = 12 # number of heads
86
+ n_embd: int = 768 # embedding dimension
87
+
88
+
89
+ class GPT(nn.Module):
90
+
91
+ def __init__(self, config):
92
+ super().__init__()
93
+ self.config = config
94
+
95
+ self.transformer = nn.ModuleDict(dict(
96
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
97
+ wpe = nn.Embedding(config.block_size, config.n_embd),
98
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
99
+ ln_f = nn.LayerNorm(config.n_embd),
100
+ ))
101
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
102
+
103
+ # weight sharing
104
+ self.transformer.wte.weight = self.lm_head.weight
105
+
106
+ # weight initialization
107
+ self.apply(self._init_weights)
108
+
109
+ def _init_weights(self, module):
110
+ if isinstance(module, nn.Linear):
111
+ std = 0.02
112
+ if hasattr(module, 'NANGPT_SCALE_INIT'):
113
+ std *= (2 * self.config.n_layer) ** -0.5
114
+ torch.nn.init.normal_(module.weight, mean = 0.0, std = std)
115
+ if module.bias is not None:
116
+ torch.nn.init.zeros_(module.bias)
117
+ elif isinstance(module, nn.Embedding):
118
+ torch.nn.init.normal_(module.weight, mean=0.0, std = 0.02)
119
+
120
+
121
+
122
+ def forward(self, idx, targets=None):
123
+ # idx is of shape (B, T)
124
+ B, T = idx.size()
125
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
126
+ # forward the token and posisition embeddings
127
+ pos = torch.arange(0, T, dtype=torch.long, device=idx.device) # shape (T)
128
+ pos_emb = self.transformer.wpe(pos) # position embeddings of shape (T, n_embd)
129
+ tok_emb = self.transformer.wte(idx) # token embeddings of shape (B, T, n_embd)
130
+ x = tok_emb + pos_emb
131
+ # forward the blocks of the transformer
132
+ for block in self.transformer.h:
133
+ x = block(x)
134
+ # forward the final layernorm and the classifier
135
+ x = self.transformer.ln_f(x)
136
+ logits = self.lm_head(x) # (B, T, vocab_size)
137
+ loss = None
138
+ if targets is not None:
139
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))
140
+ return logits, loss
141
+
142
+ @classmethod
143
+ def from_pretrained(cls, model_type):
144
+ """Loads pretrained GPT-2 model weights from huggingface"""
145
+ assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
146
+ from transformers import GPT2LMHeadModel
147
+ print("loading weights from pretrained gpt: %s" % model_type)
148
+
149
+ # n_layer, n_head and n_embd are determined from model_type
150
+ config_args = {
151
+ 'gpt2': dict(n_layer=12, n_head=12, n_embd=768), # 124M params
152
+ 'gpt2-medium': dict(n_layer=24, n_head=16, n_embd=1024), # 350M params
153
+ 'gpt2-large': dict(n_layer=36, n_head=20, n_embd=1280), # 774M params
154
+ 'gpt2-xl': dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params
155
+ }[model_type]
156
+ config_args['vocab_size'] = 50257 # always 50257 for GPT model checkpoints
157
+ config_args['block_size'] = 1024 # always 1024 for GPT model checkpoints
158
+ # create a from-scratch initialized minGPT model
159
+ config = GPTConfig(**config_args)
160
+ model = GPT(config)
161
+ sd = model.state_dict()
162
+ sd_keys = sd.keys()
163
+ sd_keys = [k for k in sd_keys if not k.endswith('.attn.bias')] # discard this mask / buffer, not a param
164
+
165
+ # init a huggingface/transformers model
166
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
167
+ sd_hf = model_hf.state_dict()
168
+
169
+ # copy while ensuring all of the parameters are aligned and match in names and shapes
170
+ sd_keys_hf = sd_hf.keys()
171
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.masked_bias')] # ignore these, just a buffer
172
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith('.attn.bias')] # same, just the mask (buffer)
173
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
174
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
175
+ # this means that we have to transpose these weights when we import them
176
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
177
+ for k in sd_keys_hf:
178
+ if any(k.endswith(w) for w in transposed):
179
+ # special treatment for the Conv1D weights we need to transpose
180
+ assert sd_hf[k].shape[::-1] == sd[k].shape
181
+ with torch.no_grad():
182
+ sd[k].copy_(sd_hf[k].t())
183
+ else:
184
+ # vanilla copy over the other parameters
185
+ assert sd_hf[k].shape == sd[k].shape
186
+ with torch.no_grad():
187
+ sd[k].copy_(sd_hf[k])
188
+
189
+ return model
190
+
191
+ def configure_optimizers(self, weight_decay, learning_rate, device_type):
192
+ # start with all of the candidate parameters (that require grad)
193
+ param_dict = {pn: p for pn, p in self.named_parameters()}
194
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
195
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
196
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
197
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
198
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
199
+ optim_groups = [
200
+ {'params': decay_params, 'weight_decay': weight_decay},
201
+ {'params': nodecay_params, 'weight_decay': 0.0}
202
+ ]
203
+ num_decay_params = sum(p.numel() for p in decay_params)
204
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
205
+
206
+ print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
207
+ print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
208
+ # Create AdamW optimizer and use the fused version if it is available
209
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
210
+ use_fused = fused_available and device_type == "cuda"
211
+
212
+ print(f"using fused AdamW: {use_fused}")
213
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=(0.9, 0.95), eps=1e-8, fused=use_fused)
214
+ return optimizer
215
+