quantuminfer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +9 -0
  2. package/README.md +96 -2
  3. package/bin/quantuminfer.js +61 -0
  4. package/c27/adapters.py +161 -0
  5. package/c27/harness27.py +349 -0
  6. package/data/input.txt +40000 -0
  7. package/data/wikitext/test.txt +7249 -0
  8. package/engine/API.txt +208 -0
  9. package/engine/PLUGINS.txt +4 -0
  10. package/engine/__init__.py +82 -0
  11. package/engine/adapter.py +505 -0
  12. package/engine/blocks.py +1180 -0
  13. package/engine/c12.py +324 -0
  14. package/engine/c12cu.py +1074 -0
  15. package/engine/ctx.py +87 -0
  16. package/engine/dev.py +11 -0
  17. package/engine/ds4.py +389 -0
  18. package/engine/kernels.py +833 -0
  19. package/engine/model.py +281 -0
  20. package/engine/record.py +140 -0
  21. package/engine/server.py +183 -0
  22. package/engine/spec.py +1030 -0
  23. package/engine/wcode.py +122 -0
  24. package/p27/SPEC.txt +66 -0
  25. package/p27/STATUS.txt +91 -0
  26. package/p27/bench_glm.py +354 -0
  27. package/p27/bench_multi.py +76 -0
  28. package/p27/mkfinal.py +98 -0
  29. package/p27/modal_comp.py +173 -0
  30. package/p27/modal_dl.py +63 -0
  31. package/p27/modal_p27.py +168 -0
  32. package/p27/modal_probe.py +49 -0
  33. package/p27/p27rules.py +29 -0
  34. package/p27/pblocks.py +1242 -0
  35. package/p27/pmodel.py +402 -0
  36. package/p27/pref.py +151 -0
  37. package/p27/prof_glm.py +34 -0
  38. package/p27/quant.py +850 -0
  39. package/p27/recipes/vllm_b300_single_node_tep_b300_agentx_ep.md +353 -0
  40. package/p27/recipes/vllm_b300_single_node_tp_b300_agentx.md +351 -0
  41. package/p27/recipes/vllm_b300_single_node_tp_baseline.md +250 -0
  42. package/p27/recipes/vllm_default_gb300.md +281 -0
  43. package/p27/recipes/vllm_glm53_h200.md +301 -0
  44. package/p27/run_window1.sh +21 -0
  45. package/p27/run_window2.sh +13 -0
  46. package/p27/sweep_glm.py +64 -0
  47. package/p27/t_align.py +42 -0
  48. package/p27/t_combine.py +28 -0
  49. package/p27/t_echo.py +31 -0
  50. package/p27/t_fp8dense.py +59 -0
  51. package/p27/t_fp8speed.py +48 -0
  52. package/p27/t_glm.py +340 -0
  53. package/p27/t_glu.py +30 -0
  54. package/p27/t_gsuf.py +23 -0
  55. package/p27/t_jac.py +22 -0
  56. package/p27/t_moebm.py +30 -0
  57. package/p27/t_nccl.py +36 -0
  58. package/p27/t_online_jac.py +31 -0
  59. package/p27/t_probe.py +4 -0
  60. package/p27/t_router.py +28 -0
  61. package/p27/t_symm.py +50 -0
  62. package/p27/t_tiny.py +116 -0
  63. package/package.json +10 -4
  64. package/results/ANALYSIS.md +156 -0
  65. package/results/comp_vllm_mtp_k5_b300mtp.json +235 -0
  66. package/results/glm53_b300x8_opt4.json +624 -0
  67. package/results/res_glm_c32w3_b300.json +638 -0
  68. package/results/res_glm_final_c32_b300.json +652 -0
  69. package/results/res_glm_multi_final_b300.json +1821 -0
  70. package/results/res_glm_online_b300.json +638 -0
  71. package/results/res_glm_online_fixed_b300.json +638 -0
  72. package/results/res_glm_opt4_b300.json +624 -0
  73. package/results/res_glm_text_plain_batch_b300.json +5792 -0
  74. package/results/res_glm_text_w1_b300.json +1635 -0
  75. package/results/res_glm_text_w3_b300.json +1639 -0
  76. package/results/res_sweep_echo_b300.json +129 -0
  77. package/results/res_sweep_final_b300.json +153 -0
  78. package/results/res_sweep_glm_b300.json +153 -0
  79. package/results/res_techo.json +29 -0
  80. package/results/res_tgsuf.json +21 -0
  81. package/results/res_tjac.json +17 -0
  82. package/results/res_tonline_jac.json +13 -0
