sayanbanerjee32 commited on
Commit
11c24e8
1 Parent(s): 8636816

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. model_gpt2.py +242 -0
  2. saved_model/ckpt.pt +1 -1
model_gpt2.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+ import inspect
6
+
7
+ #------------------------------------------
8
+
9
+ class CausalSelfAttention(nn.Module):
10
+ def __init__(self, config):
11
+ super().__init__()
12
+ # key, query, value projection for al heads but in a batch
13
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
14
+ # output projection
15
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
16
+ self.c_proj.NANOGPT_SCALE_INIT = True
17
+
18
+ # regularization
19
+ self.n_head = config.n_head
20
+ self.n_embd = config.n_embd
21
+
22
+ # not really a 'bias', more of a mask, but following a openAI/HF naming
23
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
24
+ .view(1, 1, config.block_size, config.block_size))
25
+
26
+
27
+ def forward(self, x):
28
+ B, T, C = x.size() # batch_size, sequence_length, embedding dimensionality (n_embed)
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
+ # attention (materilizes the large (T,T) matrix for all the queries and keys)
39
+ # att = (q @ k.transpose(-2, -1)) * (1.0 / torch.sqrt(torch.tensor(k.size(-1))))
40
+ # att = att.masked_fill(self.bias[:,:,:T,:T] == 0, float('-inf'))
41
+ # att = F.softmax(att, dim=-1)
42
+ # y = att @ v # (B, nh, T, T) @ (B, nh, T, hs) -> (B, nh, T, T)
43
+ # 4 lines above replaced by flash- attention
44
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
45
+
46
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
47
+
48
+ # output projection
49
+ y = self.c_proj(y)
50
+ return y
51
+
52
+ class MLP(nn.Module):
53
+ def __init__(self, config):
54
+ super().__init__()
55
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
56
+ self.gelu = nn.GELU(approximate='tanh') # historic reason for approximation
57
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
58
+ self.c_proj.NANOGPT_SCALE_INIT = True
59
+
60
+ def forward(self, x):
61
+ x = self.c_fc(x)
62
+ x = self.gelu(x)
63
+ x = self.c_proj(x)
64
+ return x
65
+
66
+ class Block(nn.Module):
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
+ @dataclass
80
+ class GPTConfig:
81
+ block_size: int = 1024 # max sequence lenghts
82
+ vocab_size: int = 50257 # number of tokens, 50,000 BPE merges + 256 byte tokens + 1 <|endoftext|>
83
+ n_layer: int = 12 # number of layers
84
+ n_head: int = 12 # number of heads
85
+ n_embd: int = 768 # embedding dim
86
+
87
+ class GPT(nn.Module):
88
+ def __init__(self, config):
89
+ super().__init__()
90
+ self.config = config
91
+ self.transformer = nn.ModuleDict(dict(
92
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
93
+ wpe = nn.Embedding(config.block_size, config.n_embd),
94
+ h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
95
+ ln_f = nn.LayerNorm(config.n_embd),
96
+ ))
97
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
98
+
99
+ # weight sharing scheme
100
+ self.transformer.wte.weight = self.lm_head.weight
101
+
102
+ # init
103
+ self.apply(self._init_weights)
104
+
105
+ def _init_weights(self, module):
106
+
107
+ if isinstance(module, nn.Linear):
108
+ std = 0.02
109
+ if hasattr(module, 'NANOGPT_SCALE_INIT'):
110
+ std = (2 * self.config.n_layer) ** -0.5 # 2 times as each layer has attention and MLP
111
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
112
+ if module.bias is not None:
113
+ torch.nn.init.zeros_(module.bias)
114
+ elif isinstance(module, nn.Embedding):
115
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02) # word embedding will be initialised twice
116
+
117
+ def forward(self, idx, target = None):
118
+ # idx of shape (B, T)
119
+ B, T = idx.size()
120
+ assert T <= self.config.block_size, f"Cannot forward sequence of length {T}, block size is only {self.config.block_size}"
121
+ # forward thetoken and position embedding
122
+ pos = torch.arange(0, T, dtype = torch.long, device=idx.device) # (T)
123
+ pos_emb = self.transformer.wpe(pos) # (T, C)
124
+ tok_emb = self.transformer.wte(idx) # (B, T, C)
125
+ x = tok_emb + pos_emb # (B, T, C)
126
+ # forward the block for transformer
127
+ for block in self.transformer.h:
128
+ x = block(x)
129
+ # forward the final layer nor and classifier
130
+ x = self.transformer.ln_f(x)
131
+ logits = self.lm_head(x) # (B, T, vocab_size)
132
+ # compute the loss
133
+ loss = None
134
+ if target is not None:
135
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), target.view(-1))
136
+ return logits, loss
137
+
138
+ @classmethod
139
+ def from_pretrained(cls, model_type):
140
+ """ Loads pretrained GPT2 model from HuggingFace """
141
+ assert model_type in {"gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl"}
142
+ from transformers import GPT2LMHeadModel
143
+ print(f"Loading {model_type} model...")
144
+
145
+ config_args = {
146
+ "gpt2": dict(n_layer = 12, n_head = 12, n_embd = 768), # 124M
147
+ "gpt2-medium": dict(n_layer = 24, n_head = 16, n_embd = 1024), # 350M
148
+ "gpt2-large": dict(n_layer = 36, n_head = 20, n_embd = 1280), # 774M
149
+ "gpt2-xl": dict(n_layer = 48, n_head = 25, n_embd = 1600), # 1558M
150
+ }[model_type]
151
+
152
+ config_args["vocab_size"] = 50257 # always for GPT2 checkpoints
153
+ config_args["block_size"] = 1024 # always for GPT2 checkpoints
154
+
155
+ config = GPTConfig(**config_args)
156
+ model = GPT(config)
157
+ sd = model.state_dict()
158
+ sd_keys = sd.keys()
159
+
160
+ sd_keys = [k for k in sd_keys if not k.endswith(".attn.bias")] # discard this mask
161
+
162
+ # init hugging face model
163
+ model_hf = GPT2LMHeadModel.from_pretrained(model_type)
164
+ sd_hf = model_hf.state_dict()
165
+ sd_keys_hf = sd_hf.keys()
166
+
167
+ # copy while ensuring all of the parameters are aligned and match in names and types
168
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith(".attn.masked_bias")] # ignore these, just a buffer
169
+ sd_keys_hf = [k for k in sd_keys_hf if not k.endswith(".attn.bias")] # same, just the mask (buffer)
170
+ transposed = ['attn.c_attn.weight', 'attn.c_proj.weight', 'mlp.c_fc.weight', 'mlp.c_proj.weight']
171
+
172
+ # basically the openai checkpoints use a "Conv1D" module, but we only want to use a vanilla Linear
173
+ # this means that we have to transpose these weights when we import them
174
+ assert len(sd_keys_hf) == len(sd_keys), f"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}"
175
+ for k in sd_keys_hf:
176
+ if any(k.endswith(w) for w in transposed):
177
+ # special treatment for the Conv1D weights we need to transpose
178
+ assert sd_hf[k].shape[::-1] == sd[k].shape
179
+ with torch.no_grad():
180
+ sd[k].copy_(sd_hf[k].t())
181
+ else:
182
+ # vanilla copy over the other parameters
183
+ assert sd_hf[k].shape == sd[k].shape
184
+ with torch.no_grad():
185
+ sd[k].copy_(sd_hf[k])
186
+
187
+ return model
188
+
189
+ def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):
190
+ # start with all of the candidate parameters
191
+ param_dict = {pn: p for pn, p in self.named_parameters()}
192
+ # filter out those that do not require grad
193
+ param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}
194
+ # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.
195
+ # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.
196
+ decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]
197
+ nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]
198
+ optim_groups = [
199
+ {'params': decay_params, 'weight_decay': weight_decay},
200
+ {'params': nodecay_params, 'weight_decay': 0.0}
201
+ ]
202
+ num_decay_params = sum(p.numel() for p in decay_params)
203
+ num_nodecay_params = sum(p.numel() for p in nodecay_params)
204
+ print(f"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters")
205
+ print(f"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters")
206
+ # Create AdamW optimizer and use the fused version if it is available
207
+ fused_available = 'fused' in inspect.signature(torch.optim.AdamW).parameters
208
+ use_fused = fused_available and device_type == 'cuda'
209
+ extra_args = dict(fused=True) if use_fused else dict()
210
+ optimizer = torch.optim.AdamW(optim_groups, lr=learning_rate, betas=betas, **extra_args)
211
+ print(f"using fused AdamW: {use_fused}")
212
+
213
+ return optimizer
214
+
215
+ @torch.no_grad()
216
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
217
+ """
218
+ Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
219
+ the sequence max_new_tokens times, feeding the predictions back into the model each time.
220
+ Most likely you'll want to make sure to be in model.eval() mode of operation for this.
221
+ """
222
+ for _ in range(max_new_tokens):
223
+ # if the sequence context is growing too long we must crop it at block_size
224
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
225
+ # forward the model to get the logits for the index in the sequence
226
+ logits, _ = self(idx_cond)
227
+ # pluck the logits at the final step and scale by desired temperature
228
+ logits = logits[:, -1, :] / temperature
229
+ # optionally crop the logits to only the top k options
230
+ if top_k is not None:
231
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
232
+ logits[logits < v[:, [-1]]] = -float('Inf')
233
+ # apply softmax to convert logits to (normalized) probabilities
234
+ probs = F.softmax(logits, dim=-1)
235
+ # sample from the distribution
236
+ idx_next = torch.multinomial(probs, num_samples=1)
237
+ # append sampled index to the running sequence and continue
238
+ idx = torch.cat((idx, idx_next), dim=1)
239
+
240
+ return idx
241
+
242
+
saved_model/ckpt.pt CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:5d605ac98cb44df934630528b0b8b37ccabcb3f11034c6762928211fd8edf83f
3
  size 1544198298
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22dd1a5c7d1d2040dd8d15df01c75f69de6cbaba8aff362718cdd4b4e7fa05ff
3
  size 1544198298