robber411 commited on
Commit
9b7e570
·
verified ·
1 Parent(s): 5385f28
Files changed (3) hide show
  1. config.json +1 -0
  2. model.safetensors +3 -0
  3. modeling_chronogpt.py +147 -0
config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"model_type": "chronogpt", "architectures": ["ChronoGPTForCausalLM"], "auto_map": {"AutoConfig": "modeling_chronogpt.ChronoGPTConfig", "AutoModelForCausalLM": "modeling_chronogpt.ChronoGPTForCausalLM"}, "vocab_size": 50304, "num_layers": 52, "num_heads": 12, "model_dim": 1536}
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c8d49269b96100140317ceaa2453ffcc3cfcb45c483f4e578fa2cd4473d4c82
3
+ size 3717113244
modeling_chronogpt.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AutoModelForCausalLM-compatible wrapper for ChronoGPT (weights map 1:1 to manelalab/chrono-gpt-v1)."""
2
+ import math
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from transformers import PreTrainedModel, PretrainedConfig
7
+ from transformers.modeling_outputs import CausalLMOutputWithPast
8
+
9
+
10
+ def norm(x):
11
+ return F.rms_norm(x, (x.size(-1),))
12
+
13
+
14
+ class CastedLinear(nn.Linear):
15
+ def __init__(self, in_features, out_features):
16
+ super().__init__(in_features, out_features, bias=False)
17
+ def forward(self, x):
18
+ return F.linear(x, self.weight.type_as(x))
19
+
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
+ 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
+
38
+ class CausalSelfAttention(nn.Module):
39
+ def __init__(self, dim, num_heads):
40
+ super().__init__()
41
+ assert dim % num_heads == 0
42
+ self.num_heads = num_heads
43
+ self.head_dim = dim // num_heads
44
+ self.c_q = CastedLinear(dim, dim)
45
+ self.c_k = CastedLinear(dim, dim)
46
+ self.c_v = CastedLinear(dim, dim)
47
+ self.lambdas = nn.Parameter(torch.tensor([0.5, 0.5]))
48
+ self.rotary = Rotary(self.head_dim)
49
+ self.c_proj = CastedLinear(dim, dim)
50
+ def forward(self, x, ve):
51
+ B, T = x.size(0), x.size(1)
52
+ q = self.c_q(x).view(B, T, self.num_heads, self.head_dim)
53
+ k = self.c_k(x).view(B, T, self.num_heads, self.head_dim)
54
+ v = self.c_v(x).view(B, T, self.num_heads, self.head_dim)
55
+ if ve is not None:
56
+ v = self.lambdas[0] * v + self.lambdas[1] * ve.view_as(v)
57
+ else:
58
+ v = self.lambdas[0] * v
59
+ q, k = norm(q), norm(k)
60
+ q, k = self.rotary(q), self.rotary(k)
61
+ y = F.scaled_dot_product_attention(q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True)
62
+ y = y.transpose(1, 2).contiguous().view(B, T, -1)
63
+ return self.c_proj(y)
64
+
65
+
66
+ class MLP(nn.Module):
67
+ def __init__(self, dim):
68
+ super().__init__()
69
+ self.c_fc = CastedLinear(dim, 4 * dim)
70
+ self.c_proj = CastedLinear(4 * dim, dim)
71
+ def forward(self, x):
72
+ return self.c_proj(F.relu(self.c_fc(x)).square())
73
+
74
+
75
+ class Block(nn.Module):
76
+ def __init__(self, model_dim, num_heads, use_attn=True):
77
+ super().__init__()
78
+ self.attn = CausalSelfAttention(model_dim, num_heads) if use_attn else None
79
+ self.mlp = MLP(model_dim)
80
+ self.lambdas = nn.Parameter(torch.tensor([1., 0.]))
81
+ def forward(self, x, ve, x0):
82
+ x = self.lambdas[0] * x + self.lambdas[1] * x0
83
+ if self.attn is not None:
84
+ x = x + self.attn(norm(x), ve)
85
+ x = x + self.mlp(norm(x))
86
+ return x
87
+
88
+
89
+ class ValueEmbedding(nn.Module):
90
+ def __init__(self, vocab_size, model_dim, num_layers=52):
91
+ super().__init__()
92
+ self.num_layers = num_layers
93
+ self.embed = nn.ModuleList([nn.Embedding(vocab_size, model_dim) for _ in range(3)])
94
+ def forward(self, inputs):
95
+ base = [emb(inputs).bfloat16() for emb in self.embed]
96
+ L = self.num_layers; half = L // 2
97
+ encoder = [base[i] if i < 3 else None for i in range(half)]
98
+ decoder = [base[i - (half - 3)] if i >= (half - 3) else None for i in range(half)]
99
+ return encoder + decoder
100
+
101
+
102
+ class ChronoGPTConfig(PretrainedConfig):
103
+ model_type = "chronogpt"
104
+ def __init__(self, vocab_size=50304, num_layers=52, num_heads=12, model_dim=1536, **kwargs):
105
+ self.vocab_size = vocab_size
106
+ self.num_layers = num_layers
107
+ self.num_heads = num_heads
108
+ self.model_dim = model_dim
109
+ super().__init__(**kwargs)
110
+
111
+
112
+ class ChronoGPTForCausalLM(PreTrainedModel):
113
+ config_class = ChronoGPTConfig
114
+
115
+ def __init__(self, config):
116
+ super().__init__(config)
117
+ self.num_heads = config.num_heads
118
+ self.vocab_size = config.vocab_size
119
+ self.embed = nn.Embedding(config.vocab_size, config.model_dim)
120
+ self.blocks = nn.ModuleList([Block(config.model_dim, config.num_heads, use_attn=True) for _ in range(config.num_layers)])
121
+ self.value_embeds = ValueEmbedding(config.vocab_size, config.model_dim, num_layers=config.num_layers)
122
+ self.lm_head = CastedLinear(config.model_dim, config.vocab_size)
123
+ self.num_encoder_layers = config.num_layers // 2
124
+ self.num_decoder_layers = config.num_layers - self.num_encoder_layers
125
+ self.skip_weights = nn.Parameter(torch.ones(self.num_decoder_layers))
126
+
127
+ @torch.inference_mode()
128
+ def forward(self, input_ids, attention_mask=None, labels=None, **kwargs):
129
+ if input_ids.dim() == 1:
130
+ input_ids = input_ids.unsqueeze(0)
131
+ B = input_ids.size(0)
132
+ x0 = norm(self.embed(input_ids).bfloat16())
133
+ x = x0
134
+ ve = [self.value_embeds(input_ids[i].view(-1)) for i in range(B)]
135
+ ve = [torch.stack([ve[b][i] for b in range(B)]) if ve[0][i] is not None else None for i in range(len(ve[0]))]
136
+ ve_enc, ve_dec = ve[:self.num_encoder_layers], ve[self.num_encoder_layers:]
137
+ skip_connections = []
138
+ for i in range(self.num_encoder_layers):
139
+ x = self.blocks[i](x, ve_enc[i], x0)
140
+ skip_connections.append(x)
141
+ for i in range(self.num_decoder_layers):
142
+ x = x + self.skip_weights[i] * skip_connections.pop()
143
+ x = self.blocks[self.num_encoder_layers + i](x, ve_dec[i], x0)
144
+ x = norm(x)
145
+ logits = self.lm_head(x)
146
+ logits = 15 * torch.tanh(logits / 15)
147
+ return CausalLMOutputWithPast(logits=logits.float())