@@ -0,0 +1,1180 @@
1
+ """Generic blocks + registry. A block is one reusable layer type; the adapter (adapter.py) maps every layer of a
2
+ model onto registered blocks. See API.txt for the contract.
3
+
4
+ Every mixer block implements three entry points over a RowCtx (ctx.py):
5
+ prefill(x, ctx) T contiguous rows of ONE user (ctx.b), positions ctx.pos0.. ; updates committed state.
6
+ tree(x, ctx) B*N tree rows (parents ctx.par); must NOT change committed state (may stash scratch on self).
7
+ commit(ctx) commit the accepted path ctx.acc_path (B, MAXL) / ctx.acc_len (B,) of the last tree() call.
8
+ State is allocated by alloc(B, Smax) and is fully owned by the block; state_bytes() reports it.
9
+ """
10
+ import math
11
+
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+ from dev import DEV, CUDA, sync # noqa: F401
16
+ from kernels import (gdn_paths, tree_attn_merge, conv_tree, gdn_gate, gated_rms, qk_norm_rope, mm_f32out, split_hilo,
17
+ attn32_cache_partials, attnhl_cache_partials)
18
+
19
+ BF = torch.bfloat16
20
+ REGISTRY = {}
21
+ ACT = torch.bfloat16 # activation dtype: bf16 (as published engines) or fp32 ("f32a": fp32-faithful mode)
22
+ PREFILL_GDN = "fla" if CUDA else "recurrent" # "fla": chunked WY kernels (bf16 tensor-core products); "recurrent": fp32 sequential walk
23
+ KV_HILO = False # f32a: store the fp32 K/V cache as exact bf16 hi+lo pairs and attend with bf16 tensor cores
24
+ FUSED_GLUE = CUDA # Triton glue kernels for tree rows (conv window, gates, gated norm); False = torch reference ops
25
+
26
+
27
+ def register(name):
28
+ def deco(cls):
29
+ REGISTRY[name] = cls
30
+ cls.kind = name
31
+ return cls
32
+ return deco
33
+
34
+
35
+ def ALLREDUCE(y, g):
36
+ """Tensor-parallel hook: sharded blocks return partial sums; P27 replaces this (identity on one GPU)."""
37
+ return y
38
+
39
+
40
+ def set_precision(p):
41
+ """"bf16": bf16 activations (fast; what vLLM/SGLang compute). "f32a": fp32 activations everywhere (residual
42
+ stream, norms, RoPE, KV cache, conv state, attention, recurrence), the published bf16 weights unchanged; every GEMM
43
+ is x = hi + lo (two bf16 rows, |x - hi - lo| <= 2^-16 |x|) times the bf16 weight with fp32 accumulation and fp32
44
+ output -> the fp32 reference computation up to ~2^-16 relative activation splitting and accumulation order. At
45
+ decode the GEMMs are weight-bandwidth bound, so the doubled rows are nearly free. Call before Model()."""
46
+ global ACT, PREFILL_GDN
47
+ ACT = torch.float32 if p == "f32a" else torch.bfloat16
48
+ PREFILL_GDN = "recurrent" if (p == "f32a" or not CUDA) else "fla"
49
+
50
+
51
+ _MM_OUT = None
52
+
53
+
54
+ def _mm_f32(a, w):
55
+ global _MM_OUT
56
+ if _MM_OUT is None:
57
+ try:
58
+ torch.mm(a[:1], w[:8].t(), out_dtype=torch.float32)
59
+ _MM_OUT = True
60
+ except Exception: # noqa (torch < 2.8: no fp32-output bf16 GEMM in torch -> Triton kernel)
61
+ _MM_OUT = False
62
+ if _MM_OUT:
63
+ return torch.mm(a, w.t(), out_dtype=torch.float32)
64
+ if a.shape[0] <= 128:
65
+ return mm_f32out(a, w)
66
+ return torch.cat([mm_f32out(a[i:i + 128], w) for i in range(0, a.shape[0], 128)], 0)
67
+
68
+
69
+ def lin_f32(x, w):
70
+ """fp32 x times bf16 w -> fp32 (hi/lo split of x, fp32 accumulation and output)."""
71
+ R = x.shape[0]
72
+ if not x.is_cuda or w.dtype == torch.float32: # CPU, or fp32 (multiplier-folded) weight: plain fp32 GEMM
73
+ return F.linear(x, w.float())
74
+ if R > 64:
75
+ _mm_f32(x[:1].to(torch.bfloat16), w[:8]) # resolves _MM_OUT
76
+ if not _MM_OUT: # no fp32-output bf16 GEMM in this torch: fp32 GEMM (TF32 off), CUDA cores
77
+ return F.linear(x, w.float())
78
+ if x.stride(-1) != 1:
79
+ x = x.contiguous()
80
+ y = _mm_f32(split_hilo(x), w) # one kernel writes [hi; lo]
81
+ return y[:R] + y[R:]
82
+
83
+
84
+ def CAT_ROWS(ws):
85
+ """Row-concatenate weights for a fused projection (P27 R3). Plain tensors -> torch.cat; coded weights (objects
86
+ with .lin) must provide a classmethod/staticmethod cat_rows(list) returning one object with .lin (e.g. a
87
+ multi-segment QWeight). Pluggable: a plug-in may replace blocks.CAT_ROWS."""
88
+ if all(isinstance(w, torch.Tensor) for w in ws):
89
+ return torch.cat(ws, 0).contiguous()
90
+ f = getattr(type(next(w for w in ws if not isinstance(w, torch.Tensor))), "cat_rows", None)
91
+ if f is None:
92
+ raise NotImplementedError("fused projection over coded weights without a cat_rows(): " + repr(type(ws[0])))
93
+ return f(ws)
94
+
95
+
96
+ def LINEAR(x, w):
97
+ """Weight-coding hook: every block GEMM goes through here. w is a bf16 tensor, or an object with .lin(x)
98
+ (a coded weight, e.g. wcode.C12Weight) -- the code decides how to multiply. fp32 x -> fp32-faithful GEMM."""
99
+ if x.dtype == torch.float32:
100
+ if not isinstance(w, torch.Tensor):
101
+ raise NotImplementedError("f32a precision with coded weights (decode them first)")
102
+ return lin_f32(x, w)
103
+ if isinstance(w, torch.Tensor):
104
+ return F.linear(x, w)
105
+ return w.lin(x)
106
+
107
+
108
+ def make(spec, W, gspec):
109
+ return REGISTRY[spec["type"]](spec, W, gspec)
110
+
111
+
112
+ def layer_norm(x, w, b, eps):
113
+ """LayerNorm in fp32 (mean-subtracting; Cohere / Starcoder 2), output in the input dtype."""
114
+ return F.layer_norm(x.float(), (x.shape[-1],), w.float(), None if b is None else b.float(), eps).to(x.dtype)
115
+
116
+
117
+ def rms(x, w, eps, offset):
118
+ """offset 1.0: (x_n * (1 + w)).to(dtype) (Qwen3.5 / Gemma style); 0.0: w * x_n.to(dtype) (Llama style)."""
119
+ xf = x.float()
120
+ xn = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps)
121
+ if offset:
122
+ return (xn * (offset + w.float())).to(x.dtype)
123
+ return w * xn.to(x.dtype)
124
+
125
+
126
+ MOE_GROUPED = True # bf16 fused experts on CUDA: grouped Triton GEMM (kernels.moe_bf16_gemm)
127
+ MOE_FUSED_EPI = True # grouped path: silu*up fused into the gate_up GEMM epilogue + one-kernel weighted combine
128
+ MOE_ROUTER_FUSED = True # grouped path: softmax/sigmoid + bias + top-k + renorm in one kernel (kernels.moe_router)
129
+
130
+ class Rope:
131
+ """Non-interleaved (rotate_half) RoPE on the first `rot` dims of each head; text-only mRoPE (t = h = w
132
+ positions) reduces exactly to this."""
133
+ _cache = {}
134
+
135
+ def __init__(self, rope, smax, device=DEV):
136
+ key = (rope["theta"], rope["rot"], smax, rope.get("type"), tuple(rope.get("inv_freq", ())))
137
+ if key not in Rope._cache:
138
+ if "inv_freq" in rope: # HF RoPE variant (llama3 / yarn / linear ...), computed by transformers itself
139
+ inv = torch.tensor(rope["inv_freq"], dtype=torch.float)
140
+ else:
141
+ inv = 1.0 / (rope["theta"] ** (torch.arange(0, rope["rot"], 2, dtype=torch.float) / rope["rot"]))
142
+ sc = rope.get("attn_scale", 1.0)
143
+ fr = torch.arange(smax, dtype=torch.float)[:, None] * inv[None]
144
+ emb = torch.cat([fr, fr], -1)
145
+ cos, sin = emb.cos() * sc, emb.sin() * sc
146
+ Rope._cache[key] = (cos.to(BF).to(device), sin.to(BF).to(device), cos.to(device), sin.to(device))
147
+ self.cos, self.sin, self.cos32, self.sin32 = Rope._cache[key]
148
+ self.rot = rope["rot"]
149
+ self.inter = bool(rope.get("interleave")) # GLM: pairs (2j, 2j+1) rotate with frequency j
150
+
151
+ def __call__(self, x, pos):
152
+ """x (R, H, hd) bf16 or fp32, pos (R,) long."""
153
+ f32 = x.dtype == torch.float32
154
+ c = (self.cos32 if f32 else self.cos)[pos][:, None]
155
+ s = (self.sin32 if f32 else self.sin)[pos][:, None]
156
+ r = self.rot
157
+ xr, xp = x[..., :r], x[..., r:]
158
+ h = r // 2
159
+ if self.inter:
160
+ c, s = c[..., :h].repeat_interleave(2, -1), s[..., :h].repeat_interleave(2, -1)
161
+ rh = torch.stack((-xr[..., 1::2], xr[..., 0::2]), -1).flatten(-2)
162
+ else:
163
+ rh = torch.cat([-xr[..., h:], xr[..., :h]], -1)
164
+ y = xr * c + rh * s
165
+ return torch.cat([y, xp], -1) if xp.shape[-1] else y
166
+
167
+
168
+ @register("dense_glu")
169
+ class DenseGLU:
170
+ def __init__(self, s, W, g):
171
+ p = s["prefix"]
172
+ if W.has(p + "gate_up_proj.weight"): # fused [gate; up] rows (Phi-3, GLM-4)
173
+ if g["tp"]["world"] > 1:
174
+ raise NotImplementedError("fused gate_up_proj under tensor parallelism")
175
+ self.wgu = W.get(p + "gate_up_proj.weight")
176
+ else:
177
+ self.wgu = CAT_ROWS([W.get(p + "gate_proj.weight"), W.get(p + "up_proj.weight")])
178
+ self.wd = W.get(p + "down_proj.weight")
179
+ self.inter = self.wd.shape[1]
180
+ self.clamp = s.get("clamp")
181
+ a = s.get("act", "silu")
182
+ self.act = {"silu": F.silu, "gelu": F.gelu,
183
+ "gelu_pytorch_tanh": lambda t: F.gelu(t, approximate="tanh")}[a]
184
+
185
+ def __call__(self, x):
186
+ gu = LINEAR(x, self.wgu)
187
+ if self.clamp:
188
+ al, lim = self.clamp
189
+ g, u = gu[:, :self.inter].clamp(max=lim), gu[:, self.inter:].clamp(-lim, lim)
190
+ return LINEAR((u + 1) * (g * torch.sigmoid(g * al)), self.wd)
191
+ return LINEAR(self.act(gu[:, :self.inter]) * gu[:, self.inter:], self.wd)
192
+
193
+ def weights(self):
194
+ return {"wgu": self.wgu, "wd": self.wd}
195
+
196
+
197
+ FP4_E2M1 = (0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0)
198
+
199
+
200
+ def mxfp4_dequant(blocks, scales, dtype=torch.bfloat16, lut=None):
201
+ """OCP MXFP4 (gpt-oss checkpoint layout): blocks (E, out, G, 16) uint8 = two e2m1 codes per byte (low nibble
202
+ first), scales (E, out, G) uint8 = shared exponent + 127 per 32 values. Returns (E, in=G*32, out)."""
203
+ if lut is None: # callers inside a CUDA graph pass a resident LUT (no host->device copy during capture)
204
+ lut = torch.tensor(FP4_E2M1, dtype=dtype, device=blocks.device)
205
+ b = blocks.to(torch.uint8)
206
+ v = torch.stack([lut[(b & 0x0F).long()], lut[(b >> 4).long()]], -1).flatten(-2) # (E, out, G, 32)
207
+ v = torch.ldexp(v, (scales.to(torch.int32) - 127)[..., None].to(v.device)).to(dtype)
208
+ return v.flatten(-2).transpose(1, 2).contiguous()
209
+
210
+
211
+ class MXFP4Experts:
212
+ """packed MXFP4 expert stack (resident at ~4.25 bits/weight); item e = dense (in, out) bf16, exact."""
213
+
214
+ def __init__(self, blocks, scales):
215
+ self.blocks, self.scales = blocks, scales
216
+ self.shape = (blocks.shape[0], blocks.shape[2] * 32, blocks.shape[1])
217
+ self.lut = torch.tensor(FP4_E2M1, dtype=torch.bfloat16, device=blocks.device)
218
+
219
+ def __getitem__(self, e):
220
+ return mxfp4_dequant(self.blocks[e:e + 1], self.scales[e:e + 1], lut=self.lut)[0]
221
+
222
+ def parts(self, n):
223
+ return {n + "_blocks": self.blocks, n + "_scales": self.scales}
224
+
225
+
226
+ @register("moe_oss")
227
+ class MoEOss:
228
+ """fused-expert MoE (gpt-oss): router with bias, softmax over the top-k logits, experts (E, d, 2I) with
229
+ interleaved [gate, up] columns + biases, clamped SwiGLU (gate <= limit, |up| <= limit, (up+1)*gate*sigmoid(alpha*gate))."""
230
+
231
+ def __init__(self, s, W, g):
232
+ p = s["prefix"]
233
+ if g["tp"]["world"] > 1:
234
+ raise NotImplementedError("moe_oss under tensor parallelism")
235
+ self.rw = W.get(p + "router.weight")
236
+ self.rb = W.get(p + "router.bias") if W.has(p + "router.bias") else None
237
+
238
+ def experts(n): # dense (E, in, out), or MXFP4 kept packed and dequantised one expert at a time on use
239
+ if W.has(n + "_blocks"):
240
+ return MXFP4Experts(W.get(n + "_blocks"), W.get(n + "_scales"))
241
+ return W.get(n)
242
+ self.gu, self.gub = experts(p + "experts.gate_up_proj"), W.get(p + "experts.gate_up_proj_bias")
243
+ self.dn, self.dnb = experts(p + "experts.down_proj"), W.get(p + "experts.down_proj_bias")
244
+ self.k, self.alpha, self.limit = s["top_k"], s["alpha"], s["limit"]
245
+
246
+ def __call__(self, x):
247
+ lg = F.linear(x, self.rw.to(x.dtype), None if self.rb is None else self.rb.to(x.dtype))
248
+ tv, ti = torch.topk(lg, self.k, dim=-1)
249
+ w = torch.softmax(tv, dim=1, dtype=tv.dtype)
250
+ out = torch.zeros_like(x)
251
+ if x.is_cuda: # graph-capturable: all experts, unrouted rows weighted 0 (no host sync)
252
+ for e in range(self.gu.shape[0]):
253
+ we = (w * (ti == e)).sum(1)
254
+ h = x @ self.gu[e].to(x.dtype) + self.gub[e].to(x.dtype)
255
+ gt, up = h[..., ::2].clamp(max=self.limit), h[..., 1::2].clamp(-self.limit, self.limit)
256
+ y = ((up + 1) * (gt * torch.sigmoid(gt * self.alpha))) @ self.dn[e].to(x.dtype) + self.dnb[e].to(x.dtype)
257
+ out += (y * we[:, None]).to(x.dtype)
258
+ return out
259
+ for e in torch.unique(ti).tolist():
260
+ rows, kk = torch.nonzero(ti == e, as_tuple=True)
261
+ h = x[rows] @ self.gu[e].to(x.dtype) + self.gub[e].to(x.dtype)
262
+ gt, up = h[..., ::2].clamp(max=self.limit), h[..., 1::2].clamp(-self.limit, self.limit)
263
+ y = ((up + 1) * (gt * torch.sigmoid(gt * self.alpha))) @ self.dn[e].to(x.dtype) + self.dnb[e].to(x.dtype)
264
+ out.index_add_(0, rows, (y * w[rows, kk, None]).to(x.dtype))
265
+ return out
266
+
267
+ def weights(self):
268
+ return {k: t for n, w in (("gu", self.gu), ("dn", self.dn))
269
+ for k, t in (w.parts(n) if isinstance(w, MXFP4Experts) else {n: w}).items()}
270
+
271
+
272
+ @register("dense_mlp")
273
+ class DenseMLP:
274
+ """non-gated MLP with optional biases: c_proj(act(c_fc(x))) (Starcoder 2)."""
275
+
276
+ def __init__(self, s, W, g):
277
+ p = s["prefix"]
278
+ if g["tp"]["world"] > 1:
279
+ raise NotImplementedError("dense_mlp under tensor parallelism")
280
+ self.w1, self.w2 = W.get(p + "c_fc.weight"), W.get(p + "c_proj.weight")
281
+ self.b1 = W.get(p + "c_fc.bias") if W.has(p + "c_fc.bias") else None
282
+ self.b2 = W.get(p + "c_proj.bias") if W.has(p + "c_proj.bias") else None
283
+ a = s.get("act", "gelu_pytorch_tanh")
284
+ self.act = {"silu": F.silu, "gelu": F.gelu,
285
+ "gelu_pytorch_tanh": lambda t: F.gelu(t, approximate="tanh")}[a]
286
+
287
+ def __call__(self, x):
288
+ h = LINEAR(x, self.w1)
289
+ if self.b1 is not None:
290
+ h = h + self.b1.to(h.dtype)
291
+ y = LINEAR(self.act(h), self.w2)
292
+ return y + self.b2.to(y.dtype) if self.b2 is not None else y
293
+
294
+ def weights(self):
295
+ return {"w1": self.w1, "w2": self.w2}
296
+
297
+
298
+ def _fa():
299
+ from flash_attn import flash_attn_func, flash_attn_with_kvcache
300
+ return flash_attn_func, flash_attn_with_kvcache
301
+
302
+
303
+ @register("attn")
304
+ class Attention:
305
+ """Full / GQA attention with optional output gate (sigmoid), QK RMSNorm, partial RoPE. KV cache (B, Smax, nkv, hd)
306
+ bf16. Sliding window: prefill honours it; tree verify asserts context <= window. Sinks: not implemented."""
307
+
308
+ def __init__(self, s, W, g):
309
+ p = s["prefix"]
310
+ self.nh, self.nkv, self.hd, self.gate = s["nh"], s["nkv"], s["hd"], s["gate"]
311
+ self.sink = W.get(p + "sinks").float() if s.get("sinks") else None # per-head sink logit (gpt-oss)
312
+ self.window = s.get("window")
313
+ self.eps, self.off = g["eps"], g["norm_offset"]
314
+ if W.has(p + "qkv_proj.weight"): # fused [q; k; v] rows (Phi-3): the layout CAT_ROWS builds
315
+ if g["tp"]["world"] > 1:
316
+ raise NotImplementedError("fused qkv_proj under tensor parallelism")
317
+ self.wqkv = W.get(p + "qkv_proj.weight")
318
+ else:
319
+ self.wqkv = CAT_ROWS([W.get(p + "q_proj.weight"), W.get(p + "k_proj.weight"),
320
+ W.get(p + "v_proj.weight")])
321
+ self.wo = W.get(p + "o_proj.weight")
322
+ self.bqkv = (torch.cat([W.get(p + n + ".bias") for n in ("q_proj", "k_proj", "v_proj")], 0)
323
+ if W.has(p + "q_proj.bias") else None)
324
+ self.bo = W.get(p + "o_proj.bias") if W.has(p + "o_proj.bias") else None
325
+ self.qn = W.get(p + "q_norm.weight") if s["qk_norm"] else None
326
+ self.kn = W.get(p + "k_norm.weight") if s["qk_norm"] else None
327
+ self.nq = self.nh * self.hd * (2 if self.gate else 1)
328
+ self.nk = self.nkv * self.hd
329
+ self.rope_spec = s["rope"]
330
+ self.scale = s.get("scale") or self.hd ** -0.5
331
+ self.softcap = s.get("softcap") # tanh logit softcap (Gemma 2): torch attention paths only
332
+ self.qflat = self.qn is not None and self.qn.numel() != self.hd # QK norm over all heads (OLMo 2)
333
+ self.idx = s.get("indexer") # lightning-indexer block selection (MiniMax-M3): masked torch paths
334
+ if self.idx:
335
+ if self.softcap or self.sink is not None or self.window or self.idx["nh"] != self.nkv:
336
+ raise NotImplementedError("indexer attention with softcap / sinks / window / index heads != kv heads")
337
+ ip = p + "indexer."
338
+ self.iwq, self.iwk = W.get(ip + "q_proj.weight"), W.get(ip + "k_proj.weight")
339
+ self.iqn, self.ikn = W.get(ip + "q_norm.weight"), W.get(ip + "k_norm.weight")
340
+
341
+ def weights(self):
342
+ return {"wqkv": self.wqkv, "wo": self.wo}
343
+
344
+ def alloc(self, B, smax):
345
+ self.f32 = ACT == torch.float32 or not CUDA or bool(self.softcap) or self.sink is not None or bool(self.idx) # head-major cache + torch/fp32 attention (also the CPU path)
346
+ self.hilo = self.f32 and KV_HILO and CUDA and ACT == torch.float32 and not self.idx
347
+ if self.hilo: # exact bf16 pairs: same bytes as fp32, read by bf16 tensor cores
348
+ z = lambda: torch.zeros(B, self.nkv, smax, self.hd, dtype=BF, device=DEV) # noqa: E731
349
+ self.kh, self.kl, self.vh, self.vl = z(), z(), z(), z()
350
+ self.kc = self.kh # shape/smax queries only
351
+ self.vc = self.vh
352
+ elif self.f32: # head-major fp32 cache for the fp32 attention path
353
+ self.kc = torch.zeros(B, self.nkv, smax, self.hd, dtype=ACT, device=DEV)
354
+ self.vc = torch.zeros_like(self.kc)
355
+ else:
356
+ self.kc = torch.zeros(B, smax, self.nkv, self.hd, dtype=BF, device=DEV)
357
+ self.vc = torch.zeros_like(self.kc)
358
+ self.rope = Rope(self.rope_spec, smax)
359
+ self.smax = smax
360
+ if self.idx:
361
+ self.ik = torch.zeros(B, smax, self.idx["hd"], dtype=torch.float32, device=DEV)
362
+
363
+ def state_bytes(self):
364
+ if getattr(self, "hilo", False):
365
+ return 4 * self.kh.numel() * 2
366
+ return 2 * self.kc.numel() * self.kc.element_size()
367
+
368
+ def _put(self, b, sl, k, v):
369
+ """write rows into the cache at [b, :, sl] (head-major layouts) from (T, nkv, hd) k/v."""
370
+ kt, vt = k.transpose(0, 1), v.transpose(0, 1)
371
+ if self.hilo:
372
+ kh = kt.to(BF)
373
+ vh = vt.to(BF)
374
+ self.kh[b, :, sl] = kh
375
+ self.kl[b, :, sl] = (kt - kh.float()).to(BF)
376
+ self.vh[b, :, sl] = vh
377
+ self.vl[b, :, sl] = (vt - vh.float()).to(BF)
378
+ else:
379
+ self.kc[b, :, sl] = kt
380
+ self.vc[b, :, sl] = vt
381
+
382
+ def _kv32(self, b, end):
383
+ if self.hilo:
384
+ return (self.kh[b, :, :end].float() + self.kl[b, :, :end].float(),
385
+ self.vh[b, :, :end].float() + self.vl[b, :, :end].float())
386
+ return self.kc[b, :, :end].float(), self.vc[b, :, :end].float()
387
+
388
+ def reset(self, b=None):
389
+ pass # committed length is owned by the caller (lens); stale KV beyond it is never read
390
+
391
+ def copy_rows(self, src, dst, n=None):
392
+ """user/world fork: KV of users src -> dst (first n positions, default all)."""
393
+ n = n or self.smax
394
+ if self.idx:
395
+ self.ik[dst, :n] = self.ik[src, :n]
396
+ if getattr(self, "hilo", False):
397
+ for t in (self.kh, self.kl, self.vh, self.vl):
398
+ t[dst, :, :n] = t[src, :, :n]
399
+ return
400
+ if self.f32:
401
+ self.kc[dst, :, :n] = self.kc[src, :, :n]
402
+ self.vc[dst, :, :n] = self.vc[src, :, :n]
403
+ return
404
+ self.kc[dst, :n] = self.kc[src, :n]
405
+ self.vc[dst, :n] = self.vc[src, :n]
406
+
407
+ def reset_rows(self, rows):
408
+ pass
409
+
410
+ def fixed_bytes(self):
411
+ return 0
412
+
413
+ def kv_bytes_per_token(self):
414
+ return 2 * self.nkv * self.hd * self.kc.element_size() * (2 if getattr(self, "hilo", False) else 1)
415
+
416
+ def _qkv(self, x, pos):
417
+ R = x.shape[0]
418
+ y = LINEAR(x, self.wqkv)
419
+ if self.bqkv is not None:
420
+ y = y + self.bqkv.to(y.dtype)
421
+ if FUSED_GLUE and self.hd <= 256 and not self.qflat and not self.rope_spec.get("interleave"):
422
+ f32 = y.dtype == torch.float32
423
+ q, k = qk_norm_rope(y, self.qn, self.kn, self.rope.cos32 if f32 else self.rope.cos,
424
+ self.rope.sin32 if f32 else self.rope.sin, pos, self.nh, self.nkv, self.hd,
425
+ self.hd * (2 if self.gate else 1), self.nq, self.rope.rot, self.eps, self.off)
426
+ v = y[:, self.nq + self.nk:].view(R, self.nkv, self.hd)
427
+ gt = y[:, :self.nq].view(R, self.nh, 2 * self.hd)[..., self.hd:].reshape(R, -1) if self.gate else None
428
+ return q, k, v.contiguous(), gt
429
+ if self.gate:
430
+ qg = y[:, :self.nq].view(R, self.nh, 2 * self.hd)
431
+ q, gt = qg[..., :self.hd], qg[..., self.hd:].reshape(R, self.nh * self.hd)
432
+ else:
433
+ q, gt = y[:, :self.nq].view(R, self.nh, self.hd), None
434
+ k = y[:, self.nq:self.nq + self.nk].view(R, self.nkv, self.hd)
435
+ v = y[:, self.nq + self.nk:].view(R, self.nkv, self.hd)
436
+ if self.qflat:
437
+ q = rms(q.reshape(R, -1), self.qn, self.eps, self.off).view(R, self.nh, self.hd)
438
+ k = rms(k.reshape(R, -1), self.kn, self.eps, self.off).view(R, self.nkv, self.hd)
439
+ elif self.qn is not None:
440
+ q = rms(q, self.qn, self.eps, self.off)
441
+ k = rms(k, self.kn, self.eps, self.off)
442
+ q = self.rope(q, pos)
443
+ k = self.rope(k, pos)
444
+ return q.contiguous(), k.contiguous(), v.contiguous(), gt
445
+
446
+ def _out(self, o, gt):
447
+ if gt is not None:
448
+ o = o * torch.sigmoid(gt)
449
+ y = LINEAR(o, self.wo)
450
+ return y if self.bo is None else y + self.bo.to(y.dtype)
451
+
452
+ def _ixf(self, x, pos):
453
+ """indexer features: per-head normed + RoPE'd queries (R, H_idx, d) and the shared key (R, d), fp32."""
454
+ R, d = x.shape[0], self.idx["hd"]
455
+ iq = rms(LINEAR(x, self.iwq).view(R, -1, d), self.iqn, self.eps, self.off)
456
+ ik = rms(LINEAR(x, self.iwk).view(R, 1, d), self.ikn, self.eps, self.off)
457
+ return self.rope(iq, pos).float(), self.rope(ik, pos).float()[:, 0]
458
+
459
+ def _isel(self, si, qpos):
460
+ """si (..., Q, S) index scores (-inf = invisible key), qpos (..., Q) -> key keep mask (..., Q, S): keys in
461
+ the top-k blocks by max score, the `local` blocks ending at the query's own block always kept."""
462
+ bs, S = self.idx["block"], si.shape[-1]
463
+ nb = -(-S // bs)
464
+ if nb * bs != S:
465
+ si = F.pad(si, (0, nb * bs - S), value=float("-inf"))
466
+ blk = si.view(*si.shape[:-1], nb, bs).amax(-1)
467
+ qb = qpos.long() // bs
468
+ for j in range(self.idx["local"]):
469
+ blk = blk.scatter(-1, (qb - j).clamp(min=0)[..., None], float("inf"))
470
+ ts, ti = blk.topk(min(self.idx["topk"], nb), -1)
471
+ keep = torch.zeros_like(blk, dtype=torch.bool).scatter(-1, ti, ts > float("-inf"))
472
+ return keep.repeat_interleave(bs, -1)[..., :S]
473
+
474
+ def _tree_isel(self, sc, st, iq, ctx, B, N, rep):
475
+ """mask tree scores sc (B, nkv, rep*N, smax) / st (B, nkv, rep*N, N) to each row's indexer selection over
476
+ committed keys plus its own root path."""
477
+ S = self.smax
478
+ iq = iq.view(B, N, self.nkv, -1)
479
+ kp = torch.arange(S, device=iq.device)
480
+ si = torch.einsum("bnhd,bsd->bhns", iq, self.ik[:B])
481
+ si = si.masked_fill(kp[None, None, None] >= ctx.lens.long()[:, None, None, None], float("-inf"))
482
+ stt = torch.einsum("bnhd,bmd->bhnm", iq, self._tik).masked_fill(~ctx.shape.anc[None, None], float("-inf"))
483
+ tpos = ctx.pos.long().view(B, N)
484
+ ix = tpos.clamp(max=S - 1)[:, None, None, :].expand(B, self.nkv, N, N)
485
+ si = si.scatter_reduce(-1, ix, stt, "amax") # ancestors sit at distinct positions >= lens
486
+ keep = self._isel(si, tpos[:, None, :].expand(B, self.nkv, N))
487
+ sc = sc.masked_fill(~keep.repeat(1, 1, rep, 1), float("-inf"))
488
+ st = st.masked_fill(~keep.gather(-1, ix).repeat(1, 1, rep, 1), float("-inf"))
489
+ return sc, st
490
+
491
+ def _prefill32(self, x, ctx, chunk=1024):
492
+ T = x.shape[0]
493
+ b, p0 = ctx.b, ctx.pos0
494
+ pos = torch.arange(p0, p0 + T, device=x.device)
495
+ q, k, v, gt = self._qkv(x, pos)
496
+ self._put(b, slice(p0, p0 + T), k, v)
497
+ if self.idx:
498
+ iq, ikk = self._ixf(x, pos)
499
+ self.ik[b, p0:p0 + T] = ikk
500
+ rep = self.nh // self.nkv
501
+ out = torch.empty(T, self.nh, self.hd, dtype=torch.float32, device=x.device)
502
+ q = q.float()
503
+ for s0 in range(0, T, chunk):
504
+ s1 = min(T, s0 + chunk)
505
+ n = s1 - s0
506
+ end = p0 + s1
507
+ qh = q[s0:s1].view(n, self.nkv, rep, self.hd).permute(1, 2, 0, 3).reshape(self.nkv, rep * n, self.hd)
508
+ K32, V32 = self._kv32(b, end)
509
+ sc = torch.matmul(qh, K32.transpose(1, 2)) * self.scale # (nkv, rep*n, end)
510
+ if self.softcap:
511
+ sc = torch.tanh(sc / self.softcap) * self.softcap
512
+ qp = (p0 + s0 + torch.arange(n, device=x.device)).repeat(rep) # query positions, (rep*n,)
513
+ kp = torch.arange(end, device=x.device)
514
+ bad = kp[None, :] > qp[:, None]
515
+ if self.window:
516
+ bad |= kp[None, :] <= qp[:, None] - self.window
517
+ bad = bad[None]
518
+ if self.idx:
519
+ qpos = p0 + s0 + torch.arange(n, device=x.device)
520
+ si = torch.einsum("nhd,sd->hns", iq[s0:s1], self.ik[b, :end])
521
+ si = si.masked_fill(kp[None, None, :] > qpos[None, :, None], float("-inf"))
522
+ bad = bad | ~self._isel(si, qpos[None].expand(self.nkv, n)).repeat(1, rep, 1)
523
+ sc = sc.masked_fill(bad, float("-inf"))
524
+ if self.sink is not None: # extra softmax column per head, dropped after normalising
525
+ sk = self.sink.view(self.nkv, rep, 1).repeat_interleave(n, 1) # rows ordered (rep, n)
526
+ o = torch.matmul(torch.softmax(torch.cat([sc, sk], -1), -1)[..., :-1], V32)
527
+ else:
528
+ o = torch.matmul(torch.softmax(sc, -1), V32) # (nkv, rep*n, hd)
529
+ out[s0:s1] = o.view(self.nkv, rep, n, self.hd).permute(2, 0, 1, 3).reshape(n, self.nh, self.hd)
530
+ return self._out(out.reshape(T, -1).to(x.dtype), gt)
531
+
532
+ def _tree32(self, x, ctx):
533
+ B, N = ctx.B, ctx.N
534
+ q, k, v, gt = self._qkv(x, ctx.pos.reshape(-1))
535
+ self._tk, self._tv = k.view(B, N, self.nkv, self.hd), v.view(B, N, self.nkv, self.hd)
536
+ if self.idx:
537
+ iq, ikk = self._ixf(x, ctx.pos.reshape(-1))
538
+ self._tik = ikk.view(B, N, -1)
539
+ rep = self.nh // self.nkv
540
+ f = torch.float32
541
+ if self.f32 and not self.window and q.is_cuda and not self.softcap and self.sink is None and not self.idx:
542
+ # fp32 flash-decoding over [0, lens) only (cost follows the live context, not smax), then an exact
543
+ # merge of the key chunks with the ancestor-masked tree block (torch, fp32)
544
+ if self.hilo:
545
+ M, Ls, A = attnhl_cache_partials(q.reshape(B * N, -1), self.kh, self.kl, self.vh, self.vl, ctx.lens,
546
+ B, N, self.nh, self.nkv, self.hd, self.scale)
547
+ else:
548
+ M, Ls, A = attn32_cache_partials(q.reshape(B * N, -1), self.kc, self.vc, ctx.lens, B, N, self.nh,
549
+ self.nkv, self.hd, self.scale)
550
+ M, Ls, A = M[..., :N], Ls[..., :N], A[..., :N, :] # (B, nh, S, N[, hd])
551
+ qq = q.view(B, N, self.nh, self.hd).permute(0, 2, 1, 3).float() # (B, nh, N, hd)
552
+ kt = self._tk.float().repeat_interleave(rep, 2).permute(0, 2, 1, 3) # (B, nh, N, hd)
553
+ vt = self._tv.float().repeat_interleave(rep, 2).permute(0, 2, 1, 3)
554
+ st = torch.matmul(qq, kt.transpose(2, 3)) * self.scale # (B, nh, N, N)
555
+ if self.softcap:
556
+ st = torch.tanh(st / self.softcap) * self.softcap
557
+ st = st.masked_fill(~ctx.shape.anc[None, None], float("-inf"))
558
+ mt = st.amax(-1) # (B, nh, N)
559
+ mx = torch.maximum(M.amax(2), mt) # (B, nh, N)
560
+ wc = torch.exp(M - mx[:, :, None]).nan_to_num(0.0) # (B, nh, S, N) (-inf chunks -> 0)
561
+ pt = torch.exp(st - mx[..., None]) # (B, nh, N, N)
562
+ den = (Ls * wc).sum(2) + pt.sum(-1) # (B, nh, N)
563
+ num = (A * wc[..., None]).sum(2) + torch.matmul(pt, vt) # (B, nh, N, hd)
564
+ o = (num / den[..., None]).permute(0, 2, 1, 3).reshape(B * N, self.nh * self.hd).to(q.dtype)
565
+ return self._out(o, gt)
566
+ rep = self.nh // self.nkv
567
+ f = torch.float32
568
+ qh = q.view(B, N, self.nkv, rep, self.hd).permute(0, 2, 3, 1, 4).reshape(B, self.nkv, rep * N, self.hd).to(f)
569
+ kc = (self.kc if self.f32 else self.kc.permute(0, 2, 1, 3)).to(f) # (B, nkv, smax, hd)
570
+ vc = (self.vc if self.f32 else self.vc.permute(0, 2, 1, 3)).to(f)
571
+ sc = torch.matmul(qh, kc.transpose(2, 3)) * self.scale # (B, nkv, rep*N, smax)
572
+ if self.softcap:
573
+ sc = torch.tanh(sc / self.softcap) * self.softcap
574
+ kp = torch.arange(self.smax, device=x.device)
575
+ valid = (kp[None, None, :] < ctx.lens.long()[:, None, None]).expand(B, N, self.smax) # (B, N, smax)
576
+ if self.window: # sliding window relative to each row's own position
577
+ valid = valid & (kp[None, None, :] > ctx.pos[:, :, None] - self.window)
578
+ valid = valid.repeat(1, rep, 1) # rows ordered (rep, N)
579
+ sc = sc.masked_fill(~valid[:, None], float("-inf"))
580
+ kt = self._tk.permute(0, 2, 1, 3).to(f) # (B, nkv, N, hd)
581
+ vt = self._tv.permute(0, 2, 1, 3).to(f)
582
+ st = torch.matmul(qh, kt.transpose(2, 3)) * self.scale # (B, nkv, rep*N, N)
583
+ if self.softcap:
584
+ st = torch.tanh(st / self.softcap) * self.softcap
585
+ anc = ctx.shape.anc # (N, N) bool: m is on n's root path
586
+ st = st.masked_fill(~anc.repeat(rep, 1)[None, None], float("-inf"))
587
+ if self.idx:
588
+ sc, st = self._tree_isel(sc, st, iq, ctx, B, N, rep)
589
+ if self.sink is not None:
590
+ sk = self.sink.view(1, self.nkv, rep, 1).repeat_interleave(N, 2).expand(B, -1, -1, -1)
591
+ p = torch.softmax(torch.cat([sc, st, sk], -1), -1)[..., :-1]
592
+ else:
593
+ p = torch.softmax(torch.cat([sc, st], -1), -1)
594
+ o = torch.matmul(p[..., :self.smax], vc) + torch.matmul(p[..., self.smax:], vt)
595
+ o = o.to(q.dtype)
596
+ o = o.view(B, self.nkv, rep, N, self.hd).permute(0, 3, 1, 2, 4).reshape(B * N, self.nh * self.hd)
597
+ return self._out(o, gt)
598
+
599
+ def prefill(self, x, ctx):
600
+ if self.f32:
601
+ return self._prefill32(x, ctx)
602
+ ffa, _ = _fa()
603
+ T = x.shape[0]
604
+ b, p0 = ctx.b, ctx.pos0
605
+ pos = torch.arange(p0, p0 + T, device=x.device)
606
+ q, k, v, gt = self._qkv(x, pos)
607
+ self.kc[b, p0:p0 + T] = k
608
+ self.vc[b, p0:p0 + T] = v
609
+ ws = (self.window - 1, 0) if self.window else (-1, -1)
610
+ o = ffa(q[None], self.kc[b:b + 1, :p0 + T], self.vc[b:b + 1, :p0 + T], causal=True, window_size=ws,
611
+ softmax_scale=self.scale)[0]
612
+ return self._out(o.reshape(T, -1), gt)
613
+
614
+ def tree(self, x, ctx):
615
+ if self.f32 or self.window: # fp32 mode, or sliding window (masked torch path, correct at any length)
616
+ return self._tree32(x, ctx)
617
+ _, fkv = _fa()
618
+ B, N = ctx.B, ctx.N
619
+ q, k, v, gt = self._qkv(x, ctx.pos.reshape(-1))
620
+ self._tk, self._tv = k.view(B, N, self.nkv, self.hd), v.view(B, N, self.nkv, self.hd)
621
+ oc, lc = fkv(q.view(B, N, self.nh, self.hd), self.kc, self.vc, cache_seqlens=ctx.lens, causal=False,
622
+ softmax_scale=self.scale, return_softmax_lse=True)
623
+ o = tree_attn_merge(q.view(B * N, -1), k.view(B * N, -1), v.view(B * N, -1), ctx.par, oc.reshape(B * N, -1),
624
+ lc.contiguous(), B, N, ctx.maxd, self.nh, self.nkv, self.hd, self.scale)
625
+ return self._out(o, gt)
626
+
627
+ def commit(self, ctx):
628
+ # write accepted rows (and MAXL-acc_len don't-care rows beyond the committed length) at lens + j
629
+ B, ML = ctx.acc_path.shape
630
+ bi = torch.arange(B, device=DEV)[:, None].expand(B, ML)
631
+ dst = (ctx.lens.long()[:, None] + torch.arange(ML, device=DEV)[None]).clamp_(max=self.smax - 1)
632
+ src = ctx.acc_path.long()
633
+ if self.idx:
634
+ self.ik[bi, dst] = self._tik[bi, src]
635
+ if self.f32:
636
+ k, v = self._tk[bi, src], self._tv[bi, src] # (B, ML, nkv, hd)
637
+ if self.hilo:
638
+ kh, vh = k.to(BF), v.to(BF)
639
+ self.kh[bi, :, dst] = kh
640
+ self.kl[bi, :, dst] = (k - kh.float()).to(BF)
641
+ self.vh[bi, :, dst] = vh
642
+ self.vl[bi, :, dst] = (v - vh.float()).to(BF)
643
+ return
644
+ self.kc[bi, :, dst] = k
645
+ self.vc[bi, :, dst] = v
646
+ return
647
+ self.kc[bi, dst] = self._tk[bi, src]
648
+ self.vc[bi, dst] = self._tv[bi, src]
649
+
650
+
651
+ @register("gdn")
652
+ class GatedDeltaNet:
653
+ """Gated DeltaNet (Qwen3-Next / Qwen3.5): causal depthwise conv (width K) + SiLU over [q|k|v], l2-normed q/k,
654
+ decay g = -exp(A_log) softplus(a + dt_bias), beta = sigmoid(b), fp32 recurrent state (B, HV, DK, DV),
655
+ gated RMSNorm (norm(o) * silu(z)), out_proj. Prefill: fla chunk kernel. Tree: kernels.gdn_paths walks every
656
+ node's root path from the committed state (state forking in registers, no copies); commit re-walks the
657
+ accepted path with STORE."""
658
+
659
+ def __init__(self, s, W, g):
660
+ p = s["prefix"]
661
+ self.hk, self.hv, self.dk, self.dv, self.K = s["hk"], s["hv"], s["dk"], s["dv"], s["conv"]
662
+ self.eps = s["eps"]
663
+ self.kd = self.hk * self.dk
664
+ self.vd = self.hv * self.dv
665
+ self.cd = 2 * self.kd + self.vd
666
+ if W.has(p + "in_proj_qkvz.weight"): # Qwen3-Next: rows grouped per key head [q|k|v_g|z_g], [b_g|a_g]
667
+ if g["tp"]["world"] > 1:
668
+ raise NotImplementedError("fused in_proj_qkvz under tensor parallelism")
669
+ hk, r = self.hk, self.hv // self.hk
670
+ wz = W.get(p + "in_proj_qkvz.weight").view(hk, 2 * self.dk + 2 * r * self.dv, -1)
671
+ q, k, v, z = torch.split(wz, [self.dk, self.dk, r * self.dv, r * self.dv], 1)
672
+ bb, aa = torch.split(W.get(p + "in_proj_ba.weight").view(hk, 2 * r, -1), [r, r], 1)
673
+ self.w = torch.cat([t.reshape(-1, t.shape[-1]) for t in (q, k, v, z, bb, aa)], 0).contiguous()
674
+ else:
675
+ self.w = CAT_ROWS([W.get(p + "in_proj_qkv.weight"), W.get(p + "in_proj_z.weight"),
676
+ W.get(p + "in_proj_b.weight"), W.get(p + "in_proj_a.weight")])
677
+ self.convw = W.get(p + "conv1d.weight").reshape(self.cd, self.K).contiguous() # (C, K)
678
+ self.A = -W.get(p + "A_log").float().exp()
679
+ self.dtb = W.get(p + "dt_bias").float()
680
+ self.nw = W.get(p + "norm.weight")
681
+ self.wo = W.get(p + "out_proj.weight")
682
+
683
+ def weights(self):
684
+ return {"w": self.w, "wo": self.wo}
685
+
686
+ def alloc(self, B, smax):
687
+ self.S = torch.zeros(B, self.hv, self.dk, self.dv, dtype=torch.float32, device=DEV)
688
+ self.cs = torch.zeros(B, self.K - 1, self.cd, dtype=ACT, device=DEV)
689
+
690
+ def state_bytes(self):
691
+ return self.S.numel() * 4 + self.cs.numel() * self.cs.element_size()
692
+
693
+ def reset(self, b=None):
694
+ (self.S if b is None else self.S[b]).zero_()
695
+ (self.cs if b is None else self.cs[b]).zero_()
696
+
697
+ def copy_rows(self, src, dst, n=None):
698
+ self.S[dst] = self.S[src]
699
+ self.cs[dst] = self.cs[src]
700
+
701
+ def reset_rows(self, rows):
702
+ self.S[rows] = 0
703
+ self.cs[rows] = 0
704
+
705
+ def fixed_bytes(self):
706
+ return self.hv * self.dk * self.dv * 4 + (self.K - 1) * self.cd * self.cs.element_size()
707
+
708
+ def kv_bytes_per_token(self):
709
+ return 0
710
+
711
+ def _proj(self, x):
712
+ y = LINEAR(x, self.w)
713
+ c = self.cd
714
+ xc = y[:, :c]
715
+ z = y[:, c:c + self.vd]
716
+ bb = y[:, c + self.vd:c + self.vd + self.hv]
717
+ a = y[:, c + self.vd + self.hv:]
718
+ beta = torch.sigmoid(bb.float())
719
+ g = self.A * F.softplus(a.float() + self.dtb)
720
+ return xc, z, beta.contiguous(), g.contiguous()
721
+
722
+ def _post(self, o, z):
723
+ R = o.shape[0]
724
+ of = o.view(R, self.hv, self.dv).float()
725
+ of = of * torch.rsqrt(of.pow(2).mean(-1, keepdim=True) + self.eps)
726
+ dt = z.dtype # activation dtype (bf16, or fp32 in f32a)
727
+ of = self.nw * of.to(dt) if dt == BF else self.nw.float() * of
728
+ of = of.float() * F.silu(z.view(R, self.hv, self.dv).float())
729
+ return LINEAR(of.to(dt).reshape(R, -1), self.wo)
730
+
731
+ def prefill(self, x, ctx):
732
+ b = ctx.b
733
+ T = x.shape[0]
734
+ xc, z, beta, g = self._proj(x)
735
+ cat = torch.cat([self.cs[b], xc], 0) # (K-1+T, C)
736
+ cw = self.convw if cat.dtype == BF else self.convw.float()
737
+ conv = F.conv1d(cat.t()[None], cw[:, None, :], groups=self.cd)[0].t() # (T, C)
738
+ conv = F.silu(conv.float()).to(cat.dtype)
739
+ self.cs[b] = cat[-(self.K - 1):]
740
+ q = conv[:, :self.kd].reshape(1, T, self.hk, self.dk).contiguous()
741
+ k = conv[:, self.kd:2 * self.kd].reshape(1, T, self.hk, self.dk).contiguous()
742
+ v = conv[:, 2 * self.kd:].reshape(1, T, self.hv, self.dv).contiguous()
743
+ if PREFILL_GDN == "recurrent" or conv.dtype == torch.float32:
744
+ o = torch.empty(T, self.vd, dtype=conv.dtype, device=DEV)
745
+ path = torch.arange(T, dtype=torch.int32, device=DEV).view(1, 1, T)
746
+ plen = torch.full((1, 1), T, dtype=torch.int32, device=DEV)
747
+ Sb = self.S[b:b + 1]
748
+ gdn_paths(q.view(T, -1), k.view(T, -1), v.view(T, -1), g, beta, Sb, path, plen, plen, o, T, self.hk,
749
+ self.hv, self.dk, self.dv, store=True, out=False, emit=True)
750
+ return LINEAR(gated_rms(o, z, self.nw, self.hv, self.dv, self.eps), self.wo)
751
+ from fla.ops.gated_delta_rule import chunk_gated_delta_rule
752
+ o, st = chunk_gated_delta_rule(q, k, v, g[None], beta[None], initial_state=self.S[b:b + 1].clone(),
753
+ output_final_state=True, use_qk_l2norm_in_kernel=True)
754
+ self.S[b] = st[0].float()
755
+ return self._post(o[0].reshape(T, -1), z)
756
+
757
+ def tree(self, x, ctx):
758
+ B, N = ctx.B, ctx.N
759
+ if not FUSED_GLUE:
760
+ return self._tree_ref(x, ctx)
761
+ y = LINEAR(x, self.w)
762
+ c = self.cd
763
+ conv = conv_tree(y, self.cs, ctx.cidx_for(self.K), self.convw, B, N, c, self.K)
764
+ g, beta = gdn_gate(y, c + self.vd, c + self.vd + self.hv, self.A, self.dtb, self.hv)
765
+ q = conv[:, :self.kd]
766
+ k = conv[:, self.kd:2 * self.kd]
767
+ v = conv[:, 2 * self.kd:]
768
+ o = torch.empty(B * N, self.vd, dtype=y.dtype, device=DEV)
769
+ # one program per root->leaf branch, emitting every node on the way (work = sum of leaf depths)
770
+ gdn_paths(q, k, v, g, beta, self.S, ctx.lpaths, ctx.lplen, ctx.lplen, o, N, self.hk, self.hv, self.dk,
771
+ self.dv, store=False, out=False, emit=True)
772
+ self._y, self._k, self._v, self._g, self._beta, self._q = y, k, v, g, beta, q
773
+ z = y[:, c:c + self.vd]
774
+ return LINEAR(gated_rms(o, z, self.nw, self.hv, self.dv, self.eps), self.wo)
775
+
776
+ def _tree_ref(self, x, ctx):
777
+ B, N = ctx.B, ctx.N
778
+ xc, z, beta, g = self._proj(x)
779
+ X = torch.cat([self.cs, xc.view(B, N, self.cd)], 1) # (B, K-1+N, C)
780
+ win = X[:, ctx.cidx_for(self.K)] # (B, N, K, C)
781
+ conv = (win.float() * self.convw.t()[None, None].float()).sum(2)
782
+ if X.dtype == BF:
783
+ conv = conv.to(BF).float() # bf16 conv output as F.conv1d in bf16, then SiLU (HF rounding)
784
+ conv = F.silu(conv).to(X.dtype).reshape(B * N, self.cd)
785
+ q = conv[:, :self.kd]
786
+ k = conv[:, self.kd:2 * self.kd]
787
+ v = conv[:, 2 * self.kd:]
788
+ o = torch.empty(B * N, self.vd, dtype=BF, device=DEV)
789
+ gdn_paths(q, k, v, g, beta, self.S, ctx.paths, ctx.plen, ctx.orow, o, N, self.hk, self.hv, self.dk, self.dv,
790
+ store=False, out=True)
791
+ self._X, self._k, self._v, self._g, self._beta, self._q = X, k, v, g, beta, q
792
+ return self._post(o, z)
793
+
794
+ def commit(self, ctx):
795
+ B, N = ctx.B, ctx.N
796
+ gdn_paths(self._q, self._k, self._v, self._g, self._beta, self.S, ctx.acc_path[:, None],
797
+ ctx.acc_len[:, None], ctx.acc_len[:, None], None, N, self.hk, self.hv, self.dk, self.dv,
798
+ store=True, out=False)
799
+ leaf = ctx.leaf # (B,) local row
800
+ idx = ctx.cidx_for(self.K)[leaf][:, 1:] # (B, K-1) indices into [cs | tree rows]
801
+ bi = torch.arange(B, device=DEV)[:, None]
802
+ if FUSED_GLUE:
803
+ X = torch.cat([self.cs, self._y[:, :self.cd].reshape(B, N, self.cd)], 1)
804
+ else:
805
+ X = self._X
806
+ self.cs.copy_(X[bi, idx])
807
+
808
+
809
+ @register("none")
810
+ class NoMLP:
811
+ """layer without a channel mixer (Mamba blocks): contributes zero."""
812
+
813
+ def __init__(self, s, W, g):
814
+ pass
815
+
816
+ def __call__(self, x):
817
+ return torch.zeros_like(x)
818
+
819
+ def weights(self):
820
+ return {}
821
+
822
+
823
+ @register("ssm")
824
+ class MambaSSM:
825
+ """Mamba selective SSM. v1: conv+SiLU over x, x_proj -> [dt_rank | B | C], per-channel dt = softplus(dt_proj),
826
+ state (d_inner, N), y = h.C + D x, y * silu(z). v2: in_proj -> [z | xBC | dt], per-head scalar decay
827
+ exp(dt A), grouped B/C, state (H, P, N), gated RMSNorm(y * silu(z)). fp32 state; conv state as GDN. Prefill:
828
+ sequential fp32 scan. Tree: every node walks its root path from the committed state (decode math, exact);
829
+ commit re-walks the accepted path."""
830
+
831
+ def __init__(self, s, W, g):
832
+ p = s["prefix"]
833
+ if g["tp"]["world"] > 1:
834
+ raise NotImplementedError("mamba ssm under tensor parallelism")
835
+ self.v, self.di, self.N, self.K = s["version"], s["d_inner"], s["state"], s["conv"]
836
+ self.win = W.get(p + "in_proj.weight")
837
+ self.wo = W.get(p + "out_proj.weight")
838
+ self.convw = W.get(p + "conv1d.weight").reshape(-1, self.K).contiguous()
839
+ self.cd = self.convw.shape[0]
840
+ self.convb = W.get(p + "conv1d.bias") if W.has(p + "conv1d.bias") else None
841
+ self.A = -W.get(p + "A_log").float().exp()
842
+ self.D = W.get(p + "D").float()
843
+ if self.v == 1:
844
+ self.R = s["dt_rank"]
845
+ self.wx = W.get(p + "x_proj.weight")
846
+ self.wdt = W.get(p + "dt_proj.weight")
847
+ self.bdt = W.get(p + "dt_proj.bias").float()
848
+ self.sshape = (self.di, self.N)
849
+ self.nrm = {k: W.get(p + k + "_layernorm.weight") for k in ("dt", "b", "c") if W.has(p + k + "_layernorm.weight")}
850
+ self.eps = s["eps"]
851
+ else:
852
+ self.H, self.G = s["heads"], s["groups"]
853
+ self.P = self.di // self.H
854
+ self.dtb = W.get(p + "dt_bias").float()
855
+ self.gmode = s.get("gate", "gate_norm")
856
+ self.ng = s.get("norm_groups", 1)
857
+ self.nw = W.get(p + "norm.weight") if self.gmode != "gate" else None
858
+ self.eps = s["eps"]
859
+ self.lim = s["dt_limit"]
860
+ self.sshape = (self.H, self.P, self.N)
861
+
862
+ def weights(self):
863
+ return {"win": self.win, "wo": self.wo}
864
+
865
+ def alloc(self, B, smax):
866
+ self.S = torch.zeros(B, *self.sshape, dtype=torch.float32, device=DEV)
867
+ self.cs = torch.zeros(B, self.K - 1, self.cd, dtype=ACT, device=DEV)
868
+
869
+ def state_bytes(self):
870
+ return self.S.numel() * 4 + self.cs.numel() * self.cs.element_size()
871
+
872
+ def reset(self, b=None):
873
+ (self.S if b is None else self.S[b]).zero_()
874
+ (self.cs if b is None else self.cs[b]).zero_()
875
+
876
+ def copy_rows(self, src, dst, n=None):
877
+ self.S[dst] = self.S[src]
878
+ self.cs[dst] = self.cs[src]
879
+
880
+ def reset_rows(self, rows):
881
+ self.S[rows] = 0
882
+ self.cs[rows] = 0
883
+
884
+ def fixed_bytes(self):
885
+ n = 1
886
+ for t in self.sshape:
887
+ n *= t
888
+ return n * 4 + (self.K - 1) * self.cd * self.cs.element_size()
889
+
890
+ def kv_bytes_per_token(self):
891
+ return 0
892
+
893
+ def _split(self, y):
894
+ if self.v == 1:
895
+ return y[:, :self.di], y[:, self.di:], None
896
+ return y[:, self.di:self.di + self.cd], y[:, :self.di], y[:, self.di + self.cd:]
897
+
898
+ def _feat(self, u, dtr):
899
+ """u (rows, cd) conv+SiLU output (activation dtype) -> fp32 per-row scan inputs x, dt, B, C."""
900
+ if self.v == 1:
901
+ dbc = LINEAR(u, self.wx)
902
+ ts, Bm, Cm = torch.split(dbc, [self.R, self.N, self.N], -1)
903
+ if self.nrm: # Jamba: RMSNorm on dt / B / C after x_proj
904
+ ts, Bm, Cm = (rms(t, self.nrm[k], self.eps, 0.0) for t, k in ((ts, "dt"), (Bm, "b"), (Cm, "c")))
905
+ dt = F.softplus(LINEAR(ts, self.wdt).float() + self.bdt)
906
+ return u.float(), dt, Bm.float(), Cm.float()
907
+ gn = self.G * self.N
908
+ x, Bm, Cm = u[:, :self.di], u[:, self.di:self.di + gn], u[:, self.di + gn:]
909
+ dt = F.softplus(dtr.float() + self.dtb).clamp(self.lim[0], self.lim[1])
910
+ return x.float(), dt, Bm.float(), Cm.float()
911
+
912
+ def _step(self, S, f, r):
913
+ """one selective-scan step for M independent states: S (M, *state), r (M,) feature rows -> (S', y (M, di))."""
914
+ x, dt, Bm, Cm = f
915
+ d, xr = dt[r], x[r]
916
+ if self.v == 1:
917
+ S = torch.exp(self.A[None] * d[:, :, None]) * S + (d * xr)[:, :, None] * Bm[r][:, None, :]
918
+ return S, (S * Cm[r][:, None, :]).sum(-1) + self.D * xr
919
+ M, rep = r.shape[0], self.H // self.G
920
+ Bh = Bm[r].view(M, self.G, self.N).repeat_interleave(rep, 1)
921
+ Ch = Cm[r].view(M, self.G, self.N).repeat_interleave(rep, 1)
922
+ xh = xr.view(M, self.H, self.P)
923
+ S = torch.exp(d * self.A)[:, :, None, None] * S + (d[:, :, None] * xh)[..., None] * Bh[:, :, None, :]
924
+ return S, ((S * Ch[:, :, None, :]).sum(-1) + self.D[None, :, None] * xh).reshape(M, -1)
925
+
926
+ def _walk(self, S, f, rows, n):
927
+ """advance states S (M, *state) along rows (M, L) for n (M,) steps each; static L, no host reads (graphs)."""
928
+ y = torch.zeros(S.shape[0], self.di, dtype=torch.float32, device=S.device)
929
+ for j in range(rows.shape[1]):
930
+ Sn, yn = self._step(S, f, rows[:, j])
931
+ on = j < n
932
+ S = torch.where(on.view(-1, *([1] * len(self.sshape))), Sn, S)
933
+ y = torch.where(on[:, None], yn, y)
934
+ return S, y
935
+
936
+ def _post(self, y, z):
937
+ dt = z.dtype
938
+ if self.v == 1:
939
+ return LINEAR((y * F.silu(z.float())).to(dt), self.wo)
940
+ if self.gmode == "gate":
941
+ return LINEAR((y * F.silu(z.float())).to(dt), self.wo)
942
+ h = y * F.silu(z.float()) if self.gmode == "gate_norm" else y
943
+ R = h.shape[0]
944
+ hg = h.view(R, self.ng, -1)
945
+ h = (hg * torch.rsqrt(hg.pow(2).mean(-1, keepdim=True) + self.eps)).view(R, -1)
946
+ if self.gmode == "norm_gate":
947
+ h = self.nw.float() * h * F.silu(z.float())
948
+ else:
949
+ h = self.nw * h.to(dt) if dt == BF else self.nw.float() * h
950
+ return LINEAR(h.to(dt), self.wo)
951
+
952
+ def _act(self, conv, dt):
953
+ if dt == BF:
954
+ conv = conv.to(BF)
955
+ return F.silu(conv.float()).to(dt)
956
+
957
+ def prefill(self, x, ctx):
958
+ b = ctx.b
959
+ T = x.shape[0]
960
+ xc, z, dtr = self._split(LINEAR(x, self.win))
961
+ cat = torch.cat([self.cs[b], xc], 0)
962
+ conv = (cat.float().t()[None] if cat.dtype == BF else cat.t()[None])
963
+ conv = F.conv1d(conv, self.convw.float()[:, None, :], None if self.convb is None else self.convb.float(),
964
+ groups=self.cd)[0].t()
965
+ self.cs[b] = cat[-(self.K - 1):]
966
+ f = self._feat(self._act(conv, cat.dtype), dtr)
967
+ S = self.S[b:b + 1].clone()
968
+ ar = torch.arange(T, device=x.device)
969
+ ys = []
970
+ for t in range(T):
971
+ S, yt = self._step(S, f, ar[t:t + 1])
972
+ ys.append(yt[0])
973
+ self.S[b] = S[0]
974
+ return self._post(torch.stack(ys), z)
975
+
976
+ def tree(self, x, ctx):
977
+ B, N = ctx.B, ctx.N
978
+ xc, z, dtr = self._split(LINEAR(x, self.win))
979
+ X = torch.cat([self.cs, xc.reshape(B, N, self.cd)], 1)
980
+ win = X[:, ctx.cidx_for(self.K)] # (B, N, K, C)
981
+ conv = (win.float() * self.convw.t()[None, None].float()).sum(2)
982
+ if self.convb is not None:
983
+ conv = conv + self.convb.float()
984
+ f = self._feat(self._act(conv, X.dtype).reshape(B * N, self.cd), dtr)
985
+ P = ctx.paths.shape[1]
986
+ bN = torch.arange(B, device=x.device)[:, None] * N
987
+ S0 = self.S[:B, None].expand(B, P, *self.sshape).reshape(B * P, *self.sshape)
988
+ rows = (bN[:, :, None] + ctx.paths.long().clamp(min=0)).reshape(B * P, -1)
989
+ n = ctx.plen.long().reshape(-1)
990
+ _, yl = self._walk(S0, f, rows, n)
991
+ orow = torch.where(n > 0, (bN + ctx.orow.long()).reshape(-1), torch.full_like(n, B * N)) # empty -> dummy
992
+ ys = torch.zeros(B * N + 1, self.di, dtype=torch.float32, device=x.device)
993
+ ys[orow] = yl
994
+ ys = ys[:B * N]
995
+ self._X, self._f = X, f
996
+ return self._post(ys, z)
997
+
998
+ def commit(self, ctx):
999
+ B, N = ctx.B, ctx.N
1000
+ bN = torch.arange(B, device=DEV)[:, None] * N
1001
+ S, _ = self._walk(self.S[:B].clone(), self._f, bN + ctx.acc_path.long().clamp(min=0), ctx.acc_len.long())
1002
+ self.S[:B] = S
1003
+ idx = ctx.cidx_for(self.K)[ctx.leaf][:, 1:]
1004
+ bi = torch.arange(B, device=DEV)[:, None]
1005
+ self.cs.copy_(self._X[bi, idx])
1006
+
1007
+
1008
+ @register("par_mix")
1009
+ class ParallelMix:
1010
+ """sum of token mixers fed the same normed input (Falcon-H1: attention + SSM); state / cache ops fan out."""
1011
+
1012
+ def __init__(self, s, W, g):
1013
+ self.parts = [make(p, W, g) for p in s["parts"]]
1014
+
1015
+ def weights(self):
1016
+ return {f"{i}.{k}": v for i, b in enumerate(self.parts) for k, v in b.weights().items()}
1017
+
1018
+ def alloc(self, B, smax):
1019
+ for b in self.parts:
1020
+ b.alloc(B, smax)
1021
+ self.smax = getattr(self.parts[0], "smax", smax)
1022
+
1023
+ def state_bytes(self):
1024
+ return sum(b.state_bytes() for b in self.parts)
1025
+
1026
+ def reset(self, b=None):
1027
+ for p in self.parts:
1028
+ p.reset(b)
1029
+
1030
+ def copy_rows(self, src, dst, n=None):
1031
+ for p in self.parts:
1032
+ p.copy_rows(src, dst, n)
1033
+
1034
+ def reset_rows(self, rows):
1035
+ for p in self.parts:
1036
+ p.reset_rows(rows)
1037
+
1038
+ def fixed_bytes(self):
1039
+ return sum(b.fixed_bytes() for b in self.parts)
1040
+
1041
+ def kv_bytes_per_token(self):
1042
+ return sum(b.kv_bytes_per_token() for b in self.parts)
1043
+
1044
+ def prefill(self, x, ctx):
1045
+ return sum(b.prefill(x, ctx) for b in self.parts)
1046
+
1047
+ def tree(self, x, ctx):
1048
+ return sum(b.tree(x, ctx) for b in self.parts)
1049
+
1050
+ def commit(self, ctx):
1051
+ for b in self.parts:
1052
+ b.commit(ctx)
1053
+
1054
+
1055
+ @register("moe_fused")
1056
+ class MoEFused:
1057
+ """MoE with fused 3-D experts gate_up_proj (E, 2I, d) = [gate | up] rows, down_proj (E, d, I); router softmax or
1058
+ sigmoid + e_score_correction_bias (choice only), optional top-k renorm, routed scale, optional shared expert,
1059
+ optional clamped SwiGLU (MiniMax-M3)."""
1060
+
1061
+ def __init__(self, s, W, g):
1062
+ p = s["prefix"]
1063
+ if g["tp"]["world"] > 1:
1064
+ raise NotImplementedError("moe_fused under tensor parallelism")
1065
+ self.rw = W.get(p + "gate.weight")
1066
+ bn = p + "gate.e_score_correction_bias"
1067
+ self.rb = W.get(bn).float() if W.has(bn) else None
1068
+ self.gu, self.dn = W.get(p + "experts.gate_up_proj"), W.get(p + "experts.down_proj")
1069
+ self.I = self.gu.shape[1] // 2
1070
+ self.k, self.sig, self.norm, self.rs, self.clamp = s["top_k"], s["sigmoid"], s["norm"], s["routed_scale"], s.get("clamp")
1071
+ self.shared = make(s["shared"], W, g) if s.get("shared") else None
1072
+ self.sg = W.get(s["shared_gate"]) if s.get("shared_gate") else None
1073
+
1074
+ def _act(self, h):
1075
+ gt, up = h[..., :self.I], h[..., self.I:]
1076
+ if self.clamp:
1077
+ al, lim = self.clamp
1078
+ gt, up = gt.clamp(max=lim), up.clamp(-lim, lim)
1079
+ return (up + 1) * (gt * torch.sigmoid(gt * al))
1080
+ return F.silu(gt) * up
1081
+
1082
+ def _grouped(self, x, ti, w):
1083
+ """expert-sorted grouped GEMMs (kernels.moe_bf16_gemm); expert output and weighted product rounded to
1084
+ x.dtype, summed in fp32 (= the per-expert loop)."""
1085
+ from kernels import moe_align, moe_bf16_gemm
1086
+ R, k = ti.shape
1087
+ BM = 16 if ti.numel() <= 4 * self.gu.shape[0] else 64
1088
+ pr, be, po = moe_align(ti, self.gu.shape[0], BM)
1089
+ if MOE_FUSED_EPI and not self.clamp:
1090
+ from kernels import moe_combine
1091
+ a = moe_bf16_gemm(x.contiguous(), self.gu, pr, be, BM, glu=True)
1092
+ y = moe_bf16_gemm(a, self.dn, pr, be, BM, slot_rows=True)
1093
+ return moe_combine(y, po, w)
1094
+ h = moe_bf16_gemm(x.contiguous(), self.gu, pr, be, BM)
1095
+ y = moe_bf16_gemm(self._act(h).contiguous(), self.dn, pr, be, BM, slot_rows=True)
1096
+ sel = y[po].view(R, k, -1).float()
1097
+ return (sel * w[:, :, None]).to(x.dtype).float().sum(1)
1098
+
1099
+ def _grouped_final(self, x, ti, w):
1100
+ """the whole layer tail in the combine kernel: bf16(sum) * rs + sigmoid(gate) * shared (torch roundings)."""
1101
+ from kernels import moe_align, moe_bf16_gemm, moe_combine
1102
+ BM = 16 if ti.numel() <= 4 * self.gu.shape[0] else 64
1103
+ pr, be, po = moe_align(ti, self.gu.shape[0], BM)
1104
+ a = moe_bf16_gemm(x.contiguous(), self.gu, pr, be, BM, glu=True)
1105
+ y = moe_bf16_gemm(a, self.dn, pr, be, BM, slot_rows=True)
1106
+ sh = self.shared(x) if self.shared is not None else None
1107
+ if sh is not None and self.sg is not None:
1108
+ sh = torch.sigmoid(F.linear(x, self.sg.to(x.dtype))) * sh
1109
+ return moe_combine(y, po, w, final=True, rs=self.rs, sh=sh)
1110
+
1111
+ def _batched(self, x, ti, w):
1112
+ """routed (row, slot) pairs <= experts: gather + batched GEMM over only those experts; else one batched GEMM
1113
+ over all experts. Each expert output rounded to x.dtype, weighted in fp32 (= the per-expert loop)."""
1114
+ R, k = ti.shape
1115
+ E = self.gu.shape[0]
1116
+ if R * k <= E:
1117
+ li = ti.reshape(-1)
1118
+ h = torch.bmm(self.gu[li].to(x.dtype), x.repeat_interleave(k, 0)[:, :, None])[:, :, 0]
1119
+ y = torch.bmm(self.dn[li].to(x.dtype), self._act(h)[:, :, None])[:, :, 0]
1120
+ return (y.to(x.dtype).float().view(R, k, -1) * w[:, :, None]).to(x.dtype).float().sum(1)
1121
+ we = torch.zeros(R, E, dtype=torch.float32, device=x.device).scatter_add_(1, ti, w.float())
1122
+ rc = max(1, (1 << 26) // (E * max(self.gu.shape[1], self.dn.shape[1]))) # static row chunk: bounded workspace
1123
+ outs = []
1124
+ for r0 in range(0, R, rc):
1125
+ h = torch.matmul(x[None, r0:r0 + rc], self.gu.to(x.dtype).transpose(1, 2)) # (E, rc, 2I)
1126
+ y = torch.bmm(self._act(h), self.dn.to(x.dtype).transpose(1, 2)).to(x.dtype).float() # (E, rc, d)
1127
+ outs.append((y * we[r0:r0 + rc].t()[:, :, None]).to(x.dtype).float().sum(0))
1128
+ return torch.cat(outs, 0)
1129
+
1130
+ def _ffn(self, x, e):
1131
+ h = F.linear(x, self.gu[e].to(x.dtype))
1132
+ gt, up = h[:, :self.I], h[:, self.I:]
1133
+ if self.clamp:
1134
+ al, lim = self.clamp
1135
+ gt, up = gt.clamp(max=lim), up.clamp(-lim, lim)
1136
+ a = (up + 1) * (gt * torch.sigmoid(gt * al))
1137
+ else:
1138
+ a = F.silu(gt) * up
1139
+ return F.linear(a, self.dn[e].to(x.dtype))
1140
+
1141
+ def __call__(self, x):
1142
+ lg = F.linear(x, self.rw.to(x.dtype)).float()
1143
+ cap = x.is_cuda and torch.cuda.is_current_stream_capturing()
1144
+ grouped = (MOE_GROUPED and x.is_cuda and torch.is_tensor(self.gu) and x.dtype == self.gu.dtype == BF
1145
+ and (cap or 2 < x.shape[0] <= 512)) # eager 1-2 rows: gather is fewer launches
1146
+ if grouped and MOE_ROUTER_FUSED and lg.shape[-1] <= 1024:
1147
+ from kernels import moe_router
1148
+ ti, w = moe_router(lg, self.k, self.sig, self.rb, self.norm)
1149
+ else:
1150
+ sc = torch.sigmoid(lg) if self.sig else torch.softmax(lg, -1)
1151
+ ti = (sc + self.rb if self.rb is not None else sc).topk(self.k, -1).indices
1152
+ w = sc.gather(1, ti)
1153
+ if self.norm:
1154
+ w = w / w.sum(-1, keepdim=True)
1155
+ if grouped and MOE_FUSED_EPI and not self.clamp and x.shape[-1] == self.dn.shape[1]:
1156
+ return self._grouped_final(x, ti, w)
1157
+ if grouped:
1158
+ out = self._grouped(x, ti, w) # graph-capturable grouped Triton GEMM: each routed expert read once
1159
+ elif x.is_cuda and torch.is_tensor(self.gu) and (cap or ti.numel() <= self.gu.shape[0]):
1160
+ out = self._batched(x, ti, w) # graph-capturable batched experts (no host sync)
1161
+ elif cap: # graph-capturable: all experts, unrouted rows weighted 0 (no host sync)
1162
+ out = torch.zeros(x.shape, dtype=torch.float32, device=x.device)
1163
+ for e in range(self.gu.shape[0]):
1164
+ out += (self._ffn(x, e).float() * (w * (ti == e)).sum(1)[:, None]).to(x.dtype).float()
1165
+ else:
1166
+ out = torch.zeros(x.shape, dtype=torch.float32, device=x.device)
1167
+ for e in torch.unique(ti).tolist():
1168
+ rows, kk = torch.nonzero(ti == e, as_tuple=True)
1169
+ out.index_add_(0, rows, (self._ffn(x[rows], e).float() * w[rows, kk, None]).to(x.dtype).float())
1170
+ out = out.to(x.dtype) * self.rs if self.rs != 1.0 else out.to(x.dtype)
1171
+ if self.shared is None:
1172
+ return out
1173
+ sh = self.shared(x)
1174
+ return out + (sh if self.sg is None else torch.sigmoid(F.linear(x, self.sg.to(x.dtype))) * sh)
1175
+
1176
+ def weights(self):
1177
+ return {"gu": self.gu, "dn": self.dn}
1178
+
1179
+
1180
+ import ds4 # noqa: E402,F401 (registers ds4_attn / moe_ds4)