Spaces:
Sleeping
Sleeping
Commit
·
e0ab940
1
Parent(s):
b53e357
Upload 4 files
Browse files- app.py +185 -0
- input.txt +0 -0
- requirements.txt +2 -0
- shakespeaere_language_model.pth +3 -0
app.py
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.nn import functional as F
|
4 |
+
import numpy as np
|
5 |
+
import random
|
6 |
+
import re
|
7 |
+
import gradio as gr
|
8 |
+
|
9 |
+
# hyperparameters
|
10 |
+
batch_size = 16 # how many independent sequences will we process in parallel?
|
11 |
+
block_size = 32 # what is the maximum context length for predictions?
|
12 |
+
max_iters = 5000
|
13 |
+
eval_interval = 100
|
14 |
+
learning_rate = 1e-3
|
15 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
16 |
+
eval_iters = 200
|
17 |
+
n_embd = 64
|
18 |
+
n_head = 4
|
19 |
+
n_layer = 4
|
20 |
+
dropout = 0.0
|
21 |
+
# ------------
|
22 |
+
|
23 |
+
torch.manual_seed(1337)
|
24 |
+
|
25 |
+
class Head(nn.Module):
|
26 |
+
""" one head of self-attention """
|
27 |
+
|
28 |
+
def __init__(self, head_size):
|
29 |
+
super().__init__()
|
30 |
+
self.key = nn.Linear(n_embd, head_size, bias=False)
|
31 |
+
self.query = nn.Linear(n_embd, head_size, bias=False)
|
32 |
+
self.value = nn.Linear(n_embd, head_size, bias=False)
|
33 |
+
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))
|
34 |
+
|
35 |
+
self.dropout = nn.Dropout(dropout)
|
36 |
+
|
37 |
+
def forward(self, x):
|
38 |
+
B,T,C = x.shape
|
39 |
+
k = self.key(x) # (B,T,C)
|
40 |
+
q = self.query(x) # (B,T,C)
|
41 |
+
# compute attention scores ("affinities")
|
42 |
+
wei = q @ k.transpose(-2,-1) * C**-0.5 # (B, T, C) @ (B, C, T) -> (B, T, T)
|
43 |
+
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
|
44 |
+
wei = F.softmax(wei, dim=-1) # (B, T, T)
|
45 |
+
wei = self.dropout(wei)
|
46 |
+
# perform the weighted aggregation of the values
|
47 |
+
v = self.value(x) # (B,T,C)
|
48 |
+
out = wei @ v # (B, T, T) @ (B, T, C) -> (B, T, C)
|
49 |
+
return out
|
50 |
+
|
51 |
+
class MultiHeadAttention(nn.Module):
|
52 |
+
""" multiple heads of self-attention in parallel """
|
53 |
+
|
54 |
+
def __init__(self, num_heads, head_size):
|
55 |
+
super().__init__()
|
56 |
+
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
|
57 |
+
self.proj = nn.Linear(n_embd, n_embd)
|
58 |
+
self.dropout = nn.Dropout(dropout)
|
59 |
+
|
60 |
+
def forward(self, x):
|
61 |
+
out = torch.cat([h(x) for h in self.heads], dim=-1)
|
62 |
+
out = self.dropout(self.proj(out))
|
63 |
+
return out
|
64 |
+
|
65 |
+
class FeedFoward(nn.Module):
|
66 |
+
""" a simple linear layer followed by a non-linearity """
|
67 |
+
|
68 |
+
def __init__(self, n_embd):
|
69 |
+
super().__init__()
|
70 |
+
self.net = nn.Sequential(
|
71 |
+
nn.Linear(n_embd, 4 * n_embd),
|
72 |
+
nn.ReLU(),
|
73 |
+
nn.Linear(4 * n_embd, n_embd),
|
74 |
+
nn.Dropout(dropout),
|
75 |
+
)
|
76 |
+
|
77 |
+
def forward(self, x):
|
78 |
+
return self.net(x)
|
79 |
+
|
80 |
+
class Block(nn.Module):
|
81 |
+
""" Transformer block: communication followed by computation """
|
82 |
+
|
83 |
+
def __init__(self, n_embd, n_head):
|
84 |
+
# n_embd: embedding dimension, n_head: the number of heads we'd like
|
85 |
+
super().__init__()
|
86 |
+
head_size = n_embd // n_head
|
87 |
+
self.sa = MultiHeadAttention(n_head, head_size)
|
88 |
+
self.ffwd = FeedFoward(n_embd)
|
89 |
+
self.ln1 = nn.LayerNorm(n_embd)
|
90 |
+
self.ln2 = nn.LayerNorm(n_embd)
|
91 |
+
|
92 |
+
def forward(self, x):
|
93 |
+
x = x + self.sa(self.ln1(x))
|
94 |
+
x = x + self.ffwd(self.ln2(x))
|
95 |
+
return x
|
96 |
+
|
97 |
+
# super simple bigram model
|
98 |
+
class BigramLanguageModel(nn.Module):
|
99 |
+
def __init__(self, dataset_text, n_embd):
|
100 |
+
super().__init__()
|
101 |
+
|
102 |
+
# Compute character-related parameters
|
103 |
+
self.chars = sorted(list(set(dataset_text)))
|
104 |
+
self.vocab_size = len(self.chars)
|
105 |
+
self.stoi = {ch: i for i, ch in enumerate(self.chars)}
|
106 |
+
self.itos = {i: ch for ch, i in self.stoi.items()}
|
107 |
+
|
108 |
+
self.token_embedding_table = nn.Embedding(self.vocab_size, n_embd)
|
109 |
+
self.position_embedding_table = nn.Embedding(block_size, n_embd)
|
110 |
+
self.blocks = nn.Sequential(*[Block(n_embd, n_head=n_head) for _ in range(n_layer)])
|
111 |
+
self.ln_f = nn.LayerNorm(n_embd)
|
112 |
+
self.lm_head = nn.Linear(n_embd, self.vocab_size)
|
113 |
+
self.encode = lambda s: [self.stoi[c] for c in s] # encoder: take a string, output a list of integers
|
114 |
+
self.decode = lambda l: ''.join([self.itos[i] for i in l]) # decoder: take a list of integers, output a string
|
115 |
+
|
116 |
+
|
117 |
+
def forward(self, idx, targets=None):
|
118 |
+
B, T = idx.shape
|
119 |
+
|
120 |
+
# idx and targets are both (B,T) tensor of integers
|
121 |
+
tok_emb = self.token_embedding_table(idx) # (B,T,C)
|
122 |
+
pos_emb = self.position_embedding_table(torch.arange(T, device=device)) # (T,C)
|
123 |
+
x = tok_emb + pos_emb # (B,T,C)
|
124 |
+
x = self.blocks(x) # (B,T,C)
|
125 |
+
x = self.ln_f(x) # (B,T,C)
|
126 |
+
logits = self.lm_head(x) # (B,T,vocab_size)
|
127 |
+
|
128 |
+
if targets is None:
|
129 |
+
loss = None
|
130 |
+
else:
|
131 |
+
B, T, C = logits.shape
|
132 |
+
logits = logits.view(B*T, C)
|
133 |
+
targets = targets.view(B*T)
|
134 |
+
loss = F.cross_entropy(logits, targets)
|
135 |
+
|
136 |
+
return logits, loss
|
137 |
+
|
138 |
+
def generate(self, idx, max_new_tokens):
|
139 |
+
# idx is (B, T) array of indices in the current context
|
140 |
+
for _ in range(max_new_tokens):
|
141 |
+
# crop idx to the last block_size tokens
|
142 |
+
idx_cond = idx[:, -block_size:]
|
143 |
+
# get the predictions
|
144 |
+
logits, loss = self(idx_cond)
|
145 |
+
# focus only on the last time step
|
146 |
+
logits = logits[:, -1, :] # becomes (B, C)
|
147 |
+
# apply softmax to get probabilities
|
148 |
+
probs = F.softmax(logits, dim=-1) # (B, C)
|
149 |
+
# sample from the distribution
|
150 |
+
idx_next = torch.multinomial(probs, num_samples=1) # (B, 1)
|
151 |
+
# append sampled index to the running sequence
|
152 |
+
idx = torch.cat((idx, idx_next), dim=1) # (B, T+1)
|
153 |
+
return idx
|
154 |
+
|
155 |
+
# Reading shakespeare data
|
156 |
+
with open('input.txt', 'r', encoding='utf-8') as f:
|
157 |
+
shakespeare_text = f.read()
|
158 |
+
|
159 |
+
# Load the shakespeaere model
|
160 |
+
shakespeare_model = BigramLanguageModel(shakespeare_text, n_embd).to(device) # Initialize an instance of your model
|
161 |
+
shakespeare_model.load_state_dict(torch.load('shakespeaere_language_model.pth', map_location=torch.device('cpu')))
|
162 |
+
shakespeare_model.eval() # Set the model to evaluation mode
|
163 |
+
|
164 |
+
def shakespeare_outputs(prompt=None, max_new_tokens=2000):
|
165 |
+
if prompt:
|
166 |
+
context = torch.tensor(shakespeare_model.encode(prompt), dtype=torch.long, device=device).view(1, -1)
|
167 |
+
else:
|
168 |
+
context = torch.zeros((1, 1), dtype=torch.long, device=device)
|
169 |
+
text_output = shakespeare_model.decode(shakespeare_model.generate(context, max_new_tokens=max_new_tokens)[0].tolist())
|
170 |
+
return text_output
|
171 |
+
|
172 |
+
title = "Nano GPT"
|
173 |
+
|
174 |
+
description1 = "Nano GPT trained on Shakespeare dataset. Trained on very small dataset to understand how GPT's are trained and built. The implementation can be found <a href='https://github.com/karpathy/nanoGPT'>here.</a>"
|
175 |
+
|
176 |
+
shakespeare_interface = gr.Interface(shakespeare_outputs,
|
177 |
+
inputs=[gr.Textbox(label="Enter any prompt ", type="text", value="Once upon a time,"),
|
178 |
+
gr.Slider(minimum=100, maximum=5000, step=100, value=2000, label="Max new tokens")],
|
179 |
+
outputs=gr.Textbox(label="Output generated", type="text"), description=description1)
|
180 |
+
|
181 |
+
demo = gr.TabbedInterface([shakespeare_interface], tab_names=["Shakespeare Data"],
|
182 |
+
title=title)
|
183 |
+
|
184 |
+
|
185 |
+
demo.launch()
|
input.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
gradio
|
shakespeaere_language_model.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:37f8d7b1b2db0791255c7f4049e1987ce53eb9ffe3c217efe0b4202b6144a09d
|
3 |
+
size 946898
|