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/quant.py ADDED
@@ -0,0 +1,850 @@
1
+ """Exact weight codecs for published low-bit checkpoints (generic: chosen from the checkpoint's own tensors /
2
+ quantization_config, never from a model name).
3
+
4
+ mxfp4 compressed-tensors "mxfp4-pack-quantized": weight_packed uint8 (N, K/2), two e2m1 codes per byte (low
5
+ nibble = even k), weight_scale uint8 (N, K/32) E8M0 (2^(s-127)). Every decoded value e2m1 * 2^(s-127) is
6
+ exactly representable in bf16 and in fp32, so decoding is lossless: the engine's GEMM and the fp32
7
+ reference multiply by the same numbers.
8
+ fp8blk e4m3 weight (N, K) + weight_scale_inv fp32 (N/128, K/128): W = w8 * s. The block-scaled GEMM applies s to
9
+ each 128x128 block's fp32 partial (y = sum_kb s[nb,kb] (x_kb . w8_kb)), i.e. the exact dequantised matrix;
10
+ the fp32 reference uses w8.float() * s.
11
+
12
+ QWeight objects stand in for a weight tensor: F.linear(x, qw) dispatches here through __torch_function__, so block
13
+ code written against plain tensors runs unchanged on quantised checkpoints.
14
+ """
15
+ import torch
16
+ import torch.nn.functional as F
17
+ try:
18
+ import triton
19
+ import triton.language as tl
20
+ except ImportError: # CPU-only installs: Triton kernels are never launched; torch reference paths run instead
21
+ from kernels import triton, tl
22
+
23
+ E2M1 = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0])
24
+
25
+
26
+ def e8m0_to_f32(s):
27
+ """uint8 E8M0 -> fp32 2^(s-127) exactly (s=0 -> 2^-127, a subnormal; 255 = NaN by OCP spec)."""
28
+ s = s.to(torch.int32)
29
+ bits = torch.where(s > 0, s << 23, torch.full_like(s, 0x00400000))
30
+ return bits.view(torch.float32)
31
+
32
+
33
+ def mxfp4_dequant(packed, scale, dtype=torch.float32):
34
+ """Reference decode (torch): packed (..., N, K/2) uint8, scale (..., N, K/32) uint8 -> (..., N, K) dtype."""
35
+ lut = E2M1.to(packed.device)
36
+ lo = lut[(packed & 0xF).long()]
37
+ hi = lut[(packed >> 4).long()]
38
+ v = torch.stack([lo, hi], -1).flatten(-2) # (..., N, K)
39
+ sc = e8m0_to_f32(scale).repeat_interleave(32, -1)
40
+ return (v * sc).to(dtype)
41
+
42
+
43
+ def fp8blk_dequant(w8, s, dtype=torch.float32, qn=None, qk=None):
44
+ """block size inferred from the scale grid when not given (ceil(N / rows), ceil(K / cols))."""
45
+ N, K = w8.shape
46
+ qn = qn or -(-N // s.shape[0])
47
+ qk = qk or -(-K // s.shape[1])
48
+ sf = s.float().repeat_interleave(qn, 0)[:N].repeat_interleave(qk, 1)[:, :K]
49
+ return (w8.float() * sf).to(dtype)
50
+
51
+
52
+ # ------------------------------------------------------------------------------------------- Triton GEMMs
53
+ @triton.jit
54
+ def _fp4_vals(c):
55
+ """e2m1 code (int32 0..15) -> fp32 value."""
56
+ e = (c >> 1) & 3
57
+ m = (c & 1).to(tl.float32)
58
+ mag = tl.where(e == 0, m * 0.5, (1.0 + 0.5 * m) * tl.exp2((e - 1).to(tl.float32)))
59
+ return tl.where((c & 8) != 0, -mag, mag)
60
+
61
+
62
+ @triton.jit
63
+ def _e8m0(s):
64
+ s = s.to(tl.int32)
65
+ bits = tl.where(s > 0, s << 23, 0x00400000)
66
+ return bits.to(tl.float32, bitcast=True)
67
+
68
+
69
+ @triton.jit
70
+ def _moe_fp4_k(A, WP, WS, C, PAIR_ROW, BLK_EXP, NPAIR,
71
+ N, K, sa, swe, swn, sse, ssn, sc,
72
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):
73
+ """Grouped MXFP4 GEMM. Pairs are sorted by expert and padded so every BM-block has one expert (BLK_EXP[blk],
74
+ -1 = empty). Row r of block blk: pair index p = blk*BM + r (p < NPAIR valid), activation row PAIR_ROW[p].
75
+ C[p, n] = sum_k A[PAIR_ROW[p], k] * W[e, n, k]."""
76
+ blk = tl.program_id(0)
77
+ nb = tl.program_id(1)
78
+ e = tl.load(BLK_EXP + blk)
79
+ if e < 0:
80
+ return
81
+ rows = blk * BM + tl.arange(0, BM)
82
+ arow = tl.load(PAIR_ROW + rows)
83
+ valid = arow >= 0
84
+ arow = tl.where(valid, arow, 0)
85
+ n = nb * BN + tl.arange(0, BN)
86
+ nm = n < N
87
+ j = tl.arange(0, BK // 2)
88
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
89
+ for k0 in range(0, K, BK):
90
+ ke = k0 + 2 * j
91
+ a_e = tl.load(A + arow[:, None] * sa + ke[None, :], mask=valid[:, None], other=0.0)
92
+ a_o = tl.load(A + arow[:, None] * sa + ke[None, :] + 1, mask=valid[:, None], other=0.0)
93
+ b = tl.load(WP + e * swe + n[:, None] * swn + (k0 // 2 + j)[None, :], mask=nm[:, None], other=0).to(tl.int32)
94
+ sc_ = _e8m0(tl.load(WS + e * sse + n[:, None] * ssn + ((k0 + 2 * j) // 32)[None, :], mask=nm[:, None],
95
+ other=127))
96
+ w_lo = (_fp4_vals(b & 15) * sc_).to(tl.bfloat16)
97
+ w_hi = (_fp4_vals(b >> 4) * sc_).to(tl.bfloat16)
98
+ acc += tl.dot(a_e.to(tl.bfloat16), tl.trans(w_lo))
99
+ acc += tl.dot(a_o.to(tl.bfloat16), tl.trans(w_hi))
100
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None] & nm[None, :])
101
+
102
+
103
+ @triton.jit
104
+ def _align_k(IDS, PR, BE, PO, P, E, e0, k, P_pad, nblk,
105
+ BP: tl.constexpr, BE_: tl.constexpr, BB: tl.constexpr, BM: tl.constexpr, BF_: tl.constexpr):
106
+ """one-program capacity-free dispatch for small pair counts (decode / verify): same outputs as the torch path."""
107
+ i = tl.arange(0, BP)
108
+ im = i < P
109
+ loc = tl.load(IDS + i, mask=im, other=0).to(tl.int32) - e0
110
+ ok = im & (loc >= 0) & (loc < E)
111
+ loc = tl.where(ok, loc, -1)
112
+ e = tl.arange(0, BE_)
113
+ oh = (loc[:, None] == e[None, :]) & ok[:, None] # (BP, BE)
114
+ cnt = tl.sum(oh.to(tl.int32), 0) # (BE,)
115
+ pad = (cnt + BM - 1) // BM * BM
116
+ endp = tl.cumsum(pad, 0)
117
+ start = endp - pad
118
+ same = (loc[:, None] == loc[None, :]) & (i[None, :] < i[:, None]) & ok[None, :] # earlier pairs, same expert
119
+ within = tl.sum(same.to(tl.int32), 1)
120
+ st_i = tl.sum(tl.where(oh, start[None, :], 0), 1)
121
+ slot = st_i + within
122
+ for f0 in range(0, P_pad, BF_):
123
+ f = f0 + tl.arange(0, BF_)
124
+ tl.store(PR + f, tl.full((BF_,), -1, tl.int32), mask=f < P_pad)
125
+ tl.debug_barrier()
126
+ tl.store(PR + slot, (i // k).to(tl.int32), mask=ok)
127
+ tl.store(PO + i, tl.where(ok, slot, -1).to(tl.int64), mask=im)
128
+ b = tl.arange(0, BB)
129
+ bs = b * BM
130
+ inr = (bs[:, None] >= start[None, :]) & (bs[:, None] < endp[None, :]) & (e[None, :] < E)
131
+ be = tl.sum(tl.where(inr, e[None, :], 0), 1)
132
+ anyr = tl.sum(inr.to(tl.int32), 1) > 0
133
+ tl.store(BE + b, tl.where(anyr, be, -1).to(tl.int32), mask=b < nblk)
134
+
135
+
136
+ @triton.jit
137
+ def _alcnt_k(IDS, CNT, P, e0, k, BP: tl.constexpr):
138
+ e = tl.program_id(0)
139
+ i = tl.arange(0, BP)
140
+ loc = tl.load(IDS + i, mask=i < P, other=-1).to(tl.int32) - e0
141
+ tl.store(CNT + e, tl.sum((loc == e).to(tl.int32), 0))
142
+
143
+
144
+ @triton.jit
145
+ def _alpre_k(CNT, START, END, E, BM: tl.constexpr, BE: tl.constexpr):
146
+ e = tl.arange(0, BE)
147
+ cnt = tl.load(CNT + e, mask=e < E, other=0)
148
+ pad = (cnt + BM - 1) // BM * BM
149
+ end = tl.cumsum(pad, 0)
150
+ tl.store(START + e, end - pad, mask=e < E)
151
+ tl.store(END + e, end, mask=e < E)
152
+
153
+
154
+ @triton.jit
155
+ def _alslot_k(IDS, START, PR, PO, P, E, e0, k, P_pad, BP: tl.constexpr, BF: tl.constexpr):
156
+ i = tl.arange(0, BP)
157
+ im = i < P
158
+ loc = tl.load(IDS + i, mask=im, other=-1).to(tl.int32) - e0
159
+ ok = im & (loc >= 0) & (loc < E)
160
+ same = (loc[:, None] == loc[None, :]) & (i[None, :] < i[:, None]) & ok[None, :]
161
+ within = tl.sum(same.to(tl.int32), 1)
162
+ st = tl.load(START + loc, mask=ok, other=0)
163
+ slot = st + within
164
+ for f0 in range(0, P_pad, BF):
165
+ f = f0 + tl.arange(0, BF)
166
+ tl.store(PR + f, tl.full((BF,), -1, tl.int32), mask=f < P_pad)
167
+ tl.debug_barrier()
168
+ tl.store(PR + slot, (i // k).to(tl.int32), mask=ok)
169
+ tl.store(PO + i, tl.where(ok, slot, -1).to(tl.int64), mask=im)
170
+
171
+
172
+ @triton.jit
173
+ def _alblk_k(END, BE, E, ebase, BM: tl.constexpr, BE_: tl.constexpr):
174
+ b = tl.program_id(0) + ebase
175
+ pos = b * BM
176
+ e = tl.arange(0, BE_)
177
+ end = tl.load(END + e, mask=e < E, other=2147483647)
178
+ cnt = tl.sum(((end <= pos) & (e < E)).to(tl.int32), 0)
179
+ tl.store(BE + b, tl.where(cnt < E, cnt, -1).to(tl.int32))
180
+
181
+
182
+ @triton.jit
183
+ def _alfill_k(PR, P_pad, BF: tl.constexpr):
184
+ f = tl.program_id(0) * BF + tl.arange(0, BF)
185
+ tl.store(PR + f, tl.full((BF,), -1, tl.int32), mask=f < P_pad)
186
+
187
+
188
+ @triton.jit
189
+ def _alslotp_k(IDS, START, PR, PO, P, E, e0, k, BP: tl.constexpr, BPB: tl.constexpr):
190
+ ii = tl.program_id(0) * BPB + tl.arange(0, BPB)
191
+ im = ii < P
192
+ loc = tl.load(IDS + ii, mask=im, other=-1).to(tl.int32) - e0
193
+ ok = im & (loc >= 0) & (loc < E)
194
+ j = tl.arange(0, BP)
195
+ jm = j < P
196
+ jl = tl.load(IDS + j, mask=jm, other=-1).to(tl.int32) - e0
197
+ jok = jm & (jl >= 0) & (jl < E)
198
+ same = (jl[None, :] == loc[:, None]) & (j[None, :] < ii[:, None]) & jok[None, :]
199
+ within = tl.sum(same.to(tl.int32), 1)
200
+ st = tl.load(START + loc, mask=ok, other=0)
201
+ slot = st + within
202
+ tl.store(PR + slot, (ii // k).to(tl.int32), mask=ok)
203
+ tl.store(PO + ii, tl.where(ok, slot, -1).to(tl.int64), mask=im)
204
+
205
+
206
+ def moe_align_fast(topk_ids, n_exp_local, e0, BM):
207
+ """Capacity-free exact dispatch in four small parallel kernels; same outputs as moe_align_torch, without the
208
+ one-SM O(PxE) dispatch kernel that dominates decode passes."""
209
+ R, k = topk_ids.shape
210
+ P = R * k
211
+ E = n_exp_local
212
+ nblk = min(E, P) + (P + BM - 1) // BM
213
+ P_pad = nblk * BM
214
+ dev = topk_ids.device
215
+ cnt = torch.empty(E, dtype=torch.int32, device=dev)
216
+ start = torch.empty(E, dtype=torch.int32, device=dev)
217
+ endp = torch.empty(E, dtype=torch.int32, device=dev)
218
+ pr = torch.empty(P_pad, dtype=torch.int32, device=dev)
219
+ be = torch.empty(nblk, dtype=torch.int32, device=dev)
220
+ po = torch.empty(P, dtype=torch.long, device=dev)
221
+ BP = max(16, triton.next_power_of_2(P))
222
+ BE_ = max(16, triton.next_power_of_2(E))
223
+ ids = topk_ids.reshape(-1).contiguous()
224
+ _alcnt_k[(E,)](ids, cnt, P, e0, k, BP=BP, num_warps=1)
225
+ _alpre_k[(1,)](cnt, start, endp, E, BM=BM, BE=BE_, num_warps=1)
226
+ if P <= 128:
227
+ _alslot_k[(1,)](ids, start, pr, po, P, E, e0, k, P_pad, BP=BP, BF=1024, num_warps=4)
228
+ else:
229
+ BPB = 16
230
+ _alfill_k[(triton.cdiv(P_pad, 1024),)](pr, P_pad, BF=1024, num_warps=4)
231
+ _alslotp_k[(triton.cdiv(P, BPB),)](ids, start, pr, po, P, E, e0, k, BP=BP, BPB=BPB, num_warps=4)
232
+ _alblk_k[(nblk,)](endp, be, E, 0, BM=BM, BE_=BE_, num_warps=1)
233
+ return pr, be, po
234
+
235
+
236
+ ALIGN_TRITON = False # single-program dispatch kernel
237
+ ALIGN_FAST = True # parallel four-kernel dispatch; exact, 9us inside decode CUDA graphs on H100 (vs ~50us)
238
+
239
+
240
+ def moe_align(topk_ids, n_exp_local, e0, BM):
241
+ R, k = topk_ids.shape
242
+ P = R * k
243
+ E = n_exp_local
244
+ nblk = min(E, P) + (P + BM - 1) // BM
245
+ if ALIGN_FAST and P <= 512 and E <= 512 and nblk <= 512:
246
+ return moe_align_fast(topk_ids, n_exp_local, e0, BM)
247
+ if ALIGN_TRITON and P <= 256 and E <= 512 and nblk <= 512:
248
+ dev = topk_ids.device
249
+ P_pad = nblk * BM
250
+ pr = torch.empty(P_pad, dtype=torch.int32, device=dev)
251
+ be = torch.empty(nblk, dtype=torch.int32, device=dev)
252
+ po = torch.empty(P, dtype=torch.long, device=dev)
253
+ _align_k[(1,)](topk_ids.reshape(-1).contiguous(), pr, be, po, P, E, e0, k, P_pad, nblk,
254
+ BP=max(16, triton.next_power_of_2(P)), BE_=max(16, triton.next_power_of_2(E)),
255
+ BB=max(16, triton.next_power_of_2(nblk)), BM=BM, BF_=1024, num_warps=8)
256
+ return pr, be, po
257
+ return moe_align_torch(topk_ids, n_exp_local, e0, BM)
258
+
259
+
260
+ def moe_align_torch(topk_ids, n_exp_local, e0, BM):
261
+ """Capacity-free exact dispatch, graph-safe (static shapes, no host sync).
262
+ topk_ids (R, k) global expert ids; this rank owns experts [e0, e0 + n_exp_local).
263
+ Returns pair_row (P_pad,) int32 activation row of each padded pair slot (-1 = padding),
264
+ blk_exp (P_pad/BM,) int32 local expert of each BM-block (-1 = empty),
265
+ pair_of (R*k,) long slot of each (row, k) pair, -1 if its expert is not local.
266
+ Every (row, expert) pair routed to a local expert gets a slot: nothing is dropped."""
267
+ R, k = topk_ids.shape
268
+ P = R * k
269
+ E = n_exp_local
270
+ dev = topk_ids.device
271
+ loc = topk_ids.reshape(-1).long() - e0
272
+ key = torch.where((loc >= 0) & (loc < E), loc, torch.full_like(loc, E))
273
+ ar = torch.arange(P, device=dev)
274
+ order = torch.argsort(key * P + ar)
275
+ sk = key[order]
276
+ cnt = torch.zeros(E + 1, dtype=torch.long, device=dev).scatter_add_(0, key, torch.ones_like(key))
277
+ first = torch.cumsum(cnt, 0) - cnt
278
+ pad = (cnt[:E] + BM - 1) // BM * BM
279
+ endp = torch.cumsum(pad, 0)
280
+ start = endp - pad
281
+ nblk = min(E, P) + (P + BM - 1) // BM
282
+ P_pad = nblk * BM
283
+ skc = sk.clamp(max=E - 1)
284
+ pos = torch.where(sk < E, start[skc] + (ar - first[sk]), torch.full_like(sk, P_pad))
285
+ pair_row = torch.full((P_pad + 1,), -1, dtype=torch.int32, device=dev)
286
+ pair_row.scatter_(0, pos, (order // k).to(torch.int32))
287
+ pair_row = pair_row[:P_pad].contiguous()
288
+ pair_of = torch.empty(P, dtype=torch.long, device=dev)
289
+ pair_of.scatter_(0, order, torch.where(pos < P_pad, pos, torch.full_like(pos, -1)))
290
+ be = torch.searchsorted(endp, torch.arange(nblk, device=dev) * BM, right=True)
291
+ blk_exp = torch.where(be < E, be, torch.full_like(be, -1)).to(torch.int32)
292
+ return pair_row, blk_exp, pair_of
293
+
294
+
295
+ def moe_fp4_gemm(a, wp, ws, pair_row, blk_exp, BM, out_dtype=torch.bfloat16, BN=64, BK=128):
296
+ """a (R, K) bf16; wp (E, N, K/2) uint8; ws (E, N, K/32) uint8 -> C (P_pad, N)."""
297
+ P = pair_row.shape[0]
298
+ E, N, K2 = wp.shape
299
+ K = 2 * K2
300
+ assert K % BK == 0
301
+ c = torch.empty(P, N, dtype=out_dtype, device=a.device)
302
+ grid = (P // BM, triton.cdiv(N, BN))
303
+ _moe_fp4_k[grid](a, wp, ws, c, pair_row, blk_exp, P, N, K, a.stride(0), wp.stride(0), wp.stride(1),
304
+ ws.stride(0), ws.stride(1), c.stride(0), BM=BM, BN=BN, BK=BK, num_warps=4)
305
+ return c
306
+
307
+
308
+ @triton.jit
309
+ def _fp8blk_k(X, W, S, Y, M, N, K, sx, sw, ss, sy, nkb,
310
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
311
+ """y = x @ (w8 * s)^T with s per (QN rows x BK cols) block: each BK slice's fp32 partial is scaled exactly."""
312
+ pm = tl.program_id(0)
313
+ pn = tl.program_id(1)
314
+ m = pm * BM + tl.arange(0, BM)
315
+ n = pn * BN + tl.arange(0, BN)
316
+ k = tl.arange(0, BK)
317
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
318
+ for kb in range(0, nkb):
319
+ kk = kb * BK + k
320
+ x = tl.load(X + m[:, None] * sx + kk[None, :], mask=(m[:, None] < M) & (kk[None, :] < K), other=0.0)
321
+ w = tl.load(W + n[:, None] * sw + kk[None, :], mask=(n[:, None] < N) & (kk[None, :] < K), other=0.0)
322
+ part = tl.dot(x.to(tl.bfloat16), tl.trans(w.to(tl.bfloat16)))
323
+ s = tl.load(S + (n // QN) * ss + kb, mask=n < N, other=0.0)
324
+ acc += part * s[None, :]
325
+ tl.store(Y + m[:, None] * sy + n[None, :], acc.to(Y.dtype.element_ty), mask=(m[:, None] < M) & (n[None, :] < N))
326
+
327
+
328
+ @triton.jit
329
+ def _fp8blke_k(X, W, S, Y, M, N, K, sx, sw, ss, sy, nkb,
330
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
331
+ """_fp8blk_k specialised for K % BK == 0 and N % BN == 0: unmasked contiguous weight loads vectorise."""
332
+ pm = tl.program_id(0)
333
+ pn = tl.program_id(1)
334
+ m = pm * BM + tl.arange(0, BM)
335
+ n = pn * BN + tl.arange(0, BN)
336
+ k = tl.arange(0, BK)
337
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
338
+ vm = m < M
339
+ for kb in range(0, nkb):
340
+ kk = kb * BK + k
341
+ x = tl.load(X + m[:, None] * sx + kk[None, :], mask=vm[:, None], other=0.0)
342
+ w = tl.load(W + n[:, None] * sw + kk[None, :])
343
+ part = tl.dot(x.to(tl.bfloat16), tl.trans(w.to(tl.bfloat16)))
344
+ sc = tl.load(S + (n // QN) * ss + kb)
345
+ acc += part * sc[None, :]
346
+ tl.store(Y + m[:, None] * sy + n[None, :], acc.to(Y.dtype.element_ty), mask=vm[:, None])
347
+
348
+
349
+ def fp8blke_linear(x, w8, s, qn, qk, out_dtype=None, BN=32, nw=4):
350
+ sh = x.shape
351
+ x2 = x.reshape(-1, sh[-1])
352
+ if x2.stride(-1) != 1:
353
+ x2 = x2.contiguous()
354
+ M, K = x2.shape
355
+ N = w8.shape[0]
356
+ assert K % qk == 0 and N % BN == 0
357
+ y = torch.empty(M, N, dtype=out_dtype or x.dtype, device=x.device)
358
+ BM = 16 if M <= 16 else (32 if M <= 64 else 64)
359
+ _fp8blke_k[(triton.cdiv(M, BM), triton.cdiv(N, BN))](x2, w8, s, y, M, N, K, x2.stride(0), w8.stride(0),
360
+ s.stride(0), y.stride(0), triton.cdiv(K, qk),
361
+ BM=BM, BN=BN, BK=qk, QN=qn, num_warps=nw)
362
+ return y.reshape(*sh[:-1], N)
363
+
364
+
365
+ @triton.jit
366
+ def _fp8blk_sk_k(X, W, S, P, M, N, K, sx, sw, ss, spz, spm, nkb, nkc,
367
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
368
+ """split-K partials for _fp8blk_k; each program covers nkc whole quant blocks."""
369
+ pm = tl.program_id(0)
370
+ pn = tl.program_id(1)
371
+ pz = tl.program_id(2)
372
+ m = pm * BM + tl.arange(0, BM)
373
+ n = pn * BN + tl.arange(0, BN)
374
+ k = tl.arange(0, BK)
375
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
376
+ vm = m < M
377
+ nm = n < N
378
+ kb0 = pz * nkc
379
+ kb1 = tl.minimum(kb0 + nkc, nkb)
380
+ for kb in range(kb0, kb1):
381
+ kk = kb * BK + k
382
+ x = tl.load(X + m[:, None] * sx + kk[None, :], mask=vm[:, None] & (kk[None, :] < K), other=0.0)
383
+ w = tl.load(W + n[:, None] * sw + kk[None, :], mask=nm[:, None] & (kk[None, :] < K), other=0.0)
384
+ part = tl.dot(x.to(tl.bfloat16), tl.trans(w.to(tl.bfloat16)))
385
+ sc = tl.load(S + (n // QN) * ss + kb, mask=nm, other=0.0)
386
+ acc += part * sc[None, :]
387
+ tl.store(P + pz * spz + m[:, None] * spm + n[None, :], acc, mask=vm[:, None] & nm[None, :])
388
+
389
+
390
+ @triton.jit
391
+ def _fp8skred_k(P, Y, total, N, spz, spm, sy, SK: tl.constexpr, BLK: tl.constexpr):
392
+ pid = tl.program_id(0)
393
+ o = pid * BLK + tl.arange(0, BLK)
394
+ msk = o < total
395
+ m = o // N
396
+ n = o - m * N
397
+ acc = tl.zeros((BLK,), dtype=tl.float32)
398
+ for z in tl.static_range(SK):
399
+ acc += tl.load(P + z * spz + m * spm + n, mask=msk, other=0.0)
400
+ tl.store(Y + m * sy + n, acc.to(Y.dtype.element_ty), mask=msk)
401
+
402
+
403
+ @triton.jit
404
+ def _fp8skred_k(P, Y, M, N, spz, spm, sy, SK: tl.constexpr, BN: tl.constexpr):
405
+ r = tl.program_id(0)
406
+ n = tl.program_id(1) * BN + tl.arange(0, BN)
407
+ nm = n < N
408
+ acc = tl.zeros((BN,), dtype=tl.float32)
409
+ for z in tl.static_range(SK):
410
+ acc += tl.load(P + z * spz + r * spm + n, mask=nm, other=0.0)
411
+ tl.store(Y + r * sy + n, acc.to(Y.dtype.element_ty), mask=nm)
412
+
413
+
414
+ def fp8blk_sk_linear(x, w8, s, qn, qk, out_dtype=None, BN=64, nw=4, SK=4):
415
+ """split-K block-fp8 linear for small decode row counts: more CTAs and a much shorter serial K loop."""
416
+ sh = x.shape
417
+ x2 = x.reshape(-1, sh[-1])
418
+ if x2.stride(-1) != 1:
419
+ x2 = x2.contiguous()
420
+ M, K = x2.shape
421
+ N = w8.shape[0]
422
+ nkb = triton.cdiv(K, qk)
423
+ nkc = triton.cdiv(nkb, SK)
424
+ BM = 16 if M <= 16 else (32 if M <= 64 else 64)
425
+ part = torch.empty(SK, BM * triton.cdiv(M, BM), N, dtype=torch.float32, device=x.device)
426
+ _fp8blk_sk_k[(triton.cdiv(M, BM), triton.cdiv(N, BN), SK)](x2, w8, s, part, M, N, K, x2.stride(0),
427
+ w8.stride(0), s.stride(0), part.stride(0), part.stride(1), nkb, nkc,
428
+ BM=BM, BN=BN, BK=qk, QN=qn, num_warps=nw)
429
+ mp = BM * triton.cdiv(M, BM)
430
+ y = torch.empty(M, N, dtype=out_dtype or x.dtype, device=x.device)
431
+ _fp8skred_k[(M, triton.cdiv(N, 128))](part, y, M, N, part.stride(0), part.stride(1), y.stride(0), SK=SK, BN=128, num_warps=4)
432
+ return y.reshape(*sh[:-1], N)
433
+
434
+
435
+ def fp8blk_linear(x, w8, s, qn, qk, out_dtype=None):
436
+ sh = x.shape
437
+ x2 = x.reshape(-1, sh[-1])
438
+ if x2.stride(-1) != 1:
439
+ x2 = x2.contiguous()
440
+ M, K = x2.shape
441
+ N = w8.shape[0]
442
+ if not x2.is_cuda: # torch reference: exact dequantised matrix, fp32 accumulation
443
+ y = F.linear(x2.float(), fp8blk_dequant(w8, s, torch.float32, qn, qk)).to(out_dtype or x.dtype)
444
+ return y.reshape(*sh[:-1], N)
445
+ if M <= 64 and K // qk >= 16:
446
+ sk = 8 if K // qk >= 32 else 4 # decode tiles are latency-bound; long-K projections want more split-K parallelism
447
+ bn = 32 if M <= 16 else 64 # wider trees need larger N tiles; single chains want more split-K CTAs
448
+ return fp8blk_sk_linear(x2, w8, s, qn, qk, out_dtype=out_dtype, BN=bn, nw=4, SK=sk).reshape(*sh[:-1], N)
449
+ y = torch.empty(M, N, dtype=out_dtype or x.dtype, device=x.device)
450
+ BM = 16 if M <= 16 else (32 if M <= 64 else 64)
451
+ BN = 64 if M <= 64 else 128
452
+ _fp8blk_k[(triton.cdiv(M, BM), triton.cdiv(N, BN))](x2, w8, s, y, M, N, K, x2.stride(0), w8.stride(0),
453
+ s.stride(0), y.stride(0), triton.cdiv(K, qk),
454
+ BM=BM, BN=BN, BK=qk, QN=qn, num_warps=4)
455
+ return y.reshape(*sh[:-1], N)
456
+
457
+
458
+ @triton.jit
459
+ def _moe_fp8_k(A, W, S, C, PAIR_ROW, BLK_EXP, N, K, sa, swe, swn, sse, ssn, sc, nkb,
460
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
461
+ """Grouped block-fp8 GEMM over expert-sorted padded pairs (see moe_align)."""
462
+ blk = tl.program_id(0)
463
+ nb = tl.program_id(1)
464
+ e = tl.load(BLK_EXP + blk)
465
+ if e < 0:
466
+ return
467
+ rows = blk * BM + tl.arange(0, BM)
468
+ arow = tl.load(PAIR_ROW + rows)
469
+ valid = arow >= 0
470
+ arow = tl.where(valid, arow, 0)
471
+ n = nb * BN + tl.arange(0, BN)
472
+ nm = n < N
473
+ k = tl.arange(0, BK)
474
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
475
+ for kb in range(0, nkb):
476
+ kk = kb * BK + k
477
+ a = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None] & (kk[None, :] < K), other=0.0)
478
+ w = tl.load(W + e * swe + n[:, None] * swn + kk[None, :], mask=nm[:, None] & (kk[None, :] < K), other=0.0)
479
+ part = tl.dot(a.to(tl.bfloat16), tl.trans(w.to(tl.bfloat16)))
480
+ s = tl.load(S + e * sse + (n // QN) * ssn + kb, mask=nm, other=0.0)
481
+ acc += part * s[None, :]
482
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None] & nm[None, :])
483
+
484
+
485
+ @triton.jit
486
+ def _moe_bf16_k(A, W, C, PAIR_ROW, BLK_EXP, N, K, sa, swe, swn, sc,
487
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):
488
+ """Grouped bf16 GEMM over expert-sorted padded pairs (see moe_align): each routed expert's weights are read
489
+ once per pass however many tree rows chose it."""
490
+ blk = tl.program_id(0)
491
+ nb = tl.program_id(1)
492
+ e = tl.load(BLK_EXP + blk).to(tl.int64)
493
+ if e < 0:
494
+ return
495
+ rows = blk * BM + tl.arange(0, BM)
496
+ arow = tl.load(PAIR_ROW + rows).to(tl.int64)
497
+ valid = arow >= 0
498
+ arow = tl.where(valid, arow, 0)
499
+ n = nb * BN + tl.arange(0, BN)
500
+ nm = n < N
501
+ k = tl.arange(0, BK)
502
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
503
+ for k0 in range(0, K, BK):
504
+ kk = k0 + k
505
+ a = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None] & (kk[None, :] < K), other=0.0)
506
+ w = tl.load(W + e * swe + n[:, None] * swn + kk[None, :], mask=nm[:, None] & (kk[None, :] < K), other=0.0)
507
+ acc += tl.dot(a.to(tl.bfloat16), tl.trans(w.to(tl.bfloat16)))
508
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None] & nm[None, :])
509
+
510
+
511
+ def moe_bf16_gemm(a, w, pair_row, blk_exp, BM, out_dtype=torch.bfloat16, BN=64, BK=64):
512
+ """a (R, K) bf16; w (E, N, K) bf16 -> C (P_pad, N); rows of padding slots are left unwritten."""
513
+ P = pair_row.shape[0]
514
+ E, N, K = w.shape
515
+ c = torch.empty(P, N, dtype=out_dtype, device=a.device)
516
+ _moe_bf16_k[(P // BM, triton.cdiv(N, BN))](a, w, c, pair_row, blk_exp, N, K, a.stride(0), w.stride(0),
517
+ w.stride(1), c.stride(0), BM=BM, BN=BN, BK=BK, num_warps=4)
518
+ return c
519
+
520
+
521
+ @triton.jit
522
+ def _moe_fp8v1_k(A, W, S, C, PAIR_ROW, BLK_EXP, N, K, sa, swe, swn, sse, ssn, sc, nkb,
523
+ BM: tl.constexpr, RV: tl.constexpr, BN: tl.constexpr, QK: tl.constexpr, QN: tl.constexpr):
524
+ """Small-row grouped block-fp8 CUDA-core GEMM. The tensor-core kernel always pays a 16-row padded tile;
525
+ decode trees and small batches have only a few rows per expert, so computing exactly RV rows is much cheaper
526
+ while the many output tiles keep every SM busy. Correct for any occupancy: dispatch blocks hold <= BM rows."""
527
+ blk = tl.program_id(0)
528
+ nb = tl.program_id(1)
529
+ e = tl.load(BLK_EXP + blk).to(tl.int64)
530
+ if e < 0:
531
+ return
532
+ rows = blk * BM + tl.arange(0, RV)
533
+ arow = tl.load(PAIR_ROW + rows).to(tl.int64)
534
+ valid = arow >= 0
535
+ arow = tl.where(valid, arow, 0)
536
+ n = nb * BN + tl.arange(0, BN)
537
+ nm = n < N
538
+ k = tl.arange(0, QK)
539
+ acc = tl.zeros((RV, BN), dtype=tl.float32)
540
+ for kb in range(0, nkb):
541
+ kk = kb * QK + k
542
+ av = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None] & (kk[None, :] < K),
543
+ other=0.0).to(tl.float32)
544
+ wv = tl.load(W + e * swe + n[:, None] * swn + kk[None, :], mask=nm[:, None] & (kk[None, :] < K),
545
+ other=0.0).to(tl.float32)
546
+ sv = tl.load(S + e * sse + (n // QN) * ssn + kb, mask=nm, other=0.0)
547
+ acc += tl.sum(av[:, None, :] * wv[None, :, :], 2) * sv[None, :]
548
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None] & nm[None, :])
549
+
550
+
551
+ @triton.jit
552
+ def _moe_fp8e_k(A, W, S, C, PAIR_ROW, BLK_EXP, N, K, sa, swe, swn, sse, ssn, sc, nkb,
553
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
554
+ """Grouped block-fp8 tensor-core GEMM specialised for dimensions divisible by the tile/quantum: unmasked
555
+ contiguous weight loads vectorise to whole cache lines, unlike the generic masked kernel."""
556
+ blk = tl.program_id(0)
557
+ nb = tl.program_id(1)
558
+ e = tl.load(BLK_EXP + blk)
559
+ if e < 0:
560
+ return
561
+ rows = blk * BM + tl.arange(0, BM)
562
+ arow = tl.load(PAIR_ROW + rows).to(tl.int64)
563
+ valid = arow >= 0
564
+ arow = tl.where(valid, arow, 0)
565
+ n = nb * BN + tl.arange(0, BN)
566
+ k = tl.arange(0, BK)
567
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
568
+ for kb in range(0, nkb):
569
+ kk = kb * BK + k
570
+ a = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None], other=0.0)
571
+ w = tl.load(W + e * swe + n[:, None] * swn + kk[None, :])
572
+ part = tl.dot(a.to(tl.bfloat16), tl.trans(w.to(tl.bfloat16)))
573
+ sv = tl.load(S + e * sse + (n // QN) * ssn + kb)
574
+ acc += part * sv[None, :]
575
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None])
576
+
577
+
578
+ def moe_fp8e_gemm(a, w8, s, qn, qk, pair_row, blk_exp, BM, out_dtype=torch.bfloat16, BN=64, nw=4):
579
+ """moe_fp8_gemm fast path for GLM-style multiples (K % qk == 0, N % BN == 0)."""
580
+ P = pair_row.shape[0]
581
+ E, N, K = w8.shape
582
+ assert K % qk == 0 and N % BN == 0 and N % qn == 0
583
+ c = torch.empty(P, N, dtype=out_dtype, device=a.device)
584
+ _moe_fp8e_k[(P // BM, triton.cdiv(N, BN))](a, w8, s, c, pair_row, blk_exp, N, K, a.stride(0), w8.stride(0),
585
+ w8.stride(1), s.stride(0), s.stride(1), c.stride(0),
586
+ triton.cdiv(K, qk), BM=BM, BN=BN, BK=qk, QN=qn, num_warps=nw)
587
+ return c
588
+
589
+
590
+ @triton.jit
591
+ def _moe_fp8glu_k(A, W, S, C, PAIR_ROW, BLK_EXP, I, K, sa, swe, swn, sse, ssn, sc, nkb,
592
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
593
+ """grouped block-fp8 gate/up GEMM with the silu GLU epilogue: one activation tile reads both matching gate/up
594
+ weight tiles and never materialises the 2I projection."""
595
+ blk = tl.program_id(0)
596
+ nb = tl.program_id(1)
597
+ e = tl.load(BLK_EXP + blk)
598
+ if e < 0:
599
+ return
600
+ rows = blk * BM + tl.arange(0, BM)
601
+ arow = tl.load(PAIR_ROW + rows)
602
+ valid = arow >= 0
603
+ arow = tl.where(valid, arow, 0)
604
+ n = nb * BN + tl.arange(0, BN)
605
+ k = tl.arange(0, BK)
606
+ ag = tl.zeros((BM, BN), dtype=tl.float32)
607
+ au = tl.zeros((BM, BN), dtype=tl.float32)
608
+ for kb in range(0, nkb):
609
+ kk = kb * BK + k
610
+ a = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None], other=0.0)
611
+ wg = tl.load(W + e * swe + n[:, None] * swn + kk[None, :])
612
+ wu = tl.load(W + e * swe + (I + n[:, None]) * swn + kk[None, :])
613
+ sg = tl.load(S + e * sse + (n // QN) * ssn + kb)
614
+ su = tl.load(S + e * sse + ((I + n) // QN) * ssn + kb)
615
+ aa = a.to(tl.bfloat16)
616
+ ag += tl.dot(aa, tl.trans(wg.to(tl.bfloat16))) * sg[None, :]
617
+ au += tl.dot(aa, tl.trans(wu.to(tl.bfloat16))) * su[None, :]
618
+ g = ag.to(tl.bfloat16).to(tl.float32)
619
+ u = au.to(tl.bfloat16).to(tl.float32)
620
+ y = (g * tl.sigmoid(g) * u).to(tl.bfloat16)
621
+ tl.store(C + rows[:, None] * sc + n[None, :], y, mask=valid[:, None])
622
+
623
+
624
+ def moe_fp8glu_gemm(a, w8, s, qn, qk, pair_row, blk_exp, BM, inter, nw=4, BN=64):
625
+ """moe_fp8_gemm specialised for [gate|up] + silu, returning the activation directly (P_pad, inter) bf16."""
626
+ P = pair_row.shape[0]
627
+ E, N, K = w8.shape
628
+ assert N == 2 * inter and inter % qn == 0 and inter % 64 == 0 and K % qk == 0
629
+ c = torch.empty(P, inter, dtype=torch.bfloat16, device=a.device)
630
+ _moe_fp8glu_k[(P // BM, triton.cdiv(inter, BN))](a, w8, s, c, pair_row, blk_exp, inter, K, a.stride(0),
631
+ w8.stride(0), w8.stride(1), s.stride(0), s.stride(1), c.stride(0), triton.cdiv(K, qk),
632
+ BM=BM, BN=BN, BK=qk, QN=qn, num_warps=nw)
633
+ return c
634
+
635
+
636
+ @triton.jit
637
+ def _moe_fp8a8_k(A, XS, W, S, C, PAIR_ROW, BLK_EXP, N, K, sa, swe, swn, sse, ssn, sc, nkb,
638
+ BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, QN: tl.constexpr):
639
+ """Grouped block-fp8 GEMM with dynamically fp8-quantised activations: fp8 x fp8 tensor-core dots, then the
640
+ exact outer scale product (per-row activation scale x per-output-block weight scale) on each BK partial."""
641
+ blk = tl.program_id(0)
642
+ nb = tl.program_id(1)
643
+ e = tl.load(BLK_EXP + blk)
644
+ if e < 0:
645
+ return
646
+ rows = blk * BM + tl.arange(0, BM)
647
+ arow = tl.load(PAIR_ROW + rows).to(tl.int64)
648
+ valid = arow >= 0
649
+ arow = tl.where(valid, arow, 0)
650
+ sx = tl.load(XS + arow, mask=valid, other=0.0)
651
+ n = nb * BN + tl.arange(0, BN)
652
+ nm = n < N
653
+ k = tl.arange(0, BK)
654
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
655
+ for kb in range(0, nkb):
656
+ kk = kb * BK + k
657
+ a = tl.load(A + arow[:, None] * sa + kk[None, :], mask=valid[:, None] & (kk[None, :] < K), other=0.0)
658
+ w = tl.load(W + e * swe + n[:, None] * swn + kk[None, :], mask=nm[:, None] & (kk[None, :] < K), other=0.0)
659
+ part = tl.dot(a, tl.trans(w))
660
+ sv = tl.load(S + e * sse + (n // QN) * ssn + kb, mask=nm, other=0.0)
661
+ acc += part * (sx[:, None] * sv[None, :])
662
+ tl.store(C + rows[:, None] * sc + n[None, :], acc.to(C.dtype.element_ty), mask=valid[:, None] & nm[None, :])
663
+
664
+
665
+ def fp8act(x):
666
+ """dynamic per-row e4m3 activation quantisation, x (R,K) -> (x8, scale); y ~= (x8 * scale) @ w."""
667
+ xf = x.float()
668
+ sc = (xf.abs().amax(-1) / 448.0).clamp_min(1e-12)
669
+ return (xf / sc[:, None]).clamp_(-448.0, 448.0).to(torch.float8_e4m3fn), sc
670
+
671
+
672
+ def moe_fp8a8_gemm(a, w8, s, qn, qk, pair_row, blk_exp, BM, out_dtype=torch.bfloat16, BN=64):
673
+ """moe_fp8_gemm with dynamic fp8 activations (the checkpoint's published activation_scheme)."""
674
+ a8, asc = fp8act(a)
675
+ P = pair_row.shape[0]
676
+ E, N, K = w8.shape
677
+ c = torch.empty(P, N, dtype=out_dtype, device=a.device)
678
+ _moe_fp8a8_k[(P // BM, triton.cdiv(N, BN))](a8, asc, w8, s, c, pair_row, blk_exp, N, K, a8.stride(0),
679
+ w8.stride(0), w8.stride(1), s.stride(0), s.stride(1), c.stride(0),
680
+ triton.cdiv(K, qk), BM=BM, BN=BN, BK=qk, QN=qn, num_warps=4)
681
+ return c
682
+
683
+
684
+ def moe_fp8_gemm(a, w8, s, qn, qk, pair_row, blk_exp, BM, out_dtype=torch.bfloat16, BN=64, gemv1=False):
685
+ """a (R, K) bf16; w8 (E, N, K) e4m3; s (E, N/qn, K/qk) fp32 -> C (P_pad, N)."""
686
+ P = pair_row.shape[0]
687
+ E, N, K = w8.shape
688
+ if not gemv1 and K % qk == 0 and N % qn == 0 and N % BN == 0:
689
+ return moe_fp8e_gemm(a, w8, s, qn, qk, pair_row, blk_exp, BM, out_dtype=out_dtype, BN=BN)
690
+ c = torch.empty(P, N, dtype=out_dtype, device=a.device)
691
+ if gemv1:
692
+ BNV = 8
693
+ RV = 1 if gemv1 is True else int(gemv1)
694
+ _moe_fp8v1_k[(P // BM, triton.cdiv(N, BNV))](a, w8, s, c, pair_row, blk_exp, N, K, a.stride(0),
695
+ w8.stride(0), w8.stride(1), s.stride(0), s.stride(1),
696
+ c.stride(0), triton.cdiv(K, qk), BM=BM, RV=RV, BN=BNV,
697
+ QK=qk, QN=qn, num_warps=4)
698
+ return c
699
+ _moe_fp8_k[(P // BM, triton.cdiv(N, BN))](a, w8, s, c, pair_row, blk_exp, N, K, a.stride(0), w8.stride(0),
700
+ w8.stride(1), s.stride(0), s.stride(1), c.stride(0),
701
+ triton.cdiv(K, qk), BM=BM, BN=BN, BK=qk, QN=qn, num_warps=4)
702
+ return c
703
+
704
+
705
+ @triton.jit
706
+ def _router8_k(X, W, B, IDX, OUT, K, sx, sw, E: tl.constexpr, BK: tl.constexpr, KTOP: tl.constexpr, RSCALE: tl.constexpr):
707
+ """fused sigmoid router for E<=256, top-k<=8: bf16 tensor-core x@w^T, fp32 logits/scores, correction-bias
708
+ selection, renormalised routed weights. One program per row."""
709
+ r = tl.program_id(0)
710
+ e = tl.arange(0, E)
711
+ k = tl.arange(0, BK)
712
+ acc = tl.zeros((E,), dtype=tl.float32)
713
+ for k0 in range(0, K, BK):
714
+ xv = tl.load(X + r * sx + k0 + k, mask=(k0 + k) < K, other=0.0).to(tl.bfloat16)
715
+ wv = tl.load(W + e[:, None] * sw + (k0 + k)[None, :], mask=((k0 + k)[None, :] < K), other=0.0).to(tl.bfloat16)
716
+ # E x BK times BK x 1 is below tensor-core tile width; use an explicit fp32 sum (the router is weight-bandwidth bound)
717
+ acc += tl.sum(xv[None, :] * wv, 1)
718
+ sc = tl.sigmoid(acc)
719
+ ch = sc + tl.load(B + e)
720
+ live = e < E
721
+ wsum = 0.0
722
+ for j in tl.static_range(KTOP):
723
+ v = tl.where(live, ch, -float("inf"))
724
+ mx = tl.max(v, 0)
725
+ ii = tl.sum(tl.where(v == mx, e, 0), 0)
726
+ ws = tl.sum(tl.where(e == ii, sc, 0.0), 0)
727
+ tl.store(IDX + r * KTOP + j, ii.to(tl.int64))
728
+ tl.store(OUT + r * KTOP + j, ws)
729
+ wsum += ws
730
+ live = live & (e != ii)
731
+ for j in tl.static_range(KTOP):
732
+ ws = tl.load(OUT + r * KTOP + j)
733
+ tl.store(OUT + r * KTOP + j, ws / (wsum + 1e-20) * RSCALE)
734
+
735
+
736
+ def router8(x, wr, bias, k, rscale):
737
+ """fused GLM-style sigmoid router (n_group=1): returns idx (R,k) long and renormalised weights fp32."""
738
+ R, K = x.shape
739
+ E = wr.shape[0]
740
+ idx = torch.empty(R, k, dtype=torch.long, device=x.device)
741
+ out = torch.empty(R, k, dtype=torch.float32, device=x.device)
742
+ _router8_k[(R,)](x, wr, bias, idx, out, K, x.stride(0), wr.stride(0), E=triton.next_power_of_2(E),
743
+ BK=128, KTOP=k, RSCALE=rscale, num_warps=8)
744
+ return idx, out
745
+
746
+
747
+ @triton.jit
748
+ def _moecomb_k(Y, PO, W, OUT, D, sy, k, BD: tl.constexpr, KTOP: tl.constexpr):
749
+ r = tl.program_id(0)
750
+ nb = tl.program_id(1)
751
+ n = nb * BD + tl.arange(0, BD)
752
+ nm = n < D
753
+ acc = tl.zeros((BD,), dtype=tl.float32)
754
+ for j in tl.static_range(KTOP):
755
+ slot = tl.load(PO + r * KTOP + j)
756
+ wt = tl.load(W + r * KTOP + j).to(tl.float32)
757
+ v = tl.load(Y + slot * sy + n, mask=(slot >= 0) & nm, other=0.0)
758
+ acc += wt * v
759
+ tl.store(OUT + r * D + n, acc, mask=nm)
760
+
761
+
762
+ def moe_combine(y, po, w, R, k):
763
+ """fused capacity-free expert gather + routed-weight sum: out[r] = sum_j w[r,j] y[po[r,j]]."""
764
+ D = y.shape[1]
765
+ out = torch.empty(R, D, dtype=torch.float32, device=y.device)
766
+ BD = 512 if D >= 512 else triton.next_power_of_2(D)
767
+ _moecomb_k[(R, triton.cdiv(D, BD))](y, po, w.reshape(-1).contiguous(), out, D, y.stride(0), k,
768
+ BD=BD, KTOP=k, num_warps=4)
769
+ return out
770
+
771
+
772
+ class QWeight:
773
+ """A quantised (N, K) weight for blocks.LINEAR (core hook: w.lin(x)). segs: list of ("bf16", t) or
774
+ ("fp8blk", w8, s, qn, qk); several segments = row-concatenated (fused projections)."""
775
+
776
+ def __init__(self, segs):
777
+ self.segs = segs
778
+ self.shape = torch.Size([sum(g[1].shape[0] for g in segs), segs[0][1].shape[1]])
779
+
780
+ def lin(self, x):
781
+ outs = [_lin(x, g) for g in self.segs]
782
+ return outs[0] if len(outs) == 1 else torch.cat(outs, -1)
783
+
784
+ def nbytes(self):
785
+ return sum(t.numel() * t.element_size() for g in self.segs for t in g[1:] if isinstance(t, torch.Tensor))
786
+
787
+ def numel(self):
788
+ return self.nbytes()
789
+
790
+ def element_size(self):
791
+ return 1
792
+
793
+ def dequant(self, dtype=torch.float32):
794
+ return torch.cat([g[1].to(dtype) if g[0] == "bf16" else
795
+ (g[1].float() * g[2].float().repeat_interleave(g[3], 0)[:g[1].shape[0]]
796
+ .repeat_interleave(g[4], 1)[:, :g[1].shape[1]]).to(dtype) for g in self.segs], 0)
797
+
798
+
799
+ def pad_fp8_rows(w8, s, qn):
800
+ """zero-pad a block-fp8 weight to a whole row tile so row-concatenation preserves the scale grid."""
801
+ N, K = w8.shape
802
+ pad = (-N) % qn
803
+ if not pad:
804
+ return w8
805
+ return torch.cat([w8, torch.zeros(pad, K, dtype=w8.dtype, device=w8.device)], 0).contiguous()
806
+
807
+
808
+ def cat_rows_fp8_padded(ws):
809
+ """row-concatenate single-segment block-fp8 QWeights, zero-padding each to its quantum tile; returns
810
+ (fused QWeight, unpadded row counts), or None if any input is another format."""
811
+ parts = []
812
+ for w in ws:
813
+ if not isinstance(w, QWeight) or len(w.segs) != 1 or w.segs[0][0] != "fp8blk":
814
+ return None
815
+ parts.append(w.segs[0])
816
+ qn, qk = parts[0][3], parts[0][4]
817
+ if any(p[3:] != (qn, qk) for p in parts):
818
+ return None
819
+ ws2 = [pad_fp8_rows(p[1], p[2], qn) for p in parts]
820
+ ss2 = [p[2] for p in parts]
821
+ return QWeight([("fp8blk", torch.cat(ws2, 0).contiguous(), torch.cat(ss2, 0).contiguous(), qn, qk)]), [p[1].shape[0] for p in parts]
822
+
823
+
824
+ def cat_rows(ws):
825
+ """row-concatenate weights (tensors and/or QWeights) into one fused weight."""
826
+ if all(isinstance(w, torch.Tensor) for w in ws):
827
+ return torch.cat(ws, 0).contiguous()
828
+ segs = []
829
+ for w in ws:
830
+ segs += w.segs if isinstance(w, QWeight) else [("bf16", w)]
831
+ # merge runs of block-fp8 segments with the same tile whose row counts are tile multiples: one GEMM instead of
832
+ # several + a concat (the scale grid concatenates exactly)
833
+ out = []
834
+ for g in segs:
835
+ p = out[-1] if out else None
836
+ if (p is not None and p[0] == "fp8blk" and g[0] == "fp8blk" and p[3:] == g[3:]
837
+ and p[1].shape[0] % p[3] == 0 and p[1].shape[1] == g[1].shape[1]):
838
+ out[-1] = ("fp8blk", torch.cat([p[1], g[1]], 0).contiguous(), torch.cat([p[2], g[2]], 0).contiguous(),
839
+ p[3], p[4])
840
+ else:
841
+ out.append(g)
842
+ return QWeight(out)
843
+
844
+
845
+ def _lin(x, g):
846
+ if g[0] == "bf16":
847
+ return F.linear(x, g[1])
848
+ if g[0] == "fp8blk":
849
+ return fp8blk_linear(x, g[1], g[2], g[3], g[4])
850
+ raise NotImplementedError(g[0])