mkthoma commited on
Commit
66ededb
·
1 Parent(s): e502843

app update

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