quantuminfer 0.0.0-stage → 0.1.1

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 (83) 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 +34 -4
  64. package/results/ANALYSIS.md +160 -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_t1_j8_b300.json +340 -0
  74. package/results/res_glm_text_plain_batch_b300.json +5792 -0
  75. package/results/res_glm_text_w1_b300.json +1635 -0
  76. package/results/res_glm_text_w3_b300.json +1639 -0
  77. package/results/res_sweep_echo_b300.json +129 -0
  78. package/results/res_sweep_final_b300.json +153 -0
  79. package/results/res_sweep_glm_b300.json +153 -0
  80. package/results/res_techo.json +29 -0
  81. package/results/res_tgsuf.json +21 -0
  82. package/results/res_tjac.json +17 -0
  83. package/results/res_tonline_jac.json +13 -0
package/p27/pblocks.py ADDED
@@ -0,0 +1,1242 @@
1
+ """Lane P27 blocks for the one engine (registered into gpu/engine/blocks.py REGISTRY; written once, reusable, no
2
+ model names). Every block is tensor-parallel aware through g["tp"] = {"rank", "world", "group"}: it loads only its
3
+ shard (W.get(name, shard=...)) and returns a PARTIAL output that the residual wiring all-reduces (blocks.ALLREDUCE).
4
+
5
+ dense_glu_act dense gated MLP with a declared activation: silu (SwiGLU) or situ(beta, linear_beta)
6
+ kda Kimi Delta Attention (per-key-channel decay delta rule, short convs, gated RMSNorm output)
7
+ mla multi-head latent attention, absorbed decode/tree form, latent KV cache (kv_lora_rank + rope dims)
8
+ moe routed (+ shared) experts: sigmoid/softmax router + correction bias, (group-limited) top-k,
9
+ renormalise, routed scaling, optional latent projection (down -> experts -> norm -> up);
10
+ expert weights bf16 / mxfp4 / fp8-block; capacity-free exact dispatch; experts sharded TP or EP.
11
+ """
12
+ import math
13
+
14
+ import torch
15
+ import torch.nn.functional as F
16
+ try:
17
+ import triton
18
+ import triton.language as tl
19
+ except ImportError: # CPU-only installs: Triton kernels are never launched; torch reference paths run instead
20
+ from kernels import triton, tl
21
+
22
+ import blocks as Bk
23
+ from blocks import register, rms, LINEAR
24
+ from kernels import gdn_paths
25
+ from dev import DEV, CUDA
26
+ import quant as Q
27
+
28
+ BF = torch.bfloat16
29
+
30
+
31
+ FAST = False # fused Triton RMSNorm (core kernels.rms_fused) + torch.compile'd elementwise glue; False = torch ops
32
+ AR32 = True # fp32 accumulation of TP partials; False uses the native low-precision collective (vLLM-style, fewer kernels/bytes)
33
+
34
+
35
+ def rmsn(x, w, eps, off):
36
+ """RMSNorm with the HF rounding (one Triton kernel for 2-D bf16 rows; torch reference otherwise)."""
37
+ if FAST and x.dim() == 2 and x.dtype == BF and x.stride(-1) == 1:
38
+ from kernels import rms_fused
39
+ return rms_fused(x, w, eps, off)
40
+ return rms(x, w, eps, off)
41
+
42
+
43
+ def _maybe_compile(fn):
44
+ if not FAST:
45
+ return fn
46
+ try:
47
+ import torch._dynamo as dyn
48
+ dyn.config.recompile_limit = max(getattr(dyn.config, "recompile_limit", 8), 64)
49
+ return torch.compile(fn, dynamic=None, fullgraph=False)
50
+ except Exception: # noqa
51
+ return fn
52
+
53
+
54
+ # ----------------------------------------------------------------------------------------------- comm helpers
55
+ def tp_of(g):
56
+ return g.get("tp") or {"rank": 0, "world": 1, "group": None}
57
+
58
+
59
+ SYM_AR = True # NVSHMEM symmetric-memory one-shot all-reduce: exact, CUDA-graph safe, ~10us vs ~24-40us NCCL at decode shapes
60
+ _SYMM = {"pool": None, "buf": {}, "ok": True}
61
+
62
+
63
+ def _symm_ar(y, t):
64
+ """one-shot all-reduce through a cached symmetric-memory staging buffer; None if unavailable for this call."""
65
+ if not SYM_AR or not _SYMM["ok"] or not y.is_cuda or y.dtype not in (torch.bfloat16, torch.float16, torch.float32):
66
+ return None
67
+ try:
68
+ import torch.distributed as dist
69
+ import torch.distributed._symmetric_memory as sm
70
+ if not sm.is_nvshmem_available():
71
+ return None
72
+ key = (tuple(y.shape), y.dtype, y.device.index)
73
+ buf = _SYMM["buf"].get(key)
74
+ if buf is None:
75
+ if torch.cuda.is_current_stream_capturing():
76
+ return None # symmetric pool allocation is host-synchronising; warm shapes are cached eagerly
77
+ if _SYMM["pool"] is None:
78
+ _SYMM["pool"] = sm.get_mem_pool(y.device)
79
+ with torch.cuda.use_mem_pool(_SYMM["pool"]):
80
+ buf = torch.empty_like(y)
81
+ _SYMM["buf"][key] = buf
82
+ g = t["group"]
83
+ gn = g.group_name if g is not None else dist.group.WORLD.group_name
84
+ return torch.ops.symm_mem.one_shot_all_reduce_copy(buf, y.contiguous(), "sum", gn)
85
+ except Exception:
86
+ _SYMM["ok"] = False
87
+ return None
88
+
89
+
90
+ def all_reduce(y, g):
91
+ """sum of partial outputs over the TP group, accumulated in fp32, returned in y's dtype."""
92
+ t = tp_of(g)
93
+ if t["world"] == 1:
94
+ return y
95
+ import torch.distributed as dist
96
+ if not AR32 and y.dtype in (torch.bfloat16, torch.float16):
97
+ z = _symm_ar(y, t)
98
+ if z is not None:
99
+ return z
100
+ dist.all_reduce(y, group=t["group"])
101
+ return y
102
+ yf = y.float()
103
+ z = _symm_ar(yf, t)
104
+ if z is not None:
105
+ return z.to(y.dtype)
106
+ dist.all_reduce(yf, group=t["group"])
107
+ return yf.to(y.dtype)
108
+
109
+
110
+ def all_gather_last(y, g):
111
+ """concatenate the ranks' shards along the last dim."""
112
+ t = tp_of(g)
113
+ if t["world"] == 1:
114
+ return y
115
+ import torch.distributed as dist
116
+ W = t["world"]
117
+ out = torch.empty((W,) + tuple(y.shape), dtype=y.dtype, device=y.device)
118
+ dist.all_gather_into_tensor(out, y.contiguous(), group=t["group"])
119
+ return out.movedim(0, -2).reshape(*y.shape[:-1], W * y.shape[-1])
120
+
121
+
122
+ QBLOCK = {"qn": 128, "qk": 128} # block-fp8 tile (set from the checkpoint's quantization_config by the adapter)
123
+ MOE_BF16_GROUPED = False # bf16 experts on CUDA: grouped Triton GEMM (quant.moe_bf16_gemm); off until GPU-validated
124
+ MOE_FP8A8 = False # dynamic-fp8 activations for block-fp8 experts (published activation_scheme); validate quality first
125
+
126
+
127
+ import threading
128
+ _TL = threading.local()
129
+
130
+
131
+ def _handle(W, f):
132
+ """thread-local safetensors handles (so several reader threads can load one rank's tensors concurrently)."""
133
+ from safetensors import safe_open
134
+ import os
135
+ hs = getattr(_TL, "h", None)
136
+ if hs is None:
137
+ hs = _TL.h = {}
138
+ key = (W.path, f)
139
+ if key not in hs:
140
+ hs[key] = safe_open(os.path.join(W.path, f), "pt", device="cpu")
141
+ return hs[key]
142
+
143
+
144
+ def _slice(W, name, dim=None, a=None, b=None):
145
+ """read tensor `name` (or only rows/cols [a, b) along dim) from storage to this rank's GPU."""
146
+ h = _handle(W, W.map[name])
147
+ if dim is None:
148
+ return h.get_tensor(name).to(DEV, non_blocking=False)
149
+ sl = h.get_slice(name)
150
+ idx = [slice(None)] * len(sl.get_shape())
151
+ idx[dim] = slice(a, b)
152
+ return sl[tuple(idx)].to(DEV)
153
+
154
+
155
+ LOAD_THREADS = 16
156
+
157
+
158
+ def pmap(fn, items):
159
+ """ordered parallel map with LOAD_THREADS reader threads (I/O bound weight loading)."""
160
+ from concurrent.futures import ThreadPoolExecutor
161
+ dev = torch.cuda.current_device() if CUDA else None
162
+
163
+ def run(x):
164
+ if CUDA:
165
+ torch.cuda.set_device(dev)
166
+ return fn(x)
167
+ with ThreadPoolExecutor(LOAD_THREADS) as ex:
168
+ return list(ex.map(run, items))
169
+
170
+
171
+ def _is_q(W, name):
172
+ return name.endswith(".weight") and W.has(name[:-len(".weight")] + ".weight_scale_inv")
173
+
174
+
175
+ def _getw(W, name, dim=None, a=None, b=None):
176
+ """weight (tensor, or QWeight for block-fp8) restricted to [a, b) along dim (None = whole)."""
177
+ if not _is_q(W, name):
178
+ return _slice(W, name, dim, a, b)
179
+ sname = name[:-len(".weight")] + ".weight_scale_inv"
180
+ qn, qk = QBLOCK["qn"], QBLOCK["qk"]
181
+ if dim is None:
182
+ w8, sc = _slice(W, name), _slice(W, sname)
183
+ else:
184
+ q = qn if dim == 0 else qk
185
+ assert a % q == 0, (name, dim, a, q)
186
+ w8 = _slice(W, name, dim, a, b)
187
+ sc = _slice(W, sname, dim, a // q, (b + q - 1) // q)
188
+ return Q.QWeight([("fp8blk", w8.contiguous(), sc.float().contiguous(), qn, qk)])
189
+
190
+
191
+ def _shape(W, name):
192
+ from safetensors import safe_open
193
+ import os
194
+ with safe_open(os.path.join(W.path, W.map[name]), "pt") as h:
195
+ return h.get_slice(name).get_shape()
196
+
197
+
198
+ def shard_rows(W, name, t, sections=None):
199
+ """rows of weight `name` for this rank. sections: row counts of concatenated sub-blocks, each split evenly."""
200
+ if t["world"] == 1:
201
+ return _getw(W, name)
202
+ n = _shape(W, name)[0]
203
+ sections = sections or [n]
204
+ parts, o = [], 0
205
+ for m in sections:
206
+ c = m // t["world"]
207
+ parts.append(_getw(W, name, 0, o + t["rank"] * c, o + (t["rank"] + 1) * c))
208
+ o += m
209
+ return Q.cat_rows(parts) if len(parts) > 1 else parts[0]
210
+
211
+
212
+ def shard_cols(W, name, t):
213
+ if t["world"] == 1:
214
+ return _getw(W, name)
215
+ n = _shape(W, name)[1]
216
+ c = n // t["world"]
217
+ return _getw(W, name, 1, t["rank"] * c, (t["rank"] + 1) * c)
218
+
219
+
220
+ def full_w(W, name):
221
+ return _getw(W, name)
222
+
223
+
224
+ def _act_glu(gu, inter, act):
225
+ """gu (R, 2*inter) = [gate | up] -> (R, inter). act = ("silu",) or ("situ", beta, linear_beta)."""
226
+ gate, up = gu[:, :inter], gu[:, inter:]
227
+ if act[0] == "silu":
228
+ return F.silu(gate) * up
229
+ if act[0] == "situ":
230
+ b, lb = act[1], act[2]
231
+ gf, uf = gate.float(), up.float()
232
+ a = b * torch.tanh(gf / b) * torch.sigmoid(gf)
233
+ if lb is not None:
234
+ uf = lb * torch.tanh(uf / lb)
235
+ return (a * uf).to(gu.dtype)
236
+ raise NotImplementedError(act)
237
+
238
+
239
+ _act_glu_c = {}
240
+
241
+
242
+ def act_glu(gu, inter, act):
243
+ key = (inter, tuple(act))
244
+ if key not in _act_glu_c:
245
+ _act_glu_c[key] = _maybe_compile(lambda g, _i=inter, _a=tuple(act): _act_glu(g, _i, _a))
246
+ return _act_glu_c[key](gu)
247
+
248
+
249
+ @register("dense_glu_act")
250
+ class DenseGLUAct:
251
+ """gate/up/down MLP, intermediate sharded across TP ranks (column- then row-parallel)."""
252
+
253
+ def __init__(self, s, W, g):
254
+ t = tp_of(g)
255
+ p = s["prefix"]
256
+ self.wgu = Q.cat_rows([shard_rows(W, p + s["gate"], t), shard_rows(W, p + s["up"], t)])
257
+ self.wd = shard_cols(W, p + s["down"], t)
258
+ self.inter = self.wd.shape[1]
259
+ self.act = tuple(s["act"])
260
+
261
+ def __call__(self, x):
262
+ return LINEAR(act_glu(LINEAR(x, self.wgu), self.inter, self.act), self.wd)
263
+
264
+ def weights(self):
265
+ return {"wgu": self.wgu, "wd": self.wd}
266
+
267
+
268
+ # ----------------------------------------------------------------------------------------------- KDA
269
+ class _Conv:
270
+ """depthwise causal conv (width K) + SiLU over channels C, state (B, K-1, C) of the last K-1 *inputs*."""
271
+
272
+ @staticmethod
273
+ def prefill(xc, cs_b, w):
274
+ """xc (T, C) bf16, cs_b (K-1, C), w (C, K) -> y (T, C) bf16, new state (K-1, C)."""
275
+ K = w.shape[1]
276
+ cat = torch.cat([cs_b, xc], 0)
277
+ y = F.conv1d(cat.t()[None].float(), w[:, None, :].float(), groups=w.shape[0])[0].t()
278
+ return F.silu(y).to(xc.dtype), cat[-(K - 1):]
279
+
280
+ @staticmethod
281
+ def tree(X, cidx, w):
282
+ """X (B, K-1+N, C) = [state | tree rows]; cidx (N, K) window rows -> (B*N, C)."""
283
+ win = X[:, cidx] # (B, N, K, C)
284
+ y = (win.float() * w.t()[None, None].float()).sum(2)
285
+ return F.silu(y).to(X.dtype).reshape(-1, X.shape[-1])
286
+
287
+
288
+ @register("kda")
289
+ class KimiDeltaAttention:
290
+ """Kimi Delta Attention (fla KDA semantics: l2-normed q/k, scale dk^-1/2, per-key-channel log decay g in
291
+ (lower_bound, 0), beta = sigmoid(b), delta rule, fp32 state (B, H, DK, DV)). Heads sharded over TP ranks.
292
+ g = lower_bound * sigmoid(exp(A_log)[d] * (f_b(f_a(x)) + dt_bias)) rounded to the activation dtype (as the
293
+ reference does), output = o_proj(rmsnorm(o) * w * sigmoid(g_out(x))). Prefill: fla chunk_kda when available
294
+ (cross-checked against the path-walk kernel), tree/decode/commit: kernels.gdn_paths with vector decay."""
295
+
296
+ def __init__(self, s, W, g):
297
+ t = tp_of(g)
298
+ self.t = t
299
+ p = s["prefix"]
300
+ H, D = s["heads"], s["head_dim"]
301
+ assert H % t["world"] == 0
302
+ self.H = H // t["world"]
303
+ self.D = D
304
+ self.K = s["conv"]
305
+ self.lb = s["lower_bound"]
306
+ self.eps = s["eps"]
307
+ hd = self.H * D
308
+ self.hd = hd
309
+ self.wq = shard_rows(W, p + "q_proj.weight", t)
310
+ self.wk = shard_rows(W, p + "k_proj.weight", t)
311
+ self.wv = shard_rows(W, p + "v_proj.weight", t)
312
+ self.wb = shard_rows(W, p + "b_proj.weight", t)
313
+ self.wfa = full_w(W, p + "f_a_proj.weight") # (D, d) replicated (small)
314
+ self.wfb = shard_rows(W, p + "f_b_proj.weight", t)
315
+ self.wga = self.wgb = None
316
+ if W.has(p + "g_proj.weight"):
317
+ self.wgo = shard_rows(W, p + "g_proj.weight", t)
318
+ else: # low-rank output gate g_b(g_a(x)) (Kimi-Linear)
319
+ self.wga, self.wgb = full_w(W, p + "g_a_proj.weight"), shard_rows(W, p + "g_b_proj.weight", t)
320
+ self.wgo = self.wq[:0]
321
+ # one fused input projection [q | k | v | gate_out | b] (all row-sharded by heads)
322
+ self.win = torch.cat([self.wq, self.wk, self.wv, self.wgo, self.wb], 0).contiguous()
323
+ del self.wq, self.wk, self.wv, self.wgo, self.wb
324
+ cw = []
325
+ for n in ("q_conv1d", "k_conv1d", "v_conv1d"):
326
+ w = full_w(W, p + n + ".weight") # (C, 1, K)
327
+ C = w.shape[0]
328
+ c = C // t["world"]
329
+ cw.append(w.reshape(C, -1)[t["rank"] * c:(t["rank"] + 1) * c])
330
+ self.convw = torch.cat(cw, 0).contiguous() # (3*hd, K)
331
+ A = full_w(W, p + "A_log").float()
332
+ # Kimi-Linear layout A_log (1, 1, H, 1): per-head rate, g = -exp(A) * softplus(f + dt_bias), no lower bound
333
+ self.softplus = A.dim() == 4 and A.shape[-1] == 1 and A.numel() == H
334
+ self.A_shared = A.numel() == D and not self.softplus # per-channel decay shared by all heads (released K3)
335
+ if self.softplus:
336
+ A = A.reshape(H, 1)[t["rank"] * self.H:(t["rank"] + 1) * self.H]
337
+ self.Aexp = A.exp()
338
+ elif not self.A_shared:
339
+ A = A.reshape(H, D)[t["rank"] * self.H:(t["rank"] + 1) * self.H]
340
+ if not self.softplus:
341
+ self.Aexp = A.exp().reshape(-1, D) # (1 or H_local, D)
342
+ dtb = full_w(W, p + "dt_bias").float().reshape(H, D)
343
+ self.dtb = dtb[t["rank"] * self.H:(t["rank"] + 1) * self.H].contiguous()
344
+ self.nw = full_w(W, p + "o_norm.weight")
345
+ self.wo = shard_cols(W, p + "o_proj.weight", t)
346
+
347
+ def weights(self):
348
+ w = {"win": self.win, "wfa": self.wfa, "wfb": self.wfb, "wo": self.wo}
349
+ if self.wga is not None:
350
+ w.update(wga=self.wga, wgb=self.wgb)
351
+ return w
352
+
353
+ def alloc(self, B, smax):
354
+ self.S = torch.zeros(B, self.H, self.D, self.D, dtype=torch.float32, device=DEV)
355
+ self.cs = torch.zeros(B, self.K - 1, 3 * self.hd, dtype=Bk.ACT, device=DEV)
356
+
357
+ def state_bytes(self):
358
+ return self.S.numel() * 4 + self.cs.numel() * 2
359
+
360
+ def reset(self, b=None):
361
+ (self.S if b is None else self.S[b]).zero_()
362
+ (self.cs if b is None else self.cs[b]).zero_()
363
+
364
+ def fork(self, src, dst):
365
+ """copy committed state of user src into users dst (LongTensor) -- shared-prompt worlds."""
366
+ self.S[dst] = self.S[src]
367
+ self.cs[dst] = self.cs[src]
368
+
369
+ def _proj(self, x):
370
+ hd = self.hd
371
+ y = LINEAR(x, self.win)
372
+ xc = y[:, :3 * hd]
373
+ if self.wga is not None:
374
+ go = LINEAR(LINEAR(x, self.wga), self.wgb)
375
+ braw = y[:, 3 * hd:]
376
+ else:
377
+ go = y[:, 3 * hd:4 * hd]
378
+ braw = y[:, 4 * hd:]
379
+ f = LINEAR(LINEAR(x, self.wfa), self.wfb).float().view(-1, self.H, self.D)
380
+ if self.softplus:
381
+ gf = f + self.dtb[None]
382
+ gdec = -self.Aexp[None] * torch.where(gf > 20.0, gf, torch.log1p(torch.exp(gf)))
383
+ else:
384
+ gdec = (self.lb * torch.sigmoid(self.Aexp[None] * (f + self.dtb[None]))).to(x.dtype).float()
385
+ beta = torch.sigmoid(braw.float())
386
+ return xc, go, gdec.contiguous(), beta.contiguous()
387
+
388
+ def _post(self, o, go):
389
+ R = o.shape[0]
390
+ of = o.view(R, self.H, self.D).float()
391
+ of = of * torch.rsqrt(of.pow(2).mean(-1, keepdim=True) + self.eps) * self.nw.float()
392
+ of = of * torch.sigmoid(go.view(R, self.H, self.D).float())
393
+ return LINEAR(of.to(o.dtype).reshape(R, -1), self.wo)
394
+
395
+ def prefill(self, x, ctx):
396
+ b = ctx.b
397
+ T = x.shape[0]
398
+ xc, go, gdec, beta = self._proj(x)
399
+ conv, self.cs[b] = _Conv.prefill(xc, self.cs[b], self.convw)
400
+ hd = self.hd
401
+ q, k, v = conv[:, :hd], conv[:, hd:2 * hd], conv[:, 2 * hd:]
402
+ o = self._recur_prefill(q, k, v, gdec, beta, b, T)
403
+ return self._post(o, go)
404
+
405
+ def _recur_prefill(self, q, k, v, gdec, beta, b, T):
406
+ if PREFILL_FLA:
407
+ try:
408
+ return self._fla_prefill(q, k, v, gdec, beta, b, T)
409
+ except Exception as e: # noqa
410
+ print("kda: fla chunk_kda unavailable, path-walk prefill:", repr(e)[:200])
411
+ _disable_fla()
412
+ o = torch.empty(T, self.hd, dtype=q.dtype, device=q.device)
413
+ CH = 4096
414
+ for s0 in range(0, T, CH):
415
+ n = min(CH, T - s0)
416
+ path = torch.arange(n, dtype=torch.int32, device=q.device).view(1, 1, n)
417
+ plen = torch.full((1, 1), n, dtype=torch.int32, device=q.device)
418
+ S0 = self.S[b:b + 1]
419
+ sl = slice(s0, s0 + n)
420
+ # emit every row's output while walking the single chain path (store final state)
421
+ gdn_paths(q[sl], k[sl], v[sl], gdec[sl], beta[sl], S0, path, plen, plen - 1, o[sl], n, self.H, self.H,
422
+ self.D, self.D, store=True, out=False, emit=True)
423
+ return o
424
+
425
+ def _fla_prefill(self, q, k, v, gdec, beta, b, T):
426
+ from fla.ops.kda import chunk_kda
427
+ H, D = self.H, self.D
428
+ o, st = chunk_kda(q=q.view(1, T, H, D), k=k.view(1, T, H, D), v=v.view(1, T, H, D),
429
+ g=gdec.view(1, T, H, D).to(q.dtype), beta=beta.view(1, T, H),
430
+ initial_state=self.S[b:b + 1].clone(), output_final_state=True,
431
+ use_qk_l2norm_in_kernel=True, **FLA_KW)
432
+ self.S[b] = st[0].float().view(H, D, D) if not FLA_T else st[0].float().view(H, D, D).transpose(-1, -2)
433
+ return o.reshape(T, -1)
434
+
435
+ def tree(self, x, ctx):
436
+ B, N = ctx.B, ctx.N
437
+ xc, go, gdec, beta = self._proj(x)
438
+ X = torch.cat([self.cs, xc.view(B, N, -1)], 1)
439
+ conv = _Conv.tree(X, ctx.cidx_for(self.K), self.convw)
440
+ hd = self.hd
441
+ q, k, v = conv[:, :hd], conv[:, hd:2 * hd], conv[:, 2 * hd:]
442
+ o = torch.empty(B * N, hd, dtype=x.dtype, device=x.device)
443
+ gdn_paths(q, k, v, gdec, beta, self.S, ctx.paths, ctx.plen, ctx.orow, o, N, self.H, self.H, self.D, self.D,
444
+ store=False, out=True)
445
+ self._st = (X, q, k, v, gdec, beta)
446
+ return self._post(o, go)
447
+
448
+ def commit(self, ctx):
449
+ X, q, k, v, gdec, beta = self._st
450
+ B, N = ctx.B, ctx.N
451
+ gdn_paths(q, k, v, gdec, beta, self.S, ctx.acc_path[:, None], ctx.acc_len[:, None], ctx.acc_len[:, None],
452
+ None, N, self.H, self.H, self.D, self.D, store=True, out=False)
453
+ idx = ctx.cidx_for(self.K)[ctx.leaf][:, 1:]
454
+ bi = torch.arange(B, device=X.device)[:, None]
455
+ self.cs.copy_(X[bi, idx])
456
+
457
+
458
+ PREFILL_FLA = True
459
+ FLA_KW = {}
460
+ FLA_T = False
461
+
462
+
463
+ def _disable_fla():
464
+ global PREFILL_FLA
465
+ PREFILL_FLA = False
466
+
467
+
468
+ # ----------------------------------------------------------------------------------------------- MLA
469
+ @triton.jit
470
+ def _mla_dec_k(Q, CK, TK, ANC, LENS, OP, LP, N, scale, CH,
471
+ sqr, sqh, sckb, scks, stkb, stkn, sor, soh, sos, slr, sls,
472
+ H: tl.constexpr, HB: tl.constexpr, DL: tl.constexpr, DR: tl.constexpr, BS: tl.constexpr):
473
+ """Absorbed MLA attention for tree rows. Program (row r = b*N + i, split s): keys = committed cache positions
474
+ [s*CH, min((s+1)*CH, lens[b])) plus (split 0 only) the N tree rows visible to row i (ancestor bits ANC[r]).
475
+ Q (R, H, DL+DR) bf16; CK (B, Smax, DL+DR); TK (B, N, DL+DR). Writes partial o (R, H, S, DL) fp32 and lse."""
476
+ r = tl.program_id(0)
477
+ s = tl.program_id(1)
478
+ b = r // N
479
+ L = tl.load(LENS + b)
480
+ hh = tl.arange(0, HB)
481
+ hm = hh < H
482
+ dl = tl.arange(0, DL)
483
+ dr = tl.arange(0, DR)
484
+ ql = tl.load(Q + r * sqr + hh[:, None] * sqh + dl[None, :], mask=hm[:, None], other=0.0)
485
+ qr = tl.load(Q + r * sqr + hh[:, None] * sqh + DL + dr[None, :], mask=hm[:, None], other=0.0)
486
+ m_i = tl.full((HB,), float("-inf"), tl.float32)
487
+ l_i = tl.zeros((HB,), tl.float32)
488
+ acc = tl.zeros((HB, DL), tl.float32)
489
+ lo = s * CH
490
+ hi = tl.minimum(lo + CH, L)
491
+ for k0 in range(lo, hi, BS):
492
+ kk = k0 + tl.arange(0, BS)
493
+ km = kk < hi
494
+ cl = tl.load(CK + b * sckb + kk[:, None] * scks + dl[None, :], mask=km[:, None], other=0.0)
495
+ cr = tl.load(CK + b * sckb + kk[:, None] * scks + DL + dr[None, :], mask=km[:, None], other=0.0)
496
+ sc = (tl.dot(ql, tl.trans(cl)) + tl.dot(qr, tl.trans(cr))) * scale
497
+ sc = tl.where(km[None, :], sc, float("-inf"))
498
+ m_new = tl.maximum(m_i, tl.max(sc, 1))
499
+ alpha = tl.exp(m_i - m_new)
500
+ p = tl.exp(sc - m_new[:, None])
501
+ l_i = l_i * alpha + tl.sum(p, 1)
502
+ acc = acc * alpha[:, None] + tl.dot(p.to(tl.bfloat16), cl)
503
+ m_i = m_new
504
+ if s == 0:
505
+ anc = tl.load(ANC + r)
506
+ jj = tl.arange(0, 16)
507
+ for t0 in range(0, N, 16):
508
+ kj = t0 + jj
509
+ vis = (kj < N) & (((anc >> kj) & 1) != 0)
510
+ cl = tl.load(TK + b * stkb + kj[:, None] * stkn + dl[None, :], mask=vis[:, None], other=0.0)
511
+ cr = tl.load(TK + b * stkb + kj[:, None] * stkn + DL + dr[None, :], mask=vis[:, None], other=0.0)
512
+ sc = (tl.dot(ql, tl.trans(cl)) + tl.dot(qr, tl.trans(cr))) * scale
513
+ sc = tl.where(vis[None, :], sc, float("-inf"))
514
+ m_new = tl.maximum(m_i, tl.max(sc, 1))
515
+ alpha = tl.where(m_new == float("-inf"), 1.0, tl.exp(m_i - m_new))
516
+ p = tl.where(vis[None, :], tl.exp(sc - m_new[:, None]), 0.0)
517
+ l_i = l_i * alpha + tl.sum(p, 1)
518
+ acc = acc * alpha[:, None] + tl.dot(p.to(tl.bfloat16), cl)
519
+ m_i = m_new
520
+ lse = tl.where(l_i > 0, m_i + tl.log(l_i), float("-inf"))
521
+ o = acc / tl.where(l_i > 0, l_i, 1.0)[:, None]
522
+ tl.store(OP + r * sor + hh[:, None] * soh + s * sos + dl[None, :], o, mask=hm[:, None])
523
+ tl.store(LP + (r * H + hh) * sls + s, lse, mask=hm)
524
+
525
+
526
+ class RopeTab:
527
+ """cos/sin tables (fp32) for `rot` rotary dims; style "interleave" (pairs (0,1),(2,3).. -> output [evens | odds],
528
+ the DeepSeek / GLM layout) or "half" (rotate_half)."""
529
+ _c = {}
530
+
531
+ def __init__(self, theta, rot, smax, style, scaling=None):
532
+ key = (theta, rot, smax)
533
+ if key not in RopeTab._c:
534
+ inv = 1.0 / (theta ** (torch.arange(0, rot, 2, dtype=torch.float) / rot))
535
+ if scaling:
536
+ raise NotImplementedError("rope scaling (yarn): add the frequency interpolation")
537
+ fr = torch.arange(smax, dtype=torch.float)[:, None] * inv[None]
538
+ RopeTab._c[key] = (fr.cos().to(DEV), fr.sin().to(DEV))
539
+ self.cos, self.sin = RopeTab._c[key]
540
+ self.style = style
541
+
542
+ def __call__(self, x, pos):
543
+ """x (R, ..., rot) any float dtype, pos (R,) long -> rotated, same dtype (computed in fp32)."""
544
+ global _rope_c
545
+ if _rope_c is None:
546
+ _rope_c = _maybe_compile(_rope_apply)
547
+ return _rope_c(x, pos, self.cos, self.sin, self.style == "interleave")
548
+
549
+
550
+ _rope_c = None
551
+
552
+
553
+ def _rope_apply(x, pos, cos, sin, inter: bool):
554
+ sh = [x.shape[0]] + [1] * (x.dim() - 2) + [-1]
555
+ c, s_ = cos[pos].view(sh), sin[pos].view(sh)
556
+ xf = x.float()
557
+ if inter:
558
+ x1, x2 = xf[..., 0::2], xf[..., 1::2]
559
+ else:
560
+ h = xf.shape[-1] // 2
561
+ x1, x2 = xf[..., :h], xf[..., h:]
562
+ return torch.cat([x1 * c - x2 * s_, x2 * c + x1 * s_], -1).to(x.dtype)
563
+
564
+
565
+ def _layernorm(x, w, b, eps):
566
+ return F.layer_norm(x.float(), (x.shape[-1],), w.float(), b.float(), eps).to(x.dtype)
567
+
568
+
569
+ @register("mla")
570
+ class MLA:
571
+ """Multi-head latent attention (DeepSeek-V2/V3/V3.2, GLM-5, Kimi), optionally with DSA (DeepSeek sparse
572
+ attention: a lightning indexer picks the top-k keys per query; layers may reuse the previous indexer's top-k).
573
+ q = q_b(norm(q_a(x))) (or q_proj(x)); [c ; k_rope] = kv_a(x); c = norm(c); [k_nope_h ; v_h] = kv_b_h(c).
574
+ RoPE on the rope dims (interleave / half style) or NoPE; optional sigmoid output gate g_proj.
575
+ Cache per token: c (kv_lora) + rotated k_rope (qk_rope), bf16, replicated on TP ranks (heads sharded); plus the
576
+ indexer key (index_dim) for layers with their own indexer.
577
+ Prefill: explicit K/V + SDPA (dense, or masked to the indexer's top-k when the context exceeds it).
578
+ Tree/decode: absorbed form (q_lat = W_uk^T q_nope, o_h = W_uv o_lat); dense Triton kernel when the allocation
579
+ never exceeds top-k (then DSA selects every key: identical), else indexer + gathered top-k keys."""
580
+
581
+ def __init__(self, s, W, g):
582
+ t = tp_of(g)
583
+ self.t = t
584
+ p = s["prefix"]
585
+ H = s["heads"]
586
+ assert H % t["world"] == 0
587
+ self.H = H // t["world"]
588
+ self.dn, self.dr, self.dv, self.dl = s["qk_nope"], s["qk_rope"], s["v_head"], s["kv_lora"]
589
+ self.dq = self.dn + self.dr
590
+ self.eps = s["eps"]
591
+ self.off = g["norm_offset"]
592
+ self.scale = s.get("scale") or self.dq ** -0.5
593
+ if s.get("q_lora"):
594
+ self.wqa = full_w(W, p + "q_a_proj.weight")
595
+ self.qan = full_w(W, p + "q_a_layernorm.weight")
596
+ self.wqb = shard_rows(W, p + "q_b_proj.weight", t)
597
+ else:
598
+ self.wqa = None
599
+ self.wqb = shard_rows(W, p + "q_proj.weight", t)
600
+ self.wkva = full_w(W, p + "kv_a_proj_with_mqa.weight")
601
+ self.kvn = full_w(W, p + "kv_a_layernorm.weight")
602
+ wkvb = shard_rows(W, p + "kv_b_proj.weight", t)
603
+ wkvb = (wkvb.dequant(torch.float32) if isinstance(wkvb, Q.QWeight) else wkvb.float())
604
+ wkvb = wkvb.view(self.H, self.dn + self.dv, self.dl)
605
+ # absorbed-form factors kept in fp32 (exact dequantised values); explicit form for prefill
606
+ self.wuk = wkvb[:, :self.dn].contiguous()
607
+ self.wuv = wkvb[:, self.dn:].contiguous()
608
+ self.wkvb = shard_rows(W, p + "kv_b_proj.weight", t)
609
+ self.wg = shard_rows(W, p + "g_proj.weight", t) if s.get("gate") else None
610
+ self.wo = shard_cols(W, p + "o_proj.weight", t)
611
+ self.rope_spec = s.get("rope")
612
+ ix = s.get("indexer")
613
+ self.ix = ix
614
+ if ix and ix.get("own"):
615
+ ip = p + "indexer."
616
+ self.iwq = full_w(W, ip + "wq_b.weight")
617
+ self.iwk = full_w(W, ip + "wk.weight")
618
+ self.ikn = (full_w(W, ip + "k_norm.weight"), full_w(W, ip + "k_norm.bias"))
619
+ self.iww = full_w(W, ip + "weights_proj.weight")
620
+ # q_b and the indexer query share the same qr input; row-concatenating them removes one latency-bound
621
+ # decode GEMM per layer. Likewise the output gate (when present) is an x-input projection.
622
+ self.wqf, self._qrows = (None, [])
623
+ if self.wqa is not None and ix and ix.get("own"):
624
+ cfq = Q.cat_rows_fp8_padded([self.wqb, self.iwq])
625
+ self.wqf, self._qrows = (cfq if cfq is not None else (None, []))
626
+ # x-input projections row-concatenated by format: fp8 quantized projections in one block-fp8 GEMM and
627
+ # unquantised indexer/gate projections in one bf16 GEMM (GLM deliberately leaves several indexer weights bf16;
628
+ # mixing them into one kernel would lose the published fp8 weight path).
629
+ xp, self._xrows, self._xkinds = [], [], []
630
+ bp, self._brows, self._bkinds = [], [], []
631
+
632
+ def xpart(kind, w):
633
+ if isinstance(w, Q.QWeight) and len(w.segs) == 1 and w.segs[0][0] == "fp8blk":
634
+ xp.append(w); self._xrows.append(w.shape[0]); self._xkinds.append(kind)
635
+ else:
636
+ bp.append(w); self._brows.append(w.shape[0]); self._bkinds.append(kind)
637
+ if self.wqa is not None:
638
+ xpart("qa", self.wqa)
639
+ xpart("kv", self.wkva)
640
+ if ix and ix.get("own"):
641
+ xpart("ki", self.iwk); xpart("wi", self.iww)
642
+ if self.wg is not None:
643
+ xpart("g", self.wg)
644
+ cf = Q.cat_rows_fp8_padded(xp) if len(xp) > 1 else None
645
+ self.wxf, self._xrows = (cf if cf is not None else (None, []))
646
+ self.wxb = Q.cat_rows(bp) if len(bp) > 1 else None
647
+ self._bsingle = bp[0] if len(bp) == 1 else None
648
+
649
+ def weights(self):
650
+ w = {"wqb": self.wqb, "wkva": self.wkva, "wo": self.wo, "wkvb": self.wkvb}
651
+ if self.wqa is not None:
652
+ w["wqa"] = self.wqa
653
+ if self.wg is not None:
654
+ w["wg"] = self.wg
655
+ if self.ix and self.ix.get("own"):
656
+ w.update(iwq=self.iwq, iwk=self.iwk, iww=self.iww)
657
+ return w
658
+
659
+ def alloc(self, B, smax):
660
+ self.cache = torch.zeros(B, smax, self.dl + self.dr, dtype=Bk.ACT, device=DEV)
661
+ self.smax = smax
662
+ self.rope = None
663
+ if self.rope_spec is not None:
664
+ r = self.rope_spec
665
+ self.rope = RopeTab(r["theta"], self.dr, smax + 64, r.get("style", "interleave"), r.get("scaling"))
666
+ self.sparse = bool(self.ix) and smax > self.ix["topk"]
667
+ if self.ix and self.ix.get("own"):
668
+ self.kcache = torch.zeros(B, smax, self.ix["dim"], dtype=Bk.ACT, device=DEV)
669
+
670
+ def state_bytes(self):
671
+ n = self.cache.numel() * 2
672
+ if hasattr(self, "kcache"):
673
+ n += self.kcache.numel() * 2
674
+ return n
675
+
676
+ def reset(self, b=None):
677
+ pass
678
+
679
+ def fork(self, src, dst, L):
680
+ self.cache[dst, :L] = self.cache[src, :L]
681
+ if hasattr(self, "kcache"):
682
+ self.kcache[dst, :L] = self.kcache[src, :L]
683
+
684
+ # ---- projections
685
+ def _xproj(self, x):
686
+ """the x-input projections as (q_a, kv_a, indexer_k, indexer_w); one fused GEMM when formats allow."""
687
+ self._g0 = None
688
+ if self.wxf is None:
689
+ qa = LINEAR(x, self.wqa) if self.wqa is not None else None
690
+ kv = LINEAR(x, self.wkva)
691
+ ki = LINEAR(x, self.iwk) if self.ix and self.ix.get("own") else None
692
+ wi = LINEAR(x, self.iww) if self.ix and self.ix.get("own") else None
693
+ return qa, kv, ki, wi
694
+ got = {}
695
+ if self.wxf is not None:
696
+ z = LINEAR(x, self.wxf)
697
+ o = 0
698
+ qn = self.wxf.segs[0][3]
699
+ for kind, n in zip(self._xkinds, self._xrows):
700
+ got[kind] = z[:, o:o + n]
701
+ o += (-n) % qn + n # skip the zero row-padding after this logical output
702
+ if self.wxb is not None:
703
+ z = LINEAR(x, self.wxb)
704
+ o = 0
705
+ for kind, n in zip(self._bkinds, self._brows):
706
+ got[kind] = z[:, o:o + n]
707
+ o += n
708
+ elif self._bsingle is not None:
709
+ got[self._bkinds[0]] = LINEAR(x, self._bsingle)
710
+ self._g0 = got.get("g")
711
+ return got.get("qa"), got.get("kv"), got.get("ki"), got.get("wi")
712
+
713
+ def _q(self, x, pos, qa=None):
714
+ self._qi0 = None
715
+ if self.wqa is not None:
716
+ qr = rmsn(LINEAR(x, self.wqa) if qa is None else qa, self.qan, self.eps, self.off)
717
+ if self.wqf is not None:
718
+ z = LINEAR(qr, self.wqf)
719
+ n0 = self._qrows[0]
720
+ q = z[:, :n0]
721
+ o = n0 + ((-n0) % self.wqf.segs[0][3])
722
+ self._qi0 = z[:, o:o + self._qrows[1]]
723
+ else:
724
+ q = LINEAR(qr, self.wqb)
725
+ else:
726
+ qr = None
727
+ q = LINEAR(x, self.wqb)
728
+ q = q.view(-1, self.H, self.dq)
729
+ if self.rope is not None:
730
+ q = torch.cat([q[..., :self.dn], self.rope(q[..., self.dn:], pos)], -1)
731
+ return q, qr
732
+
733
+ def _ckv(self, x, pos, y=None):
734
+ y = LINEAR(x, self.wkva) if y is None else y
735
+ c = rmsn(y[:, :self.dl], self.kvn, self.eps, self.off)
736
+ kr = y[:, self.dl:]
737
+ if self.rope is not None:
738
+ kr = self.rope(kr, pos)
739
+ return torch.cat([c, kr], -1) # (R, dl + dr)
740
+
741
+ def _ix_qkw(self, x, qr, pos, ki0=None, wi0=None):
742
+ """indexer query (R, Hi, Di), key (R, Di), head weights (R, Hi) fp32."""
743
+ ix = self.ix
744
+ Hi, Di = ix["heads"], ix["dim"]
745
+ qi = (self._qi0 if self._qi0 is not None else LINEAR(qr, self.iwq)).view(-1, Hi, Di)
746
+ ki = _layernorm(LINEAR(x, self.iwk) if ki0 is None else ki0, self.ikn[0], self.ikn[1], 1e-6)
747
+ if self.rope is not None:
748
+ rr = self.dr
749
+ qi = torch.cat([self.rope(qi[..., :rr], pos), qi[..., rr:]], -1)
750
+ ki = torch.cat([self.rope(ki[:, None, :rr], pos)[:, 0], ki[:, rr:]], -1)
751
+ wi = (LINEAR(x, self.iww) if wi0 is None else wi0).float() * (Hi ** -0.5)
752
+ return qi, ki, wi
753
+
754
+ @staticmethod
755
+ def _ix_scores(qi, kk, wi, Di):
756
+ """sum_h w_h relu(q_h . k / sqrt(Di)) in fp32: qi (R, Hi, Di), kk (1, S, Di) -> (R, S); head loop keeps the
757
+ working set at R x S."""
758
+ kf = kk[0].float()
759
+ acc = None
760
+ for h in range(qi.shape[1]):
761
+ sh = F.relu((qi[:, h].float() @ kf.t()) * (Di ** -0.5)) * wi[:, h:h + 1]
762
+ acc = sh if acc is None else acc + sh
763
+ return acc
764
+
765
+ def _out(self, o, x):
766
+ R = o.shape[0]
767
+ o = o.reshape(R, -1)
768
+ if self.wg is not None:
769
+ o = o * torch.sigmoid(self._g0 if getattr(self, "_g0", None) is not None else LINEAR(x, self.wg))
770
+ return LINEAR(o, self.wo)
771
+
772
+ # ---- prefill
773
+ def prefill(self, x, ctx):
774
+ b, p0 = ctx.b, ctx.pos0
775
+ T = x.shape[0]
776
+ pos = torch.arange(p0, p0 + T, device=x.device)
777
+ qa0, kv0, ki0, wi0 = self._xproj(x)
778
+ q, qr = self._q(x, pos, qa0)
779
+ ckv = self._ckv(x, pos, kv0)
780
+ self.cache[b, p0:p0 + T] = ckv
781
+ S = p0 + T
782
+ if self.ix and self.ix.get("own"):
783
+ qi, ki, wi = self._ix_qkw(x, qr, pos, ki0, wi0)
784
+ self.kcache[b, p0:p0 + T] = ki
785
+ cc = self.cache[b, :S]
786
+ kv = LINEAR(cc[:, :self.dl].contiguous(), self.wkvb).view(S, self.H, self.dn + self.dv)
787
+ k = torch.cat([kv[..., :self.dn], cc[:, None, self.dl:].expand(S, self.H, self.dr)], -1)
788
+ v = kv[..., self.dn:]
789
+ kh, vh = k.transpose(0, 1)[None], v.transpose(0, 1)[None]
790
+ causal = torch.arange(S, device=x.device)[None] <= pos[:, None] # (T, S)
791
+ if self.ix and S > self.ix["topk"]:
792
+ # DSA: own indexer, or the top-k of the previous indexer layer in this forward (ctx slot)
793
+ if self.ix.get("own"):
794
+ kk = self.kcache[b:b + 1, :S]
795
+ tops = []
796
+ for c0 in range(0, T, 1024):
797
+ sc = self._ix_scores(qi[c0:c0 + 1024], kk, wi[c0:c0 + 1024], self.ix["dim"])
798
+ sc = sc.masked_fill(~causal[c0:c0 + 1024], float("-inf"))
799
+ tops.append(sc.topk(self.ix["topk"], -1).indices)
800
+ ctx.__dict__.setdefault("_topk", {})["cur"] = torch.cat(tops, 0)
801
+ top = ctx._topk["cur"]
802
+ sel = torch.zeros(T, S, dtype=torch.bool, device=x.device).scatter_(1, top, True)
803
+ mask = sel & causal
804
+ else:
805
+ mask = None
806
+ qh = q.transpose(0, 1)[None]
807
+ if mask is None and p0 == 0:
808
+ o = F.scaled_dot_product_attention(qh, kh, vh, is_causal=True, scale=self.scale)
809
+ else:
810
+ o = F.scaled_dot_product_attention(qh, kh, vh, attn_mask=mask if mask is not None else causal,
811
+ scale=self.scale)
812
+ return self._out(o[0].transpose(0, 1), x)
813
+
814
+ # ---- tree / decode
815
+ def tree(self, x, ctx):
816
+ B, N = ctx.B, ctx.N
817
+ R = B * N
818
+ pos = ctx.pos.reshape(-1)
819
+ qa0, kv0, ki0, wi0 = self._xproj(x)
820
+ q, qr = self._q(x, pos, qa0) # (R, H, dq)
821
+ ql = torch.einsum("rhn,hnl->rhl", q[..., :self.dn].float(), self.wuk).to(Bk.ACT)
822
+ qa = torch.cat([ql, q[..., self.dn:]], -1).contiguous() # (R, H, dl + dr)
823
+ ckv = self._ckv(x, pos, kv0).view(B, N, -1).contiguous()
824
+ self._tk = ckv
825
+ if not hasattr(ctx, "_anc"):
826
+ ctx._anc = _anc_bits(ctx)
827
+ if self.ix and self.ix.get("own"):
828
+ qi, ki, wi = self._ix_qkw(x, qr, pos, ki0, wi0)
829
+ self._tki = ki.view(B, N, -1)
830
+ if not self.sparse:
831
+ o_lat = mla_attend(qa, self.cache, ckv, ctx._anc, ctx.lens, N, self.scale, self.dl, self.dr, self.smax)
832
+ else:
833
+ o_lat = self._sparse_tree(qa, ckv, ctx, (qi, ki, wi) if self.ix.get("own") else None)
834
+ o = torch.einsum("rhl,hvl->rhv", o_lat, self.wuv).to(Bk.ACT)
835
+ return self._out(o, x)
836
+
837
+ def _sparse_tree(self, qa, ckv, ctx, ixq):
838
+ B, N = ctx.B, ctx.N
839
+ R = B * N
840
+ S = self.smax
841
+ dev = qa.device
842
+ jj = torch.arange(N, device=dev)
843
+ anc = ((ctx._anc.view(B, N, 1).long() >> jj.view(1, 1, N)) & 1).bool() # (B, N, N) visible tree keys
844
+ valid_c = (torch.arange(S, device=dev)[None] < ctx.lens.long()[:, None]) # (B, S)
845
+ if ixq is not None:
846
+ qi, ki, wi = ixq
847
+ Di = self.ix["dim"]
848
+ qi4 = qi.view(B, N, -1, Di)
849
+ sc_c = torch.einsum("bnhd,bsd->bnhs", qi4.float(), self.kcache.float()) * (Di ** -0.5)
850
+ sc_c = torch.einsum("bnh,bnhs->bns", wi.view(B, N, -1), F.relu(sc_c))
851
+ sc_t = torch.einsum("bnhd,bmd->bnhm", qi4.float(), self._tki.float()) * (Di ** -0.5)
852
+ sc_t = torch.einsum("bnh,bnhm->bnm", wi.view(B, N, -1), F.relu(sc_t))
853
+ sc = torch.cat([sc_c.masked_fill(~valid_c[:, None], float("-inf")),
854
+ sc_t.masked_fill(~anc, float("-inf"))], -1) # (B, N, S + N)
855
+ top = sc.topk(self.ix["topk"], -1).indices
856
+ ctx.__dict__.setdefault("_topk", {})["cur"] = top
857
+ top = ctx._topk["cur"] # (B, N, K) into [cache S | tree N] (own, or the previous indexer layer's)
858
+ vis = torch.cat([valid_c[:, None].expand(B, N, S), anc], -1).gather(2, top) # (B, N, K)
859
+ allk = torch.cat([self.cache, ckv], 1) # (B, S + N, dl + dr)
860
+ bi = torch.arange(B, device=dev)[:, None, None]
861
+ kv = allk[bi, top] # (B, N, K, dl + dr)
862
+ qa4 = qa.view(B, N, self.H, -1).float()
863
+ s = torch.einsum("bnhd,bnkd->bnhk", qa4, kv.float()) * self.scale
864
+ s = s.masked_fill(~vis[:, :, None], float("-inf"))
865
+ p = torch.softmax(s, -1)
866
+ o = torch.einsum("bnhk,bnkd->bnhd", p, kv[..., :self.dl].float())
867
+ return o.reshape(R, self.H, self.dl)
868
+
869
+ def commit(self, ctx):
870
+ B, ML = ctx.acc_path.shape
871
+ bi = torch.arange(B, device=DEV)[:, None].expand(B, ML)
872
+ dst = (ctx.lens.long()[:, None] + torch.arange(ML, device=DEV)[None]).clamp_(max=self.smax - 1)
873
+ src = ctx.acc_path.long()
874
+ self.cache[bi, dst] = self._tk[bi, src]
875
+ if hasattr(self, "kcache"):
876
+ self.kcache[bi, dst] = self._tki[bi, src]
877
+
878
+
879
+ def _anc_bits(ctx):
880
+ """(B*N,) int64: bit j set iff tree row j is an ancestor-or-self of the row (N <= 63)."""
881
+ B, N = ctx.B, ctx.N
882
+ assert N <= 63
883
+ P = ctx.paths.long() # (B, N, MAXL)
884
+ bits = torch.zeros(B, N, dtype=torch.long, device=P.device)
885
+ ML = P.shape[-1]
886
+ for j in range(ML):
887
+ valid = j < ctx.plen.long()
888
+ bits = bits | torch.where(valid, 1 << P[..., j], torch.zeros_like(bits))
889
+ return bits.reshape(-1)
890
+
891
+
892
+ MLA_CH = 512
893
+
894
+
895
+ def mla_attend_torch(qa, cache, tk, anc, lens, N, scale, dl, dr):
896
+ """reference: N tree rows per user over the committed latent cache (< lens) + their ancestor tree keys, fp32."""
897
+ B, S, D = cache.shape
898
+ R, H, _ = qa.shape
899
+ q = qa.view(B, N, H, -1).float()
900
+ valid = torch.arange(S, device=qa.device)[None] < lens.long()[:, None]
901
+ sc = (torch.einsum("bnhd,bsd->bnhs", q, cache.float()) * scale).masked_fill(~valid[:, None, None], float("-inf"))
902
+ jj = torch.arange(N, device=qa.device)
903
+ am = ((anc.view(B, N, 1).long() >> jj.view(1, 1, N)) & 1).bool()
904
+ st = (torch.einsum("bnhd,bmd->bnhm", q, tk.float()) * scale).masked_fill(~am[:, :, None], float("-inf"))
905
+ p = torch.softmax(torch.cat([sc, st], -1), -1)
906
+ kv = torch.cat([cache[..., :dl], tk[..., :dl]], 1).float()
907
+ return torch.einsum("bnhk,bkd->bnhd", p, kv).reshape(R, H, dl)
908
+
909
+
910
+ def mla_attend(qa, cache, tk, anc, lens, N, scale, dl, dr, smax):
911
+ if not qa.is_cuda or cache.dtype == torch.float32: # f32a: fp32 latent cache -> torch path (kernel is bf16)
912
+ return mla_attend_torch(qa, cache, tk, anc, lens, N, scale, dl, dr)
913
+ R, H, _ = qa.shape
914
+ NS = triton.cdiv(smax, MLA_CH)
915
+ op = torch.empty(R, H, NS, dl, dtype=torch.float32, device=qa.device)
916
+ lp = torch.empty(R, H, NS, dtype=torch.float32, device=qa.device)
917
+ HB = max(16, triton.next_power_of_2(H))
918
+ _mla_dec_k[(R, NS)](qa, cache, tk, anc, lens, op, lp, N, scale, MLA_CH,
919
+ qa.stride(0), qa.stride(1), cache.stride(0), cache.stride(1), tk.stride(0), tk.stride(1),
920
+ op.stride(0), op.stride(1), op.stride(2), 0, NS,
921
+ H=H, HB=HB, DL=dl, DR=dr, BS=32, num_warps=4 if HB <= 16 else 8)
922
+ m = lp.max(-1, keepdim=True).values
923
+ w = torch.exp(lp - m)
924
+ w = torch.where(torch.isfinite(lp), w, torch.zeros_like(w))
925
+ return (op * w[..., None]).sum(2) / w.sum(-1, keepdim=True)
926
+
927
+
928
+ # ----------------------------------------------------------------------------------------------- MoE
929
+ _route_c = None
930
+
931
+
932
+ def _route_fn(x, wr, bias, k: int, sigmoid: bool, renorm: bool, rscale: float, n_group: int, topk_group: int):
933
+ """router: fp32 logits, sigmoid/softmax scores, + correction bias for the choice only, (group-limited) top-k,
934
+ renormalise, routed scaling -- the reference's order of operations."""
935
+ z = F.linear(x.float(), wr) # (R, E) fp32
936
+ if x.is_cuda and n_group == 1:
937
+ from kernels import moe_router
938
+ return moe_router(z, k, sigmoid, bias, renorm and k > 1, rscale)
939
+ sc = torch.sigmoid(z) if sigmoid else torch.softmax(z, -1)
940
+ ch = sc + bias[None] if bias is not None else sc
941
+ E = wr.shape[0]
942
+ if n_group > 1 and n_group > topk_group:
943
+ R = ch.shape[0]
944
+ gs = ch.view(R, n_group, -1).topk(2, -1)[0].sum(-1)
945
+ gi = gs.topk(topk_group, -1, sorted=False)[1]
946
+ gm = torch.zeros_like(gs).scatter_(1, gi, 1.0)
947
+ ch = ch.masked_fill(~gm[:, :, None].expand(R, n_group, E // n_group).reshape(R, -1).bool(), float("-inf"))
948
+ idx = ch.topk(k, -1, sorted=False)[1]
949
+ w = sc.gather(1, idx)
950
+ if k > 1 and renorm:
951
+ w = w / (w.sum(-1, keepdim=True) + 1e-20)
952
+ return idx, w * rscale
953
+
954
+
955
+ class Experts:
956
+ """Routed expert weights in their published code (bf16 / mxfp4 / fp8-block), stacked (E_local, N, K...).
957
+ TP mode: every rank holds all experts, intermediate dim sharded. EP mode: rank holds experts
958
+ [e0, e0+E_local) whole."""
959
+
960
+ def __init__(self, s, W, t, mode):
961
+ p = s["prefix"]
962
+ E = s["n_experts"]
963
+ self.mode = mode
964
+ if mode == "ep":
965
+ assert E % t["world"] == 0
966
+ self.El = E // t["world"]
967
+ self.e0 = t["rank"] * self.El
968
+ ish = None
969
+ else:
970
+ self.El, self.e0 = E, 0
971
+ ish = t
972
+ names = s["expert_names"] # gate, up, down
973
+ self.fmt = s["expert_format"]
974
+ def one(e):
975
+ ep = f"{p}{s['experts_key']}.{e}."
976
+ return self._load(W, ep, names[0], names[1], ish, "rows"), self._load(W, ep, names[2], None, ish, "cols")
977
+ res = pmap(one, range(self.e0, self.e0 + self.El))
978
+ g13, d2 = [r[0] for r in res], [r[1] for r in res]
979
+ if self.fmt == "fp8blk":
980
+ self.w13 = torch.stack([torch.cat([a[0].segs[0][1], a[1].segs[0][1]], 0) for a in g13])
981
+ self.s13 = torch.stack([torch.cat([a[0].segs[0][2], a[1].segs[0][2]], 0) for a in g13])
982
+ self.w2 = torch.stack([a.segs[0][1] for a in d2])
983
+ self.s2 = torch.stack([a.segs[0][2] for a in d2])
984
+ self.inter = self.w2.shape[2]
985
+ elif self.fmt == "mxfp4":
986
+ self.w13p = torch.stack([a[0] for a in g13])
987
+ self.w13s = torch.stack([a[1] for a in g13])
988
+ self.w2p = torch.stack([a[0] for a in d2])
989
+ self.w2s = torch.stack([a[1] for a in d2])
990
+ self.inter = self.w2p.shape[2] * 2
991
+ else:
992
+ self.w13 = torch.stack(g13)
993
+ self.w2 = torch.stack(d2)
994
+ self.inter = self.w2.shape[2]
995
+
996
+ def _load(self, W, ep, a, b, t, how):
997
+ """returns (packed, scale) for mxfp4 or a bf16 tensor; rows: cat(a, b) row-sharded; cols: a col-sharded."""
998
+ if self.fmt == "mxfp4":
999
+ def g(n, part):
1000
+ key = ep + n + "." + part
1001
+ if t is None or t["world"] == 1:
1002
+ return full_w(W, key)
1003
+ return (shard_rows if how == "rows" else shard_cols)(W, key, t)
1004
+ if how == "rows":
1005
+ return (torch.cat([g(a, "weight_packed"), g(b, "weight_packed")], 0),
1006
+ torch.cat([g(a, "weight_scale"), g(b, "weight_scale")], 0))
1007
+ return g(a, "weight_packed").contiguous(), g(a, "weight_scale").contiguous()
1008
+ if self.fmt == "fp8blk": # (gate, up) QWeights or down QWeight; TP slices block-aligned
1009
+ tt = t or {"world": 1, "rank": 0}
1010
+ if how == "rows":
1011
+ return (shard_rows(W, ep + a + ".weight", tt), shard_rows(W, ep + b + ".weight", tt))
1012
+ return shard_cols(W, ep + a + ".weight", tt)
1013
+ if how == "rows":
1014
+ if t is None or t["world"] == 1:
1015
+ return torch.cat([full_w(W, ep + a + ".weight"), full_w(W, ep + b + ".weight")], 0)
1016
+ return torch.cat([shard_rows(W, ep + a + ".weight", t), shard_rows(W, ep + b + ".weight", t)], 0)
1017
+ return full_w(W, ep + a + ".weight") if (t is None or t["world"] == 1) else shard_cols(W, ep + a + ".weight", t)
1018
+
1019
+ def ep_to_tp(self, t):
1020
+ """Generic EP -> TP re-layout over NVLink (all-to-all): experts are LOADED whole (contiguous reads, each
1021
+ byte read once from storage) and then every rank keeps a 1/world slice of the intermediate dim of ALL
1022
+ experts, so a decode step reads 1/world of each active expert on every rank (balanced) instead of whole
1023
+ experts on the ranks that own them. Block-fp8 slices stay block aligned (asserted)."""
1024
+ import torch.distributed as dist
1025
+ W, r = t["world"], t["rank"]
1026
+ assert self.mode == "ep" and self.fmt == "fp8blk"
1027
+ I = self.inter
1028
+ c = I // W
1029
+ qn, qk = QBLOCK["qn"], QBLOCK["qk"]
1030
+ assert c % qn == 0 and c % qk == 0, (I, W, qn, qk)
1031
+
1032
+ def a2a(x, piece):
1033
+ """x (El, ...) -> list over destination ranks q of piece(x, q); exchange; returns (E, ...) ordered."""
1034
+ send = torch.stack([piece(x, q) for q in range(W)]) # (W, El, ...)
1035
+ recv = torch.empty_like(send)
1036
+ dist.all_to_all_single(recv.view(W, -1), send.view(W, -1).contiguous(), group=t["group"])
1037
+ return recv.reshape(W * self.El, *send.shape[2:]) # rank-major = expert order
1038
+ cs, cqs = c, c // qn
1039
+ g13 = lambda x, q: torch.cat([x[:, q * cs:(q + 1) * cs], x[:, I + q * cs:I + (q + 1) * cs]], 1).contiguous()
1040
+ g13s = lambda x, q: torch.cat([x[:, q * cqs:(q + 1) * cqs], x[:, I // qn + q * cqs:I // qn + (q + 1) * cqs]],
1041
+ 1).contiguous()
1042
+ cks = c // qk
1043
+ g2 = lambda x, q: x[:, :, q * cs:(q + 1) * cs].contiguous()
1044
+ g2s = lambda x, q: x[:, :, q * cks:(q + 1) * cks].contiguous()
1045
+ self.w13 = a2a(self.w13.view(torch.uint8), g13).view(torch.float8_e4m3fn)
1046
+ self.s13 = a2a(self.s13, g13s)
1047
+ self.w2 = a2a(self.w2.view(torch.uint8), g2).view(torch.float8_e4m3fn)
1048
+ self.s2 = a2a(self.s2, g2s)
1049
+ self.El, self.e0, self.mode = W * self.El, 0, "tp"
1050
+ self.inter = c
1051
+
1052
+ def nbytes(self):
1053
+ if self.fmt == "fp8blk":
1054
+ return sum(x.numel() * x.element_size() for x in (self.w13, self.s13, self.w2, self.s2))
1055
+ if self.fmt == "mxfp4":
1056
+ return sum(x.numel() for x in (self.w13p, self.w13s, self.w2p, self.w2s))
1057
+ return 2 * (self.w13.numel() + self.w2.numel())
1058
+
1059
+
1060
+ @register("moe")
1061
+ class MoE:
1062
+ def __init__(self, s, W, g):
1063
+ t = tp_of(g)
1064
+ self.t, self.g = t, g
1065
+ p = s["prefix"]
1066
+ self.k = s["top_k"]
1067
+ self.E = s["n_experts"]
1068
+ self.score = s["score"] # sigmoid | softmax
1069
+ self.renorm = s["renorm"]
1070
+ self.rscale = s["routed_scale"]
1071
+ self.n_group, self.topk_group = s.get("n_group", 1), s.get("topk_group", 1)
1072
+ self.wr = full_w(W, p + s["router"] + ".weight").float() # replicated, fp32 (reference computes in fp32)
1073
+ bn = p + (s.get("router_bias_name") or s["router"] + ".e_score_correction_bias")
1074
+ self.bias = full_w(W, bn).float() if s.get("router_bias") else None
1075
+ self.act = tuple(s["act"])
1076
+ self.mode = s.get("shard", "tp") if t["world"] > 1 else "tp"
1077
+ self._pending_tp = None
1078
+ if self.mode == "ep_tp": # load as EP (contiguous reads); re-layout to TP over NVLink later, in layer order
1079
+ self.ex = Experts(s, W, t, "ep")
1080
+ self._pending_tp = t
1081
+ else:
1082
+ self.ex = Experts(s, W, t, self.mode)
1083
+ self.latent = s.get("latent")
1084
+ if self.latent:
1085
+ self.wld = shard_rows(W, p + self.latent["down"], t) # column-parallel -> all-gather
1086
+ self.ln = full_w(W, p + self.latent["norm"]) if self.latent.get("norm") else None
1087
+ self.wlu = shard_cols(W, p + self.latent["up"], t) # row-parallel -> partial
1088
+ self.eps = s["eps"]
1089
+ self.shared = None
1090
+ if s.get("shared"):
1091
+ sh = s["shared"]
1092
+ self.shared = DenseGLUAct({"prefix": p + sh["prefix"], "gate": sh["gate"], "up": sh["up"],
1093
+ "down": sh["down"], "act": s["act"]}, W, g)
1094
+ self.shared_gate = full_w(W, p + sh["gate_w"]) if sh.get("gate_w") else None
1095
+ self.n_shared = 1
1096
+ self.BM = 16
1097
+
1098
+ def weights(self):
1099
+ w = {}
1100
+ if self.latent:
1101
+ w.update(wld=self.wld, wlu=self.wlu)
1102
+ return w
1103
+
1104
+ def route(self, x):
1105
+ global _route_c
1106
+ if _route_c is None:
1107
+ _route_c = _maybe_compile(_route_fn)
1108
+ return _route_c(x, self.wr, self.bias, self.k, self.score == "sigmoid", self.renorm, self.rscale,
1109
+ self.n_group, self.topk_group)
1110
+
1111
+ def _experts(self, xe, idx, w):
1112
+ """xe (R, Din) bf16 -> sum_k w_k expert_k(xe) (R, Dout) fp32 PARTIAL (TP: intermediate shard; EP: local)."""
1113
+ R = xe.shape[0]
1114
+ ex = self.ex
1115
+ if not xe.is_cuda or (ex.fmt == "bf16" and not (xe.dtype == ex.w13.dtype == torch.bfloat16 and MOE_BF16_GROUPED)):
1116
+ return self._experts_loop(xe, idx, w)
1117
+ small_fp8 = False # CUDA-core small-row fp8 was exact but slower than tensor cores on H100 microbench
1118
+ BM = 16 if R * self.k <= 4 * ex.El else 64 # static per shape (graph-safe); big blocks for prefill
1119
+ pr, be, po = Q.moe_align(idx, ex.El, ex.e0, BM)
1120
+ pr2 = torch.where(pr >= 0, torch.arange(pr.shape[0], device=pr.device, dtype=pr.dtype), pr) # slot rows
1121
+ if ex.fmt == "fp8blk":
1122
+ qn, qk = QBLOCK["qn"], QBLOCK["qk"]
1123
+ gv = (1 if R == 1 else BM) if small_fp8 else False
1124
+ gemm = Q.moe_fp8a8_gemm if MOE_FP8A8 else Q.moe_fp8_gemm
1125
+ if not MOE_FP8A8 and self.act[0] == "silu" and ex.w13.shape[1] == 2 * ex.inter and ex.inter % qn == 0 and ex.inter % 32 == 0 and ex.w13.shape[2] % qk == 0:
1126
+ a = Q.moe_fp8glu_gemm(xe, ex.w13, ex.s13, qn, qk, pr, be, BM, ex.inter, BN=32)
1127
+ else:
1128
+ h = gemm(xe, ex.w13, ex.s13, qn, qk, pr, be, BM, gemv1=gv) if not MOE_FP8A8 else gemm(xe, ex.w13, ex.s13, qn, qk, pr, be, BM)
1129
+ a = act_glu(h, ex.inter, self.act)
1130
+ y = (gemm(a, ex.w2, ex.s2, qn, qk, pr2, be, BM, out_dtype=torch.float32, gemv1=gv) if not MOE_FP8A8
1131
+ else gemm(a, ex.w2, ex.s2, qn, qk, pr2, be, BM, out_dtype=torch.float32))
1132
+ elif ex.fmt == "mxfp4":
1133
+ h = Q.moe_fp4_gemm(xe, ex.w13p, ex.w13s, pr, be, BM)
1134
+ a = act_glu(h, ex.inter, self.act)
1135
+ y = Q.moe_fp4_gemm(a, ex.w2p, ex.w2s, pr2, be, BM, out_dtype=torch.float32)
1136
+ else: # bf16: expert outputs rounded to bf16 (= _experts_loop), weighted sum in fp32
1137
+ h = Q.moe_bf16_gemm(xe, ex.w13, pr, be, BM)
1138
+ a = act_glu(h, ex.inter, self.act)
1139
+ y = Q.moe_bf16_gemm(a.to(torch.bfloat16), ex.w2, pr2, be, BM).float()
1140
+ # fused expert gather + routed-weight sum (same fp32 arithmetic, without materialising/gathering all pairs)
1141
+ return Q.moe_combine(y, po, w, R, self.k)
1142
+
1143
+ def _expert_w(self, e):
1144
+ """local expert e -> (w13 (2I, K), w2 (D, I)) as plain tensors (dequantised fp32 for coded formats)."""
1145
+ ex = self.ex
1146
+ if ex.fmt == "fp8blk":
1147
+ qn, qk = QBLOCK["qn"], QBLOCK["qk"]
1148
+ return (Q.fp8blk_dequant(ex.w13[e], ex.s13[e], torch.float32, qn, qk),
1149
+ Q.fp8blk_dequant(ex.w2[e], ex.s2[e], torch.float32, qn, qk))
1150
+ if ex.fmt == "mxfp4":
1151
+ return Q.mxfp4_dequant(ex.w13p[e], ex.w13s[e]), Q.mxfp4_dequant(ex.w2p[e], ex.w2s[e])
1152
+ return ex.w13[e], ex.w2[e]
1153
+
1154
+ def _experts_loop(self, xe, idx, w):
1155
+ """exact per-expert dispatch in torch (CPU reference, and bf16 checkpoints): only the routed rows of each
1156
+ active local expert are computed; expert outputs rounded to bf16, weighted sum in fp32 (reference order).
1157
+ Host-synchronising (not CUDA-graph capturable)."""
1158
+ ex = self.ex
1159
+ out = torch.zeros(xe.shape[0], self._dout(), dtype=torch.float32, device=xe.device)
1160
+ loc = idx - ex.e0
1161
+ cap = xe.is_cuda and torch.cuda.is_current_stream_capturing()
1162
+ if xe.is_cuda and ex.fmt == "bf16" and (cap or loc.numel() <= ex.El):
1163
+ return self._experts_batched(xe, loc, w)
1164
+ if cap: # graph-capturable: every local expert over all rows, unrouted rows weighted 0 (no host sync)
1165
+ for e in range(ex.El):
1166
+ we = (w.float() * (loc == e)).sum(1)
1167
+ w13, w2 = self._expert_w(e)
1168
+ wd = torch.float32 if torch.float32 in (xe.dtype, w13.dtype) else w13.dtype
1169
+ h = F.linear(xe.to(wd), w13.to(wd)).to(xe.dtype)
1170
+ y = F.linear(_act_glu(h, ex.inter, self.act).to(wd), w2.to(wd)).to(xe.dtype).float()
1171
+ out += y * we[:, None]
1172
+ return out
1173
+ for e in torch.unique(loc).tolist():
1174
+ if e < 0 or e >= ex.El:
1175
+ continue
1176
+ rows, kk = torch.nonzero(loc == e, as_tuple=True)
1177
+ w13, w2 = self._expert_w(e)
1178
+ xr = xe[rows]
1179
+ wd = torch.float32 if torch.float32 in (xe.dtype, w13.dtype) else w13.dtype
1180
+ h = F.linear(xr.to(wd), w13.to(wd)).to(xe.dtype)
1181
+ a = _act_glu(h, ex.inter, self.act)
1182
+ y = F.linear(a.to(wd), w2.to(wd)).to(xe.dtype).float()
1183
+ out.index_add_(0, rows, y * w[rows, kk, None].float())
1184
+ return out
1185
+
1186
+ def _experts_batched(self, xe, loc, w):
1187
+ """graph-capturable stacked-expert dispatch (no host sync, a handful of kernels per layer): R*k routed
1188
+ (row, slot) pairs <= local experts -> gather each pair's expert and batch-GEMM (reads only the routed
1189
+ experts); otherwise one batched GEMM over every local expert (reads each expert once). Same rounding
1190
+ points as _experts_loop: expert output rounded to the activation dtype, weighted sum in fp32."""
1191
+ ex = self.ex
1192
+ R, k = loc.shape
1193
+ ok = (loc >= 0) & (loc < ex.El)
1194
+ wf = w.float() * ok
1195
+ lc = loc.clamp(0, ex.El - 1)
1196
+ wd = torch.float32 if torch.float32 in (xe.dtype, ex.w13.dtype) else ex.w13.dtype
1197
+ if R * k <= ex.El:
1198
+ li = lc.reshape(-1)
1199
+ xr = xe.to(wd).repeat_interleave(k, 0)[:, :, None] # (Rk, K, 1)
1200
+ h = torch.bmm(ex.w13[li].to(wd), xr)[:, :, 0].to(xe.dtype) # (Rk, 2I)
1201
+ a = _act_glu(h, ex.inter, self.act).to(wd)
1202
+ y = torch.bmm(ex.w2[li].to(wd), a[:, :, None])[:, :, 0].to(xe.dtype).float() # (Rk, D)
1203
+ return (y.view(R, k, -1) * wf[:, :, None]).sum(1)
1204
+ El = ex.El
1205
+ we = torch.zeros(R, El, dtype=torch.float32, device=xe.device).scatter_add_(1, lc, wf)
1206
+ rc = max(1, (1 << 26) // (El * max(ex.w13.shape[1], ex.w2.shape[1]))) # static row chunk: bounded workspace
1207
+ outs = []
1208
+ for r0 in range(0, R, rc):
1209
+ xc = xe[r0:r0 + rc]
1210
+ n = xc.shape[0]
1211
+ h = torch.matmul(xc.to(wd)[None], ex.w13.to(wd).transpose(1, 2)).to(xe.dtype) # (El, n, 2I)
1212
+ a = _act_glu(h.reshape(El * n, -1), ex.inter, self.act).view(El, n, -1).to(wd)
1213
+ y = torch.bmm(a, ex.w2.to(wd).transpose(1, 2)).to(xe.dtype).float() # (El, n, D)
1214
+ outs.append(torch.einsum("erd,re->rd", y, we[r0:r0 + rc]))
1215
+ return torch.cat(outs, 0)
1216
+
1217
+ def _dout(self):
1218
+ ex = self.ex
1219
+ if ex.fmt == "mxfp4":
1220
+ return ex.w2p.shape[1]
1221
+ return ex.w2.shape[1]
1222
+
1223
+ def __call__(self, x):
1224
+ idx, w = self.route(x)
1225
+ if self.latent:
1226
+ xe = all_gather_last(LINEAR(x, self.wld), self.g)
1227
+ else:
1228
+ xe = x
1229
+ y = self._experts(xe, idx, w) # fp32 partial
1230
+ if self.latent:
1231
+ y = all_reduce(y, self.g).to(x.dtype)
1232
+ if self.ln is not None:
1233
+ y = rms(y, self.ln, self.eps, self.g["norm_offset"])
1234
+ out = LINEAR(y, self.wlu) # partial over the latent shard
1235
+ else:
1236
+ out = y.to(x.dtype) # partial (TP or EP); the wiring all-reduces
1237
+ if self.shared is not None:
1238
+ sh = self.shared(x)
1239
+ if self.shared_gate is not None:
1240
+ sh = sh * torch.sigmoid(LINEAR(x, self.shared_gate))
1241
+ out = out + sh
1242
+ return out