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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import math
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from typing import Optional, List, Tuple
|
8 |
+
from huggingface_hub import PyTorchModelHubMixin, hf_hub_download
|
9 |
+
|
10 |
+
def norm(x):
|
11 |
+
return F.rms_norm(x, (x.size(-1),))
|
12 |
+
|
13 |
+
class CastedLinear(nn.Linear):
|
14 |
+
def __init__(self, in_features, out_features):
|
15 |
+
super().__init__(in_features, out_features, bias=False)
|
16 |
+
|
17 |
+
@torch.inference_mode()
|
18 |
+
def forward(self, x):
|
19 |
+
return F.linear(x, self.weight.type_as(x))
|
20 |
+
|
21 |
+
class Rotary(nn.Module):
|
22 |
+
def __init__(self, dim, max_seq_len=65536):
|
23 |
+
super().__init__()
|
24 |
+
angular_freq = (1 / 1024) ** torch.linspace(0, 1, steps=dim//4, dtype=torch.float32)
|
25 |
+
angular_freq = torch.cat([angular_freq, angular_freq.new_zeros(dim//4)])
|
26 |
+
t = torch.arange(max_seq_len, dtype=torch.float32)
|
27 |
+
theta = torch.einsum('i,j -> ij', t, angular_freq)
|
28 |
+
self.register_buffer('cos', theta.cos(), persistent=False)
|
29 |
+
self.register_buffer('sin', theta.sin(), persistent=False)
|
30 |
+
|
31 |
+
@torch.inference_mode()
|
32 |
+
def forward(self, x):
|
33 |
+
cos, sin = self.cos[None, :x.size(-3), None, :], self.sin[None, :x.size(-3), None, :]
|
34 |
+
x1, x2 = x.float().chunk(2, dim=-1)
|
35 |
+
y1 = x1 * cos + x2 * sin
|
36 |
+
y2 = x1 * (-sin) + x2 * cos
|
37 |
+
return torch.cat((y1, y2), 3).type_as(x)
|
38 |
+
|
39 |
+
class CausalSelfAttention(nn.Module):
|
40 |
+
def __init__(self, dim, num_heads):
|
41 |
+
super().__init__()
|
42 |
+
assert dim % num_heads == 0
|
43 |
+
self.num_heads = num_heads
|
44 |
+
self.head_dim = dim // num_heads
|
45 |
+
self.c_q = CastedLinear(dim, dim)
|
46 |
+
self.c_k = CastedLinear(dim, dim)
|
47 |
+
self.c_v = CastedLinear(dim, dim)
|
48 |
+
self.lambdas = nn.Parameter(torch.tensor([0.5, 0.5]))
|
49 |
+
self.rotary = Rotary(self.head_dim)
|
50 |
+
self.c_proj = CastedLinear(dim, dim)
|
51 |
+
self.register_buffer('kv_cache', None, persistent=False)
|
52 |
+
|
53 |
+
@torch.inference_mode()
|
54 |
+
def forward(self, x, ve):
|
55 |
+
B, T = x.size(0), x.size(1)
|
56 |
+
|
57 |
+
# Generate Q, K, V
|
58 |
+
q = self.c_q(x).view(B, T, self.num_heads, self.head_dim)
|
59 |
+
k = self.c_k(x).view(B, T, self.num_heads, self.head_dim)
|
60 |
+
v = self.c_v(x).view(B, T, self.num_heads, self.head_dim)
|
61 |
+
|
62 |
+
if ve is not None:
|
63 |
+
v = self.lambdas[0] * v + self.lambdas[1] * ve.view_as(v)
|
64 |
+
else:
|
65 |
+
v = self.lambdas[0] * v
|
66 |
+
|
67 |
+
q, k = norm(q), norm(k)
|
68 |
+
q, k = self.rotary(q), self.rotary(k)
|
69 |
+
|
70 |
+
# Use KV cache if available
|
71 |
+
if self.kv_cache is not None:
|
72 |
+
k = torch.cat([self.kv_cache[0], k], dim=1)
|
73 |
+
v = torch.cat([self.kv_cache[1], v], dim=1)
|
74 |
+
self.kv_cache = torch.stack([k, v])
|
75 |
+
|
76 |
+
# Efficient attention with flash attention if available
|
77 |
+
if hasattr(F, 'scaled_dot_product_attention'):
|
78 |
+
y = F.scaled_dot_product_attention(
|
79 |
+
q.transpose(1, 2), # (B, num_heads, T, head_dim)
|
80 |
+
k.transpose(1, 2), # (B, num_heads, T, head_dim)
|
81 |
+
v.transpose(1, 2), # (B, num_heads, T, head_dim)
|
82 |
+
is_causal=True
|
83 |
+
)
|
84 |
+
else:
|
85 |
+
# Fallback to regular attention
|
86 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.head_dim))
|
87 |
+
att = att.masked_fill(
|
88 |
+
torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool(),
|
89 |
+
float('-inf')
|
90 |
+
)
|
91 |
+
att = F.softmax(att, dim=-1)
|
92 |
+
y = att @ v
|
93 |
+
|
94 |
+
y = y.transpose(1, 2).contiguous().view(B, T, -1)
|
95 |
+
y = self.c_proj(y)
|
96 |
+
return y
|
97 |
+
|
98 |
+
class MLP(nn.Module):
|
99 |
+
def __init__(self, dim):
|
100 |
+
super().__init__()
|
101 |
+
self.c_fc = CastedLinear(dim, 4 * dim)
|
102 |
+
self.c_proj = CastedLinear(4 * dim, dim)
|
103 |
+
self.c_proj.weight.data.zero_()
|
104 |
+
|
105 |
+
@torch.inference_mode()
|
106 |
+
def forward(self, x):
|
107 |
+
x = self.c_fc(x)
|
108 |
+
x = F.relu(x).square()
|
109 |
+
x = self.c_proj(x)
|
110 |
+
return x
|
111 |
+
|
112 |
+
class Block(nn.Module):
|
113 |
+
def __init__(self, model_dim, num_heads, use_attn=True):
|
114 |
+
super().__init__()
|
115 |
+
self.attn = CausalSelfAttention(model_dim, num_heads) if use_attn else None
|
116 |
+
self.mlp = MLP(model_dim)
|
117 |
+
self.lambdas = nn.Parameter(torch.tensor([1., 0.]))
|
118 |
+
|
119 |
+
@torch.inference_mode()
|
120 |
+
def forward(self, x, ve, x0):
|
121 |
+
x = self.lambdas[0] * x + self.lambdas[1] * x0
|
122 |
+
if self.attn is not None:
|
123 |
+
x = x + self.attn(norm(x), ve)
|
124 |
+
x = x + self.mlp(norm(x))
|
125 |
+
return x
|
126 |
+
|
127 |
+
class ValueEmbedding(nn.Module):
|
128 |
+
def __init__(self, vocab_size, model_dim):
|
129 |
+
super().__init__()
|
130 |
+
self.embed = nn.ModuleList([nn.Embedding(vocab_size, model_dim) for _ in range(3)])
|
131 |
+
|
132 |
+
@torch.inference_mode()
|
133 |
+
def forward(self, inputs):
|
134 |
+
ve = [emb(inputs).bfloat16() for emb in self.embed]
|
135 |
+
ve = [ve[0], ve[1], ve[2], None, None, None, None, None, None, ve[0], ve[1], ve[2]]
|
136 |
+
return ve
|
137 |
+
|
138 |
+
class ChronoGPT(nn.Module, PyTorchModelHubMixin):
|
139 |
+
def __init__(self, vocab_size, num_layers, num_heads, model_dim, **kwargs):
|
140 |
+
super().__init__()
|
141 |
+
self.num_heads = num_heads
|
142 |
+
self.vocab_size = vocab_size # Store vocab_size as instance variable
|
143 |
+
self.embed = nn.Embedding(vocab_size, model_dim)
|
144 |
+
self.blocks = nn.ModuleList([Block(model_dim, num_heads, use_attn=(i != 7))
|
145 |
+
for i in range(num_layers)])
|
146 |
+
self.value_embeds = ValueEmbedding(vocab_size, model_dim)
|
147 |
+
self.lm_head = CastedLinear(model_dim, vocab_size)
|
148 |
+
self.lm_head.weight.data.zero_()
|
149 |
+
self.num_encoder_layers = num_layers // 2
|
150 |
+
self.num_decoder_layers = num_layers - self.num_encoder_layers
|
151 |
+
self.skip_weights = nn.Parameter(torch.ones(self.num_decoder_layers))
|
152 |
+
@torch.inference_mode()
|
153 |
+
def forward(self, inputs, past_key_values=None):
|
154 |
+
B = inputs.size(0)
|
155 |
+
if inputs.dim() == 1:
|
156 |
+
inputs = inputs.unsqueeze(0) # Add batch dimension if not present
|
157 |
+
|
158 |
+
x0 = norm(self.embed(inputs).bfloat16())
|
159 |
+
x = x0
|
160 |
+
|
161 |
+
# Modify value embedding handling for batched input
|
162 |
+
ve = [self.value_embeds(inputs[i].view(-1)) for i in range(B)]
|
163 |
+
ve = [torch.stack([ve[b][i] for b in range(B)]) if ve[0][i] is not None else None
|
164 |
+
for i in range(len(ve[0]))]
|
165 |
+
ve_enc, ve_dec = ve[:self.num_encoder_layers], ve[self.num_encoder_layers:]
|
166 |
+
|
167 |
+
# Handle cached states for batched input
|
168 |
+
if past_key_values is not None:
|
169 |
+
for i, block in enumerate(self.blocks):
|
170 |
+
if block.attn is not None:
|
171 |
+
block.attn.kv_cache = past_key_values[i]
|
172 |
+
|
173 |
+
present = []
|
174 |
+
layer_outputs = []
|
175 |
+
skip_connections = []
|
176 |
+
|
177 |
+
# Process through encoder layers
|
178 |
+
for i in range(self.num_encoder_layers):
|
179 |
+
block = self.blocks[i]
|
180 |
+
x = block(x, ve_enc[i], x0)
|
181 |
+
if block.attn is not None:
|
182 |
+
present.append(block.attn.kv_cache)
|
183 |
+
block.attn.kv_cache = None
|
184 |
+
skip_connections.append(x)
|
185 |
+
layer_outputs.append(norm(x))
|
186 |
+
|
187 |
+
# Process through decoder layers
|
188 |
+
for i in range(self.num_decoder_layers):
|
189 |
+
x = x + self.skip_weights[i] * skip_connections.pop()
|
190 |
+
block = self.blocks[self.num_encoder_layers + i]
|
191 |
+
x = block(x, ve_dec[i], x0)
|
192 |
+
layer_outputs.append(norm(x))
|
193 |
+
if block.attn is not None:
|
194 |
+
present.append(block.attn.kv_cache)
|
195 |
+
block.attn.kv_cache = None
|
196 |
+
|
197 |
+
x = norm(x)
|
198 |
+
logits = self.lm_head(x)
|
199 |
+
logits = 15 * torch.tanh(logits / 15)
|
200 |
+
|
201 |
+
return logits.float(), layer_outputs
|
202 |
+
@classmethod
|
203 |
+
def from_pretrained(cls, repo_id, cache_dir=None, **kwargs):
|
204 |
+
config_path = hf_hub_download(repo_id=repo_id, filename="config.pt", cache_dir=cache_dir)
|
205 |
+
bin_path = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin", cache_dir=cache_dir)
|
206 |
+
config = torch.load(config_path)
|
207 |
+
model = cls(**config)
|
208 |
+
model.load_state_dict(torch.load(bin_path))
|
209 |
+
return model
|
210 |
+
|
211 |
+
class ValueEmbedding_xl(nn.Module):
|
212 |
+
def __init__(self, vocab_size, model_dim, num_layers=52):
|
213 |
+
super().__init__()
|
214 |
+
self.num_layers = num_layers
|
215 |
+
# We only have 3 distinct embedding modules, reused at beginning and end.
|
216 |
+
self.embed = nn.ModuleList([nn.Embedding(vocab_size, model_dim) for _ in range(3)])
|
217 |
+
|
218 |
+
def forward(self, inputs):
|
219 |
+
# Compute the base embeddings (a list of length 3)
|
220 |
+
base = [emb(inputs).bfloat16() for emb in self.embed]
|
221 |
+
L = self.num_layers
|
222 |
+
half = L // 2 # number of encoder layers (assumes num_layers is even)
|
223 |
+
# Build encoder: first 3 layers get embeddings, rest get None.
|
224 |
+
encoder = [base[i] if i < 3 else None for i in range(half)]
|
225 |
+
# Build decoder: last 3 layers get embeddings, others get None.
|
226 |
+
# For decoder layers, if i is in [half-3, half-1] then assign base[0], base[1], base[2]
|
227 |
+
decoder = [base[i - (half - 3)] if i >= (half - 3) else None for i in range(half)]
|
228 |
+
return encoder + decoder
|
229 |
+
|
230 |
+
|
231 |
+
class ChronoGPT_xl(nn.Module, PyTorchModelHubMixin):
|
232 |
+
def __init__(self, vocab_size, num_layers, num_heads, model_dim, **kwargs):
|
233 |
+
super().__init__()
|
234 |
+
self.num_heads = num_heads
|
235 |
+
self.vocab_size = vocab_size # Store vocab_size as instance variable
|
236 |
+
self.embed = nn.Embedding(vocab_size, model_dim)
|
237 |
+
self.blocks = nn.ModuleList([Block(model_dim, num_heads, use_attn=True) for i in range(num_layers)])
|
238 |
+
self.value_embeds = ValueEmbedding_xl(vocab_size, model_dim, num_layers=num_layers)
|
239 |
+
self.lm_head = CastedLinear(model_dim, vocab_size)
|
240 |
+
self.lm_head.weight.data.zero_()
|
241 |
+
self.num_encoder_layers = num_layers // 2
|
242 |
+
self.num_decoder_layers = num_layers - self.num_encoder_layers
|
243 |
+
self.skip_weights = nn.Parameter(torch.ones(self.num_decoder_layers))
|
244 |
+
@torch.inference_mode()
|
245 |
+
def forward(self, inputs, past_key_values=None):
|
246 |
+
# Remove fixed batch size assumption
|
247 |
+
B = inputs.size(0) # Get batch size from input tensor
|
248 |
+
if inputs.dim() == 1:
|
249 |
+
inputs = inputs.unsqueeze(0) # Add batch dimension if not present
|
250 |
+
|
251 |
+
x0 = norm(self.embed(inputs).bfloat16())
|
252 |
+
x = x0
|
253 |
+
|
254 |
+
# Modify value embedding handling for batched input
|
255 |
+
ve = [self.value_embeds(inputs[i].view(-1)) for i in range(B)]
|
256 |
+
ve = [torch.stack([ve[b][i] for b in range(B)]) if ve[0][i] is not None else None
|
257 |
+
for i in range(len(ve[0]))]
|
258 |
+
ve_enc, ve_dec = ve[:self.num_encoder_layers], ve[self.num_encoder_layers:]
|
259 |
+
|
260 |
+
# Handle cached states for batched input
|
261 |
+
if past_key_values is not None:
|
262 |
+
for i, block in enumerate(self.blocks):
|
263 |
+
if block.attn is not None:
|
264 |
+
block.attn.kv_cache = past_key_values[i]
|
265 |
+
|
266 |
+
present = []
|
267 |
+
layer_outputs = []
|
268 |
+
skip_connections = []
|
269 |
+
|
270 |
+
# Process through encoder layers
|
271 |
+
for i in range(self.num_encoder_layers):
|
272 |
+
block = self.blocks[i]
|
273 |
+
x = block(x, ve_enc[i], x0)
|
274 |
+
if block.attn is not None:
|
275 |
+
present.append(block.attn.kv_cache)
|
276 |
+
block.attn.kv_cache = None
|
277 |
+
skip_connections.append(x)
|
278 |
+
layer_outputs.append(norm(x))
|
279 |
+
|
280 |
+
# Process through decoder layers
|
281 |
+
for i in range(self.num_decoder_layers):
|
282 |
+
x = x + self.skip_weights[i] * skip_connections.pop()
|
283 |
+
block = self.blocks[self.num_encoder_layers + i]
|
284 |
+
x = block(x, ve_dec[i], x0)
|
285 |
+
layer_outputs.append(norm(x))
|
286 |
+
if block.attn is not None:
|
287 |
+
present.append(block.attn.kv_cache)
|
288 |
+
block.attn.kv_cache = None
|
289 |
+
|
290 |
+
x = norm(x)
|
291 |
+
logits = self.lm_head(x)
|
292 |
+
logits = 15 * torch.tanh(logits / 15)
|
293 |
+
|
294 |
+
return logits.float(), layer_outputs
|
295 |
+
def save_pretrained(self, save_directory, **kwargs):
|
296 |
+
os.makedirs(save_directory, exist_ok=True)
|
297 |
+
torch.save(self.state_dict(), os.path.join(save_directory, "pytorch_model.bin"))
|
298 |
+
config = {
|
299 |
+
"model_type": "ChronoGPT",
|
300 |
+
"vocab_size": self.embed.num_embeddings,
|
301 |
+
"num_layers": len(self.blocks),
|
302 |
+
"num_heads": self.num_heads,
|
303 |
+
"model_dim": self.embed.embedding_dim
|
304 |
+
}
|
305 |
+
torch.save(config, os.path.join(save_directory, "config.pt"))
|
306 |
+
with open(os.path.join(save_directory, "config.json"), "w") as f:
|
307 |
+
json.dump(config, f)
|
308 |
+
@classmethod
|
309 |
+
def from_pretrained(cls, repo_id, cache_dir=None, **kwargs):
|
310 |
+
config_path = hf_hub_download(repo_id=repo_id, filename="config.pt", cache_dir=cache_dir)
|
311 |
+
bin_path = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin", cache_dir=cache_dir)
|
312 |
+
config = torch.load(config_path)
|
313 |
+
model = cls(**config)
|
314 |
+
model.load_state_dict(torch.load(bin_path))
|
315 |
+
return model
|