TharunSivamani commited on
Commit
1c954f5
·
verified ·
1 Parent(s): 7d9b90f

final code

Browse files
Files changed (4) hide show
  1. app.py +39 -0
  2. input.txt +0 -0
  3. model.py +207 -0
  4. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import torch
5
+ from model import GPTLanguageModel, decode, context
6
+
7
+ # Clone the repository if not already cloned
8
+ REPO_URL = "https://huggingface.co/TharunSivamani/tiny-shakespeare"
9
+ REPO_NAME = "tiny-shakespeare"
10
+
11
+ if not os.path.exists(REPO_NAME):
12
+ subprocess.run(["git", "clone", REPO_URL])
13
+
14
+ # Set the device
15
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+ # Load the model
18
+ model = GPTLanguageModel().to(DEVICE)
19
+ model.load_state_dict(torch.load(f"{REPO_NAME}/model.pth", map_location=DEVICE), strict=False)
20
+ model.eval()
21
+
22
+ # Define the display function
23
+ def display(text, number):
24
+ answer = decode(model.generate(context, max_new_tokens=number)[0].tolist())
25
+ return text + " \n" + answer
26
+
27
+ # Gradio app interface
28
+ input_box = gr.Textbox(label="Story Lines", value="Once Upon a Time")
29
+ input_slider = gr.Slider(
30
+ minimum=200, maximum=500, label="Select the maximum number of tokens/words:", step=100
31
+ )
32
+ output_text = gr.Textbox()
33
+
34
+ gr.Interface(
35
+ fn=display,
36
+ inputs=[input_box, input_slider],
37
+ outputs=output_text,
38
+ examples=[["Shakespeare Once Said", 500], ["A Long Time Ago", 300]]
39
+ ).launch()
input.txt ADDED
The diff for this file is too large to render. See raw diff
 
