Upload modeling_chronogpt.py with huggingface_hub
Browse files- modeling_chronogpt.py +196 -0
modeling_chronogpt.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
@torch.inference_mode()
|
17 |
+
def forward(self, x):
|
18 |
+
return F.linear(x, self.weight.type_as(x))
|
19 |
+
|
20 |
+
class Rotary(nn.Module):
|
21 |
+
def __init__(self, dim, max_seq_len=65536):
|
22 |
+
super().__init__()
|
23 |
+
angular_freq = (1 / 1024) ** torch.linspace(0, 1, steps=dim//4, dtype=torch.float32)
|
24 |
+
angular_freq = torch.cat([angular_freq, angular_freq.new_zeros(dim//4)])
|
25 |
+
t = torch.arange(max_seq_len, dtype=torch.float32)
|
26 |
+
theta = torch.einsum('i,j -> ij', t, angular_freq)
|
27 |
+
self.register_buffer('cos', theta.cos(), persistent=False)
|
28 |
+
self.register_buffer('sin', theta.sin(), persistent=False)
|
29 |
+
@torch.inference_mode()
|
30 |
+
def forward(self, x):
|
31 |
+
cos, sin = self.cos[None, :x.size(-3), None, :], self.sin[None, :x.size(-3), None, :]
|
32 |
+
x1, x2 = x.float().chunk(2, dim=-1)
|
33 |
+
y1 = x1 * cos + x2 * sin
|
34 |
+
y2 = x1 * (-sin) + x2 * cos
|
35 |
+
return torch.cat((y1, y2), 3).type_as(x)
|
36 |
+
|
37 |
+
class CausalSelfAttention(nn.Module):
|
38 |
+
def __init__(self, dim, num_heads):
|
39 |
+
super().__init__()
|
40 |
+
assert dim % num_heads == 0
|
41 |
+
self.num_heads = num_heads
|
42 |
+
self.head_dim = dim // num_heads
|
43 |
+
self.c_q = CastedLinear(dim, dim)
|
44 |
+
self.c_k = CastedLinear(dim, dim)
|
45 |
+
self.c_v = CastedLinear(dim, dim)
|
46 |
+
self.lambdas = nn.Parameter(torch.tensor([0.5, 0.5]))
|
47 |
+
self.rotary = Rotary(self.head_dim)
|
48 |
+
self.c_proj = CastedLinear(dim, dim)
|
49 |
+
self.register_buffer('kv_cache', None, persistent=False)
|
50 |
+
@torch.inference_mode()
|
51 |
+
def forward(self, x, ve):
|
52 |
+
B, T = x.size(0), x.size(1)
|
53 |
+
q = self.c_q(x).view(B, T, self.num_heads, self.head_dim)
|
54 |
+
k = self.c_k(x).view(B, T, self.num_heads, self.head_dim)
|
55 |
+
v = self.c_v(x).view(B, T, self.num_heads, self.head_dim)
|
56 |
+
if ve is not None:
|
57 |
+
v = self.lambdas[0] * v + self.lambdas[1] * ve.view_as(v)
|
58 |
+
else:
|
59 |
+
v = self.lambdas[0] * v
|
60 |
+
q, k = norm(q), norm(k)
|
61 |
+
q, k = self.rotary(q), self.rotary(k)
|
62 |
+
if self.kv_cache is not None:
|
63 |
+
k = torch.cat([self.kv_cache[0], k], dim=1)
|
64 |
+
v = torch.cat([self.kv_cache[1], v], dim=1)
|
65 |
+
self.kv_cache = torch.stack([k, v])
|
66 |
+
if hasattr(F, 'scaled_dot_product_attention'):
|
67 |
+
y = F.scaled_dot_product_attention(
|
68 |
+
q.transpose(1, 2),
|
69 |
+
k.transpose(1, 2),
|
70 |
+
v.transpose(1, 2),
|
71 |
+
is_causal=True
|
72 |
+
)
|
73 |
+
else:
|
74 |
+
att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.head_dim))
|
75 |
+
att = att.masked_fill(
|
76 |
+
torch.triu(torch.ones(T, T, device=x.device), diagonal=1).bool(),
|
77 |
+
float('-inf')
|
78 |
+
)
|
79 |
+
att = F.softmax(att, dim=-1)
|
80 |
+
y = att @ v
|
81 |
+
y = y.transpose(1, 2).contiguous().view(B, T, -1)
|
82 |
+
y = self.c_proj(y)
|
83 |
+
return y
|
84 |
+
|
85 |
+
class MLP(nn.Module):
|
86 |
+
def __init__(self, dim):
|
87 |
+
super().__init__()
|
88 |
+
self.c_fc = CastedLinear(dim, 4 * dim)
|
89 |
+
self.c_proj = CastedLinear(4 * dim, dim)
|
90 |
+
self.c_proj.weight.data.zero_()
|
91 |
+
@torch.inference_mode()
|
92 |
+
def forward(self, x):
|
93 |
+
x = self.c_fc(x)
|
94 |
+
x = F.relu(x).square()
|
95 |
+
x = self.c_proj(x)
|
96 |
+
return x
|
97 |
+
|
98 |
+
class Block(nn.Module):
|
99 |
+
def __init__(self, model_dim, num_heads, use_attn=True):
|
100 |
+
super().__init__()
|
101 |
+
self.attn = CausalSelfAttention(model_dim, num_heads) if use_attn else None
|
102 |
+
self.mlp = MLP(model_dim)
|
103 |
+
self.lambdas = nn.Parameter(torch.tensor([1., 0.]))
|
104 |
+
@torch.inference_mode()
|
105 |
+
def forward(self, x, ve, x0):
|
106 |
+
x = self.lambdas[0] * x + self.lambdas[1] * x0
|
107 |
+
if self.attn is not None:
|
108 |
+
x = x + self.attn(norm(x), ve)
|
109 |
+
x = x + self.mlp(norm(x))
|
110 |
+
return x
|
111 |
+
|
112 |
+
class ValueEmbedding(nn.Module):
|
113 |
+
def __init__(self, vocab_size, model_dim):
|
114 |
+
super().__init__()
|
115 |
+
self.embed = nn.ModuleList([nn.Embedding(vocab_size, model_dim) for _ in range(3)])
|
116 |
+
@torch.inference_mode()
|
117 |
+
def forward(self, inputs):
|
118 |
+
ve = [emb(inputs).bfloat16() for emb in self.embed]
|
119 |
+
ve = [ve[0], ve[1], ve[2], None, None, None, None, None, None, ve[0], ve[1], ve[2]]
|
120 |
+
return ve
|
121 |
+
|
122 |
+
class ChronoGPT(nn.Module, PyTorchModelHubMixin):
|
123 |
+
def __init__(self, vocab_size, num_layers, num_heads, model_dim, **kwargs):
|
124 |
+
super().__init__()
|
125 |
+
# Removed undefined "device" reference
|
126 |
+
self.num_heads = num_heads
|
127 |
+
self.vocab_size = vocab_size
|
128 |
+
self.embed = nn.Embedding(vocab_size, model_dim)
|
129 |
+
self.blocks = nn.ModuleList([Block(model_dim, num_heads, use_attn=(i != 7))
|
130 |
+
for i in range(num_layers)])
|
131 |
+
self.value_embeds = ValueEmbedding(vocab_size, model_dim)
|
132 |
+
self.lm_head = CastedLinear(model_dim, vocab_size)
|
133 |
+
self.lm_head.weight.data.zero_()
|
134 |
+
self.num_encoder_layers = num_layers // 2
|
135 |
+
self.num_decoder_layers = num_layers - self.num_encoder_layers
|
136 |
+
self.skip_weights = nn.Parameter(torch.ones(self.num_decoder_layers))
|
137 |
+
@torch.inference_mode()
|
138 |
+
def forward(self, inputs, past_key_values=None):
|
139 |
+
B = inputs.size(0)
|
140 |
+
if inputs.dim() == 1:
|
141 |
+
inputs = inputs.unsqueeze(0)
|
142 |
+
layer_outputs = []
|
143 |
+
x0 = norm(self.embed(inputs).bfloat16())
|
144 |
+
x = x0
|
145 |
+
layer_outputs.append(norm(x))
|
146 |
+
ve = [self.value_embeds(inputs[i].view(-1)) for i in range(B)]
|
147 |
+
ve = [torch.stack([ve[b][i] for b in range(B)]) if ve[0][i] is not None else None
|
148 |
+
for i in range(len(ve[0]))]
|
149 |
+
ve_enc, ve_dec = ve[:self.num_encoder_layers], ve[self.num_encoder_layers:]
|
150 |
+
if past_key_values is not None:
|
151 |
+
for i, block in enumerate(self.blocks):
|
152 |
+
if block.attn is not None:
|
153 |
+
block.attn.kv_cache = past_key_values[i]
|
154 |
+
present = []
|
155 |
+
skip_connections = []
|
156 |
+
for i in range(self.num_encoder_layers):
|
157 |
+
block = self.blocks[i]
|
158 |
+
x = block(x, ve_enc[i], x0)
|
159 |
+
if block.attn is not None:
|
160 |
+
present.append(block.attn.kv_cache)
|
161 |
+
block.attn.kv_cache = None
|
162 |
+
skip_connections.append(x)
|
163 |
+
layer_outputs.append(norm(x))
|
164 |
+
for i in range(self.num_decoder_layers):
|
165 |
+
x = x + self.skip_weights[i] * skip_connections.pop()
|
166 |
+
block = self.blocks[self.num_encoder_layers + i]
|
167 |
+
x = block(x, ve_dec[i], x0)
|
168 |
+
layer_outputs.append(norm(x))
|
169 |
+
if block.attn is not None:
|
170 |
+
present.append(block.attn.kv_cache)
|
171 |
+
block.attn.kv_cache = None
|
172 |
+
x = norm(x)
|
173 |
+
logits = self.lm_head(x)
|
174 |
+
logits = 15 * torch.tanh(logits / 15)
|
175 |
+
return logits.float(), layer_outputs
|
176 |
+
def save_pretrained(self, save_directory, **kwargs):
|
177 |
+
os.makedirs(save_directory, exist_ok=True)
|
178 |
+
torch.save(self.state_dict(), os.path.join(save_directory, "pytorch_model.bin"))
|
179 |
+
config = {
|
180 |
+
"model_type": "ChronoGPT",
|
181 |
+
"vocab_size": self.embed.num_embeddings,
|
182 |
+
"num_layers": len(self.blocks),
|
183 |
+
"num_heads": self.num_heads,
|
184 |
+
"model_dim": self.embed.embedding_dim
|
185 |
+
}
|
186 |
+
torch.save(config, os.path.join(save_directory, "config.pt"))
|
187 |
+
with open(os.path.join(save_directory, "config.json"), "w") as f:
|
188 |
+
json.dump(config, f)
|
189 |
+
@classmethod
|
190 |
+
def from_pretrained(cls, repo_id, cache_dir=None, **kwargs):
|
191 |
+
config_path = hf_hub_download(repo_id=repo_id, filename="config.pt", cache_dir=cache_dir)
|
192 |
+
bin_path = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin", cache_dir=cache_dir)
|
193 |
+
config = torch.load(config_path)
|
194 |
+
model = cls(**config)
|
195 |
+
model.load_state_dict(torch.load(bin_path))
|
196 |
+
return model
|