HimankJ commited on
Commit
67b3a01
·
verified ·
1 Parent(s): c676354

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -0
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch.nn import functional as F
4
+ import json
5
+ import gradio as gr
6
+
7
+ with open('vocab.json') as itos_json:
8
+ itos = json.load(itos_json)
9
+
10
+ new_itos = {}
11
+ for k,v in itos.items():
12
+ new_itos[int(k)] = v
13
+ itos = new_itos
14
+
15
+ # hyperparameters
16
+ vocab_size = len(itos)
17
+ n_embd = 64
18
+ n_head = 4
19
+ n_layer = 4
20
+ dropout = 0.0
21
+ block_size = 32 # what is the maximum context length for predictions?
22
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
23
+ print(device)
24
+
25
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
26
+
27
+ class Head(nn.Module):
28
+ """ one head of self-attention """
29
+
30
+ def __init__(self, head_size):
31
+ super().__init__()
32
+ self.key = nn.Linear(n_embd, head_size, bias=False)
33
+ self.query = nn.Linear(n_embd, head_size, bias=False)
34
+ self.value = nn.Linear(n_embd, head_size, bias=False)
35
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
36
+
37
+ self.dropout = nn.Dropout(dropout)
38
+
39
+ def forward(self, x):
40
+ B,T,C = x.shape
41
+ k = self.key(x) # (B,T,C)
42
+ q = self.query(x) # (B,T,C)
43
+ # compute attention scores ("affinities")
44
+ wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
45
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
46
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
47
+ wei = self.dropout(wei)
48
+ # perform the weighted aggregation of the values
49
+ v = self.value(x) # (B,T,C)
50
+ out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
51
+ return out
52
+
53
+ class MultiHeadAttention(nn.Module):
54
+ """ multiple heads of self-attention in parallel """
55
+
56
+ def __init__(self, num_heads, head_size):
57
+ super().__init__()
58
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
59
+ self.proj = nn.Linear(n_embd, n_embd)
60
+ self.dropout = nn.Dropout(dropout)
61
+
62
+ def forward(self, x):
63
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
64
+ out = self.dropout(self.proj(out))
65
+ return out
66
+
67
+ class FeedFoward(nn.Module):
68
+ """ a simple linear layer followed by a non-linearity """
69
+
70
+ def __init__(self, n_embd):
71
+ super().__init__()
72
+ self.net = nn.Sequential(
73
+ nn.Linear(n_embd, 4 * n_embd),
74
+ nn.ReLU(),
75
+ nn.Linear(4 * n_embd, n_embd),
76
+ nn.Dropout(dropout),
77
+ )
78
+
79
+ def forward(self, x):
80
+ return self.net(x)
81
+
82
+ class Block(nn.Module):
83
+ """ Transformer block: communication followed by computation """
84
+
85
+ def __init__(self, n_embd, n_head):
86
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
87
+ super().__init__()
88
+ head_size = n_embd // n_head
89
+ self.sa = MultiHeadAttention(n_head, head_size)
90
+ self.ffwd = FeedFoward(n_embd)
91
+ self.ln1 = nn.LayerNorm(n_embd)
92
+ self.ln2 = nn.LayerNorm(n_embd)
93
+
94
+ def forward(self, x):
95
+ x = x + self.sa(self.ln1(x))
96
+ x = x + self.ffwd(self.ln2(x))
97
+ return x
98
+
99
+ # super simple bigram model
100
+ class BigramLanguageModel(nn.Module):
101
+
102
+ def __init__(self):
103
+ super().__init__()
104
+ # each token directly reads off the logits for the next token from a lookup table
105
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
106
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
107
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
108
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
109
+ self.lm_head = nn.Linear(n_embd, vocab_size)
110
+
111
+ def forward(self, idx, targets=None):
112
+ B, T = idx.shape
113
+
114
+ # idx and targets are both (B,T) tensor of integers
115
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
116
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
117
+ x = tok_emb + pos_emb # (B,T,C)
118
+ x = self.blocks(x) # (B,T,C)
119
+ x = self.ln_f(x) # (B,T,C)
120
+ logits = self.lm_head(x) # (B,T,vocab_size)
121
+
122
+ if targets is None:
123
+ loss = None
124
+ else:
125
+ B, T, C = logits.shape
126
+ logits = logits.view(B*T, C)
127
+ targets = targets.view(B*T)
128
+ loss = F.cross_entropy(logits, targets)
129
+
130
+ return logits, loss
131
+
132
+ def generate(self, idx, max_new_tokens):
133
+ # idx is (B, T) array of indices in the current context
134
+ for _ in range(max_new_tokens):
135
+ # crop idx to the last block_size tokens
136
+ idx_cond = idx[:, -block_size:]
137
+ # get the predictions
138
+ logits, loss = self(idx_cond)
139
+ # focus only on the last time step
140
+ logits = logits[:, -1, :] # becomes (B, C)
141
+ # apply softmax to get probabilities
142
+ probs = F.softmax(logits, dim=-1) # (B, C)
143
+ # sample from the distribution
144
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
145
+ # append sampled index to the running sequence
146
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
147
+ return idx
148
+
149
+ model = BigramLanguageModel()
150
+ model.load_state_dict(torch.load('S19BasicGPT_model.pt', map_location=torch.device('cpu')))
151
+ # m = model.to(device)
152
+ # print the number of parameters in the model
153
+ # print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
154
+
155
+ def generateOutput(num_tokens = 2000):
156
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
157
+ return(decode(model.generate(context, max_new_tokens=num_tokens)[0].tolist()))
158
+
159
+ title = "Basic GPT From Scratch"
160
+ description = "This is GPT model trained on 'tinyshakespeare' dataset. It is an implementation of decoder-only architecture."
161
+ demo = gr.Interface(
162
+ generateOutput,
163
+ inputs = [
164
+ gr.Slider(1, 10000, value = 2000, step=100, label="Number of chars that you want in your output"),
165
+ ],
166
+ outputs = [
167
+ gr.Text(),
168
+ ],
169
+ title = title,
170
+ description = description,
171
+ )
172
+ demo.launch()