model.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import torch
3
+ import torch.nn as nn
4
+ from torch.nn import functional as F
5
+
6
+ import warnings
7
+ warnings.simplefilter(action='ignore', category=FutureWarning)
8
+
9
+ # hyperparameters
10
+ batch_size = 8
11
+ block_size = 2048
12
+ eval_interval = 500
13
+ learning_rate = 3e-4
14
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
15
+ eval_iters = 200
16
+ n_embd = 784
17
+ n_head = 12
18
+ n_layer = 12
19
+ dropout = 0.1
20
+
21
+ # Mixed precision training setup
22
+ scaler = torch.cuda.amp.GradScaler()
23
+
24
+ torch.manual_seed(1337)
25
+
26
+ with open('input.txt', 'r', encoding='utf-8') as f:
27
+ text = f.read()
28
+
29
+ chars = sorted(list(set(text)))
30
+ vocab_size = 50257
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]
34
+ decode = lambda l: ''.join([itos[i] for i in l])
35
+
36
+ data = torch.tensor(encode(text), dtype=torch.long)
37
+ n = int(0.9 * len(data))
38
+ train_data = data[:n]
39
+ val_data = data[n:]
40
+
41
+ def get_batch(split):
42
+ data = train_data if split == 'train' else val_data
43
+ ix = torch.randint(len(data) - block_size, (batch_size,))
44
+ x = torch.stack([data[i:i + block_size] for i in ix])
45
+ y = torch.stack([data[i + 1:i + block_size + 1] for i in ix])
46
+ x, y = x.to(device), y.to(device)
47
+ return x, y
48
+
49
+ @torch.no_grad()
50
+ def estimate_loss():
51
+ out = {}
52
+ model.eval()
53
+ eval_start_time = time.time()
54
+ for split in ['train', 'val']:
55
+ losses = torch.zeros(eval_iters)
56
+ for k in range(eval_iters):
57
+ X, Y = get_batch(split)
58
+ with torch.cuda.amp.autocast():
59
+ logits, loss = model(X, Y)
60
+ losses[k] = loss.item()
61
+ out[split] = losses.mean()
62
+ eval_time = time.time() - eval_start_time
63
+ print(f"Evaluation time: {eval_time:.2f} seconds")
64
+ model.train()
65
+ return out
66
+
67
+ class Head(nn.Module):
68
+ """ one head of self-attention """
69
+
70
+ def __init__(self, head_size):
71
+ super().__init__()
72
+ self.key = nn.Linear(n_embd, head_size, bias=False)
73
+ self.query = nn.Linear(n_embd, head_size, bias=False)
74
+ self.value = nn.Linear(n_embd, head_size, bias=False)
75
+ self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
76
+
77
+ self.dropout = nn.Dropout(dropout)
78
+
79
+ def forward(self, x):
80
+ # input of size (batch, time-step, channels)
81
+ # output of size (batch, time-step, head size)
82
+ B,T,C = x.shape
83
+ k = self.key(x) # (B,T,hs)
84
+ q = self.query(x) # (B,T,hs)
85
+ # compute attention scores ("affinities")
86
+ wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
87
+ wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
88
+ wei = F.softmax(wei, dim=-1) # (B, T, T)
89
+ wei = self.dropout(wei)
90
+ # perform the weighted aggregation of the values
91
+ v = self.value(x) # (B,T,hs)
92
+ out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
93
+ return out
94
+
95
+ class MultiHeadAttention(nn.Module):
96
+ """ multiple heads of self-attention in parallel """
97
+
98
+ def __init__(self, num_heads, head_size):
99
+ super().__init__()
100
+ self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
101
+ self.proj = nn.Linear(head_size * num_heads, n_embd)
102
+ self.dropout = nn.Dropout(dropout)
103
+
104
+ def forward(self, x):
105
+ out = torch.cat([h(x) for h in self.heads], dim=-1)
106
+ out = self.dropout(self.proj(out))
107
+ return out
108
+
109
+ class FeedFoward(nn.Module):
110
+ """ a simple linear layer followed by a non-linearity """
111
+
112
+ def __init__(self, n_embd):
113
+ super().__init__()
114
+ self.net = nn.Sequential(
115
+ nn.Linear(n_embd, 4 * n_embd),
116
+ nn.ReLU(),
117
+ nn.Linear(4 * n_embd, n_embd),
118
+ nn.Dropout(dropout),
119
+ )
120
+
121
+ def forward(self, x):
122
+ return self.net(x)
123
+
124
+ class Block(nn.Module):
125
+ """ Transformer block: communication followed by computation """
126
+
127
+ def __init__(self, n_embd, n_head):
128
+ # n_embd: embedding dimension, n_head: the number of heads we'd like
129
+ super().__init__()
130
+ head_size = n_embd // n_head
131
+ self.sa = MultiHeadAttention(n_head, head_size)
132
+ self.ffwd = FeedFoward(n_embd)
133
+ self.ln1 = nn.LayerNorm(n_embd)
134
+ self.ln2 = nn.LayerNorm(n_embd)
135
+
136
+ def forward(self, x):
137
+ x = x + self.sa(self.ln1(x))
138
+ x = x + self.ffwd(self.ln2(x))
139
+ return x
140
+
141
+ class GPTLanguageModel(nn.Module):
142
+
143
+ def __init__(self):
144
+ super().__init__()
145
+ # each token directly reads off the logits for the next token from a lookup table
146
+ self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
147
+ self.position_embedding_table = nn.Embedding(block_size, n_embd)
148
+ self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
149
+ self.ln_f = nn.LayerNorm(n_embd) # final layer norm
150
+ self.lm_head = nn.Linear(n_embd, vocab_size)
151
+
152
+ # better init, not covered in the original GPT video, but important, will cover in followup video
153
+ self.apply(self._init_weights)
154
+
155
+ def _init_weights(self, module):
156
+ if isinstance(module, nn.Linear):
157
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
158
+ if module.bias is not None:
159
+ torch.nn.init.zeros_(module.bias)
160
+ elif isinstance(module, nn.Embedding):
161
+ torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
162
+
163
+ def forward(self, idx, targets=None):
164
+ B, T = idx.shape
165
+
166
+ # idx and targets are both (B,T) tensor of integers
167
+ tok_emb = self.token_embedding_table(idx) # (B,T,C)
168
+ pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
169
+ x = tok_emb + pos_emb # (B,T,C)
170
+ x = self.blocks(x) # (B,T,C)
171
+ x = self.ln_f(x) # (B,T,C)
172
+ logits = self.lm_head(x) # (B,T,vocab_size)
173
+
174
+ if targets is None:
175
+ loss = None
176
+ else:
177
+ B, T, C = logits.shape
178
+ logits = logits.view(B*T, C)
179
+ targets = targets.view(B*T)
180
+ loss = F.cross_entropy(logits, targets)
181
+
182
+ return logits, loss
183
+
184
+ def generate(self, idx, max_new_tokens):
185
+ # idx is (B, T) array of indices in the current context
186
+ for _ in range(max_new_tokens):
187
+ # crop idx to the last block_size tokens
188
+ idx_cond = idx[:, -block_size:]
189
+ # get the predictions
190
+ logits, loss = self(idx_cond)
191
+ # focus only on the last time step
192
+ logits = logits[:, -1, :] # becomes (B, C)
193
+ # apply softmax to get probabilities
194
+ probs = F.softmax(logits, dim=-1) # (B, C)
195
+ # sample from the distribution
196
+ idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
197
+ # append sampled index to the running sequence
198
+ idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
199
+ return idx
200
+
201
+ model = GPTLanguageModel()
202
+ m = model.to(device)
203
+ # print the number of parameters in the model
204
+ print(sum(p.numel() for p in m.parameters())/1e6, 'M parameters')
205
+
206
+ # Generate text from the model
207
+ context = torch.zeros((1, 1), dtype=torch.long, device=device)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ torch
2
+ gradio