shashnk commited on
Commit
0fa489a
1 Parent(s): c6fb233

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +179 -0
  2. input.txt +0 -0
  3. model.pth +3 -0
app.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+
6
+ with open('input.txt', 'r', encoding='utf-8') as f:
7
+ text = f.read()
8
+
9
+ chars = sorted(list(set(text)))
10
+ vocab_size = len(chars)
11
+
12
+ # create a mapping from characters to integers
13
+ stoi = { ch:i for i,ch in enumerate(chars) }
14
+ itos = { i:ch for i,ch in enumerate(chars) }
15
+ encode = lambda s: [stoi[c] for c in s] # encoder: take a string, output a list of integers
16
+ decode = lambda l: ''.join([itos[i] for i in l]) # decoder: take a list of integers, output a string
17
+
18
+ # hyperparameters
19
+ batch_size = 16 # how many independent sequences will we process in parallel?
20
+ block_size = 32 # what is the maximum context length for predictions?
21
+ max_iters = 5000
22
+ eval_interval = 100
23
+ learning_rate = 1e-3
24
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
25
+ eval_iters = 200
26
+ n_embd = 64
27
+ n_head = 4
28
+ n_layer = 4
29
+ dropout = 0.0
30
+
31
+ torch.manual_seed(1337)
32
+
33
+ class Head(nn.Module):
34
+ """ one head of self-attention """
35
+
36
+ def __init__(self, head_size):
37
+ super().__init__()
38
+ self.key = nn.Linear(n_embd, head_size, bias=False)
39
+ self.query = nn.Linear(n_embd, head_size, bias=False)
40
+ self.value = nn.Linear(n_embd, head_size, bias=False)
41
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
42
+
43
+ self.dropout = nn.Dropout(dropout)
44
+
45
+ def forward(self, x):
46
+ B,T,C = x.shape
47
+ k = self.key(x) # (B,T,C)
48
+ q = self.query(x) # (B,T,C)
49
+ # compute attention scores ("affinities")
50
+ wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
51
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
52
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
53
+ wei = self.dropout(wei)
54
+ # perform the weighted aggregation of the values
55
+ v = self.value(x) # (B,T,C)
56
+ out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
57
+ return out
58
+
59
+ class MultiHeadAttention(nn.Module):
60
+ """ multiple heads of self-attention in parallel """
61
+
62
+ def __init__(self, num_heads, head_size):
63
+ super().__init__()
64
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
65
+ self.proj = nn.Linear(n_embd, n_embd)
66
+ self.dropout = nn.Dropout(dropout)
67
+
68
+ def forward(self, x):
69
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
70
+ out = self.dropout(self.proj(out))
71
+ return out
72
+
73
+ class FeedFoward(nn.Module):
74
+ """ a simple linear layer followed by a non-linearity """
75
+
76
+ def __init__(self, n_embd):
77
+ super().__init__()
78
+ self.net = nn.Sequential(
79
+ nn.Linear(n_embd, 4 * n_embd),
80
+ nn.ReLU(),
81
+ nn.Linear(4 * n_embd, n_embd),
82
+ nn.Dropout(dropout),
83
+ )
84
+
85
+ def forward(self, x):
86
+ return self.net(x)
87
+
88
+ class Block(nn.Module):
89
+ """ Transformer block: communication followed by computation """
90
+
91
+ def __init__(self, n_embd, n_head):
92
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
93
+ super().__init__()
94
+ head_size = n_embd // n_head
95
+ self.sa = MultiHeadAttention(n_head, head_size)
96
+ self.ffwd = FeedFoward(n_embd)
97
+ self.ln1 = nn.LayerNorm(n_embd)
98
+ self.ln2 = nn.LayerNorm(n_embd)
99
+
100
+ def forward(self, x):
101
+ x = x + self.sa(self.ln1(x))
102
+ x = x + self.ffwd(self.ln2(x))
103
+ return x
104
+
105
+
106
+ # super simple bigram model
107
+ class BigramLanguageModel(nn.Module):
108
+
109
+ def __init__(self):
110
+ super().__init__()
111
+ vocab_size = 65
112
+ # each token directly reads off the logits for the next token from a lookup table
113
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
114
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
115
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
116
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
117
+ self.lm_head = nn.Linear(n_embd, vocab_size)
118
+
119
+ def forward(self, idx, targets=None):
120
+ B, T = idx.shape
121
+
122
+ # idx and targets are both (B,T) tensor of integers
123
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
124
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
125
+ x = tok_emb + pos_emb # (B,T,C)
126
+ x = self.blocks(x) # (B,T,C)
127
+ x = self.ln_f(x) # (B,T,C)
128
+ logits = self.lm_head(x) # (B,T,vocab_size)
129
+
130
+ if targets is None:
131
+ loss = None
132
+ else:
133
+ B, T, C = logits.shape
134
+ logits = logits.view(B*T, C)
135
+ targets = targets.view(B*T)
136
+ loss = F.cross_entropy(logits, targets)
137
+
138
+ return logits, loss
139
+
140
+ def generate(self, idx, max_new_tokens):
141
+ # idx is (B, T) array of indices in the current context
142
+ for _ in range(max_new_tokens):
143
+ # crop idx to the last block_size tokens
144
+ idx_cond = idx[:, -block_size:]
145
+ # get the predictions
146
+ logits, loss = self(idx_cond)
147
+ # focus only on the last time step
148
+ logits = logits[:, -1, :] # becomes (B, C)
149
+ # apply softmax to get probabilities
150
+ probs = F.softmax(logits, dim=-1) # (B, C)
151
+ # sample from the distribution
152
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
153
+ # append sampled index to the running sequence
154
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
155
+ return idx
156
+
157
+
158
+ def generate_text(seed_text):
159
+ # Convert seed text to tensor
160
+ loaded_model = torch.load("model.pth")
161
+ loaded_model.to(device)
162
+ loaded_model.eval()
163
+
164
+ idx = torch.tensor(encode(seed_text), dtype=torch.long, device=device).unsqueeze(0)
165
+ # Generate continuation
166
+ generated_idx = loaded_model.generate(idx, max_new_tokens=200).squeeze().tolist()
167
+ generated_text = decode(generated_idx)
168
+ return generated_text
169
+
170
+
171
+ # Define Gradio interface
172
+ def gradio_interface(seed_text=""):
173
+ return generate_text(seed_text)
174
+
175
+ iface = gr.Interface(fn=gradio_interface,
176
+ inputs=gr.Textbox(default="Enter some starting text..."),
177
+ outputs="text")
178
+
179
+ iface.launch(debug=True)
input.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44811f93e727af6132c1f581a12d9e242f401bb977fb46ca582796c4e4fff5aa
3
+ size 971916