Upload 4 files
Browse files- app.py +127 -0
- nano_gpt_inferencing.py +197 -0
- nano_gpt_model.pth +3 -0
- requirements.txt +2 -0
app.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
# In[2]:
|
5 |
+
|
6 |
+
|
7 |
+
import gradio as gr
|
8 |
+
import torch
|
9 |
+
from torch import nn
|
10 |
+
from torch.nn import functional as F
|
11 |
+
from nano_gpt_inferencing import generate_paragraph
|
12 |
+
|
13 |
+
|
14 |
+
HTML_TEMPLATE = """
|
15 |
+
<style>
|
16 |
+
body {
|
17 |
+
font-family: 'Arial', sans-serif;
|
18 |
+
background: #3498db; /* Blue background color */
|
19 |
+
margin: 0;
|
20 |
+
padding: 0;
|
21 |
+
}
|
22 |
+
|
23 |
+
#app-header {
|
24 |
+
text-align: center;
|
25 |
+
background: rgba(255, 255, 255, 0.7); /* Semi-transparent white */
|
26 |
+
padding: 20px;
|
27 |
+
border-radius: 10px;
|
28 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
29 |
+
position: relative; /* To position the artifacts */
|
30 |
+
margin: 30px auto;
|
31 |
+
max-width: 600px;
|
32 |
+
}
|
33 |
+
|
34 |
+
#app-header h1 {
|
35 |
+
color: #FF0000;
|
36 |
+
font-size: 2.5em;
|
37 |
+
margin-bottom: 10px;
|
38 |
+
}
|
39 |
+
|
40 |
+
.header-images {
|
41 |
+
display: flex;
|
42 |
+
justify-content: center;
|
43 |
+
align-items: center;
|
44 |
+
margin: 20px 0;
|
45 |
+
}
|
46 |
+
|
47 |
+
.header-image {
|
48 |
+
width: 100px;
|
49 |
+
height: 100px;
|
50 |
+
margin: 0 10px;
|
51 |
+
background: #fff;
|
52 |
+
border-radius: 50%;
|
53 |
+
display: flex;
|
54 |
+
justify-content: center;
|
55 |
+
align-items: center;
|
56 |
+
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
|
57 |
+
}
|
58 |
+
|
59 |
+
.header-image img {
|
60 |
+
max-width: 80px;
|
61 |
+
max-height: 80px;
|
62 |
+
border-radius: 50%;
|
63 |
+
}
|
64 |
+
|
65 |
+
.concept-description {
|
66 |
+
position: absolute;
|
67 |
+
bottom: -30px;
|
68 |
+
left: 50%;
|
69 |
+
transform: translateX(-50%);
|
70 |
+
background-color: #4CAF50;
|
71 |
+
color: white;
|
72 |
+
padding: 5px 10px;
|
73 |
+
border-radius: 5px;
|
74 |
+
opacity: 0;
|
75 |
+
transition: opacity 0.3s;
|
76 |
+
}
|
77 |
+
|
78 |
+
.concept:hover .concept-description {
|
79 |
+
opacity: 1;
|
80 |
+
}
|
81 |
+
</style>
|
82 |
+
</head>
|
83 |
+
<body>
|
84 |
+
<div id="app-header">
|
85 |
+
<!-- Header Images -->
|
86 |
+
<div class="header-images">
|
87 |
+
<div class="header-image">
|
88 |
+
<img src="https://github.com/nkanungo/ERAS20/blob/main/images/ss1.jpg?raw=true" alt="Image 1">
|
89 |
+
</div>
|
90 |
+
<div class="header-image">
|
91 |
+
<img src="https://github.com/nkanungo/ERAS20/blob/main/images/ss1.jpg?raw=true" alt="Image 2">
|
92 |
+
</div>
|
93 |
+
</div>
|
94 |
+
<!-- Content -->
|
95 |
+
<h1>Paragraph Auto Completion like Shakespeare </h1>
|
96 |
+
<p>Generate dialogue using the intellignece from Shakespeare Dataset .</p>
|
97 |
+
<p>Model: GPT, Dataset: Tiny Shakespeare, Token limit: User input ,Input Text: User input.</p>
|
98 |
+
</div>
|
99 |
+
"""
|
100 |
+
with gr.Blocks(theme=gr.themes.Glass()) as interface:
|
101 |
+
gr.HTML(value=HTML_TEMPLATE, show_label=False)
|
102 |
+
|
103 |
+
with gr.Row(scale=1):
|
104 |
+
|
105 |
+
|
106 |
+
inputs = [
|
107 |
+
gr.Textbox(label="Input Text Prompt"),
|
108 |
+
gr.Textbox(label="Token Limit")
|
109 |
+
]
|
110 |
+
outputs = gr.Textbox(
|
111 |
+
label="Generated Paragraph"
|
112 |
+
)
|
113 |
+
|
114 |
+
|
115 |
+
with gr.Column(scale=1):
|
116 |
+
button = gr.Button("Generate")
|
117 |
+
button.click(generate_paragraph, inputs=inputs, outputs=outputs)
|
118 |
+
|
119 |
+
if __name__ == "__main__":
|
120 |
+
interface.launch(enable_queue=True)
|
121 |
+
|
122 |
+
|
123 |
+
# In[ ]:
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
|
nano_gpt_inferencing.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
# coding: utf-8
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
from torch.nn import functional as F
|
7 |
+
|
8 |
+
# hyperparameters
|
9 |
+
batch_size = 16 # how many independent sequences will we process in parallel?
|
10 |
+
block_size = 64 # what is the maximum context length for predictions?
|
11 |
+
max_iters = 20000
|
12 |
+
eval_interval = 100
|
13 |
+
learning_rate = 1e-3
|
14 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
15 |
+
eval_iters = 200
|
16 |
+
n_embd = 64
|
17 |
+
n_head = 8
|
18 |
+
n_layer = 8
|
19 |
+
dropout = 0.2
|
20 |
+
# ------------
|
21 |
+
|
22 |
+
torch.manual_seed(1337)
|
23 |
+
|
24 |
+
# wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
|
25 |
+
with open('input.txt', 'r', encoding='utf-8') as f:
|
26 |
+
text = f.read()
|
27 |
+
|
28 |
+
# here are all the unique characters that occur in this text
|
29 |
+
chars = sorted(list(set(text)))
|
30 |
+
vocab_size = len(chars)
|
31 |
+
# create a mapping from characters to integers
|
32 |
+
stoi = { ch:i for i,ch in enumerate(chars) }
|
33 |
+
itos = { i:ch for i,ch in enumerate(chars) }
|
34 |
+
encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
|
35 |
+
decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
|
36 |
+
|
37 |
+
# Train and test splits
|
38 |
+
data = torch.tensor(encode(text), dtype=torch.long)
|
39 |
+
n = int(0.9*len(data)) # first 90% will be train, rest val
|
40 |
+
train_data = data[:n]
|
41 |
+
val_data = data[n:]
|
42 |
+
|
43 |
+
# data loading
|
44 |
+
def get_batch(split):
|
45 |
+
# generate a small batch of data of inputs x and targets y
|
46 |
+
data = train_data if split == 'train' else val_data
|
47 |
+
ix = torch.randint(len(data) - block_size, (batch_size,))
|
48 |
+
x = torch.stack([data[i:i+block_size] for i in ix])
|
49 |
+
y = torch.stack([data[i+1:i+block_size+1] for i in ix])
|
50 |
+
x, y = x.to(device), y.to(device)
|
51 |
+
return x, y
|
52 |
+
|
53 |
+
@torch.no_grad()
|
54 |
+
def estimate_loss():
|
55 |
+
out = {}
|
56 |
+
model.eval()
|
57 |
+
for split in ['train', 'val']:
|
58 |
+
losses = torch.zeros(eval_iters)
|
59 |
+
for k in range(eval_iters):
|
60 |
+
X, Y = get_batch(split)
|
61 |
+
logits, loss = model(X, Y)
|
62 |
+
losses[k] = loss.item()
|
63 |
+
out[split] = losses.mean()
|
64 |
+
model.train()
|
65 |
+
return out
|
66 |
+
|
67 |
+
class Head(nn.Module):
|
68 |
+
""" one head of self-attention """
|
69 |
+
|
70 |
+
def __init__(self, head_size):
|
71 |
+
super().__init__()
|
72 |
+
self.key = nn.Linear(n_embd, head_size, bias=False)
|
73 |
+
self.query = nn.Linear(n_embd, head_size, bias=False)
|
74 |
+
self.value = nn.Linear(n_embd, head_size, bias=False)
|
75 |
+
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
|
76 |
+
|
77 |
+
self.dropout = nn.Dropout(dropout)
|
78 |
+
|
79 |
+
def forward(self, x):
|
80 |
+
B,T,C = x.shape
|
81 |
+
k = self.key(x) # (B,T,C)
|
82 |
+
q = self.query(x) # (B,T,C)
|
83 |
+
# compute attention scores ("affinities")
|
84 |
+
wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
|
85 |
+
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
|
86 |
+
wei = F.softmax(wei, dim=-1) # (B, T, T)
|
87 |
+
wei = self.dropout(wei)
|
88 |
+
# perform the weighted aggregation of the values
|
89 |
+
v = self.value(x) # (B,T,C)
|
90 |
+
out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
|
91 |
+
return out
|
92 |
+
|
93 |
+
class MultiHeadAttention(nn.Module):
|
94 |
+
""" multiple heads of self-attention in parallel """
|
95 |
+
|
96 |
+
def __init__(self, num_heads, head_size):
|
97 |
+
super().__init__()
|
98 |
+
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
|
99 |
+
self.proj = nn.Linear(n_embd, n_embd)
|
100 |
+
self.dropout = nn.Dropout(dropout)
|
101 |
+
|
102 |
+
def forward(self, x):
|
103 |
+
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
104 |
+
out = self.dropout(self.proj(out))
|
105 |
+
return out
|
106 |
+
|
107 |
+
class FeedFoward(nn.Module):
|
108 |
+
""" a simple linear layer followed by a non-linearity """
|
109 |
+
|
110 |
+
def __init__(self, n_embd):
|
111 |
+
super().__init__()
|
112 |
+
self.net = nn.Sequential(
|
113 |
+
nn.Linear(n_embd, 4 * n_embd),
|
114 |
+
nn.ReLU(),
|
115 |
+
nn.Linear(4 * n_embd, n_embd),
|
116 |
+
nn.Dropout(dropout),
|
117 |
+
)
|
118 |
+
|
119 |
+
def forward(self, x):
|
120 |
+
return self.net(x)
|
121 |
+
|
122 |
+
class Block(nn.Module):
|
123 |
+
""" Transformer block: communication followed by computation """
|
124 |
+
|
125 |
+
def __init__(self, n_embd, n_head):
|
126 |
+
# n_embd: embedding dimension, n_head: the number of heads we'd like
|
127 |
+
super().__init__()
|
128 |
+
head_size = n_embd // n_head
|
129 |
+
self.sa = MultiHeadAttention(n_head, head_size)
|
130 |
+
self.ffwd = FeedFoward(n_embd)
|
131 |
+
self.ln1 = nn.LayerNorm(n_embd)
|
132 |
+
self.ln2 = nn.LayerNorm(n_embd)
|
133 |
+
|
134 |
+
def forward(self, x):
|
135 |
+
x = x + self.sa(self.ln1(x))
|
136 |
+
x = x + self.ffwd(self.ln2(x))
|
137 |
+
return x
|
138 |
+
|
139 |
+
# super simple bigram model
|
140 |
+
class BigramLanguageModel(nn.Module):
|
141 |
+
|
142 |
+
def __init__(self):
|
143 |
+
super().__init__()
|
144 |
+
# each token directly reads off the logits for the next token from a lookup table
|
145 |
+
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
|
146 |
+
self.position_embedding_table = nn.Embedding(block_size, n_embd)
|
147 |
+
self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
|
148 |
+
self.ln_f = nn.LayerNorm(n_embd) # final layer norm
|
149 |
+
self.lm_head = nn.Linear(n_embd, vocab_size)
|
150 |
+
|
151 |
+
def forward(self, idx, targets=None):
|
152 |
+
B, T = idx.shape
|
153 |
+
|
154 |
+
# idx and targets are both (B,T) tensor of integers
|
155 |
+
tok_emb = self.token_embedding_table(idx) # (B,T,C)
|
156 |
+
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
|
157 |
+
x = tok_emb + pos_emb # (B,T,C)
|
158 |
+
x = self.blocks(x) # (B,T,C)
|
159 |
+
x = self.ln_f(x) # (B,T,C)
|
160 |
+
logits = self.lm_head(x) # (B,T,vocab_size)
|
161 |
+
|
162 |
+
if targets is None:
|
163 |
+
loss = None
|
164 |
+
else:
|
165 |
+
B, T, C = logits.shape
|
166 |
+
logits = logits.view(B*T, C)
|
167 |
+
targets = targets.view(B*T)
|
168 |
+
loss = F.cross_entropy(logits, targets)
|
169 |
+
|
170 |
+
return logits, loss
|
171 |
+
|
172 |
+
def generate(self, idx, max_new_tokens):
|
173 |
+
# idx is (B, T) array of indices in the current context
|
174 |
+
for _ in range(max_new_tokens):
|
175 |
+
# crop idx to the last block_size tokens
|
176 |
+
idx_cond = idx[:, -block_size:]
|
177 |
+
# get the predictions
|
178 |
+
logits, loss = self(idx_cond)
|
179 |
+
# focus only on the last time step
|
180 |
+
logits = logits[:, -1, :] # becomes (B, C)
|
181 |
+
# apply softmax to get probabilities
|
182 |
+
probs = F.softmax(logits, dim=-1) # (B, C)
|
183 |
+
# sample from the distribution
|
184 |
+
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
|
185 |
+
# append sampled index to the running sequence
|
186 |
+
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
|
187 |
+
return idx
|
188 |
+
|
189 |
+
|
190 |
+
def generate_paragraph(initial_text,max_token):
|
191 |
+
model = BigramLanguageModel()
|
192 |
+
model.load_state_dict(torch.load('nano_gpt_model.pth'))
|
193 |
+
final_model = model.to(device)
|
194 |
+
encoded_text= encode(initial_text)
|
195 |
+
encoded_text_tensor = torch.tensor(encoded_text).view(1, -1)
|
196 |
+
return decode(final_model.generate(encoded_text_tensor, max_new_tokens=int(max_token))[0].tolist())
|
197 |
+
|
nano_gpt_model.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2007cc588e3cb9df071ee89a38153c9f38857f7da86c436cda60d5ce3c6d09d7
|
3 |
+
size 2793298
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
torch
|