kalekarnn commited on
Commit
c6746f5
·
verified ·
1 Parent(s): b7ee99a

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +300 -0
  2. input.txt +0 -0
  3. requirements.txt +6 -0
  4. trained_model_quantized.pt +3 -0
app.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+ import tiktoken
6
+ import sys
7
+ import os
8
+ import logging
9
+ import warnings
10
+ from dataclasses import dataclass
11
+ import math
12
+
13
+ class MLP(nn.Module):
14
+
15
+ def __init__(self, config):
16
+ super().__init__()
17
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd)
18
+ self.gelu = nn.GELU(approximate='tanh')
19
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd)
20
+ self.c_proj.NANOGPT_SCALE_INIT = 1
21
+
22
+ def forward(self, x):
23
+ x = self.c_fc(x)
24
+ x = self.gelu(x)
25
+ x = self.c_proj(x)
26
+ return x
27
+
28
+
29
+ class CausalSelfAttention(nn.Module):
30
+
31
+ def __init__(self, config):
32
+ super().__init__()
33
+ assert config.n_embd % config.n_head == 0
34
+ # key, query, value projections for all heads, but in a batch
35
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd)
36
+ # output projection
37
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd)
38
+ self.c_proj.NANGPT_SCALE_INIT = 1
39
+ # regularization
40
+ self.n_head = config.n_head
41
+ self.n_embd = config.n_embd
42
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size)).view(1, 1, config.block_size, config.block_size))
43
+
44
+ def forward(self, x):
45
+ B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
46
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
47
+ # nh is "number of heads", hs is "head size", and C (number of channels) = nh * hs
48
+ # e.g. in GPT-2 (124M), n_head=12, hs=64, so nh*hs=C=768 channels in the Transformer
49
+ qkv = self.c_attn(x)
50
+ q, k, v = qkv.split(self.n_embd, dim=2)
51
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
52
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
53
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) # (B, nh, T, hs)
54
+
55
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
56
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
57
+ att = F.softmax(att, dim=-1)
58
+ y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)
59
+
60
+ y = y.transpose(1, 2).contiguous().view(B, T, C) # re-assemble all head outputs side by side
61
+ # output projection
62
+ y = self.c_proj(y)
63
+ return y
64
+
65
+
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
+ # Configure logging and warnings
197
+ logging.getLogger('streamlit').setLevel(logging.ERROR)
198
+ warnings.filterwarnings('ignore', message='.*torch.classes.*')
199
+ warnings.filterwarnings('ignore', category=FutureWarning)
200
+
201
+ # Add the project root to Python path
202
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
203
+
204
+
205
+
206
+ @st.cache_resource
207
+ def load_model():
208
+ device = "cpu"
209
+ config = GPTConfig()
210
+ model = GPT(config)
211
+
212
+ # Load the trained weights from root directory
213
+ checkpoint = torch.load('trained_model_quantized.pt', map_location=device, weights_only=True)
214
+
215
+ # Handle pruned weights
216
+ state_dict = checkpoint['model_state_dict']
217
+ new_state_dict = {}
218
+
219
+ for key in model.state_dict().keys():
220
+ if key.endswith('.weight'):
221
+ # Check if this is a pruned weight
222
+ orig_key = key[:-7] + '.weight_orig' if key.endswith('.weight') else key
223
+ mask_key = key[:-7] + '.weight_mask' if key.endswith('.weight') else key
224
+
225
+ if orig_key in state_dict and mask_key in state_dict:
226
+ # Reconstruct the pruned weight
227
+ new_state_dict[key] = state_dict[orig_key] * state_dict[mask_key]
228
+ else:
229
+ # Use the weight as is
230
+ new_state_dict[key] = state_dict[key] if key in state_dict else model.state_dict()[key]
231
+ else:
232
+ # Copy non-weight parameters as is
233
+ new_state_dict[key] = state_dict[key] if key in state_dict else model.state_dict()[key]
234
+
235
+ # Load the processed state dict
236
+ model.load_state_dict(new_state_dict)
237
+
238
+ # Convert back to float32 for inference
239
+ model = model.float()
240
+ model.to(device)
241
+ model.eval()
242
+
243
+ return model, device
244
+
245
+ def generate_text(model, prompt, max_length=100, num_return_sequences=1, device='cpu'):
246
+ tokenizer = tiktoken.get_encoding('gpt2')
247
+ input_tokens = tokenizer.encode(prompt)
248
+ x = torch.tensor(input_tokens).unsqueeze(0).repeat(num_return_sequences, 1)
249
+ x = x.to(device)
250
+
251
+ # Calculate final length (input length + requested additional tokens)
252
+ input_length = x.size(1)
253
+ target_length = input_length + max_length
254
+
255
+ # Generate text
256
+ with torch.no_grad():
257
+ while x.size(1) < target_length:
258
+ logits = model(x)[0]
259
+ next_token_logits = logits[:, -1, :]
260
+ probs = torch.softmax(next_token_logits, dim=-1)
261
+ next_token = torch.multinomial(probs, num_samples=1)
262
+ x = torch.cat((x, next_token), dim=1)
263
+
264
+ # Print token information once before generating sequences
265
+ st.text(f"Size of Input tokens: {input_length}, Additional tokens to be predicted: {max_length}, Total tokens to be generated: {x.size(1)}")
266
+
267
+ # Decode generated sequences
268
+ generated_texts = []
269
+ for i in range(num_return_sequences):
270
+ tokens = x[i].tolist()
271
+ text = tokenizer.decode(tokens)
272
+ generated_texts.append(text)
273
+
274
+ return generated_texts
275
+
276
+ # Streamlit UI
277
+ st.title("GPT Text Generator")
278
+
279
+ # Load model
280
+ model, device = load_model()
281
+
282
+ # Input form
283
+ prompt = st.text_area("Enter your prompt:", "Once upon a time")
284
+ max_length = st.slider("Predict additional text of length:", min_value=1, max_value=50, value=5)
285
+ num_sequences = st.slider("Number of sequences to generate:", 1, 5, 1)
286
+
287
+ if st.button("Generate"):
288
+ with st.spinner("Generating text..."):
289
+ generated_texts = generate_text(
290
+ model=model,
291
+ prompt=prompt,
292
+ max_length=max_length,
293
+ num_return_sequences=num_sequences,
294
+ device=device
295
+ )
296
+
297
+ # Display results
298
+ for i, text in enumerate(generated_texts, 1):
299
+ st.write(f"\nSequence {i}:")
300
+ st.write(text)
input.txt ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ tiktoken
4
+ torchsummary
5
+ gradio
6
+ streamlit
trained_model_quantized.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e3d71eeb703354e72af3b0205521e19e34d59fbc166bada1c5136a95fac0881e
3
+ size 548146590