Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,187 @@
|
|
1 |
import gradio as gr
|
2 |
|
3 |
-
|
4 |
-
|
|
|
5 |
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
iface.launch()
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.nn.functional as F
|
6 |
|
7 |
+
batch_size = 64 # how many independent sequences will we process in parallel?
|
8 |
+
block_size = 256 # what is the maximum context length for predictions?
|
9 |
+
max_iters = 5000
|
10 |
+
eval_interval = 500
|
11 |
+
learning_rate = 3e-4
|
12 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
13 |
+
print(f"The code is running on {device} : GPU={torch.cuda.get_device_name(0)}")
|
14 |
+
eval_iters = 200
|
15 |
+
n_embd = 384
|
16 |
+
n_head = 6
|
17 |
+
n_layer = 6
|
18 |
+
dropout = 0.2
|
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 |
+
|
37 |
+
class Head(nn.Module):
|
38 |
+
""" one head of self-attention """
|
39 |
+
|
40 |
+
def __init__(self, head_size):
|
41 |
+
super().__init__()
|
42 |
+
self.key = nn.Linear(n_embd, head_size, bias=False)
|
43 |
+
self.query = nn.Linear(n_embd, head_size, bias=False)
|
44 |
+
self.value = nn.Linear(n_embd, head_size, bias=False)
|
45 |
+
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size))) # create lower triangular matrix
|
46 |
+
|
47 |
+
self.dropout = nn.Dropout(dropout)
|
48 |
+
|
49 |
+
def forward(self, x):
|
50 |
+
B,T,C = x.shape
|
51 |
+
k = self.key(x) # B, T, C
|
52 |
+
q = self.query(x) # B, T, C
|
53 |
+
# compute attention scores = ("affinities")
|
54 |
+
wei = q @ k.transpose(-2, -1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
|
55 |
+
#wei = wei.masked_fill(self.tril[:T, :T]==0, float('-inf')) # (B, T, T)
|
56 |
+
tril = torch.tril(torch.ones(T, T)).to(device)
|
57 |
+
wei = wei.masked_fill(tril == 0, float('-inf'))
|
58 |
+
wei = F.softmax(wei, dim=-1) # (B, T, T)
|
59 |
+
wei = self.dropout(wei)
|
60 |
+
# perform the weighted aggregation of the values
|
61 |
+
v = self.value(x) # (B, T, C)
|
62 |
+
out = wei @ v
|
63 |
+
return out
|
64 |
+
|
65 |
+
|
66 |
+
class MultiHeadAttention(nn.Module):
|
67 |
+
""" multiple heads of self-attention in parallel """
|
68 |
+
|
69 |
+
def __init__(self, num_heads, head_size):
|
70 |
+
super().__init__()
|
71 |
+
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
|
72 |
+
self.proj = nn.Linear(n_embd, n_embd)
|
73 |
+
self.dropout = nn.Dropout(dropout)
|
74 |
+
|
75 |
+
def forward(self, x):
|
76 |
+
out = torch.cat([h(x) for h in self.heads], dim=-1) # h(x) call forward function is Head class
|
77 |
+
out = self.dropout(self.proj(out))
|
78 |
+
return out
|
79 |
+
|
80 |
+
class FeedForward(nn.Module): # per token level, every token does this independently, its allowing tokens to think on data provided by self attention
|
81 |
+
""" a simple linear layer followed by a non-linearity"""
|
82 |
+
|
83 |
+
def __init__(self, n_embd):
|
84 |
+
super().__init__()
|
85 |
+
self.net = nn.Sequential(
|
86 |
+
nn.Linear(n_embd, 4 * n_embd), # we multiply by 4 cause the paper says so
|
87 |
+
nn.ReLU(),
|
88 |
+
nn.Linear(4 * n_embd, n_embd),
|
89 |
+
nn.Dropout(dropout)
|
90 |
+
)
|
91 |
+
|
92 |
+
def forward(self, x):
|
93 |
+
return self.net(x)
|
94 |
+
|
95 |
+
class Block(nn.Module):
|
96 |
+
"""Transformer block: communication followed by computation """
|
97 |
+
|
98 |
+
def __init__(self, n_embed, n_head):
|
99 |
+
# n_embd: embedding dimension, n_head: the number of heads we'd like
|
100 |
+
super().__init__()
|
101 |
+
head_size = n_embd // n_head
|
102 |
+
self.sa = MultiHeadAttention(n_head, head_size)
|
103 |
+
self.ffwd = FeedForward(n_embd)
|
104 |
+
self.ln1 = nn.LayerNorm(n_embd)
|
105 |
+
self.ln2 = nn.LayerNorm(n_embd)
|
106 |
+
|
107 |
+
def forward(self, x):
|
108 |
+
x = x + self.sa(self.ln1(x)) # x = x + self .. is residual connection
|
109 |
+
x = x + self.ffwd(self.ln2(x))
|
110 |
+
return x
|
111 |
+
|
112 |
+
|
113 |
+
class BigramLanguageModel(nn.Module):
|
114 |
+
|
115 |
+
def __init__(self):
|
116 |
+
super().__init__()
|
117 |
+
# each token directly reads off the logits for the next token from a lookup table
|
118 |
+
self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
|
119 |
+
self.position_embedding_table = nn.Embedding(block_size, n_embd) # so each position from 0 to block_size - 1 will also get its own embedding vector
|
120 |
+
self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
|
121 |
+
self.ln_f = nn.LayerNorm(n_embd) # final layer Norm
|
122 |
+
self.lm_head = nn.Linear(n_embd, vocab_size)
|
123 |
+
|
124 |
+
def forward(self, idx, targets=None):
|
125 |
+
B, T = idx.shape
|
126 |
+
|
127 |
+
# idx and targets are both (B,T) tensor of integers
|
128 |
+
tok_emb = self.token_embedding_table(idx) # (B,T,C=n_embed)
|
129 |
+
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T, C)
|
130 |
+
# pos_emb tensor will be a (block_size, n_emb) tensor # block_size is max context length for predictions
|
131 |
+
# each row represents the embedding vector for the corresponding position
|
132 |
+
# so 0th row will represent the vector for 0th position
|
133 |
+
x = tok_emb + pos_emb # (B, T, C)
|
134 |
+
x = self.blocks(x) # (B, T, C)
|
135 |
+
logits = self.lm_head(x) # (B, T, C=vocab_size)
|
136 |
+
|
137 |
+
if targets is None:
|
138 |
+
loss = None
|
139 |
+
else:
|
140 |
+
B, T, C = logits.shape
|
141 |
+
logits = logits.view(B*T, C)
|
142 |
+
targets = targets.view(B*T)
|
143 |
+
loss = F.cross_entropy(logits, targets)
|
144 |
+
|
145 |
+
return logits, loss
|
146 |
+
|
147 |
+
def generate(self, idx, max_new_tokens):
|
148 |
+
# idx is (B, T) array of indices in the current context
|
149 |
+
for _ in range(max_new_tokens):
|
150 |
+
# crop idx to the last block_size tokens
|
151 |
+
idx_cond = idx[:, -block_size:]
|
152 |
+
# get the predictions
|
153 |
+
logits, loss = self.forward(idx_cond)
|
154 |
+
# focus only on the last time step
|
155 |
+
logits = logits[:, -1, :] # becomes (B, C)
|
156 |
+
# apply softmax to get probabilities
|
157 |
+
probs = F.softmax(logits, dim=-1) # (B, C)
|
158 |
+
# sample from the distribution
|
159 |
+
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
|
160 |
+
# append sampled index to the running sequence
|
161 |
+
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
|
162 |
+
return idx
|
163 |
+
|
164 |
+
|
165 |
+
# Instantiate the model
|
166 |
+
model = BigramLanguageModel()
|
167 |
+
|
168 |
+
# Specify the path to the pre-trained model checkpoint
|
169 |
+
checkpoint_path = 'checkpoint.pth'
|
170 |
+
|
171 |
+
# Load the model checkpoint
|
172 |
+
checkpoint = torch.load(checkpoint_path)
|
173 |
+
model.load_state_dict(checkpoint['model_state_dict'])
|
174 |
+
model.eval()
|
175 |
+
model.to(device)
|
176 |
+
|
177 |
+
|
178 |
+
# generate from the model
|
179 |
+
context = torch.zeros((1, 1), dtype=torch.long, device=device)
|
180 |
+
|
181 |
+
def greet(start_character, number_of_tokens):
|
182 |
+
context[0][0] = encode(start_character)
|
183 |
+
max_new_tokens = number_of_tokens
|
184 |
+
return decode(model.generate(context, max_new_tokens=max_new_tokens)[0].tolist())
|
185 |
+
|
186 |
+
iface = gr.Interface(fn=greet, inputs=["text", "number"], outputs="text")
|
187 |
iface.launch()
|