srikanthp07 commited on
Commit
66823b4
·
1 Parent(s): 784a061

Create app.py

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