godsofheaven commited on
Commit
a3bb43f
·
verified ·
1 Parent(s): caaf9df

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +366 -0
app.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shakespeare Text Generator - Hugging Face Gradio App
3
+ Trained GPT-2 model (124M params)
4
+ """
5
+
6
+ import gradio as gr
7
+ import torch
8
+ import tiktoken
9
+ import os
10
+ from dataclasses import dataclass
11
+
12
+
13
+ # GPT Model Architecture
14
+ @dataclass
15
+ class GPTConfig:
16
+ block_size: int = 1024
17
+ vocab_size: int = 50257
18
+ n_layer: int = 12
19
+ n_head: int = 12
20
+ n_embd: int = 768
21
+ dropout: float = 0.0
22
+ bias: bool = True
23
+
24
+
25
+ import torch.nn as nn
26
+ from torch.nn import functional as F
27
+ import math
28
+
29
+
30
+ class CausalSelfAttention(nn.Module):
31
+ def __init__(self, config):
32
+ super().__init__()
33
+ assert config.n_embd % config.n_head == 0
34
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
35
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
36
+ self.attn_dropout = nn.Dropout(config.dropout)
37
+ self.resid_dropout = nn.Dropout(config.dropout)
38
+ self.n_head = config.n_head
39
+ self.n_embd = config.n_embd
40
+ self.dropout = config.dropout
41
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
42
+ .view(1, 1, config.block_size, config.block_size))
43
+ self.c_proj.NANOGPT_SCALE_INIT = 1
44
+
45
+ def forward(self, x):
46
+ B, T, C = x.size()
47
+ qkv = self.c_attn(x)
48
+ q, k, v = qkv.split(self.n_embd, dim=2)
49
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
50
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
51
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
52
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
53
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
54
+ att = F.softmax(att, dim=-1)
55
+ att = self.attn_dropout(att)
56
+ y = att @ v
57
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
58
+ y = self.resid_dropout(self.c_proj(y))
59
+ return y
60
+
61
+
62
+ class MLP(nn.Module):
63
+ def __init__(self, config):
64
+ super().__init__()
65
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
66
+ self.gelu = nn.GELU(approximate='tanh')
67
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
68
+ self.dropout = nn.Dropout(config.dropout)
69
+ self.c_proj.NANOGPT_SCALE_INIT = 1
70
+
71
+ def forward(self, x):
72
+ x = self.c_fc(x)
73
+ x = self.gelu(x)
74
+ x = self.c_proj(x)
75
+ x = self.dropout(x)
76
+ return x
77
+
78
+
79
+ class Block(nn.Module):
80
+ def __init__(self, config):
81
+ super().__init__()
82
+ self.ln_1 = nn.LayerNorm(config.n_embd)
83
+ self.attn = CausalSelfAttention(config)
84
+ self.ln_2 = nn.LayerNorm(config.n_embd)
85
+ self.mlp = MLP(config)
86
+
87
+ def forward(self, x):
88
+ x = x + self.attn(self.ln_1(x))
89
+ x = x + self.mlp(self.ln_2(x))
90
+ return x
91
+
92
+
93
+ class GPT(nn.Module):
94
+ def __init__(self, config):
95
+ super().__init__()
96
+ self.config = config
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
+ drop=nn.Dropout(config.dropout),
101
+ h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
102
+ ln_f=nn.LayerNorm(config.n_embd),
103
+ ))
104
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
105
+ self.transformer.wte.weight = self.lm_head.weight
106
+ self.apply(self._init_weights)
107
+
108
+ def _init_weights(self, module):
109
+ if isinstance(module, nn.Linear):
110
+ std = 0.02
111
+ if hasattr(module, 'NANOGPT_SCALE_INIT'):
112
+ std *= (2 * self.config.n_layer) ** -0.5
113
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
114
+ if module.bias is not None:
115
+ torch.nn.init.zeros_(module.bias)
116
+ elif isinstance(module, nn.Embedding):
117
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
118
+
119
+ def forward(self, idx, targets=None):
120
+ device = idx.device
121
+ b, t = idx.size()
122
+ assert t <= self.config.block_size
123
+ pos = torch.arange(0, t, dtype=torch.long, device=device)
124
+ pos_emb = self.transformer.wpe(pos)
125
+ tok_emb = self.transformer.wte(idx)
126
+ x = self.transformer.drop(tok_emb + pos_emb)
127
+ for block in self.transformer.h:
128
+ x = block(x)
129
+ x = self.transformer.ln_f(x)
130
+ if targets is not None:
131
+ logits = self.lm_head(x)
132
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
133
+ else:
134
+ logits = self.lm_head(x[:, [-1], :])
135
+ loss = None
136
+ return logits, loss
137
+
138
+ @torch.no_grad()
139
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
140
+ for _ in range(max_new_tokens):
141
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
142
+ logits, _ = self(idx_cond)
143
+ logits = logits[:, -1, :] / temperature
144
+ if top_k is not None:
145
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
146
+ logits[logits < v[:, [-1]]] = -float('Inf')
147
+ probs = F.softmax(logits, dim=-1)
148
+ idx_next = torch.multinomial(probs, num_samples=1)
149
+ idx = torch.cat((idx, idx_next), dim=1)
150
+ return idx
151
+
152
+
153
+ # Load model
154
+ print("Loading model...")
155
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
156
+ config = GPTConfig()
157
+ model = GPT(config)
158
+
159
+ # Load checkpoint
160
+ checkpoint_path = "model_quantized.pt"
161
+ if os.path.exists(checkpoint_path):
162
+ checkpoint = torch.load(checkpoint_path, map_location=device)
163
+ model.load_state_dict(checkpoint['model_state_dict'])
164
+ print(f"✓ Loaded quantized model from {checkpoint_path}")
165
+ print(f" Training loss: {checkpoint.get('loss', 'N/A')}")
166
+ print(f" Model size: 330MB (FP16 quantized)")
167
+ else:
168
+ print("⚠️ Checkpoint not found. Please upload 'model_quantized.pt'")
169
+
170
+ model.to(device)
171
+ model.eval()
172
+ print(f"✓ Model ready on {device}")
173
+
174
+ # Tokenizer
175
+ enc = tiktoken.get_encoding('gpt2')
176
+
177
+
178
+ # ---- Derived Stats (dynamic, for UI) ----
179
+ try:
180
+ model_params = sum(p.numel() for p in model.parameters())
181
+ model_params_m = model_params / 1e6
182
+ except Exception:
183
+ model_params = None
184
+ model_params_m = None
185
+
186
+ training_loss = None
187
+ training_step = None
188
+ if 'checkpoint' in locals():
189
+ training_loss = checkpoint.get('loss', None)
190
+ training_step = checkpoint.get('step', None)
191
+
192
+ def build_stats_md() -> str:
193
+ params_line = f"- **Parameters**: {model_params:,} ({model_params_m:.0f}M)" if model_params is not None else "- **Parameters**: 124M"
194
+ loss_line = f"- **Training Loss**: {training_loss:.6f}" if isinstance(training_loss, (float, int)) else "- **Training Loss**: N/A"
195
+ step_line = f"- **Training Step**: {training_step}" if training_step is not None else "- **Training Step**: N/A"
196
+ return f"""
197
+ ### 📊 Model Details
198
+ {params_line}
199
+ - **Architecture**: GPT-2 (Decoder-only Transformer)
200
+ {loss_line}
201
+ {step_line}
202
+ - **Model Format**: FP16 quantized (≈330MB)
203
+ - **Device**: {device.upper()}
204
+ """.strip()
205
+
206
+
207
+ def generate_text(prompt, max_tokens=100, temperature=0.8, top_k=50):
208
+ """Generate text from a prompt"""
209
+
210
+ if not prompt:
211
+ return "⚠️ Please enter a prompt!"
212
+
213
+ try:
214
+ # Tokenize
215
+ tokens = enc.encode(prompt)
216
+ tokens = torch.tensor(tokens, dtype=torch.long).unsqueeze(0).to(device)
217
+
218
+ # Generate
219
+ with torch.no_grad():
220
+ generated = model.generate(
221
+ tokens,
222
+ max_new_tokens=max_tokens,
223
+ temperature=temperature,
224
+ top_k=top_k if (top_k and int(top_k) > 0) else None
225
+ )
226
+
227
+ # Decode
228
+ generated_text = enc.decode(generated[0].tolist())
229
+
230
+ return generated_text
231
+
232
+ except Exception as e:
233
+ return f"❌ Error: {str(e)}"
234
+
235
+
236
+ # Example prompts
237
+ examples = [
238
+ ["First Citizen:", 150, 0.8, 50],
239
+ ["ROMEO:", 150, 0.8, 50],
240
+ ["To be, or not to be,", 200, 0.7, 40],
241
+ ["What light through yonder window breaks?", 150, 0.8, 50],
242
+ ["Friends, Romans, countrymen,", 150, 0.8, 50],
243
+ ]
244
+
245
+
246
+ # Gradio Interface with Teal Theme
247
+ with gr.Blocks(
248
+ title="Shakespeare Text Generator",
249
+ theme=gr.themes.Soft(
250
+ primary_hue="teal",
251
+ secondary_hue="cyan",
252
+ neutral_hue="slate"
253
+ ),
254
+ css="""
255
+ .gradio-container {
256
+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
257
+ }
258
+ .gr-button-primary {
259
+ background: linear-gradient(135deg, #14b8a6 0%, #0d9488 100%) !important;
260
+ border: none !important;
261
+ color: white !important;
262
+ font-weight: 600 !important;
263
+ }
264
+ .gr-button-primary:hover {
265
+ background: linear-gradient(135deg, #0d9488 0%, #0f766e 100%) !important;
266
+ transform: translateY(-1px);
267
+ box-shadow: 0 4px 12px rgba(20, 184, 166, 0.3) !important;
268
+ }
269
+ h1 {
270
+ color: #0f766e !important;
271
+ text-align: center;
272
+ }
273
+ .badge {
274
+ display: inline-block;
275
+ padding: 6px 10px;
276
+ margin: 4px 6px 0 0;
277
+ border-radius: 8px;
278
+ background: #ecfeff;
279
+ color: #0f766e;
280
+ font-size: 12px;
281
+ border: 1px solid #ccfbf1;
282
+ }
283
+ """
284
+ ) as demo:
285
+ gr.Markdown(f"""
286
+ # 🎭 Shakespeare Text Generator
287
+
288
+ <div>
289
+ <span class="badge">Architecture: GPT-2</span>
290
+ <span class="badge">Device: {device.upper()}</span>
291
+ <span class="badge">Quantized: FP16</span>
292
+ <span class="badge">Params: {int(model_params_m):d}M</span>
293
+ </div>
294
+
295
+ Enter a Shakespearean prompt and watch the AI continue the text!
296
+ """)
297
+
298
+ with gr.Row():
299
+ with gr.Column(scale=2):
300
+ prompt_input = gr.Textbox(
301
+ label="Prompt",
302
+ placeholder="Enter a Shakespearean prompt (e.g., 'First Citizen:', 'ROMEO:', 'To be, or not to be,')",
303
+ lines=3
304
+ )
305
+
306
+ with gr.Accordion("Advanced Settings", open=False):
307
+ with gr.Row():
308
+ max_tokens = gr.Slider(
309
+ minimum=50,
310
+ maximum=600,
311
+ value=150,
312
+ step=10,
313
+ label="Max Tokens"
314
+ )
315
+ temperature = gr.Slider(
316
+ minimum=0.5,
317
+ maximum=1.5,
318
+ value=0.8,
319
+ step=0.1,
320
+ label="Temperature (creativity)"
321
+ )
322
+ top_k = gr.Slider(
323
+ minimum=0,
324
+ maximum=100,
325
+ value=50,
326
+ step=10,
327
+ label="Top-K (diversity) (0 disables)"
328
+ )
329
+
330
+ generate_btn = gr.Button("✨ Generate Shakespeare", variant="primary", size="lg")
331
+
332
+ with gr.Column(scale=2):
333
+ output_text = gr.Textbox(
334
+ label="Generated Text",
335
+ lines=15,
336
+ show_copy_button=True
337
+ )
338
+
339
+ gr.Markdown(build_stats_md())
340
+
341
+ gr.Markdown("""
342
+ ### 💡 Tips:
343
+ - **Temperature**: Lower (0.5-0.7) = more focused, Higher (0.9-1.2) = more creative
344
+ - **Top-K**: Controls vocabulary diversity (40-60 recommended)
345
+ - **Prompts**: Try character names (ROMEO:, JULIET:) or famous phrases
346
+ """)
347
+
348
+ gr.Examples(
349
+ examples=examples,
350
+ inputs=[prompt_input, max_tokens, temperature, top_k],
351
+ label="Example Prompts"
352
+ )
353
+
354
+ gr.Markdown(build_stats_md())
355
+
356
+ # Connect button
357
+ generate_btn.click(
358
+ fn=generate_text,
359
+ inputs=[prompt_input, max_tokens, temperature, top_k],
360
+ outputs=output_text
361
+ )
362
+
363
+
364
+ if __name__ == "__main__":
365
+ demo.launch()
366
+