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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import tiktoken
|
| 6 |
+
import math
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
|
| 9 |
+
class LayerNorm(nn.Module):
|
| 10 |
+
def __init__(self, ndim, bias):
|
| 11 |
+
super().__init__()
|
| 12 |
+
self.weight = nn.Parameter(torch.ones(ndim))
|
| 13 |
+
self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
|
| 14 |
+
def forward(self, x):
|
| 15 |
+
return F.layer_norm(x, self.weight.shape, self.weight, self.bias, 1e-5)
|
| 16 |
+
|
| 17 |
+
class CausalSelfAttention(nn.Module):
|
| 18 |
+
def __init__(self, config):
|
| 19 |
+
super().__init__()
|
| 20 |
+
assert config.n_embd % config.n_head == 0
|
| 21 |
+
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
|
| 22 |
+
self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
|
| 23 |
+
self.attn_dropout = nn.Dropout(config.dropout)
|
| 24 |
+
self.resid_dropout = nn.Dropout(config.dropout)
|
| 25 |
+
self.n_head, self.n_embd = config.n_head, config.n_embd
|
| 26 |
+
self.flash = hasattr(F, 'scaled_dot_product_attention')
|
| 27 |
+
if not self.flash:
|
| 28 |
+
self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
|
| 29 |
+
.view(1, 1, config.block_size, config.block_size))
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
B, T, C = x.size()
|
| 33 |
+
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
|
| 34 |
+
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
| 35 |
+
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
| 36 |
+
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
|
| 37 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=0.0, is_causal=True)
|
| 38 |
+
y = y.transpose(1, 2).contiguous().view(B, T, C)
|
| 39 |
+
return self.resid_dropout(self.c_proj(y))
|
| 40 |
+
|
| 41 |
+
class MLP(nn.Module):
|
| 42 |
+
def __init__(self, config):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
|
| 45 |
+
self.gelu = nn.GELU()
|
| 46 |
+
self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
|
| 47 |
+
self.dropout = nn.Dropout(config.dropout)
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
return self.dropout(self.c_proj(self.gelu(self.c_fc(x))))
|
| 50 |
+
|
| 51 |
+
class Block(nn.Module):
|
| 52 |
+
def __init__(self, config):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.ln1 = LayerNorm(config.n_embd, config.bias)
|
| 55 |
+
self.attn = CausalSelfAttention(config)
|
| 56 |
+
self.ln2 = LayerNorm(config.n_embd, config.bias)
|
| 57 |
+
self.mlp = MLP(config)
|
| 58 |
+
def forward(self, x):
|
| 59 |
+
x = x + self.attn(self.ln1(x))
|
| 60 |
+
x = x + self.mlp(self.ln2(x))
|
| 61 |
+
return x
|
| 62 |
+
|
| 63 |
+
@dataclass
|
| 64 |
+
class GPTConfig:
|
| 65 |
+
block_size: int = 256
|
| 66 |
+
vocab_size: int = 50257
|
| 67 |
+
n_layer: int = 6
|
| 68 |
+
n_head: int = 6
|
| 69 |
+
n_embd: int = 384
|
| 70 |
+
dropout: float = 0.0
|
| 71 |
+
bias: bool = True
|
| 72 |
+
|
| 73 |
+
class GPT(nn.Module):
|
| 74 |
+
def __init__(self, config):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.config = config
|
| 77 |
+
self.transformer = nn.ModuleDict(dict(
|
| 78 |
+
wte = nn.Embedding(config.vocab_size, config.n_embd),
|
| 79 |
+
wpe = nn.Embedding(config.block_size, config.n_embd),
|
| 80 |
+
drop = nn.Dropout(config.dropout),
|
| 81 |
+
h = nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
| 82 |
+
ln_f = LayerNorm(config.n_embd, config.bias),
|
| 83 |
+
))
|
| 84 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 85 |
+
self.transformer.wte.weight = self.lm_head.weight
|
| 86 |
+
self.apply(self._init_weights)
|
| 87 |
+
|
| 88 |
+
def _init_weights(self, module):
|
| 89 |
+
if isinstance(module, nn.Linear):
|
| 90 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 91 |
+
if module.bias is not None:
|
| 92 |
+
torch.nn.init.zeros_(module.bias)
|
| 93 |
+
elif isinstance(module, nn.Embedding):
|
| 94 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 95 |
+
|
| 96 |
+
def forward(self, idx, targets=None):
|
| 97 |
+
device = idx.device
|
| 98 |
+
b, t = idx.size()
|
| 99 |
+
pos = torch.arange(0, t, dtype=torch.long, device=device)
|
| 100 |
+
tok_emb = self.transformer.wte(idx)
|
| 101 |
+
pos_emb = self.transformer.wpe(pos)
|
| 102 |
+
x = self.transformer.drop(tok_emb + pos_emb)
|
| 103 |
+
for block in self.transformer.h:
|
| 104 |
+
x = block(x)
|
| 105 |
+
x = self.transformer.ln_f(x)
|
| 106 |
+
logits = self.lm_head(x[:, [-1], :])
|
| 107 |
+
return logits, None
|
| 108 |
+
|
| 109 |
+
@torch.no_grad()
|
| 110 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
| 111 |
+
for _ in range(max_new_tokens):
|
| 112 |
+
idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
| 113 |
+
logits, _ = self(idx_cond)
|
| 114 |
+
logits = logits[:, -1, :] / temperature
|
| 115 |
+
if top_k is not None:
|
| 116 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
| 117 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
| 118 |
+
probs = F.softmax(logits, dim=-1)
|
| 119 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
| 120 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
| 121 |
+
return idx
|
| 122 |
+
|
| 123 |
+
device = 'cpu'
|
| 124 |
+
enc = tiktoken.get_encoding("gpt2")
|
| 125 |
+
|
| 126 |
+
config = GPTConfig(
|
| 127 |
+
vocab_size=50257,
|
| 128 |
+
block_size=128,
|
| 129 |
+
n_layer=6,
|
| 130 |
+
n_head=6,
|
| 131 |
+
n_embd=384,
|
| 132 |
+
dropout=0.1,
|
| 133 |
+
bias=True
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
model = GPT(config)
|
| 137 |
+
model.load_state_dict(torch.load('C:/Users/91981/OneDrive/Desktop/ai project/My-Project-Folder/best_model_params.pt', map_location=device))
|
| 138 |
+
model.eval()
|
| 139 |
+
model.to(device)
|
| 140 |
+
|
| 141 |
+
def generate_story(prompt, max_new_tokens=100, temperature=0.8):
|
| 142 |
+
start_ids = enc.encode_ordinary(prompt)
|
| 143 |
+
x = torch.tensor(start_ids, dtype=torch.long, device=device)[None, ...]
|
| 144 |
+
y = model.generate(x, max_new_tokens=int(max_new_tokens), temperature=temperature, top_k=200)
|
| 145 |
+
return enc.decode(y[0].tolist())
|
| 146 |
+
|
| 147 |
+
article = """
|
| 148 |
+
<div style="text-align: center; margin-top: 20px;">
|
| 149 |
+
<p>
|
| 150 |
+
This model was trained on the <strong>TinyStories dataset</strong> and uses a GPT-style architecture to generate new stories from a starting prompt.
|
| 151 |
+
</p>
|
| 152 |
+
<p>
|
| 153 |
+
<strong>Created by:</strong> <a href="https://www.linkedin.com/in/harshitchawla4705/" target="_blank">Harshit Chawla</a>
|
| 154 |
+
</p>
|
| 155 |
+
<hr>
|
| 156 |
+
<h4>Relevant Research Papers</h4>
|
| 157 |
+
<p>
|
| 158 |
+
<a href="https://arxiv.org/abs/2305.07759" target="_blank">TinyStories: How Small Can Language Models Be and Still Speak Coherent English?</a><br>
|
| 159 |
+
<a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf" target="_blank">Language Models are Unsupervised Multitask Learners (GPT-2)</a><br>
|
| 160 |
+
<a href="https://arxiv.org/abs/1706.03762" target="_blank">Attention Is All You Need</a>
|
| 161 |
+
</p>
|
| 162 |
+
</div>
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
iface = gr.Interface(
|
| 166 |
+
fn=generate_story,
|
| 167 |
+
inputs=[
|
| 168 |
+
gr.Textbox(lines=3, placeholder="E.g., Once upon a time, there was a little red fox..."),
|
| 169 |
+
gr.Slider(minimum=20, maximum=500, step=10, value=150, label="Number of Words to Generate"),
|
| 170 |
+
gr.Slider(minimum=0.1, maximum=1.5, step=0.1, value=0.8, label="Creativity (Temperature)")
|
| 171 |
+
],
|
| 172 |
+
outputs=gr.Textbox(label="Generated Story", lines=20),
|
| 173 |
+
title="📖 AI Story Generator",
|
| 174 |
+
description="Enter a sentence to start a story and see what the AI writes next! Adjust the sliders to control the length and creativity of the story.",
|
| 175 |
+
article=article,
|
| 176 |
+
theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky"),
|
| 177 |
+
allow_flagging="never",
|
| 178 |
+
examples=[
|
| 179 |
+
["Once upon a time, a curious cat named Whiskers", 150, 0.7],
|
| 180 |
+
["In a land filled with candy, a brave gingerbread man", 200, 0.9],
|
| 181 |
+
["A lonely robot sat on a hill, looking at the stars", 100, 0.5]
|
| 182 |
+
]
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
if __name__ == "__main__":
|
| 186 |
+
iface.launch()
|
best_model_params.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c28b0a004e6c7a01156e82f03a7140903ac75188f74ff81cf28f1bfe7fca7459
|
| 3 |
+
size 120011315
|