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|
5 |
+
import tiktoken
|
6 |
+
|
7 |
+
import safetensors.torch
|
8 |
+
|
9 |
+
tokenizer = tiktoken.get_encoding("gpt2")
|
10 |
+
|
11 |
+
import gradio as gr
|
12 |
+
from huggingface_hub import hf_hub_download
|
13 |
+
|
14 |
+
# Define the GPTConfig dataclass
|
15 |
+
@dataclass
|
16 |
+
class GPTConfig:
|
17 |
+
vocab_size : int = 50304
|
18 |
+
n_layer : int = 12
|
19 |
+
n_head : int = 6 # head dim 128 suggested by @Grad62304977
|
20 |
+
n_embd : int = 768
|
21 |
+
|
22 |
+
# Define the Rotary class
|
23 |
+
class Rotary(torch.nn.Module):
|
24 |
+
|
25 |
+
def __init__(self, dim, base=10000):
|
26 |
+
super().__init__()
|
27 |
+
self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
28 |
+
self.seq_len_cached = None
|
29 |
+
self.cos_cached = None
|
30 |
+
self.sin_cached = None
|
31 |
+
|
32 |
+
def forward(self, x):
|
33 |
+
seq_len = x.shape[1]
|
34 |
+
if seq_len!= self.seq_len_cached:
|
35 |
+
self.seq_len_cached = seq_len
|
36 |
+
t = torch.arange(seq_len, device=x.device).type_as(self.inv_freq)
|
37 |
+
freqs = torch.outer(t, self.inv_freq).to(x.device)
|
38 |
+
self.cos_cached = freqs.cos().bfloat16()
|
39 |
+
self.sin_cached = freqs.sin().bfloat16()
|
40 |
+
return self.cos_cached[None, :, None, :], self.sin_cached[None, :, None, :]
|
41 |
+
|
42 |
+
def apply_rotary_emb(x, cos, sin):
|
43 |
+
assert x.ndim == 4 # multihead attention
|
44 |
+
d = x.shape[3]//2
|
45 |
+
x1 = x[..., :d]
|
46 |
+
x2 = x[..., d:]
|
47 |
+
y1 = x1 * cos + x2 * sin
|
48 |
+
y2 = x1 * (-sin) + x2 * cos
|
49 |
+
return torch.cat([y1, y2], 3).type_as(x)
|
50 |
+
|
51 |
+
# Define the CausalSelfAttention class
|
52 |
+
class CausalSelfAttention(torch.nn.Module):
|
53 |
+
|
54 |
+
def __init__(self, config):
|
55 |
+
super().__init__()
|
56 |
+
self.n_head = config.n_head
|
57 |
+
self.n_embd = config.n_embd
|
58 |
+
self.head_dim = self.n_embd // self.n_head
|
59 |
+
assert self.n_embd % self.n_head == 0
|
60 |
+
self.c_q = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
|
61 |
+
self.c_k = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
|
62 |
+
self.c_v = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
|
63 |
+
# output projection
|
64 |
+
self.c_proj = torch.nn.Linear(self.n_embd, self.n_embd, bias=False)
|
65 |
+
self.c_proj.weight.data.zero_() # zero init suggested by @Grad62304977
|
66 |
+
self.rotary = Rotary(self.head_dim)
|
67 |
+
self.lamb = torch.nn.Parameter(torch.tensor(0.5)) # @Grad62304977
|
68 |
+
|
69 |
+
def forward(self, x, v1=None):
|
70 |
+
B, T, C = x.size() # batch size, sequence length, embedding dimensionality (n_embd)
|
71 |
+
q = self.c_q(x).view(B, T, self.n_head, self.head_dim)
|
72 |
+
k = self.c_k(x).view(B, T, self.n_head, self.head_dim)
|
73 |
+
v = self.c_v(x).view(B, T, self.n_head, self.head_dim)
|
74 |
+
if v1 is None:
|
75 |
+
v1 = v # This happens if we are in the first block. v needs to be accessed by subsequent blocks
|
76 |
+
v = (1 - self.lamb) * v + self.lamb * v1.view_as(v) # @Grad62304977
|
77 |
+
cos, sin = self.rotary(q)
|
78 |
+
q, k = F.rms_norm(q, (q.size(-1),)), F.rms_norm(k, (k.size(-1),)) # QK norm suggested by @Grad62304977
|
79 |
+
q, k = apply_rotary_emb(q, cos, sin), apply_rotary_emb(k, cos, sin)
|
80 |
+
y = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True)
|
81 |
+
y = y.transpose(1, 2).contiguous().view_as(x) # re-assemble all head outputs side by side
|
82 |
+
y = self.c_proj(y)
|
83 |
+
return y, v1
|
84 |
+
|
85 |
+
# Define the MLP class
|
86 |
+
class MLP(torch.nn.Module):
|
87 |
+
|
88 |
+
def __init__(self, config):
|
89 |
+
super().__init__()
|
90 |
+
self.c_fc = torch.nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
|
91 |
+
self.c_proj = torch.nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
|
92 |
+
self.c_proj.weight.data.zero_() # zero init suggested by @Grad62304977
|
93 |
+
|
94 |
+
def forward(self, x):
|
95 |
+
x = self.c_fc(x)
|
96 |
+
x = F.relu(x).square() # https://arxiv.org/abs/2109.08668v2; ~1-2% better than GELU; suggested by @SKYLINEZ007 and @Grad62304977
|
97 |
+
x = self.c_proj(x)
|
98 |
+
return x
|
99 |
+
|
100 |
+
# Define the Block class
|
101 |
+
class Block(torch.nn.Module):
|
102 |
+
|
103 |
+
def __init__(self, config):
|
104 |
+
super().__init__()
|
105 |
+
self.attn = CausalSelfAttention(config)
|
106 |
+
self.mlp = MLP(config)
|
107 |
+
self.lambdas = torch.nn.Parameter(torch.tensor([1., 0.]))
|
108 |
+
|
109 |
+
def forward(self, x, v1, x0):
|
110 |
+
x = self.lambdas[0] * x + self.lambdas[1] * x0
|
111 |
+
x1, v1 = self.attn(F.rms_norm(x, (x.size(-1),)), v1)
|
112 |
+
x = x + x1
|
113 |
+
x = x + self.mlp(F.rms_norm(x, (x.size(-1),)))
|
114 |
+
return x, v1
|
115 |
+
|
116 |
+
# Define the GPT class
|
117 |
+
class GPT(torch.nn.Module):
|
118 |
+
|
119 |
+
def __init__(self, config):
|
120 |
+
super().__init__()
|
121 |
+
self.config = config
|
122 |
+
|
123 |
+
self.transformer = torch.nn.ModuleDict(dict(
|
124 |
+
wte = torch.nn.Embedding(config.vocab_size, config.n_embd),
|
125 |
+
h = torch.nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
|
126 |
+
))
|
127 |
+
self.lm_head = torch.nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
128 |
+
self.lm_head.weight.data.zero_() # @Grad62304977
|
129 |
+
|
130 |
+
def forward(self, idx, targets=None, return_logits=True):
|
131 |
+
|
132 |
+
# forward the GPT model itself
|
133 |
+
x = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)
|
134 |
+
x = F.rms_norm(x, (x.size(-1),)) # @Grad62304977
|
135 |
+
x0 = x
|
136 |
+
v1 = None
|
137 |
+
for block in self.transformer.h:
|
138 |
+
x, v1 = block(x, v1, x0)
|
139 |
+
x = F.rms_norm(x, (x.size(-1),))
|
140 |
+
|
141 |
+
if targets is not None:
|
142 |
+
# if we are given some desired targets also calculate the loss
|
143 |
+
logits = self.lm_head(x)
|
144 |
+
logits = 30 * torch.tanh(logits / 30) # @Grad62304977
|
145 |
+
logits = logits.float() # use tf32/fp32 for logits
|
146 |
+
loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
|
147 |
+
else:
|
148 |
+
# inference-time mini-optimization: only forward the lm_head on the very last position
|
149 |
+
logits = self.lm_head(x[:, [-1], :]) # note: using list [-1] to preserve the time dim
|
150 |
+
logits = 30 * torch.tanh(logits / 30) # @Grad62304977
|
151 |
+
logits = logits.float() # use tf32/fp32 for logits
|
152 |
+
loss = None
|
153 |
+
|
154 |
+
# there are performance reasons why not returning logits is prudent, if not needed
|
155 |
+
if not return_logits:
|
156 |
+
logits = None
|
157 |
+
|
158 |
+
return logits, loss
|
159 |
+
|
160 |
+
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
|
161 |
+
"""
|
162 |
+
Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete
|
163 |
+
the sequence max_new_tokens times, feeding the predictions back into the model each time.
|
164 |
+
Most likely you'll want to make sure to be in model.eval() mode of operation for this.
|
165 |
+
"""
|
166 |
+
for _ in range(max_new_tokens):
|
167 |
+
# if the sequence context is growing too long we must crop it at block_size
|
168 |
+
#idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
|
169 |
+
# forward the model to get the logits for the index in the sequence
|
170 |
+
logits, _ = self(idx)
|
171 |
+
# pluck the logits at the final step and scale by desired temperature
|
172 |
+
logits = logits[:, -1, :] / temperature
|
173 |
+
# optionally crop the logits to only the top k options
|
174 |
+
if top_k is not None:
|
175 |
+
v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
|
176 |
+
logits[logits < v[:, [-1]]] = -float('Inf')
|
177 |
+
# apply softmax to convert logits to (normalized) probabilities
|
178 |
+
probs = F.softmax(logits, dim=-1)
|
179 |
+
# sample from the distribution
|
180 |
+
idx_next = torch.multinomial(probs, num_samples=1)
|
181 |
+
# append sampled index to the running sequence and continue
|
182 |
+
idx = torch.cat((idx, idx_next), dim=1)
|
183 |
+
|
184 |
+
return idx
|
185 |
+
|
186 |
+
|
187 |
+
# Run LLM inference
|
188 |
+
def run_inference(model, input_ids, max_new_tokens, temperature):
|
189 |
+
input_ids = torch.tensor(input_ids).unsqueeze(0)
|
190 |
+
return model.generate(input_ids, max_new_tokens=max_new_tokens, temperature=temperature)
|
191 |
+
|
192 |
+
# Main function
|
193 |
+
def load_model():
|
194 |
+
config = GPTConfig()
|
195 |
+
model = GPT(config)
|
196 |
+
model_path = 'nanogpt-speedrun-baseline.safetensors' # replace with your checkpoint path
|
197 |
+
hf_path = hf_hub_download("lemonteaa/nanogpt-speedrun", model_path)
|
198 |
+
missing, unexpected = safetensors.torch.load_model(model, hf_path)
|
199 |
+
model.eval()
|
200 |
+
return model
|
201 |
+
|
202 |
+
nanogpt_model = load_model()
|
203 |
+
|
204 |
+
def text_complete(prompt, max_new_tokens, temperature):
|
205 |
+
input_ids = tokenizer.encode_ordinary(prompt)
|
206 |
+
output_ids = run_inference(nanogpt_model, input_ids, max_new_tokens, temperature)
|
207 |
+
tmp = output_ids.squeeze().tolist()
|
208 |
+
return tokenizer.decode(tmp)
|
209 |
+
|
210 |
+
|
211 |
+
demo = gr.Interface(
|
212 |
+
title="NanoGPT Speedrun Baseline Model Inference Demo",
|
213 |
+
fn=text_complete,
|
214 |
+
inputs=[
|
215 |
+
gr.Text(label="Prompt"),
|
216 |
+
gr.Slider(label="max new tokens", minimum=10, maximum=500, value=100, step=1),
|
217 |
+
gr.Slider(label="temperature", minimum=0.0, maximum=2.0, value=0.9, step=0.1)
|
218 |
+
],
|
219 |
+
outputs=["text"],
|
220 |
+
examples=[["Once upon a time, "], ["A quick and delicious recipe for pancake: "], ["The role of IT in supply chain is "]]
|
221 |
+
)
|
222 |
+
|
223 |
+
demo.queue()
|
224 |
+
demo.launch()
|