dusaurabh commited on
Commit
476ebeb
1 Parent(s): 74eb6a9

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +221 -0
app.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import gradio as gr
4
+ from IPython.display import Image, display
5
+
6
+ # Define paths
7
+ weights_path = os.path.join('era_v2_assignment_19_model.pt')
8
+
9
+ torch.manual_seed(1337)
10
+
11
+ # wget https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt
12
+ with open('input.txt', 'r', encoding='utf-8') as f:
13
+ text = f.read()
14
+
15
+ # here are all the unique characters that occur in this text
16
+ chars = sorted(list(set(text)))
17
+ vocab_size = len(chars)
18
+ # create a mapping from characters to integers
19
+ stoi = { ch:i for i,ch in enumerate(chars) }
20
+ itos = { i:ch for i,ch in enumerate(chars) }
21
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
22
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
23
+
24
+ # Train and test splits
25
+ data = torch.tensor(encode(text), dtype=torch.long)
26
+ n = int(0.9*len(data)) # first 90% will be train, rest val
27
+ train_data = data[:n]
28
+ val_data = data[n:]
29
+
30
+ # data loading
31
+ def get_batch(split):
32
+ # generate a small batch of data of inputs x and targets y
33
+ data = train_data if split == 'train' else val_data
34
+ ix = torch.randint(len(data) - block_size, (batch_size,))
35
+ x = torch.stack([data[i:i+block_size] for i in ix])
36
+ y = torch.stack([data[i+1:i+block_size+1] for i in ix])
37
+ x, y = x.to(device), y.to(device)
38
+ return x, y
39
+
40
+
41
+ @torch.no_grad()
42
+ def estimate_loss():
43
+ out = {}
44
+ model.eval()
45
+ for split in ['train', 'val']:
46
+ losses = torch.zeros(eval_iters)
47
+ for k in range(eval_iters):
48
+ X, Y = get_batch(split)
49
+ logits, loss = model(X, Y)
50
+ losses[k] = loss.item()
51
+ out[split] = losses.mean()
52
+ model.train()
53
+ return out
54
+
55
+
56
+ class Head(nn.Module):
57
+ """ one head of self-attention """
58
+
59
+ def __init__(self, head_size):
60
+ super().__init__()
61
+ self.key = nn.Linear(n_embd, head_size, bias=False)
62
+ self.query = nn.Linear(n_embd, head_size, bias=False)
63
+ self.value = nn.Linear(n_embd, head_size, bias=False)
64
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
65
+
66
+ self.dropout = nn.Dropout(dropout)
67
+
68
+ def forward(self, x):
69
+ # input of size (batch, time-step, channels)
70
+ # output of size (batch, time-step, head size)
71
+ B,T,C = x.shape
72
+ k = self.key(x) # (B,T,hs)
73
+ q = self.query(x) # (B,T,hs)
74
+ # compute attention scores ("affinities")
75
+ wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
76
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
77
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
78
+ wei = self.dropout(wei)
79
+ # perform the weighted aggregation of the values
80
+ v = self.value(x) # (B,T,hs)
81
+ out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
82
+ return out
83
+
84
+ class MultiHeadAttention(nn.Module):
85
+ """ multiple heads of self-attention in parallel """
86
+
87
+ def __init__(self, num_heads, head_size):
88
+ super().__init__()
89
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
90
+ self.proj = nn.Linear(head_size * num_heads, n_embd)
91
+ self.dropout = nn.Dropout(dropout)
92
+
93
+ def forward(self, x):
94
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
95
+ out = self.dropout(self.proj(out))
96
+ return out
97
+
98
+ class FeedFoward(nn.Module):
99
+ """ a simple linear layer followed by a non-linearity """
100
+
101
+ def __init__(self, n_embd):
102
+ super().__init__()
103
+ self.net = nn.Sequential(
104
+ nn.Linear(n_embd, 4 * n_embd),
105
+ nn.ReLU(),
106
+ nn.Linear(4 * n_embd, n_embd),
107
+ nn.Dropout(dropout),
108
+ )
109
+
110
+ def forward(self, x):
111
+ return self.net(x)
112
+
113
+ class Block(nn.Module):
114
+ """ Transformer block: communication followed by computation """
115
+
116
+ def __init__(self, n_embd, n_head):
117
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
118
+ super().__init__()
119
+ head_size = n_embd // n_head
120
+ self.sa = MultiHeadAttention(n_head, head_size)
121
+ self.ffwd = FeedFoward(n_embd)
122
+ self.ln1 = nn.LayerNorm(n_embd)
123
+ self.ln2 = nn.LayerNorm(n_embd)
124
+
125
+ def forward(self, x):
126
+ x = x + self.sa(self.ln1(x))
127
+ x = x + self.ffwd(self.ln2(x))
128
+ return x
129
+
130
+ class GPTLanguageModel(nn.Module):
131
+
132
+ def __init__(self):
133
+ super().__init__()
134
+ # each token directly reads off the logits for the next token from a lookup table
135
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
136
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
137
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
138
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
139
+ self.lm_head = nn.Linear(n_embd, vocab_size)
140
+
141
+ # better init, not covered in the original GPT video, but important, will cover in followup video
142
+ self.apply(self._init_weights)
143
+
144
+ def _init_weights(self, module):
145
+ if isinstance(module, nn.Linear):
146
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
147
+ if module.bias is not None:
148
+ torch.nn.init.zeros_(module.bias)
149
+ elif isinstance(module, nn.Embedding):
150
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
151
+
152
+ def forward(self, idx, targets=None):
153
+ B, T = idx.shape
154
+
155
+ # idx and targets are both (B,T) tensor of integers
156
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
157
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
158
+ x = tok_emb + pos_emb # (B,T,C)
159
+ x = self.blocks(x) # (B,T,C)
160
+ x = self.ln_f(x) # (B,T,C)
161
+ logits = self.lm_head(x) # (B,T,vocab_size)
162
+
163
+ if targets is None:
164
+ loss = None
165
+ else:
166
+ B, T, C = logits.shape
167
+ logits = logits.view(B*T, C)
168
+ targets = targets.view(B*T)
169
+ loss = F.cross_entropy(logits, targets)
170
+
171
+ return logits, loss
172
+
173
+ def generate(self, idx, max_new_tokens):
174
+ # idx is (B, T) array of indices in the current context
175
+ for _ in range(max_new_tokens):
176
+ # crop idx to the last block_size tokens
177
+ idx_cond = idx[:, -block_size:]
178
+ # get the predictions
179
+ logits, loss = self(idx_cond)
180
+ # focus only on the last time step
181
+ logits = logits[:, -1, :] # becomes (B, C)
182
+ # apply softmax to get probabilities
183
+ probs = F.softmax(logits, dim=-1) # (B, C)
184
+ # sample from the distribution
185
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
186
+ # append sampled index to the running sequence
187
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
188
+ return idx
189
+
190
+ model = GPTLanguageModel()
191
+
192
+ # Load the saved state dictionary into the model
193
+ model.load_state_dict(torch.load('era_v2_assignment_19_model.pth'))
194
+
195
+ # Set the model to evaluation mode
196
+ model.eval()
197
+
198
+ def inference(input_text, conf=0.1, device="cpu"):
199
+
200
+ input_sentence = input_text
201
+ sample_input = torch.tensor(encode(input_sentence), dtype=torch.long, device=device).unsqueeze(0)
202
+
203
+
204
+ output = decode(model.generate(sample_input, max_new_tokens=500)[0].tolist())
205
+
206
+ return output
207
+
208
+ title = "ChatGPT"
209
+ description = "Simple ChatGPT"
210
+ examples = [["We cannot, sir, we are undone already."], ["Ye're long about it."]]
211
+
212
+ demo = gr.Interface(
213
+ inference,
214
+ inputs=gr.Interface(inputs="Input text"),
215
+ outputs=gr.Interface(outputs="text"),
216
+ title=title,
217
+ description=description,
218
+ examples=examples,
219
+ )
220
+
221
+ demo.launch(share=True)