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,833 @@
1
+ """Generic kernels of the engine core (model-agnostic).
2
+
3
+ gdn_paths gated delta rule along arbitrary token paths (tree verify, commit, plain decode): one program per
4
+ (user, path, value head, value block) walks its path from the committed fp32 state S0 in registers.
5
+ No per-node state is ever materialised: a tree of N nodes forks the recurrent state N times for free
6
+ (each fork lives only in registers), and the accepted path is committed by re-walking it with STORE.
7
+ tree_attn_merge ancestor-masked attention of N tree rows over the N tree keys, merged exactly (log-sum-exp) with
8
+ the flash-attention partial over the committed cache (copied from exp_z1_fixedpoint/qengine.py).
9
+ """
10
+ import torch
11
+ try:
12
+ import triton
13
+ import triton.language as tl
14
+ try:
15
+ from triton.language.extra import libdevice
16
+ except ImportError:
17
+ from triton.language.extra.cuda import libdevice
18
+ HAVE_TRITON = True
19
+ except ImportError: # CPU-only installs: kernels are never launched there; give @triton.jit a harmless stub
20
+ import types as _types
21
+
22
+ def _jit(fn=None, **kw):
23
+ return fn if fn is not None else (lambda f: f)
24
+
25
+ def _cdiv(a, b):
26
+ return -(-a // b)
27
+
28
+ def _np2(n):
29
+ return 1 << max(int(n) - 1, 0).bit_length()
30
+ triton = _types.SimpleNamespace(jit=_jit, cdiv=_cdiv, next_power_of_2=_np2)
31
+ tl = _types.SimpleNamespace(constexpr=object)
32
+ HAVE_TRITON = False
33
+
34
+
35
+ @triton.jit
36
+ def _gdn_paths_k(Q, K, V, G, BETA, S0, PATH, PLEN, OROW, O,
37
+ R, sq, sk, sv, so, P,
38
+ HK: tl.constexpr, HV: tl.constexpr, DK: tl.constexpr, DV: tl.constexpr, BV: tl.constexpr,
39
+ MAXL: tl.constexpr, STORE: tl.constexpr, OUT: tl.constexpr, NORM: tl.constexpr,
40
+ GVEC: tl.constexpr, EMIT: tl.constexpr, UNROLL: tl.constexpr):
41
+ """Q,K: (B*R, HK*DK) rows (row stride sq/sk), V: (B*R, HV*DV) (stride sv), G,BETA: (B*R, HV) fp32.
42
+ S0: (B, HV, DK, DV) fp32. PATH: (B, P, MAXL) int32 row indices within user b (local, < R), PLEN (B, P).
43
+ OROW (B, P): row whose output o = S^T q is written (O (B*R, HV*DV), stride so). STORE: write final S to S0."""
44
+ pid = tl.program_id(0)
45
+ h = tl.program_id(1)
46
+ vb = tl.program_id(2)
47
+ b = pid // P
48
+ p = pid % P
49
+ kh = h // (HV // HK)
50
+ dk = tl.arange(0, DK)
51
+ dv = vb * BV + tl.arange(0, BV)
52
+ sbase = S0 + ((b * HV + h) * DK) * DV
53
+ S = tl.load(sbase + dk[:, None] * DV + dv[None, :])
54
+ n = tl.load(PLEN + b * P + p)
55
+ scale = 1.0 / tl.sqrt(DK * 1.0)
56
+ if UNROLL:
57
+ for j in tl.static_range(MAXL): # unrolled: loads of step j+1 can be issued before step j's math
58
+ if j < n:
59
+ r = tl.load(PATH + (b * P + p) * MAXL + j)
60
+ row = b * R + r
61
+ kk = tl.load(K + row * sk + kh * DK + dk).to(tl.float32)
62
+ if NORM:
63
+ kk = kk / tl.sqrt(tl.sum(kk * kk, 0) + 1e-6)
64
+ vv = tl.load(V + row * sv + h * DV + dv).to(tl.float32)
65
+ bb = tl.load(BETA + row * HV + h)
66
+ if GVEC: # per-key-channel decay (Kimi Delta Attention): G (rows, HV, DK)
67
+ gv = tl.load(G + (row * HV + h) * DK + dk)
68
+ S = S * tl.exp(gv)[:, None]
69
+ else:
70
+ gg = tl.load(G + row * HV + h)
71
+ S = S * tl.exp(gg)
72
+ u = (vv - tl.sum(S * kk[:, None], 0)) * bb
73
+ S = S + kk[:, None] * u[None, :]
74
+ if EMIT: # output at every node of the path (one program per root->leaf branch)
75
+ qe = tl.load(Q + row * sq + kh * DK + dk).to(tl.float32)
76
+ if NORM:
77
+ qe = qe / tl.sqrt(tl.sum(qe * qe, 0) + 1e-6)
78
+ qe = qe * scale
79
+ tl.store(O + row * so + h * DV + dv, tl.sum(S * qe[:, None], 0).to(O.dtype.element_ty))
80
+
81
+ else:
82
+ for j in range(0, n):
83
+ r = tl.load(PATH + (b * P + p) * MAXL + j)
84
+ row = b * R + r
85
+ kk = tl.load(K + row * sk + kh * DK + dk).to(tl.float32)
86
+ if NORM:
87
+ kk = kk / tl.sqrt(tl.sum(kk * kk, 0) + 1e-6)
88
+ vv = tl.load(V + row * sv + h * DV + dv).to(tl.float32)
89
+ bb = tl.load(BETA + row * HV + h)
90
+ if GVEC: # per-key-channel decay (Kimi Delta Attention): G (rows, HV, DK)
91
+ gv = tl.load(G + (row * HV + h) * DK + dk)
92
+ S = S * tl.exp(gv)[:, None]
93
+ else:
94
+ gg = tl.load(G + row * HV + h)
95
+ S = S * tl.exp(gg)
96
+ u = (vv - tl.sum(S * kk[:, None], 0)) * bb
97
+ S = S + kk[:, None] * u[None, :]
98
+ if EMIT: # output at every node of the path (one program per root->leaf branch)
99
+ qe = tl.load(Q + row * sq + kh * DK + dk).to(tl.float32)
100
+ if NORM:
101
+ qe = qe / tl.sqrt(tl.sum(qe * qe, 0) + 1e-6)
102
+ qe = qe * scale
103
+ tl.store(O + row * so + h * DV + dv, tl.sum(S * qe[:, None], 0).to(O.dtype.element_ty))
104
+ if OUT:
105
+ orow = tl.load(OROW + b * P + p)
106
+ row = b * R + orow
107
+ qq = tl.load(Q + row * sq + kh * DK + dk).to(tl.float32)
108
+ if NORM:
109
+ qq = qq / tl.sqrt(tl.sum(qq * qq, 0) + 1e-6)
110
+ qq = qq * scale
111
+ o = tl.sum(S * qq[:, None], 0)
112
+ tl.store(O + row * so + h * DV + dv, o.to(O.dtype.element_ty))
113
+ if STORE:
114
+ tl.store(sbase + dk[:, None] * DV + dv[None, :], S)
115
+
116
+
117
+ def _gdn_paths_torch(q, k, v, g, beta, S0, path, plen, orow, o, R, hk, hv, dk, dv, store, out, norm, emit):
118
+ """CPU / reference path of gdn_paths (same math, fp32, one path at a time)."""
119
+ B, P, MAXL = path.shape
120
+ rep = hv // hk
121
+ scale = dk ** -0.5
122
+
123
+ def nrm(x):
124
+ return x / torch.sqrt((x * x).sum(-1, keepdim=True) + 1e-6) if norm else x
125
+ for b in range(B):
126
+ for p in range(P):
127
+ S = S0[b].clone().float() # (hv, dk, dv)
128
+ n = int(plen[b, p])
129
+ for j in range(n):
130
+ row = b * R + int(path[b, p, j])
131
+ kk = nrm(k[row].float().view(hk, dk)).repeat_interleave(rep, 0) # (hv, dk)
132
+ vv = v[row].float().view(hv, dv)
133
+ gg = g[row].float()
134
+ S = S * (gg.exp()[:, :, None] if gg.dim() == 2 else gg.exp()[:, None, None])
135
+ u = (vv - (S * kk[:, :, None]).sum(1)) * beta[row].float()[:, None]
136
+ S = S + kk[:, :, None] * u[:, None, :]
137
+ if emit:
138
+ qq = nrm(q[row].float().view(hk, dk)).repeat_interleave(rep, 0) * scale
139
+ o[row] = (S * qq[:, :, None]).sum(1).reshape(-1).to(o.dtype)
140
+ if out:
141
+ row = b * R + int(orow[b, p])
142
+ qq = nrm(q[row].float().view(hk, dk)).repeat_interleave(rep, 0) * scale
143
+ o[row] = (S * qq[:, :, None]).sum(1).reshape(-1).to(o.dtype)
144
+ if store:
145
+ S0[b].copy_(S)
146
+
147
+
148
+ def gdn_paths(q, k, v, g, beta, S0, path, plen, orow, o, R, hk, hv, dk, dv, store, out, norm=True, BV=32,
149
+ emit=False):
150
+ """g: (rows, hv) scalar log-decay per head (Gated DeltaNet) or (rows, hv, dk) per-key-channel (KDA)."""
151
+ if not q.is_cuda:
152
+ return _gdn_paths_torch(q, k, v, g, beta, S0, path, plen, orow, o, R, hk, hv, dk, dv, store, out, norm, emit)
153
+ B, P, MAXL = path.shape
154
+ _gdn_paths_k[(B * P, hv, dv // BV)](q, k, v, g, beta, S0, path, plen, orow, o if o is not None else q,
155
+ R, q.stride(0), k.stride(0), v.stride(0), o.stride(0) if o is not None else 0,
156
+ P, HK=hk, HV=hv, DK=dk, DV=dv, BV=BV, MAXL=MAXL, STORE=store, OUT=out,
157
+ NORM=norm, GVEC=(g.dim() == 3), EMIT=emit, UNROLL=MAXL <= 64,
158
+ num_warps=4)
159
+
160
+
161
+ @triton.jit
162
+ def _tree_attn_k(Q, K, V, PAR, OC, LC, O, N, sm_scale, sq, sk, sv, lb, lh,
163
+ NH: tl.constexpr, NKV: tl.constexpr, HD: tl.constexpr, BN: tl.constexpr, MAXD: tl.constexpr,
164
+ BQ: tl.constexpr):
165
+ """One program per (user b, query head h, query block): ancestors-only attention of the N tree rows over the N
166
+ tree keys, exact lse merge with the committed-cache partial (OC, LC). FA2 lse=+inf (empty set) -> weight 0."""
167
+ b = tl.program_id(0)
168
+ h = tl.program_id(1)
169
+ kvh = h // (NH // NKV)
170
+ qi = tl.program_id(2) * BQ + tl.arange(0, BQ)
171
+ ki = tl.arange(0, BN)
172
+ dd = tl.arange(0, HD)
173
+ qm = qi < N
174
+ km = ki < N
175
+ rows = b * N + qi
176
+ krow = b * N + ki
177
+ q = tl.load(Q + rows[:, None] * sq + h * HD + dd[None, :], mask=qm[:, None], other=0.0)
178
+ k = tl.load(K + krow[:, None] * sk + kvh * HD + dd[None, :], mask=km[:, None], other=0.0)
179
+ v = tl.load(V + krow[:, None] * sv + kvh * HD + dd[None, :], mask=km[:, None], other=0.0)
180
+ s = tl.dot(q, tl.trans(k)) * sm_scale
181
+ cur = qi
182
+ anc = cur[:, None] == ki[None, :]
183
+ for _ in tl.static_range(MAXD):
184
+ p = tl.load(PAR + b * N + cur, mask=qm, other=-1)
185
+ cur = tl.where(p >= 0, p, cur)
186
+ anc = anc | (cur[:, None] == ki[None, :])
187
+ ok = (anc & km[None, :]) | (qi[:, None] == ki[None, :])
188
+ s = tl.where(ok, s, float("-inf"))
189
+ m = tl.max(s, 1)
190
+ pe = tl.exp(s - m[:, None])
191
+ l = tl.sum(pe, 1)
192
+ ot = tl.dot(pe.to(tl.bfloat16), v) / l[:, None]
193
+ lt = m + tl.log(l)
194
+ lc = tl.load(LC + b * lb + h * lh + qi, mask=qm, other=0.0)
195
+ lc = tl.where(lc == float("inf"), float("-inf"), lc)
196
+ oc = tl.load(OC + rows[:, None] * (NH * HD) + h * HD + dd[None, :], mask=qm[:, None], other=0.0).to(tl.float32)
197
+ mx = tl.maximum(lc, lt)
198
+ wc = tl.exp(lc - mx)
199
+ wt = tl.exp(lt - mx)
200
+ o = (oc * wc[:, None] + ot * wt[:, None]) / (wc + wt)[:, None]
201
+ tl.store(O + rows[:, None] * (NH * HD) + h * HD + dd[None, :], o.to(tl.bfloat16), mask=qm[:, None])
202
+
203
+
204
+ def tree_attn_merge(q, k, v, par, oc, lc, B, N, maxd, nh, nkv, hd, sm_scale):
205
+ """q (B*N, nh*hd) [row stride any], k/v (B*N, nkv*hd) [row stride any], oc (B*N, nh*hd) contiguous,
206
+ lc (B, nh, N) contiguous fp32 lse of the cache partial. Returns o (B*N, nh*hd) bf16."""
207
+ o = torch.empty(B * N, nh * hd, device=q.device, dtype=torch.bfloat16)
208
+ BN = max(16, triton.next_power_of_2(N))
209
+ BQ = 16
210
+ _tree_attn_k[(B, nh, triton.cdiv(N, BQ))](q, k, v, par, oc, lc, o, N, sm_scale, q.stride(0), k.stride(0),
211
+ v.stride(0), lc.stride(0), lc.stride(1), NH=nh, NKV=nkv, HD=hd, BN=BN,
212
+ MAXD=maxd, BQ=BQ, num_warps=4 if hd <= 128 else 8)
213
+ return o
214
+
215
+
216
+ @triton.jit
217
+ def _rms_k(X, Y, W, OUT, R, D, eps, off, sx, sy, HAS_Y: tl.constexpr, OFFSET: tl.constexpr, BD: tl.constexpr,
218
+ ROUND: tl.constexpr):
219
+ """row r: s = x (+ y) [bf16 add, stored to X if HAS_Y]; out = rms_norm(s) * w with the HF rounding of the
220
+ variant: OFFSET (Qwen3.5/Gemma): (s_n * (off + w)).bf16 ; else (Llama): w * s_n.bf16."""
221
+ r = tl.program_id(0)
222
+ c = tl.arange(0, BD)
223
+ m = c < D
224
+ x = tl.load(X + r * sx + c, mask=m, other=0.0)
225
+ if HAS_Y:
226
+ y = tl.load(Y + r * sy + c, mask=m, other=0.0)
227
+ x = (x.to(tl.float32) + y.to(tl.float32)).to(X.dtype.element_ty)
228
+ tl.store(X + r * sx + c, x, mask=m)
229
+ xf = x.to(tl.float32)
230
+ var = tl.sum(xf * xf, 0) / D
231
+ xn = xf * tl.rsqrt(var + eps)
232
+ w = tl.load(W + c, mask=m, other=0.0).to(tl.float32)
233
+ if OFFSET:
234
+ o = xn * (off + w)
235
+ else:
236
+ if ROUND:
237
+ o = w * xn.to(tl.bfloat16).to(tl.float32)
238
+ else:
239
+ o = w * xn
240
+ tl.store(OUT + r * D + c, o.to(OUT.dtype.element_ty), mask=m)
241
+
242
+
243
+ def rms_fused(x, w, eps, offset, y=None):
244
+ """x (R, D) bf16 [updated in place to x + y when y is given], returns rms(x) (R, D) bf16."""
245
+ R, D = x.shape
246
+ out = torch.empty_like(x)
247
+ _rms_k[(R,)](x, y if y is not None else x, w, out, R, D, eps, float(offset), x.stride(0),
248
+ y.stride(0) if y is not None else 0, HAS_Y=y is not None, OFFSET=bool(offset),
249
+ BD=triton.next_power_of_2(D), ROUND=x.dtype == torch.bfloat16, num_warps=8 if D >= 4096 else 4)
250
+ return out
251
+
252
+
253
+ @triton.jit
254
+ def _conv_tree_k(Y, sy, CS, CIDX, W, OUT, N, C, K: tl.constexpr, BC: tl.constexpr, ROUND: tl.constexpr):
255
+ """Depthwise causal conv (width K) + SiLU along each tree row's root path. Y (B*N, >=C) pre-conv rows (row
256
+ stride sy), CS (B, K-1, C) committed conv state, CIDX (N, K) window indices into [CS | tree rows], W (C, K)."""
257
+ r = tl.program_id(0)
258
+ cb = tl.program_id(1)
259
+ b = r // N
260
+ i = r % N
261
+ c = cb * BC + tl.arange(0, BC)
262
+ m = c < C
263
+ acc = tl.zeros([BC], tl.float32)
264
+ for j in tl.static_range(K):
265
+ idx = tl.load(CIDX + i * K + j)
266
+ if idx < K - 1:
267
+ x = tl.load(CS + (b * (K - 1) + idx) * C + c, mask=m, other=0.0)
268
+ else:
269
+ x = tl.load(Y + (b * N + idx - (K - 1)) * sy + c, mask=m, other=0.0)
270
+ w = tl.load(W + c * K + j, mask=m, other=0.0)
271
+ acc += x.to(tl.float32) * w.to(tl.float32)
272
+ if ROUND:
273
+ acc = acc.to(tl.bfloat16).to(tl.float32) # bf16 conv output (as F.conv1d in bf16), then SiLU
274
+ o = acc / (1.0 + tl.exp(-acc))
275
+ tl.store(OUT + r * C + c, o.to(OUT.dtype.element_ty), mask=m)
276
+
277
+
278
+ def conv_tree(y, cs, cidx, w, B, N, C, K):
279
+ out = torch.empty(B * N, C, dtype=y.dtype, device=y.device)
280
+ BC = 1024
281
+ _conv_tree_k[(B * N, triton.cdiv(C, BC))](y, y.stride(0), cs, cidx, w, out, N, C, K=K, BC=BC,
282
+ ROUND=y.dtype == torch.bfloat16, num_warps=4)
283
+ return out
284
+
285
+
286
+ @triton.jit
287
+ def _gdn_gate_k(Y, sy, ob, oa, A, DTB, G, BETA, HV: tl.constexpr, BH: tl.constexpr):
288
+ """beta = sigmoid(b), g = A * softplus(a + dt_bias) (fp32), per row."""
289
+ r = tl.program_id(0)
290
+ h = tl.arange(0, BH)
291
+ m = h < HV
292
+ bb = tl.load(Y + r * sy + ob + h, mask=m, other=0.0).to(tl.float32)
293
+ aa = tl.load(Y + r * sy + oa + h, mask=m, other=0.0).to(tl.float32)
294
+ a_ = tl.load(A + h, mask=m, other=0.0)
295
+ d_ = tl.load(DTB + h, mask=m, other=0.0)
296
+ x = aa + d_
297
+ sp = tl.where(x > 20.0, x, tl.log(1.0 + tl.exp(x)))
298
+ tl.store(G + r * HV + h, a_ * sp, mask=m)
299
+ tl.store(BETA + r * HV + h, 1.0 / (1.0 + tl.exp(-bb)), mask=m)
300
+
301
+
302
+ def gdn_gate(y, ob, oa, A, dtb, HV):
303
+ R = y.shape[0]
304
+ g = torch.empty(R, HV, dtype=torch.float32, device=y.device)
305
+ beta = torch.empty_like(g)
306
+ _gdn_gate_k[(R,)](y, y.stride(0), ob, oa, A, dtb, g, beta, HV=HV, BH=triton.next_power_of_2(HV), num_warps=1)
307
+ return g, beta
308
+
309
+
310
+ @triton.jit
311
+ def _gated_rms_k(O, Z, sz, W, OUT, HV, eps, DV: tl.constexpr, ROUND: tl.constexpr):
312
+ """per (row, head): out = (w * rmsnorm(o).bf16) * silu(z) -> bf16 (Qwen3.5 RMSNormGated rounding)."""
313
+ r = tl.program_id(0)
314
+ h = tl.program_id(1)
315
+ d = tl.arange(0, DV)
316
+ o = tl.load(O + (r * HV + h) * DV + d).to(tl.float32)
317
+ var = tl.sum(o * o, 0) / DV
318
+ on = o * tl.rsqrt(var + eps)
319
+ if ROUND:
320
+ on = on.to(tl.bfloat16).to(tl.float32)
321
+ w = tl.load(W + d).to(tl.float32)
322
+ x = w * on
323
+ if ROUND:
324
+ x = x.to(tl.bfloat16).to(tl.float32)
325
+ z = tl.load(Z + r * sz + h * DV + d).to(tl.float32)
326
+ y = x * (z / (1.0 + tl.exp(-z)))
327
+ tl.store(OUT + (r * HV + h) * DV + d, y.to(OUT.dtype.element_ty))
328
+
329
+
330
+ def gated_rms(o, z, w, HV, DV, eps):
331
+ R = o.shape[0]
332
+ if not o.is_cuda: # reference path (HF Qwen3.5 RMSNormGated roundings when o is bf16)
333
+ of = o.view(R, HV, DV).float()
334
+ on = of * torch.rsqrt(of.pow(2).mean(-1, keepdim=True) + eps)
335
+ rnd = o.dtype == torch.bfloat16
336
+ if rnd:
337
+ on = on.to(o.dtype).float()
338
+ x = w.float() * on
339
+ if rnd:
340
+ x = x.to(o.dtype).float()
341
+ zz = z.reshape(R, HV, DV).float()
342
+ return (x * (zz * torch.sigmoid(zz))).reshape(R, -1).to(o.dtype)
343
+ out = torch.empty(R, HV * DV, dtype=o.dtype, device=o.device)
344
+ _gated_rms_k[(R, HV)](o, z, z.stride(0), w, out, HV, eps, DV=DV, ROUND=o.dtype == torch.bfloat16, num_warps=1)
345
+ return out
346
+
347
+
348
+ @triton.jit
349
+ def _qk_norm_rope_k(Y, sy, QW, KW, COS, SIN, POS, QO, KO, eps, off, NH: tl.constexpr, NKV: tl.constexpr,
350
+ HD: tl.constexpr, QSTRIDE: tl.constexpr, KOFF, ROT: tl.constexpr, NORM: tl.constexpr,
351
+ OFFSET: tl.constexpr, ROUND: tl.constexpr):
352
+ """per (row, head): optional per-head RMSNorm (HF rounding of the variant) then RoPE (rotate_half on the first
353
+ ROT dims, bf16 products as in HF). q heads at Y[r, h*QSTRIDE ...], k heads at Y[r, KOFF + h*HD ...]."""
354
+ r = tl.program_id(0)
355
+ hh = tl.program_id(1)
356
+ d = tl.arange(0, HD)
357
+ isq = hh < NH
358
+ if isq:
359
+ base = Y + r * sy + hh * QSTRIDE
360
+ Wt = QW
361
+ out = QO + (r * NH + hh) * HD
362
+ else:
363
+ base = Y + r * sy + KOFF + (hh - NH) * HD
364
+ Wt = KW
365
+ out = KO + (r * NKV + hh - NH) * HD
366
+ half: tl.constexpr = ROT // 2
367
+ perm = tl.where(d < half, d + half, tl.where(d < ROT, d - half, d))
368
+ x = tl.load(base + d).to(tl.float32)
369
+ xp = tl.load(base + perm).to(tl.float32)
370
+ if NORM:
371
+ rs = tl.rsqrt(tl.sum(x * x, 0) / HD + eps)
372
+ w = tl.load(Wt + d).to(tl.float32)
373
+ wp = tl.load(Wt + perm).to(tl.float32)
374
+ if ROUND:
375
+ if OFFSET:
376
+ x = (x * rs * (off + w)).to(tl.bfloat16).to(tl.float32)
377
+ xp = (xp * rs * (off + wp)).to(tl.bfloat16).to(tl.float32)
378
+ else:
379
+ x = (w * (x * rs).to(tl.bfloat16).to(tl.float32)).to(tl.bfloat16).to(tl.float32)
380
+ xp = (wp * (xp * rs).to(tl.bfloat16).to(tl.float32)).to(tl.bfloat16).to(tl.float32)
381
+ else:
382
+ if OFFSET:
383
+ x = x * rs * (off + w)
384
+ xp = xp * rs * (off + wp)
385
+ else:
386
+ x = w * (x * rs)
387
+ xp = wp * (xp * rs)
388
+ p = tl.load(POS + r)
389
+ dm = d < ROT
390
+ c = tl.load(COS + p * ROT + d, mask=dm, other=1.0).to(tl.float32)
391
+ s = tl.load(SIN + p * ROT + d, mask=dm, other=0.0).to(tl.float32)
392
+ rh = tl.where(d < half, -xp, xp)
393
+ if ROUND:
394
+ a = (x * c).to(tl.bfloat16).to(tl.float32)
395
+ bq = (rh * s).to(tl.bfloat16).to(tl.float32)
396
+ else:
397
+ a = x * c
398
+ bq = rh * s
399
+ y = tl.where(dm, a + bq, x)
400
+ tl.store(out + d, y.to(QO.dtype.element_ty))
401
+
402
+
403
+ def qk_norm_rope(y, qw, kw, cos, sin, pos, nh, nkv, hd, qstride, koff, rot, eps, off):
404
+ R = y.shape[0]
405
+ q = torch.empty(R, nh, hd, dtype=y.dtype, device=y.device)
406
+ k = torch.empty(R, nkv, hd, dtype=y.dtype, device=y.device)
407
+ norm = qw is not None
408
+ _qk_norm_rope_k[(R, nh + nkv)](y, y.stride(0), qw if norm else y, kw if norm else y, cos, sin, pos, q, k, eps,
409
+ float(off), NH=nh, NKV=nkv, HD=hd, QSTRIDE=qstride, KOFF=koff, ROT=rot,
410
+ NORM=norm, OFFSET=bool(off), ROUND=y.dtype == torch.bfloat16, num_warps=2)
411
+ return q, k
412
+
413
+
414
+ @triton.jit
415
+ def _mm_f32o_k(A, W, P, M, N, K, KS, sa, sw, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):
416
+ """partial[s] = A[:, ks:ks+KS] @ W[n-tile, ks:ks+KS]^T, bf16 tensor-core products, fp32 accumulate/store."""
417
+ pn = tl.program_id(0)
418
+ ps = tl.program_id(1)
419
+ rm = tl.arange(0, BM)
420
+ rn = pn * BN + tl.arange(0, BN)
421
+ acc = tl.zeros([BM, BN], tl.float32)
422
+ k0 = ps * KS
423
+ for kk in range(k0, k0 + KS, BK):
424
+ rk = kk + tl.arange(0, BK)
425
+ a = tl.load(A + rm[:, None] * sa + rk[None, :], mask=(rm[:, None] < M) & (rk[None, :] < K), other=0.0)
426
+ w = tl.load(W + rn[:, None] * sw + rk[None, :], mask=(rn[:, None] < N) & (rk[None, :] < K), other=0.0)
427
+ acc += tl.dot(a, tl.trans(w))
428
+ tl.store(P + (ps * M + rm[:, None]) * N + rn[None, :], acc, mask=(rm[:, None] < M) & (rn[None, :] < N))
429
+
430
+
431
+ def mm_f32out(a, w):
432
+ """a (M, K) bf16, w (N, K) bf16 -> (M, N) fp32 = exact-product fp32-accumulated GEMM (deterministic split-K)."""
433
+ M, K = a.shape
434
+ N = w.shape[0]
435
+ BM = max(16, triton.next_power_of_2(M))
436
+ assert BM <= 128
437
+ BN, BK = 64, 128
438
+ nt = triton.cdiv(N, BN)
439
+ S = max(1, min(16, (264 + nt - 1) // nt))
440
+ KS = triton.cdiv(triton.cdiv(K, S), BK) * BK
441
+ S = triton.cdiv(K, KS)
442
+ P = torch.empty(S, M, N, dtype=torch.float32, device=a.device)
443
+ _mm_f32o_k[(nt, S)](a, w, P, M, N, K, KS, a.stride(0), w.stride(0), BM=BM, BN=BN, BK=BK, num_warps=4,
444
+ num_stages=3)
445
+ return P.sum(0) if S > 1 else P[0]
446
+
447
+
448
+ @triton.jit
449
+ def _split_k(X, O, R, K, sx, BK: tl.constexpr):
450
+ """O[r] = bf16(x), O[R + r] = bf16(x - bf16(x)) for one row block (x fp32)."""
451
+ r = tl.program_id(0)
452
+ c = tl.program_id(1) * BK + tl.arange(0, BK)
453
+ m = c < K
454
+ x = tl.load(X + r * sx + c, mask=m, other=0.0)
455
+ hi = x.to(tl.bfloat16)
456
+ lo = (x - hi.to(tl.float32)).to(tl.bfloat16)
457
+ tl.store(O + r * K + c, hi, mask=m)
458
+ tl.store(O + (R + r) * K + c, lo, mask=m)
459
+
460
+
461
+ def split_hilo(x):
462
+ R, K = x.shape
463
+ o = torch.empty(2 * R, K, dtype=torch.bfloat16, device=x.device)
464
+ BK = 2048
465
+ _split_k[(R, triton.cdiv(K, BK))](x, o, R, K, x.stride(0), BK=BK, num_warps=4)
466
+ return o
467
+
468
+
469
+ @triton.jit
470
+ def _attn32_part_k(Q, KC, VC, LENS, M, L, A, N, sm_scale, skb, skh, sks,
471
+ NH: tl.constexpr, NKV: tl.constexpr, HD: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr,
472
+ CH: tl.constexpr, S: tl.constexpr, BQ: tl.constexpr, NQB: tl.constexpr):
473
+ """fp32 flash-decoding partial over the committed cache: program (user b, query head h, key chunk s x query
474
+ block of BQ tree rows) handles
475
+ keys [s*CH, min((s+1)*CH, lens[b])) for the N tree rows; writes running max M, sum L, unnormalised acc A.
476
+ Dots in tf32x3 (fp32-accurate on tensor cores). (A GQA-packed variant -- one program per KV head and query
477
+ block -- was measured slower here: fewer programs, longer serial loops.)"""
478
+ b = tl.program_id(0)
479
+ h = tl.program_id(1)
480
+ sq = tl.program_id(2)
481
+ s = sq // NQB
482
+ qb = sq % NQB
483
+ kvh = h // (NH // NKV)
484
+ qi = qb * BQ + tl.arange(0, BQ)
485
+ dd = tl.arange(0, HD)
486
+ qm = qi < N
487
+ q = tl.load(Q + (b * N + qi)[:, None] * (NH * HD) + h * HD + dd[None, :], mask=qm[:, None], other=0.0)
488
+ Lb = tl.load(LENS + b)
489
+ c0 = s * CH
490
+ c1 = tl.minimum(c0 + CH, Lb)
491
+ m_i = tl.full([BQ], float("-inf"), tl.float32)
492
+ l_i = tl.zeros([BQ], tl.float32)
493
+ acc = tl.zeros([BQ, HD], tl.float32)
494
+ base = KC + b * skb + kvh * skh
495
+ vbase = VC + b * skb + kvh * skh
496
+ for start in range(c0, c1, BK):
497
+ kk = start + tl.arange(0, BK)
498
+ km = kk < c1
499
+ k = tl.load(base + kk[:, None] * sks + dd[None, :], mask=km[:, None], other=0.0)
500
+ v = tl.load(vbase + kk[:, None] * sks + dd[None, :], mask=km[:, None], other=0.0)
501
+ sc = tl.dot(q, tl.trans(k), input_precision="tf32x3") * sm_scale
502
+ sc = tl.where(km[None, :], sc, float("-inf"))
503
+ m_new = tl.maximum(m_i, tl.max(sc, 1))
504
+ alpha = tl.where(m_new == float("-inf"), 1.0, tl.exp(m_i - m_new))
505
+ p = tl.where(m_new[:, None] == float("-inf"), 0.0, tl.exp(sc - m_new[:, None]))
506
+ l_i = l_i * alpha + tl.sum(p, 1)
507
+ acc = acc * alpha[:, None] + tl.dot(p, v, input_precision="tf32x3")
508
+ m_i = m_new
509
+ o = ((b * NH + h) * S + s) * BN + qi
510
+ tl.store(M + o, m_i, mask=qm)
511
+ tl.store(L + o, l_i, mask=qm)
512
+ tl.store(A + o[:, None] * HD + dd[None, :], acc, mask=qm[:, None])
513
+
514
+
515
+ def attn32_cache_partials(q, kc, vc, lens, B, N, nh, nkv, hd, sm_scale, CH=1024, BK=32):
516
+ """q (B*N, nh*hd) fp32; kc/vc (B, nkv, smax, hd) fp32 head-major. Returns (M, L, A) with shapes
517
+ (B, nh, S, BN), (B, nh, S, BN), (B, nh, S, BN, hd); rows >= N are padding."""
518
+ smax = kc.shape[2]
519
+ S = triton.cdiv(smax, CH)
520
+ BQ = 16 if N <= 16 else 32 # query rows per program (32 x 256 fp32 q + acc tiles fit; 64 do not)
521
+ NQB = triton.cdiv(N, BQ)
522
+ BN = NQB * BQ
523
+ M = torch.empty(B, nh, S, BN, device=q.device, dtype=torch.float32)
524
+ Lb = torch.empty_like(M)
525
+ A = torch.empty(B, nh, S, BN, hd, device=q.device, dtype=torch.float32)
526
+ _attn32_part_k[(B, nh, S * NQB)](q, kc, vc, lens, M, Lb, A, N, sm_scale, kc.stride(0), kc.stride(1),
527
+ kc.stride(2), NH=nh, NKV=nkv, HD=hd, BN=BN, BK=BK, CH=CH, S=S, BQ=BQ, NQB=NQB,
528
+ num_warps=8, num_stages=2)
529
+ return M, Lb, A
530
+
531
+
532
+ @triton.jit
533
+ def _attnhl_part_k(Q, KH, KL, VH, VL, LENS, M, L, A, N, sm_scale, skb, skh, sks,
534
+ NH: tl.constexpr, NKV: tl.constexpr, HD: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr,
535
+ CH: tl.constexpr, S: tl.constexpr, BQ: tl.constexpr, NQB: tl.constexpr):
536
+ """fp32-faithful flash-decoding over a cache stored as exact bf16 pairs (k = k_hi + k_lo, |k - k_hi - k_lo| <=
537
+ 2^-16 |k|): scores q.k = q_h.k_h + q_h.k_l + q_l.k_h and p.v likewise, bf16 tensor-core products with fp32
538
+ accumulation. GQA-packed: one program per (user, KV head, key chunk x block of BQ (query head, row) pairs),
539
+ so each K/V byte of a chunk is read once per block instead of once per query head."""
540
+ b = tl.program_id(0)
541
+ kvh = tl.program_id(1)
542
+ sq = tl.program_id(2)
543
+ s = sq // NQB
544
+ qb = sq % NQB
545
+ REP: tl.constexpr = NH // NKV
546
+ r = qb * BQ + tl.arange(0, BQ)
547
+ rm = r < REP * N
548
+ j = r // N
549
+ n = r % N
550
+ h = kvh * REP + j
551
+ dd = tl.arange(0, HD)
552
+ q = tl.load(Q + (b * N + n)[:, None] * (NH * HD) + h[:, None] * HD + dd[None, :], mask=rm[:, None], other=0.0)
553
+ qh = q.to(tl.bfloat16)
554
+ ql = (q - qh.to(tl.float32)).to(tl.bfloat16)
555
+ Lb = tl.load(LENS + b)
556
+ c0 = s * CH
557
+ c1 = tl.minimum(c0 + CH, Lb)
558
+ m_i = tl.full([BQ], float("-inf"), tl.float32)
559
+ l_i = tl.zeros([BQ], tl.float32)
560
+ acc = tl.zeros([BQ, HD], tl.float32)
561
+ off = b * skb + kvh * skh
562
+ for start in range(c0, c1, BK):
563
+ kk = start + tl.arange(0, BK)
564
+ km = kk < c1
565
+ p_ = off + kk[:, None] * sks + dd[None, :]
566
+ kh = tl.load(KH + p_, mask=km[:, None], other=0.0)
567
+ kl = tl.load(KL + p_, mask=km[:, None], other=0.0)
568
+ sc = tl.dot(qh, tl.trans(kh)) + tl.dot(qh, tl.trans(kl)) + tl.dot(ql, tl.trans(kh))
569
+ sc = sc * sm_scale
570
+ sc = tl.where(km[None, :], sc, float("-inf"))
571
+ m_new = tl.maximum(m_i, tl.max(sc, 1))
572
+ alpha = tl.where(m_new == float("-inf"), 1.0, tl.exp(m_i - m_new))
573
+ p = tl.where(m_new[:, None] == float("-inf"), 0.0, tl.exp(sc - m_new[:, None]))
574
+ l_i = l_i * alpha + tl.sum(p, 1)
575
+ ph = p.to(tl.bfloat16)
576
+ pl = (p - ph.to(tl.float32)).to(tl.bfloat16)
577
+ vh = tl.load(VH + p_, mask=km[:, None], other=0.0)
578
+ vl = tl.load(VL + p_, mask=km[:, None], other=0.0)
579
+ acc = acc * alpha[:, None] + tl.dot(ph, vh) + tl.dot(ph, vl) + tl.dot(pl, vh)
580
+ m_i = m_new
581
+ o = ((b * NH + h) * S + s) * BN + n
582
+ tl.store(M + o, m_i, mask=rm)
583
+ tl.store(L + o, l_i, mask=rm)
584
+ tl.store(A + o[:, None] * HD + dd[None, :], acc, mask=rm[:, None])
585
+
586
+
587
+ def attnhl_cache_partials(q, kh, kl, vh, vl, lens, B, N, nh, nkv, hd, sm_scale, CH=1024, BK=32, BQ=32):
588
+ """Same outputs as attn32_cache_partials, from a hi/lo bf16 cache (B, nkv, smax, hd) x 4."""
589
+ smax = kh.shape[2]
590
+ S = triton.cdiv(smax, CH)
591
+ BN = max(16, triton.next_power_of_2(N))
592
+ NQB = triton.cdiv((nh // nkv) * N, BQ)
593
+ M = torch.empty(B, nh, S, BN, device=q.device, dtype=torch.float32)
594
+ Lb = torch.empty_like(M)
595
+ A = torch.empty(B, nh, S, BN, hd, device=q.device, dtype=torch.float32)
596
+ _attnhl_part_k[(B, nkv, S * NQB)](q, kh, kl, vh, vl, lens, M, Lb, A, N, sm_scale, kh.stride(0), kh.stride(1),
597
+ kh.stride(2), NH=nh, NKV=nkv, HD=hd, BN=BN, BK=BK, CH=CH, S=S, BQ=BQ, NQB=NQB,
598
+ num_warps=8, num_stages=2)
599
+ return M, Lb, A
600
+
601
+
602
+ MOE_TILE = [32, 128, 4, 3] # grouped expert GEMM (BN, BK, num_warps, num_stages): gate/up (GLU) GEMM
603
+ MOE_TILE_DN = None # second (down) GEMM; None = MOE_TILE
604
+
605
+
606
+ MOE_ALIGN_FUSED = True # one-kernel dispatch on CUDA (the torch path is ~20 small launches per MoE layer)
607
+
608
+
609
+ @triton.jit
610
+ def _moe_align_k(TI, PAIR_ROW, BLK_EXP, PAIR_OF, SCR, P, NSLOT, NBLK, K: tl.constexpr, BM: tl.constexpr,
611
+ PB: tl.constexpr, QB: tl.constexpr, SB: tl.constexpr):
612
+ """single-CTA moe_align: slot of pair p = BM * (blocks of all lower experts) + (# earlier pairs of its expert);
613
+ identical to the stable expert sort of the torch path. SCR = [lead blocks (PB) | slot expert (NSLOT)]."""
614
+ p = tl.arange(0, PB)
615
+ pm = p < P
616
+ ep = tl.load(TI + p, mask=pm, other=-1).to(tl.int64)
617
+ cnt = tl.zeros([PB], tl.int32)
618
+ rank = tl.zeros([PB], tl.int32)
619
+ for q0 in range(0, P, QB):
620
+ q = q0 + tl.arange(0, QB)
621
+ eq = tl.load(TI + q, mask=q < P, other=-2).to(tl.int64)
622
+ same = ep[:, None] == eq[None, :]
623
+ cnt += tl.sum(same.to(tl.int32), 1)
624
+ rank += tl.sum((same & (q[None, :] < p[:, None])).to(tl.int32), 1)
625
+ lead = tl.where(rank == 0, (cnt + BM - 1) // BM, 0)
626
+ tl.store(SCR + p, lead.to(tl.int64), mask=pm)
627
+ for s0 in range(0, NSLOT, SB):
628
+ s = s0 + tl.arange(0, SB)
629
+ tl.store(PAIR_ROW + s, tl.full([SB], -1, tl.int32), mask=s < NSLOT)
630
+ tl.store(SCR + PB + s, tl.full([SB], -1, tl.int64), mask=s < NSLOT)
631
+ tl.debug_barrier()
632
+ start = tl.zeros([PB], tl.int64)
633
+ for q0 in range(0, P, QB):
634
+ q = q0 + tl.arange(0, QB)
635
+ eq = tl.load(TI + q, mask=q < P, other=1 << 30).to(tl.int64)
636
+ lq = tl.load(SCR + q, mask=q < P, other=0)
637
+ start += tl.sum(tl.where(eq[None, :] < ep[:, None], lq[None, :], 0), 1)
638
+ slot = start * BM + rank
639
+ tl.store(PAIR_ROW + slot, (p // K).to(tl.int32), mask=pm)
640
+ tl.store(SCR + PB + slot, ep, mask=pm)
641
+ tl.store(PAIR_OF + p, slot, mask=pm)
642
+ tl.debug_barrier()
643
+ for b0 in range(0, NBLK, SB):
644
+ b = b0 + tl.arange(0, SB)
645
+ bm = b < NBLK
646
+ tl.store(BLK_EXP + b, tl.load(SCR + PB + b * BM, mask=bm, other=-1).to(tl.int32), mask=bm)
647
+
648
+
649
+ def moe_align(ti, E, BM):
650
+ R, k = ti.shape
651
+ P = R * k
652
+ if MOE_ALIGN_FUSED and ti.is_cuda and HAVE_TRITON and P <= 2048:
653
+ nblk = min(E, P) + (P + BM - 1) // BM
654
+ NS = nblk * BM
655
+ PB = max(16, triton.next_power_of_2(P))
656
+ dev = ti.device
657
+ pair_row = torch.empty(NS, dtype=torch.int32, device=dev)
658
+ blk_exp = torch.empty(nblk, dtype=torch.int32, device=dev)
659
+ pair_of = torch.empty(P, dtype=torch.long, device=dev)
660
+ scr = torch.empty(PB + NS, dtype=torch.long, device=dev)
661
+ _moe_align_k[(1,)](ti.contiguous(), pair_row, blk_exp, pair_of, scr, P, NS, nblk, K=k, BM=BM, PB=PB,
662
+ QB=16 if PB >= 1024 else 32, SB=256, num_warps=8 if PB >= 512 else 4)
663
+ return pair_row, blk_exp, pair_of
664
+ return moe_align_torch(ti, E, BM)
665
+
666
+
667
+ if HAVE_TRITON:
668
+ @triton.jit
669
+ def _router_k(LG, RB, TI, WT, E, K: tl.constexpr, BE: tl.constexpr, BK: tl.constexpr, SIG: tl.constexpr,
670
+ HAS_B: tl.constexpr, NORM: tl.constexpr, SCALE: tl.constexpr = 1.0):
671
+ r = tl.program_id(0).to(tl.int64)
672
+ e = tl.arange(0, BE)
673
+ em = e < E
674
+ x = tl.load(LG + r * E + e, mask=em, other=-float("inf"))
675
+ if SIG:
676
+ p = tl.math.div_rn(1.0, 1.0 + libdevice.exp(-x))
677
+ else:
678
+ ex = libdevice.exp(x - tl.max(x, 0))
679
+ p = tl.math.div_rn(ex, tl.sum(tl.where(em, ex, 0.0), 0))
680
+ p = tl.where(em, p, 0.0)
681
+ sc = p + tl.load(RB + e, mask=em, other=0.0) if HAS_B else p
682
+ sc = tl.where(em, sc, -float("inf"))
683
+ kk = tl.arange(0, BK)
684
+ ti = tl.zeros([BK], tl.int64)
685
+ w = tl.zeros([BK], tl.float32)
686
+ for j in tl.static_range(K): # descending, ties -> lowest expert id (row-independent)
687
+ mx = tl.max(sc, 0)
688
+ i = tl.min(tl.where(sc == mx, e, BE), 0)
689
+ ti = tl.where(kk == j, i.to(tl.int64), ti)
690
+ w = tl.where(kk == j, tl.sum(tl.where(e == i, p, 0.0), 0), w)
691
+ sc = tl.where(e == i, -float("inf"), sc)
692
+ if NORM:
693
+ w = tl.math.div_rn(w, tl.sum(w, 0))
694
+ w = w * SCALE
695
+ tl.store(TI + r * K + kk, ti, mask=kk < K)
696
+ tl.store(WT + r * K + kk, w, mask=kk < K)
697
+
698
+
699
+ def moe_router(lg, k, sig=False, rb=None, norm=True, scale=1.0):
700
+ """fp32 router logits (R, E) -> (top-k expert ids (R, k) long, weights (R, k) fp32) in one kernel: softmax or
701
+ sigmoid, + choice-only correction bias, top-k, optional renorm (MoEFused.__call__ routing)."""
702
+ R, E = lg.shape
703
+ ti = torch.empty(R, k, dtype=torch.long, device=lg.device)
704
+ w = torch.empty(R, k, dtype=torch.float32, device=lg.device)
705
+ _router_k[(R,)](lg.contiguous(), rb if rb is not None else lg, ti, w, E, K=k, BE=triton.next_power_of_2(E),
706
+ BK=max(2, triton.next_power_of_2(k)), SIG=sig, HAS_B=rb is not None, NORM=norm,
707
+ SCALE=scale, num_warps=4 if E > 256 else 2)
708
+ return ti, w
709
+
710
+
711
+ def moe_align_torch(ti, E, BM):
712
+ """capacity-free exact expert dispatch, graph-safe (static shapes, no host sync). ti (R, k) expert ids ->
713
+ pair_row (P_pad,) int32 activation row of each expert-sorted padded slot (-1 = padding), blk_exp (P_pad/BM,)
714
+ int32 expert of each BM-block (-1 = empty), pair_of (R*k,) long slot of each (row, k) pair."""
715
+ R, k = ti.shape
716
+ P = R * k
717
+ dev = ti.device
718
+ key = ti.reshape(-1).long()
719
+ ar = torch.arange(P, device=dev)
720
+ order = torch.argsort(key * P + ar)
721
+ sk = key[order]
722
+ cnt = torch.zeros(E, dtype=torch.long, device=dev).scatter_add_(0, key, torch.ones_like(key))
723
+ first = torch.cumsum(cnt, 0) - cnt
724
+ pad = (cnt + BM - 1) // BM * BM
725
+ endp = torch.cumsum(pad, 0)
726
+ start = endp - pad
727
+ nblk = min(E, P) + (P + BM - 1) // BM
728
+ P_pad = nblk * BM
729
+ pos = start[sk] + (ar - first[sk])
730
+ pair_row = torch.full((P_pad,), -1, dtype=torch.int32, device=dev)
731
+ pair_row.scatter_(0, pos, (order // k).to(torch.int32))
732
+ pair_of = torch.empty(P, dtype=torch.long, device=dev)
733
+ pair_of.scatter_(0, order, pos)
734
+ be = torch.searchsorted(endp, torch.arange(nblk, device=dev) * BM, right=True)
735
+ blk_exp = torch.where(be < E, be, torch.full_like(be, -1)).to(torch.int32)
736
+ return pair_row, blk_exp, pair_of
737
+
738
+
739
+ @triton.jit
740
+ def _moe_bf16_k(A, W, C, PAIR_ROW, BLK_EXP, N, K, sa, swe, swn, sc,
741
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, SLOT_ROWS: tl.constexpr,
742
+ GLU: tl.constexpr = False):
743
+ """grouped bf16 GEMM over expert-sorted padded slots: each routed expert's weights are read once per pass,
744
+ however many tree rows chose it. SLOT_ROWS: A is indexed by slot (second GEMM) instead of activation row."""
745
+ blk = tl.program_id(0)
746
+ nb = tl.program_id(1)
747
+ e = tl.load(BLK_EXP + blk).to(tl.int64)
748
+ if e < 0:
749
+ return
750
+ rows = blk * BM + tl.arange(0, BM)
751
+ arow = tl.load(PAIR_ROW + rows).to(tl.int64)
752
+ valid = arow >= 0
753
+ if SLOT_ROWS:
754
+ arow = rows.to(tl.int64)
755
+ arow = tl.where(valid, arow, 0)
756
+ n = nb * BN + tl.arange(0, BN)
757
+ nm = n < N
758
+ kk0 = tl.arange(0, BK)
759
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
760
+ acu = tl.zeros((BM, BN), dtype=tl.float32)
761
+ for k0 in range(0, K, BK):
762
+ kk = k0 + kk0
763
+ km = kk[None, :] < K
764
+ a = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None] & km, other=0.0).to(tl.bfloat16)
765
+ w = tl.load(W + e * swe + n[:, None] * swn + kk[None, :], mask=nm[:, None] & km, other=0.0)
766
+ acc += tl.dot(a, tl.trans(w.to(tl.bfloat16)))
767
+ if GLU: # up rows N + n of the same expert
768
+ u = tl.load(W + e * swe + (n[:, None] + N) * swn + kk[None, :], mask=nm[:, None] & km, other=0.0)
769
+ acu += tl.dot(a, tl.trans(u.to(tl.bfloat16)))
770
+ if GLU: # == F.silu(gate_bf16) * up_bf16 with torch's bf16 roundings (IEEE exp/div)
771
+ g = acc.to(tl.bfloat16).to(tl.float32)
772
+ sg = tl.math.div_rn(g, 1.0 + libdevice.exp(-g)).to(tl.bfloat16).to(tl.float32)
773
+ acc = sg * acu.to(tl.bfloat16).to(tl.float32)
774
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None] & nm[None, :])
775
+
776
+
777
+ @triton.jit
778
+ def _moe_combine_k(Y, PO, WT, OUT, SH, GL, D, sy, rs, KT: tl.constexpr, BN: tl.constexpr, FINAL: tl.constexpr,
779
+ SCALE: tl.constexpr, HAS_SH: tl.constexpr, HAS_SG: tl.constexpr):
780
+ """acc[r] = sum_j fp32(bf16(fp32(y[slot(r, j)]) * w[r, j])), j ascending (= the torch combine). FINAL: the
781
+ MoEFused tail bf16(acc) [* rs] + [sigmoid gate] * shared, each op rounded to bf16 like torch."""
782
+ r = tl.program_id(0).to(tl.int64)
783
+ n = tl.program_id(1) * BN + tl.arange(0, BN)
784
+ nm = n < D
785
+ acc = tl.zeros((BN,), dtype=tl.float32)
786
+ for j in tl.static_range(KT):
787
+ sl = tl.load(PO + r * KT + j)
788
+ wj = tl.load(WT + r * KT + j)
789
+ y = tl.load(Y + sl * sy + n, mask=nm, other=0.0).to(tl.float32)
790
+ acc += (y * wj).to(tl.bfloat16).to(tl.float32)
791
+ if FINAL:
792
+ o = acc.to(tl.bfloat16).to(tl.float32)
793
+ if SCALE:
794
+ o = (o * rs).to(tl.bfloat16).to(tl.float32)
795
+ if HAS_SH:
796
+ sh = tl.load(SH + r * D + n, mask=nm, other=0.0).to(tl.float32)
797
+ if HAS_SG: # GL = torch.sigmoid(gate logit), bf16 (R, 1)
798
+ sh = (tl.load(GL + r).to(tl.float32) * sh).to(tl.bfloat16).to(tl.float32)
799
+ o = (o + sh).to(tl.bfloat16).to(tl.float32)
800
+ tl.store(OUT + r * D + n, o.to(OUT.dtype.element_ty), mask=nm)
801
+ else:
802
+ tl.store(OUT + r * D + n, acc, mask=nm)
803
+
804
+
805
+ def moe_combine(y, pair_of, w, final=False, rs=1.0, sh=None, gl=None):
806
+ """y (P_pad, D) bf16 expert outputs by slot, pair_of (R*k,), w (R, k) fp32 -> (R, D) fp32 weighted sum, or
807
+ (final) the bf16 layer output with routed scale rs, shared expert sh (R, D) and its sigmoid gate gl (R, 1)."""
808
+ R, k = w.shape
809
+ D = y.shape[1]
810
+ out = torch.empty(R, D, dtype=y.dtype if final else torch.float32, device=y.device)
811
+ BN = 1024
812
+ shc = sh.contiguous() if sh is not None else y
813
+ glc = gl.contiguous() if gl is not None else y
814
+ _moe_combine_k[(R, triton.cdiv(D, BN))](y, pair_of, w.float().contiguous(), out, shc, glc, D, y.stride(0),
815
+ float(rs), KT=k, BN=BN, FINAL=final, SCALE=final and rs != 1.0,
816
+ HAS_SH=sh is not None, HAS_SG=gl is not None, num_warps=4)
817
+ return out
818
+
819
+
820
+ def moe_bf16_gemm(a, w, pair_row, blk_exp, BM, slot_rows=False, BN=None, BK=None, nw=None, glu=False, ns=None):
821
+ """a (R or P_pad, K) bf16; w (E, N, K) bf16 -> C (P_pad, N) bf16 (padding slots unwritten).
822
+ glu: w rows are [gate | up] halves, C = silu(gate) * up (P_pad, N/2)."""
823
+ P = pair_row.shape[0]
824
+ E, N, K = w.shape
825
+ if glu:
826
+ N //= 2
827
+ t = MOE_TILE_DN if slot_rows and MOE_TILE_DN else MOE_TILE
828
+ BN, BK, nw, ns = BN or t[0], BK or t[1], nw or t[2], ns or (t[3] if len(t) > 3 else 3)
829
+ c = torch.empty(P, N, dtype=torch.bfloat16, device=a.device)
830
+ _moe_bf16_k[(P // BM, triton.cdiv(N, BN))](a, w, c, pair_row, blk_exp, N, K, a.stride(0), w.stride(0),
831
+ w.stride(1), c.stride(0), BM=BM, BN=BN, BK=BK,
832
+ SLOT_ROWS=slot_rows, GLU=glu, num_warps=nw, num_stages=ns)
833
+ return c