Chintan-Shah commited on
Commit
0c70985
·
verified ·
1 Parent(s): 6ec474a

Upload 2 files

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