hashtagg1 commited on
Commit
fb9477a
·
verified ·
1 Parent(s): 20501bf

Upload 4 files

Browse files
Files changed (4) hide show
  1. config.json +40 -0
  2. model.py +637 -0
  3. presets.py +42 -0
  4. tokenizer.json +0 -0
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "vocab_size": 32768,
3
+ "hidden_size": 128,
4
+ "num_layers": 4,
5
+ "max_seq_len": 512,
6
+ "rms_eps": 1e-06,
7
+ "full_attn_every": 4,
8
+ "num_heads": 2,
9
+ "q_lora_rank": 64,
10
+ "kv_lora_rank": 32,
11
+ "qk_nope_head_dim": 32,
12
+ "qk_rope_head_dim": 16,
13
+ "v_head_dim": 64,
14
+ "rope_theta": 10000.0,
15
+ "kda_head_dim": 64,
16
+ "kda_conv_size": 4,
17
+ "kda_gate_lower_bound": -5.0,
18
+ "num_experts": 8,
19
+ "experts_per_token": 2,
20
+ "num_shared_experts": 1,
21
+ "moe_latent_size": 96,
22
+ "moe_intermediate_size": 64,
23
+ "dense_intermediate_size": 512,
24
+ "first_k_dense": 1,
25
+ "num_expert_groups": 2,
26
+ "topk_groups": 1,
27
+ "routed_scaling": 2.5,
28
+ "swiglu_limit": 10.0,
29
+ "moe_capacity_factor": 2.0,
30
+ "hc_mult": 4,
31
+ "hc_sinkhorn_iters": 20,
32
+ "attn_res_block_size": 2,
33
+ "engram_layers": [
34
+ 1
35
+ ],
36
+ "engram_max_ngram": 3,
37
+ "engram_table_size": 65521,
38
+ "engram_heads": 2,
39
+ "engram_head_dim": 32
40
+ }
model.py ADDED
@@ -0,0 +1,637 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ try:
6
+ from fla.ops.kda import chunk_kda
7
+ except ImportError:
8
+ chunk_kda = None
9
+
10
+ USE_FLA_KDA = True
11
+
12
+ @dataclass
13
+ class MeridianConfig:
14
+ # core
15
+ vocab_size: int = 32768
16
+ hidden_size: int = 512
17
+ num_layers: int = 12
18
+ max_seq_len: int = 2048
19
+ rms_eps: float = 1e-6
20
+
21
+ # attention (MLA): full attention every 4th layer
22
+ full_attn_every: int = 4
23
+ num_heads: int = 8
24
+ q_lora_rank: int = 256
25
+ kv_lora_rank: int = 128
26
+ qk_nope_head_dim: int = 64
27
+ qk_rope_head_dim: int = 32
28
+ v_head_dim: int = 64
29
+ rope_theta: float = 10000.0
30
+
31
+ # linear attention (KDA)
32
+ kda_head_dim: int = 64
33
+ kda_conv_size: int = 4
34
+ kda_gate_lower_bound: float = -5.0
35
+
36
+ # MoE
37
+ num_experts: int = 32
38
+ experts_per_token: int = 4
39
+ num_shared_experts: int = 1
40
+ moe_latent_size: int = 384
41
+ moe_intermediate_size: int = 256
42
+ dense_intermediate_size: int = 2048
43
+ first_k_dense: int = 1
44
+ num_expert_groups: int = 4
45
+ topk_groups: int = 2
46
+ routed_scaling: float = 2.5
47
+ swiglu_limit: float = 10.0
48
+ moe_capacity_factor: float = 2.0
49
+
50
+ # mHC + AttnRes
51
+ hc_mult: int = 4
52
+ hc_sinkhorn_iters: int = 20
53
+ attn_res_block_size: int = 4
54
+
55
+ # Engram
56
+ engram_layers: tuple = (1, 6)
57
+ engram_max_ngram: int = 3
58
+ engram_table_size: int = 524_287
59
+ engram_heads: int = 4
60
+ engram_head_dim: int = 64
61
+
62
+ def is_full_attn(self, layer_idx):
63
+ return (layer_idx + 1) % self.full_attn_every == 0
64
+
65
+
66
+ class RMSNorm(nn.Module):
67
+ def __init__(self, dim, eps=1e-6):
68
+ super().__init__()
69
+ self.eps = eps
70
+ self.weight = nn.Parameter(torch.ones(dim))
71
+
72
+ def forward(self, x):
73
+ rms = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
74
+ return (x.float() * rms * self.weight.float()).type_as(x)
75
+
76
+
77
+ def build_rope_cache(seq_len, dim, theta, device=None):
78
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, device=device).float () / dim))
79
+ t = torch.arange(seq_len, device=device).float()
80
+ freqs = torch.outer(t, inv_freq)
81
+ emb = torch.cat([freqs, freqs], dim=-1)
82
+ return emb.cos(), emb.sin()
83
+
84
+
85
+ def rotate_half(x):
86
+ x1, x2 = x.chunk(2, dim=-1)
87
+ return torch.cat([-x2, x1], dim=-1)
88
+
89
+
90
+ def apply_rope(x, cos, sin):
91
+ return x * cos + rotate_half(x) * sin
92
+
93
+
94
+ class MLA(nn.Module):
95
+ def __init__(self, cfg):
96
+ super().__init__()
97
+ self.num_heads = cfg.num_heads
98
+ self.nope = cfg.qk_nope_head_dim
99
+ self.rope = cfg.qk_rope_head_dim
100
+ self.v_dim = cfg.v_head_dim
101
+ self.kv_rank = cfg.kv_lora_rank
102
+ h = cfg.num_heads
103
+
104
+ self.q_a = nn.Linear(cfg.hidden_size, cfg.q_lora_rank, bias=False)
105
+ self.q_norm = RMSNorm(cfg.q_lora_rank, cfg.rms_eps)
106
+ self.q_b = nn.Linear(cfg.q_lora_rank, h * (self.nope + self.rope), bias=False)
107
+
108
+ self.kv_a = nn.Linear(cfg.hidden_size, self.kv_rank + self.rope, bias=False)
109
+ self.kv_norm = RMSNorm(self.kv_rank, cfg.rms_eps)
110
+ self.kv_b = nn.Linear(self.kv_rank, h * (self.nope + self.v_dim), bias=False)
111
+
112
+ self.gate = nn.Linear(cfg.hidden_size, h * self.v_dim, bias=False)
113
+ self.o_proj = nn.Linear(h * self.v_dim, cfg.hidden_size, bias=False)
114
+
115
+ def forward(self, x, cos, sin):
116
+ b, s, _ = x.shape
117
+ h = self.num_heads
118
+
119
+ q = self.q_b(self.q_norm(self.q_a(x)))
120
+ q = q.view(b, s, h, self.nope + self.rope).transpose(1, 2)
121
+ q_nope, q_rope = q.split([self.nope, self.rope], dim=-1)
122
+
123
+ c_kv, k_rope = self.kv_a(x).split([self.kv_rank, self.rope], dim=-1)
124
+ kv = self.kv_b(self.kv_norm(c_kv))
125
+ kv = kv.view(b, s, h, self.nope + self.v_dim).transpose(1, 2)
126
+ k_nope, v = kv.split([self.nope, self.v_dim], dim=-1)
127
+
128
+ q_rope = apply_rope(q_rope, cos, sin)
129
+ k_rope = apply_rope(k_rope.unsqueeze(1), cos, sin).expand(b, h, s, self.rope)
130
+
131
+ q = torch.cat([q_nope, q_rope], dim=-1)
132
+ k = torch.cat([k_nope, k_rope], dim=-1)
133
+
134
+ out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
135
+ out = out.transpose(1, 2).reshape(b, s, h * self.v_dim)
136
+ out = out * torch.sigmoid(self.gate(x))
137
+ return self.o_proj(out)
138
+
139
+
140
+ def kda_recurrent(q, k, v, a, beta):
141
+ out_dtype = v.dtype
142
+ q, k, v, a, beta = (x.float() for x in (q, k, v, a, beta))
143
+ b, s, h, dk = q.shape
144
+ dv = v.shape[-1]
145
+
146
+ S = torch.zeros(b, h, dk, dv, device=q.device)
147
+ outs = []
148
+ for t in range(s):
149
+ S = S * a[:, t, :, :, None]
150
+ pred = torch.einsum("bhk,bhkv->bhv", k[:, t], S)
151
+ S = S + beta[:, t, :, None, None] * k[:, t, :, :, None] * (v[:, t] - pred)[:, :, None, :]
152
+ outs.append(torch.einsum("bhk,bhkv->bhv", q[:, t], S))
153
+
154
+ return torch.stack(outs, dim=1).to(out_dtype)
155
+
156
+
157
+ class KDA(nn.Module):
158
+ def __init__(self, cfg):
159
+ super().__init__()
160
+ self.num_heads = cfg.num_heads
161
+ self.head_dim = cfg.kda_head_dim
162
+ self.lower_bound = cfg.kda_gate_lower_bound
163
+ inner = cfg.num_heads * cfg.kda_head_dim
164
+
165
+ self.qkv = nn.Linear(cfg.hidden_size, 3 * inner, bias=False)
166
+ self.conv = nn.Conv1d(3 * inner, 3 * inner, cfg.kda_conv_size,
167
+ groups=3 * inner, padding=cfg.kda_conv_size - 1, bias=False)
168
+ self.a_proj = nn.Linear(cfg.hidden_size, inner, bias=False)
169
+ self.b_proj = nn.Linear(cfg.hidden_size, cfg.num_heads, bias=False)
170
+ self.o_norm = RMSNorm(cfg.kda_head_dim, cfg.rms_eps)
171
+ self.gate = nn.Linear(cfg.hidden_size, inner, bias=False)
172
+ self.o_proj = nn.Linear(inner, cfg.hidden_size, bias=False)
173
+
174
+ def forward(self, x):
175
+ b, s, _ = x.shape
176
+ h, d = self.num_heads, self.head_dim
177
+
178
+ qkv = self.conv(self.qkv(x).transpose(1, 2))[..., :s].transpose(1, 2)
179
+ q, k, v = F.silu(qkv).chunk(3, dim=-1)
180
+
181
+ q = F.normalize(q.view(b, s, h, d), dim=-1) * d ** -0.5
182
+ k = F.normalize(k.view(b, s, h, d), dim=-1)
183
+ v = v.view(b, s, h, d)
184
+
185
+ log_a = (self.lower_bound * torch.sigmoid(self.a_proj(x).float())).view(b, s, h, d)
186
+ beta = torch.sigmoid(self.b_proj(x))
187
+
188
+ if x.is_cuda and chunk_kda is not None and USE_FLA_KDA:
189
+ dt = v.dtype
190
+ o, _ = chunk_kda(q=q.to(dt), k=k.to(dt), v=v.to(dt), g=log_a, beta=beta.to(dt), scale=1.0)
191
+ else:
192
+ o = kda_recurrent(q, k, v, log_a.exp(), beta)
193
+ o = self.o_norm(o)
194
+ o = o.reshape(b, s, h * d) * torch.sigmoid(self.gate(x))
195
+ return self.o_proj(o)
196
+
197
+
198
+ class SwiGLU(nn.Module):
199
+ def __init__(self, dim, hidden, limit):
200
+ super().__init__()
201
+ self.limit = limit
202
+ self.gate = nn.Linear(dim, hidden, bias=False)
203
+ self.up = nn.Linear(dim, hidden, bias=False)
204
+ self.down = nn.Linear(hidden, dim, bias=False)
205
+
206
+ def forward(self, x):
207
+ g = self.gate(x).clamp(max=self.limit)
208
+ u = self.up(x).clamp(-self.limit, self.limit)
209
+ return self.down(F.silu(g) * u)
210
+
211
+
212
+ class MoE(nn.Module):
213
+ def __init__(self, cfg):
214
+ super().__init__()
215
+ E, L, I = cfg.num_experts, cfg.moe_latent_size, cfg.moe_intermediate_size
216
+ self.num_experts = E
217
+ self.k = cfg.experts_per_token
218
+ self.n_groups = cfg.num_expert_groups
219
+ self.per_group = E // cfg.num_expert_groups
220
+ self.topk_groups = cfg.topk_groups
221
+ self.scaling = cfg.routed_scaling
222
+ self.limit = cfg.swiglu_limit
223
+
224
+ self.router = nn.Linear(cfg.hidden_size, E, bias=False)
225
+ self.register_buffer("route_bias", torch.zeros(E))
226
+ self.register_buffer("expert_counts", torch.zeros(E), persistent=False)
227
+
228
+ self.latent_down = nn.Linear(cfg.hidden_size, L, bias=False)
229
+ self.latent_norm = RMSNorm(L, cfg.rms_eps)
230
+ self.latent_up = nn.Linear(L, cfg.hidden_size, bias=False)
231
+
232
+ self.w_gate = nn.Parameter(torch.randn(E, L, I) * 0.02)
233
+ self.w_up = nn.Parameter(torch.randn(E, L, I) * 0.02)
234
+ self.w_down = nn.Parameter(torch.randn(E, I, L) * 0.02)
235
+
236
+ self.shared = SwiGLU(cfg.hidden_size, I * cfg.num_shared_experts, cfg.swiglu_limit)
237
+ self.capacity_factor = cfg.moe_capacity_factor
238
+
239
+ def route(self, x):
240
+ scores = torch.sigmoid(self.router(x).float())
241
+ biased = scores + self.route_bias
242
+
243
+ grouped = biased.view(-1, self.n_groups, self.per_group)
244
+ group_scores = grouped.topk(2, dim=-1).values.sum(-1)
245
+ top_groups = group_scores.topk(self.topk_groups, dim=-1).indices
246
+ group_mask = torch.zeros_like(group_scores).scatter_(1, top_groups, 1.0)
247
+ expert_mask = group_mask.unsqueeze(-1).expand_as(grouped).reshape(-1, self.num_experts)
248
+
249
+ masked = biased.masked_fill(expert_mask == 0, float("-inf"))
250
+ idx = masked.topk(self.k, dim=-1).indices
251
+ weights = scores.gather(1, idx)
252
+ weights = weights / weights.sum(-1, keepdim=True) * self.scaling
253
+ return weights, idx
254
+
255
+ def forward(self, x):
256
+ b, s, d = x.shape
257
+ x_flat = x.reshape(-1, d)
258
+ n = x_flat.shape[0]
259
+ weights, idx = self.route(x_flat)
260
+
261
+ flat_e = idx.reshape(-1)
262
+ counts = torch.zeros(self.num_experts, device=x.device)
263
+ counts.scatter_add_(0, flat_e, torch.ones_like(flat_e, dtype=counts.dtype))
264
+ if self.training:
265
+ self.expert_counts += counts
266
+
267
+ cap = int(self.capacity_factor * n * self.k / self.num_experts) + 1
268
+ order = torch.argsort(flat_e, stable=True)
269
+ starts = (torch.cumsum(counts, 0) - counts).long()
270
+ rank_sorted = torch.arange(flat_e.numel(), device=x.device) - starts[flat_e[order]]
271
+ rank = torch.empty_like(rank_sorted).scatter_(0, order, rank_sorted)
272
+ slot = rank.clamp(max=cap)
273
+ keep = (rank < cap).to(weights.dtype)
274
+
275
+ z = self.latent_norm(self.latent_down(x_flat))
276
+ buf = z.new_zeros(self.num_experts, cap + 1, z.shape[-1])
277
+ buf[flat_e, slot] = z.repeat_interleave(self.k, dim=0)
278
+
279
+ g = torch.bmm(buf, self.w_gate).clamp(max=self.limit)
280
+ u = torch.bmm(buf, self.w_up).clamp(-self.limit, self.limit)
281
+ h = torch.bmm(F.silu(g) * u, self.w_down)
282
+
283
+ w = (weights.reshape(-1) * keep).unsqueeze(-1).to(h.dtype)
284
+ out = (h[flat_e, slot] * w).view(n, self.k, -1).sum(1).to(z.dtype)
285
+
286
+ y = self.latent_up(out) + self.shared(x_flat)
287
+ return y.view(b, s, d)
288
+
289
+ def forward_reference(self, x):
290
+ b, s, d = x.shape
291
+ x_flat = x.reshape(-1, d)
292
+ weights, idx = self.route(x_flat)
293
+ if self.training:
294
+ self.expert_counts += torch.bincount(idx.flatten(), minlength=self.num_experts).float()
295
+
296
+ z = self.latent_norm(self.latent_down(x_flat))
297
+ out = torch.zeros_like(z)
298
+ for e in range(self.num_experts):
299
+ token_ids, slot = (idx == e).nonzero(as_tuple=True)
300
+ if token_ids.numel() == 0:
301
+ continue
302
+ ze = z[token_ids]
303
+ g = (ze @ self.w_gate[e]).clamp(max=self.limit)
304
+ u = (ze @ self.w_up[e]).clamp(-self.limit, self.limit)
305
+ h = (F.silu(g) * u) @ self.w_down[e]
306
+ out.index_add_(0, token_ids, (h * weights[token_ids, slot, None]).to(out.dtype))
307
+
308
+ y = self.latent_up(out) + self.shared(x_flat)
309
+ return y.view(b, s, d)
310
+
311
+ @torch.no_grad()
312
+ def update_bias(self, rate=1e-3):
313
+ load = self.expert_counts
314
+ self.route_bias += rate * torch.sign(load.mean() - load)
315
+ self.expert_counts.zero_()
316
+
317
+
318
+ def sinkhorn(logits, iters):
319
+ m = (logits - logits.amax(dim=(-1, -2), keepdim=True)).exp()
320
+ for _ in range(iters):
321
+ m = m / m.sum(-1, keepdim=True)
322
+ m = m / m.sum(-2, keepdim=True)
323
+ return m
324
+
325
+
326
+ _sinkhorn_compiled = torch.compile(sinkhorn)
327
+
328
+
329
+ USE_COMPILED_SINKHORN = True
330
+
331
+
332
+ def sinkhorn_fast(logits, iters):
333
+ if logits.shape[-1] == 1:
334
+ return torch.ones_like(logits)
335
+ if logits.is_cuda and USE_COMPILED_SINKHORN:
336
+ return _sinkhorn_compiled(logits, iters)
337
+ return sinkhorn(logits, iters)
338
+
339
+
340
+ class HyperConnection(nn.Module):
341
+ def __init__(self, cfg):
342
+ super().__init__()
343
+ n, d = cfg.hc_mult, cfg.hidden_size
344
+ self.n = n
345
+ self.iters = cfg.hc_sinkhorn_iters
346
+
347
+ self.norm = RMSNorm(n * d, cfg.rms_eps)
348
+ self.proj = nn.Linear(n * d, n + n + n * n, bias=False)
349
+ nn.init.zeros_(self.proj.weight)
350
+ self.alpha = nn.Parameter(torch.full((3,), 0.01))
351
+
352
+ self.b_pre = nn.Parameter(torch.full((n,), -1.0986))
353
+ self.b_post = nn.Parameter(torch.zeros(n))
354
+ self.b_res = nn.Parameter(torch.eye(n) * 4.0)
355
+
356
+ def forward(self, streams, fn):
357
+ b, s, n, d = streams.shape
358
+ h = self.proj(self.norm(streams.reshape(b, s, n * d))).float()
359
+ h_pre, h_post, h_res = h.split([n, n, n * n], dim=-1)
360
+
361
+ pre = torch.sigmoid(self.alpha[0] * h_pre + self.b_pre)
362
+ post = 2 * torch.sigmoid(self.alpha[1] * h_post + self.b_post)
363
+ res = sinkhorn_fast(self.alpha[2] * h_res.view(b, s, n, n) + self.b_res, self.iters)
364
+
365
+ x_in = torch.einsum("bsn,bsnd->bsd", pre.to(streams.dtype), streams)
366
+ y = fn(x_in)
367
+
368
+ mixed = torch.einsum("bsmn,bsnd->bsmd", res.to(streams.dtype), streams)
369
+ return mixed + post.to(streams.dtype).unsqueeze(-1) * y.unsqueeze(2)
370
+
371
+
372
+ class AttnRes(nn.Module):
373
+ def __init__(self, cfg):
374
+ super().__init__()
375
+ self.norm = RMSNorm(cfg.hidden_size, cfg.rms_eps)
376
+ self.query = nn.Parameter(torch.zeros(cfg.hidden_size))
377
+
378
+ def forward(self, snapshots):
379
+ stack = torch.stack(snapshots, dim=0)
380
+ keys = self.norm(stack.mean(dim=3))
381
+ scores = torch.einsum("kbsd,d->kbs", keys.float(), self.query.float())
382
+ w = torch.softmax(scores, dim=0)
383
+ return torch.einsum("kbs,kbsnd->bsnd", w.to(stack.dtype), stack)
384
+
385
+
386
+ class Engram(nn.Module):
387
+ def __init__(self, cfg):
388
+ super().__init__()
389
+ self.orders = list(range(2, cfg.engram_max_ngram + 1))
390
+ self.heads = cfg.engram_heads
391
+ self.table_size = cfg.engram_table_size
392
+ n_lookups = len(self.orders) * cfg.engram_heads
393
+ mem_dim = n_lookups * cfg.engram_head_dim
394
+
395
+ self.table = nn.Embedding(cfg.engram_table_size, cfg.engram_head_dim)
396
+ nn.init.normal_(self.table.weight, std=0.02)
397
+
398
+ g = torch.Generator().manual_seed(1234)
399
+ mults = torch.randint(1, 2**30, (n_lookups, cfg.engram_max_ngram), generator=g) * 2 + 1
400
+ self.register_buffer("mults", mults)
401
+
402
+ self.key = nn.Linear(mem_dim, cfg.hidden_size, bias=False)
403
+ self.value = nn.Linear(mem_dim, cfg.hidden_size, bias=False)
404
+ self.h_norm = RMSNorm(cfg.hidden_size, cfg.rms_eps)
405
+ self.k_norm = RMSNorm(cfg.hidden_size, cfg.rms_eps)
406
+ d = cfg.hidden_size
407
+ self.conv = nn.Conv1d(d, d, 4, groups=d, padding=3, bias=False)
408
+
409
+ def hash_ids(self, ids):
410
+ b, s = ids.shape
411
+ max_n = max(self.orders)
412
+ padded = F.pad(ids, (max_n - 1, 0), value=0)
413
+ shifted = [padded[:, max_n - 1 - j : max_n - 1 - j + s] for j in range(max_n)]
414
+
415
+ out = []
416
+ i = 0
417
+ for n in self.orders:
418
+ for _ in range(self.heads):
419
+ h = torch.zeros_like(ids)
420
+ for j in range(n):
421
+ h = h ^ (shifted[j] * self.mults[i, j])
422
+ out.append(h % self.table_size)
423
+ i += 1
424
+ return torch.stack(out, dim=-1)
425
+
426
+ def forward(self, h, ids):
427
+ b, s, _ = h.shape
428
+ mem = self.table(self.hash_ids(ids)).reshape(b, s, -1)
429
+ k = self.k_norm(self.key(mem))
430
+ v = self.value(mem)
431
+
432
+ gate = torch.sigmoid((self.h_norm(h) * k).sum(-1, keepdim=True) / h.shape[-1] ** 0.5)
433
+ out = gate * v
434
+ return out + self.conv(out.transpose(1, 2))[..., :s].transpose(1, 2)
435
+
436
+
437
+ class Block(nn.Module):
438
+ def __init__(self, cfg, idx):
439
+ super().__init__()
440
+ d = cfg.hidden_size
441
+ self.full_attn = cfg.is_full_attn(idx)
442
+
443
+ self.engram = Engram(cfg) if idx in cfg.engram_layers else None
444
+ if self.engram is not None:
445
+ self.hc_engram = HyperConnection(cfg)
446
+
447
+ self.mixer_norm = RMSNorm(d, cfg.rms_eps)
448
+ self.mixer = MLA(cfg) if self.full_attn else KDA(cfg)
449
+ self.hc_mixer = HyperConnection(cfg)
450
+
451
+ self.ffn_norm = RMSNorm(d, cfg.rms_eps)
452
+ if idx < cfg.first_k_dense:
453
+ self.ffn = SwiGLU(d, cfg.dense_intermediate_size, cfg.swiglu_limit)
454
+ else:
455
+ self.ffn = MoE(cfg)
456
+ self.hc_ffn = HyperConnection(cfg)
457
+
458
+ def forward(self, streams, ids, cos, sin):
459
+ if self.engram is not None:
460
+ streams = self.hc_engram(streams, lambda z: self.engram(z, ids))
461
+
462
+ if self.full_attn:
463
+ streams = self.hc_mixer(streams, lambda z: self.mixer(self.mixer_norm(z), cos, sin))
464
+ else:
465
+ streams = self.hc_mixer(streams, lambda z: self.mixer(self.mixer_norm(z)))
466
+
467
+ return self.hc_ffn(streams, lambda z: self.ffn(self.ffn_norm(z)))
468
+
469
+
470
+ class MiniMeridian(nn.Module):
471
+ def __init__(self, cfg):
472
+ super().__init__()
473
+ self.cfg = cfg
474
+ d = cfg.hidden_size
475
+
476
+ self.embed = nn.Embedding(cfg.vocab_size, d)
477
+ self.blocks = nn.ModuleList([Block(cfg, i) for i in range(cfg.num_layers)])
478
+
479
+ bs = cfg.attn_res_block_size
480
+ self.boundaries = list(range(bs, cfg.num_layers, bs)) if bs > 0 else []
481
+ self.attn_res = nn.ModuleList([AttnRes(cfg) for _ in self.boundaries])
482
+
483
+ self.final_norm = RMSNorm(d, cfg.rms_eps)
484
+ self.lm_head = nn.Linear(d, cfg.vocab_size, bias=False)
485
+
486
+ cos, sin = build_rope_cache(cfg.max_seq_len, cfg.qk_rope_head_dim, cfg.rope_theta)
487
+ self.register_buffer("rope_cos", cos, persistent=False)
488
+ self.register_buffer("rope_sin", sin, persistent=False)
489
+
490
+ self.apply(self._init_weights)
491
+ for m in self.modules():
492
+ if isinstance(m, HyperConnection):
493
+ nn.init.zeros_(m.proj.weight)
494
+
495
+ def _init_weights(self, m):
496
+ if isinstance(m, (nn.Linear, nn.Embedding)):
497
+ nn.init.normal_(m.weight, std=0.02)
498
+
499
+ def forward(self, ids, targets=None):
500
+ b, s = ids.shape
501
+ x = self.embed(ids)
502
+ streams = x.unsqueeze(2).expand(-1, -1, self.cfg.hc_mult, -1).contiguous()
503
+ cos, sin = self.rope_cos[:s], self.rope_sin[:s]
504
+
505
+ snapshots = [streams]
506
+ for i, block in enumerate(self.blocks):
507
+ if i in self.boundaries:
508
+ snapshots.append(streams)
509
+ streams = self.attn_res[self.boundaries.index(i)](snapshots)
510
+ streams = block(streams, ids, cos, sin)
511
+
512
+ h = self.final_norm(streams.mean(dim=2))
513
+ logits = self.lm_head(h)
514
+ if targets is None:
515
+ return logits
516
+
517
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)).float(), targets.view(-1))
518
+ return logits, loss
519
+
520
+
521
+ if __name__ == "__main__":
522
+ cfg = MeridianConfig()
523
+ print("full-attn layers:", [i for i in range(cfg.num_layers) if cfg.is_full_attn(i)])
524
+
525
+ norm = RMSNorm(cfg.hidden_size)
526
+ x = torch.randn(2, 16, cfg.hidden_size)
527
+ print("norm out:", norm(x).shape)
528
+
529
+ cos, sin = build_rope_cache(16, cfg.qk_rope_head_dim, cfg.rope_theta)
530
+ q = torch.randn(2, cfg.num_heads, 16, cfg.qk_rope_head_dim)
531
+ q_rot = apply_rope(q, cos, sin)
532
+ print("rope out:", q_rot.shape)
533
+ print("length preserved:", torch.allclose(q.norm(dim=-1), q_rot.norm(dim=-1), atol=1e-5))
534
+
535
+ attn = MLA(cfg)
536
+ y = attn(x, cos, sin)
537
+ print("mla out:", y.shape)
538
+
539
+ x2 = x.clone()
540
+ x2[:, -1] = torch.randn(2, cfg.hidden_size)
541
+ y2 = attn(x2, cos, sin)
542
+ print("causal:", torch.allclose(y[:, :-1], y2[:, :-1], atol=1e-5))
543
+
544
+ n_params = sum(p.numel() for p in attn.parameters())
545
+ print(f"mla params: {n_params:,}")
546
+
547
+ kda = KDA(cfg)
548
+ y = kda(x)
549
+ print("kda out:", y.shape)
550
+
551
+ y2 = kda(x2)
552
+ print("kda causal:", torch.allclose(y[:, :-1], y2[:, :-1], atol=1e-5))
553
+
554
+ n_params = sum(p.numel() for p in kda.parameters())
555
+ print(f"kda params: {n_params:,}")
556
+
557
+ moe = MoE(cfg)
558
+ y = moe(x)
559
+ print("moe out:", y.shape)
560
+ print("tokens routed:", int(moe.expert_counts.sum()))
561
+
562
+ w, idx = moe.route(x.reshape(-1, cfg.hidden_size))
563
+ groups = idx // (cfg.num_experts // cfg.num_expert_groups)
564
+ used = torch.zeros(idx.shape[0], cfg.num_expert_groups).scatter_(1, groups, 1.0).sum(-1)
565
+ print("max groups per token:", int(used.max()))
566
+ print("weight sums:", [round(v, 3) for v in w.sum(-1)[:4].tolist()])
567
+
568
+ n_params = sum(p.numel() for p in moe.parameters())
569
+ print(f"moe params: {n_params:,}")
570
+
571
+ moe.capacity_factor = 100.0
572
+ ref = moe.forward_reference(x)
573
+ fast = moe(x)
574
+ print("moe fast matches reference:", torch.allclose(ref, fast, atol=1e-5))
575
+
576
+ hc = HyperConnection(cfg)
577
+ streams = x.unsqueeze(2).expand(-1, -1, cfg.hc_mult, -1).contiguous()
578
+ out = hc(streams, lambda z: torch.zeros_like(z))
579
+ print("hc out:", out.shape)
580
+ print("hc identity:", torch.allclose(out, streams, atol=1e-4))
581
+
582
+ m = sinkhorn(torch.randn(5, 4, 4), cfg.hc_sinkhorn_iters)
583
+ print("row sums:", [round(v, 3) for v in m.sum(-1)[0].tolist()])
584
+ print("col sums:", [round(v, 3) for v in m.sum(-2)[0].tolist()])
585
+
586
+ if torch.cuda.is_available():
587
+ lg = torch.randn(4, 2048, 4, 4, device="cuda")
588
+ same = torch.allclose(sinkhorn(lg, 20), sinkhorn_fast(lg, 20), atol=1e-5)
589
+ print("compiled sinkhorn matches:", same)
590
+
591
+ n_params = sum(p.numel() for p in hc.parameters())
592
+ print(f"hc params: {n_params:,}")
593
+
594
+ ar = AttnRes(cfg)
595
+ snaps = [torch.randn(2, 16, cfg.hc_mult, cfg.hidden_size) for _ in range(3)]
596
+ out = ar(snaps)
597
+ print("attnres out:", out.shape)
598
+ print("attnres uniform at init:", torch.allclose(out, torch.stack(snaps).mean(0), atol=1e-5))
599
+
600
+ with torch.no_grad():
601
+ ar.query.copy_(ar.norm(snaps[0].mean(dim=2))[0, 0] * 10)
602
+ w_first = torch.softmax(torch.einsum("kbsd,d->kbs", ar.norm(torch.stack(snaps).mean(3)), ar.query), dim=0)
603
+ print("attnres can focus:", round(w_first[0, 0, 0].item(), 3))
604
+
605
+ n_params = sum(p.numel() for p in ar.parameters())
606
+ print(f"attnres params: {n_params:,}")
607
+
608
+ eng = Engram(cfg)
609
+ ids = torch.randint(0, cfg.vocab_size, (2, 16))
610
+ out = eng(x, ids)
611
+ print("engram out:", out.shape)
612
+
613
+ ids2 = ids.clone()
614
+ ids2[:, -1] = (ids2[:, -1] + 1) % cfg.vocab_size
615
+ out2 = eng(x, ids2)
616
+ print("engram causal:", torch.allclose(out[:, :-1], out2[:, :-1], atol=1e-5))
617
+
618
+ rep = torch.tensor([[5, 6, 7, 1, 5, 6, 7]])
619
+ rows = eng.hash_ids(rep)
620
+ print("same trigram, same rows:", torch.equal(rows[0, 2], rows[0, 6]))
621
+
622
+ n_params = sum(p.numel() for p in eng.parameters())
623
+ print(f"engram params: {n_params:,}")
624
+
625
+ model = MiniMeridian(cfg)
626
+ ids = torch.randint(0, cfg.vocab_size, (2, 16))
627
+ targets = torch.randint(0, cfg.vocab_size, (2, 16))
628
+ logits, loss = model(ids, targets)
629
+ print("model logits:", logits.shape)
630
+ print("initial loss:", round(loss.item(), 3))
631
+
632
+ loss.backward()
633
+ missing = [n for n, p in model.named_parameters() if p.grad is None]
634
+ print("params without grads:", len(missing))
635
+
636
+ total = sum(p.numel() for p in model.parameters())
637
+ print(f"total params: {total:,}")
presets.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ from model import MeridianConfig
3
+
4
+ TINY = dict(
5
+ model=MeridianConfig(
6
+ hidden_size=128, num_layers=4, max_seq_len=512, num_heads=2,
7
+ q_lora_rank=64, kv_lora_rank=32, qk_nope_head_dim=32, qk_rope_head_dim=16, v_head_dim=64,
8
+ num_experts=8, experts_per_token=2, num_expert_groups=2, topk_groups=1,
9
+ moe_latent_size=96, moe_intermediate_size=64, dense_intermediate_size=512,
10
+ attn_res_block_size=2, engram_layers=(1,), engram_table_size=65_521,
11
+ engram_heads=2, engram_head_dim=32,
12
+ ),
13
+ seq_len=512, micro_batch=8, grad_accum=1, total_tokens=20_000_000,
14
+ peak_lr=2e-3, eval_every=100, ckpt_every=500, out_dir="runs/tiny",
15
+ )
16
+
17
+ FULL = dict(
18
+ model=MeridianConfig(),
19
+ seq_len=2048, micro_batch=1, grad_accum=64, total_tokens=1_000_000_000,
20
+ peak_lr=6e-4, eval_every=250, ckpt_every=500, out_dir="runs/full",
21
+ )
22
+
23
+ ABLATIONS = {
24
+ "--no-attnres": {"attn_res_block_size": 0},
25
+ "--no-engram": {"engram_layers": ()},
26
+ "--no-mhc": {"hc_mult": 1},
27
+ }
28
+
29
+
30
+ def build_run(argv):
31
+ run = dict(TINY if "--tiny" in argv else FULL)
32
+ tags = []
33
+ for flag, changes in ABLATIONS.items():
34
+ if flag in argv:
35
+ run["model"] = dataclasses.replace(run["model"], **changes)
36
+ tags.append(flag.strip("-"))
37
+ seed = 1 if "--seed1" in argv else 0
38
+ if seed:
39
+ tags.append("seed1")
40
+ if tags:
41
+ run["out_dir"] = run["out_dir"] + "_" + "_".join(tags)
42
+ return run, seed
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff