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