binade 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,995 @@
1
+ """R4 and Rice kernels for MLX's CUDA backend (mx.fast.cuda_kernel), the counterparts of
2
+ kernel.py and rice_kernel.py.
3
+
4
+ The matvec mirrors MLX 0.32.2's CUDA gemv (mlx/backend/cuda/gemms/gemv.cu, gemv_impl): one
5
+ warp per output row; thread t owns n consecutive weights of every block of 32 n along K,
6
+ accumulating float products in K order; then cooperative_groups::reduce over the warp,
7
+ called here too, so the reduction is the same code. n is 4 when K % 128 == 0, 2 when
8
+ K % 64 == 0, else 1, as MLX picks it (for aligned pointers). An R4 tile (128 weights) holds
9
+ whole blocks for every n, so a block's escapes are found with one warp prefix sum and a
10
+ running pointer per row. gemv and the expert gather (gather_mv) share gemv_impl, so one
11
+ kernel serves both. Products of two BF16 values are exact in float, so fused or separate
12
+ multiply-adds give the same sums.
13
+ """
14
+
15
+ import mlx.core as mx
16
+
17
+ from ..format import TILE
18
+
19
+ HEADER = """
20
+ #include <cooperative_groups.h>
21
+ #include <cooperative_groups/reduce.h>
22
+ """
23
+
24
+
25
+ def available() -> bool:
26
+ """Whether MLX runs on its CUDA backend (then these kernels replace the Metal ones)."""
27
+ return hasattr(mx, "cuda") and mx.cuda.is_available()
28
+
29
+
30
+ def n_per_thread(K: int) -> int:
31
+ return 4 if K % 128 == 0 else 2 if K % 64 == 0 else 1
32
+
33
+
34
+ def _escapes(n: int) -> str:
35
+ """Replace code-15 exponents in e[] from esc[], advancing epos (whole warp takes part)."""
36
+ return f"""
37
+ if (f) {{
38
+ uint32_t cnt = 0;
39
+ for (int j = 0; j < {n}; j++) {{ cnt += (in && c[j] == 15u) ? 1u : 0u; }}
40
+ uint32_t incl = cnt;
41
+ for (int o = 1; o < 32; o <<= 1) {{ uint32_t v = __shfl_up_sync(0xffffffffu, incl, o); if (lane >= o) incl += v; }}
42
+ uint32_t q = epos + incl - cnt;
43
+ for (int j = 0; j < {n}; j++) {{ if (in && c[j] == 15u) {{ e[j] = esc[q]; q++; }} }}
44
+ epos += __shfl_sync(0xffffffffu, incl, 31);
45
+ }}"""
46
+
47
+
48
+ def source_matvec(n: int, gather: bool, split: bool = False) -> str:
49
+ """split (gather only): rows below SPLIT go to y [G, SPLIT], the rest to y2 [G, N - SPLIT]
50
+ (the gate and up halves of fused expert rows, without slicing afterwards)."""
51
+ rowsel = (
52
+ "uint32_t g = blockIdx.y; size_t row = size_t(ei[g]) * RS + R0 + size_t(r); const __nv_bfloat16* xv = x + size_t(xi[g]) * K; size_t yo = size_t(g) * N + r;"
53
+ if gather
54
+ else "size_t row = size_t(r); const __nv_bfloat16* xv = x; size_t yo = size_t(r);"
55
+ )
56
+ store = (
57
+ "if (lane == 0) { if (r < SPLIT) { y[size_t(g) * SPLIT + r] = static_cast<__nv_bfloat16>(sum); } else { y2[size_t(g) * (N - SPLIT) + (r - SPLIT)] = static_cast<__nv_bfloat16>(sum); } }"
58
+ if split
59
+ else "if (lane == 0) { y[yo] = static_cast<__nv_bfloat16>(sum); }"
60
+ )
61
+ return f"""
62
+ namespace cg = cooperative_groups;
63
+ auto warp = cg::tiled_partition<32>(cg::this_thread_block());
64
+ uint32_t lane = threadIdx.x % 32;
65
+ int r = int(blockIdx.x) * 8 + int(threadIdx.x / 32);
66
+ if (r >= N) {{ return; }}
67
+ {rowsel}
68
+ float sum = 0.0f;
69
+ uint32_t epos = row_esc[row];
70
+ for (int base = 0; base < K; base += {32 * n}) {{
71
+ int col = base + {n} * int(lane);
72
+ bool in = col < K;
73
+ int t = base >> 7;
74
+ int i = col & 127;
75
+ uint32_t f = flags[row * T + t];
76
+ uint32_t c[{n}]; uint32_t e[{n}]; uint32_t rw[{n}];
77
+ uint32_t g4 = in ? uint32_t(codes[(row * T + t) * 32 + (i >> 2)]) : 0u;
78
+ for (int j = 0; j < {n}; j++) {{
79
+ c[j] = (g4 >> (4u * uint32_t((i & 3) + j))) & 15u;
80
+ e[j] = tbl[c[j]];
81
+ rw[j] = in ? uint32_t(raw[row * K + col + j]) : 0u;
82
+ }}
83
+ {_escapes(n)}
84
+ if (in) {{
85
+ for (int j = 0; j < {n}; j++) {{
86
+ unsigned short u = (unsigned short)(((rw[j] & 0x80u) << 8) | (e[j] << 7) | (rw[j] & 0x7Fu));
87
+ __nv_bfloat16 w = __ushort_as_bfloat16(u);
88
+ sum += static_cast<float>(w) * static_cast<float>(xv[col + j]);
89
+ }}
90
+ }}
91
+ }}
92
+ sum = cg::reduce(warp, sum, cg::plus<float>());
93
+ {store}
94
+ """
95
+
96
+
97
+ _MV = {}
98
+
99
+
100
+ def _matvec_kernel(n: int, gather: bool, split: bool = False):
101
+ key = (n, gather, split)
102
+ if key not in _MV:
103
+ inputs = ["x", "raw", "codes", "flags", "esc", "tbl", "row_esc"] + (["xi", "ei"] if gather else [])
104
+ _MV[key] = mx.fast.cuda_kernel(
105
+ name=f"binade_cuda_r4_mv_n{n}{'_g' if gather else ''}{'_s' if split else ''}",
106
+ input_names=inputs,
107
+ output_names=["y", "y2"] if split else ["y"],
108
+ source=source_matvec(n, gather, split),
109
+ header=HEADER,
110
+ )
111
+ return _MV[key]
112
+
113
+
114
+ def _u32(a: mx.array) -> mx.array:
115
+ return a if a.dtype == mx.uint32 else a.astype(mx.uint32)
116
+
117
+
118
+ def r4_matvec(a: dict, x: mx.array, N: int, K: int) -> mx.array:
119
+ """x [..., K] holding one row -> [..., N]. Inputs and output keep the caller's shapes, so
120
+ the call adds no reshape to the graph (decoding on a fast GPU can be CPU-bound)."""
121
+ T = -(-K // TILE)
122
+ (y,) = _matvec_kernel(n_per_thread(K), False)(
123
+ inputs=[x, a["raw"], a["codes"], a["flags"], a["esc"], a["table"], a["row_esc"]],
124
+ template=[("N", N), ("K", K), ("T", T)],
125
+ grid=(-(-N // 8) * 256, 1, 1),
126
+ threadgroup=(256, 1, 1),
127
+ output_shapes=[(*x.shape[:-1], N)],
128
+ output_dtypes=[mx.bfloat16],
129
+ )
130
+ return y
131
+
132
+
133
+ def r4_gather(a: dict, x: mx.array, xi: mx.array, ei: mx.array, n: int, rs: int, r0: int, K: int, split: int | None = None, shape: tuple | None = None):
134
+ """[G, n] (or `shape`), or with split the pair [G, split], [G, n - split]."""
135
+ T = -(-K // TILE)
136
+ G = int(ei.size)
137
+ shapes = [(G, split), (G, n - split)] if split else [shape or (G, n)]
138
+ out = _matvec_kernel(n_per_thread(K), True, bool(split))(
139
+ inputs=[x, a["raw"], a["codes"], a["flags"], a["esc"], a["table"], a["row_esc"], _u32(xi), _u32(ei)],
140
+ template=[("N", n), ("K", K), ("T", T), ("RS", rs), ("R0", r0)] + ([("SPLIT", split)] if split else []),
141
+ grid=(-(-n // 8) * 256, G, 1),
142
+ threadgroup=(256, 1, 1),
143
+ output_shapes=shapes,
144
+ output_dtypes=[mx.bfloat16] * len(shapes),
145
+ )
146
+ return (out[0], out[1]) if split else out[0]
147
+
148
+
149
+ FLOAT_PARTIALS = ("f32", "inplace") # split-K schemes whose partitions leave float32 sums
150
+
151
+
152
+ def source_r4_mma(bm: int, bn: int, wm: int, wn: int, split: str) -> str:
153
+ """R4 GEMM on tensor cores, bit-identical to cuBLAS's BF16 GEMM as MLX calls it
154
+ (binade/mlx/cublas_plan.py): every output is a sequence of mma.sync m16n8k16 steps along K,
155
+ in order, from zero, over its split-K partition (blockIdx.z, bounds kr[]). split "none":
156
+ the sum is rounded to BF16 into y; "bf16": the partition's sum is rounded to BF16 into
157
+ part[S, M, N] (cuBLAS's OUTPUT_TYPE reduction scheme); "f32": kept in float32 (COMPUTE_TYPE);
158
+ r4_gemm then adds the partials in partition order.
159
+
160
+ A block of 4 warps (wm x wn) owns bm rows of x by bn weight rows and walks its partition in
161
+ chunks of 32: it stages the chunk's inputs in shared memory while two threads per weight row
162
+ decode 16 weights each from R4 (escape counts from the code nibbles, exchanged between the
163
+ pair; one lookup turns a byte of codes into two exponents in place), then each warp runs the
164
+ chunk's two m16n8k16 steps on its (bm / wm) x (bn / wn) tile. A partition starting inside a
165
+ row finds its escape pointer by counting escapes in the flagged tiles before it. K % 32 == 0."""
166
+ nthr = wm * wn * 32
167
+ tm, tn = bm // wm // 16, bn // wn // 8
168
+ assert nthr == 128 and bn * 2 == nthr and tm >= 1 and tn >= 1, (bm, bn, wm, wn)
169
+ a_bytes = bm * 64 // nthr # input bytes staged per thread per chunk
170
+ assert a_bytes in (8, 16, 32), bm
171
+ ld = 40 # padded row of a staged chunk, in BF16 elements
172
+ store = "y[size_t(r) * N + c]" if split == "none" else "part[size_t(s) * M * N + size_t(r) * N + c]"
173
+ conv = "" if split in FLOAT_PARTIALS else "__float2bfloat16_rn"
174
+ a_stage = {
175
+ 8: "uint2 v = make_uint2(0u, 0u); int r = int(tid) >> 3, c = (int(tid) & 7) * 4; if (rb + r < M) { v = *reinterpret_cast<const uint2*>(x + size_t(rb + r) * K + k0 + c); } *reinterpret_cast<uint2*>(&As[r * LD + c]) = v;",
176
+ 16: "uint4 v = make_uint4(0u, 0u, 0u, 0u); int r = int(tid) >> 2, c = (int(tid) & 3) * 8; if (rb + r < M) { v = *reinterpret_cast<const uint4*>(x + size_t(rb + r) * K + k0 + c); } *reinterpret_cast<uint4*>(&As[r * LD + c]) = v;",
177
+ 32: "for (int h = 0; h < 2; h++) { uint4 v = make_uint4(0u, 0u, 0u, 0u); int i = int(tid) + h * 128; int r = i >> 2, c = (i & 3) * 8; if (rb + r < M) { v = *reinterpret_cast<const uint4*>(x + size_t(rb + r) * K + k0 + c); } *reinterpret_cast<uint4*>(&As[r * LD + c]) = v; }",
178
+ }[a_bytes]
179
+ return f"""
180
+ constexpr int LD = {ld};
181
+ __shared__ __align__(16) uint16_t As[{bm} * LD];
182
+ __shared__ __align__(16) uint16_t Bs[{bn} * LD];
183
+ __shared__ uint32_t lut2[256];
184
+ uint32_t tid = threadIdx.x, lane = tid & 31u, warp = tid >> 5;
185
+ for (int i = int(tid); i < 256; i += {nthr}) {{ lut2[i] = (uint32_t(tbl[i & 15]) << 7) | (uint32_t(tbl[i >> 4]) << 23); }}
186
+ int s = int(blockIdx.z);
187
+ int kb = kr[s], ke = kr[s + 1];
188
+ int rb = int(blockIdx.y) * {bm}, cb = int(blockIdx.x) * {bn};
189
+ // decoding role: weight row nl, weights 16 g .. 16 g + 15 of each chunk
190
+ int nl = int(tid) >> 1, g = int(tid) & 1;
191
+ int n = cb + nl;
192
+ bool nok = n < N;
193
+ size_t row = size_t(nok ? n : 0);
194
+ // escape pointer at the partition start: escapes in [0, kb) of this row
195
+ uint32_t cnt0 = 0;
196
+ if (nok && kb > 0) {{
197
+ int tk = kb >> 7;
198
+ for (int t = g; t < tk; t += 2) {{
199
+ if (flags[row * T + t]) {{
200
+ const uint4* cw4 = reinterpret_cast<const uint4*>(codes + (row * T + t) * 32);
201
+ for (int q = 0; q < 4; q++) {{ uint4 u = cw4[q]; uint32_t w[4] = {{u.x, u.y, u.z, u.w}};
202
+ for (int z = 0; z < 4; z++) {{ cnt0 += __popc(w[z] & (w[z] >> 1) & (w[z] >> 2) & (w[z] >> 3) & 0x11111111u); }} }}
203
+ }}
204
+ }}
205
+ int wpart = (kb & 127) >> 2; // code words (4 weights each) of tile tk before kb
206
+ if (g == 0 && wpart > 0 && flags[row * T + tk]) {{
207
+ const uint16_t* cw = codes + (row * T + tk) * 32;
208
+ for (int q = 0; q < wpart; q++) {{ uint32_t w = cw[q]; cnt0 += __popc(w & (w >> 1) & (w >> 2) & (w >> 3) & 0x1111u); }}
209
+ }}
210
+ }}
211
+ cnt0 += __shfl_xor_sync(0xffffffffu, cnt0, 1);
212
+ uint32_t epos = (nok ? row_esc[row] : 0u) + cnt0;
213
+ // MMA role
214
+ int qg = int(lane >> 2), qt = int(lane & 3u);
215
+ int wr = int(warp) / {wn} * {bm // wm}, wc = int(warp) % {wn} * {bn // wn};
216
+ float acc[{tm}][{tn}][4];
217
+ #pragma unroll
218
+ for (int i = 0; i < {tm}; i++) {{
219
+ #pragma unroll
220
+ for (int j = 0; j < {tn}; j++) {{ acc[i][j][0] = acc[i][j][1] = acc[i][j][2] = acc[i][j][3] = 0.f; }}
221
+ }}
222
+ for (int k0 = kb; k0 < ke; k0 += 32) {{
223
+ __syncthreads();
224
+ {{ {a_stage} }}
225
+ {{
226
+ int t = k0 >> 7, c = k0 & 127;
227
+ uint2 cv = make_uint2(0u, 0u); uint4 rv = make_uint4(0u, 0u, 0u, 0u);
228
+ if (nok) {{
229
+ cv = *reinterpret_cast<const uint2*>(codes + (row * T + t) * 32 + ((c + 16 * g) >> 2));
230
+ rv = *reinterpret_cast<const uint4*>(raw + row * K + k0 + 16 * g);
231
+ }}
232
+ uint32_t cw[2] = {{cv.x, cv.y}};
233
+ uint32_t rw[4] = {{rv.x, rv.y, rv.z, rv.w}};
234
+ uint32_t f[2];
235
+ uint32_t cnt = 0;
236
+ #pragma unroll
237
+ for (int z = 0; z < 2; z++) {{ f[z] = cw[z] & (cw[z] >> 1) & (cw[z] >> 2) & (cw[z] >> 3) & 0x11111111u; cnt += __popc(f[z]); }}
238
+ uint32_t other = __shfl_xor_sync(0xffffffffu, cnt, 1);
239
+ uint32_t q = epos + (g ? other : 0u);
240
+ epos += cnt + other;
241
+ #pragma unroll
242
+ for (int hh = 0; hh < 2; hh++) {{
243
+ uint32_t pk[4];
244
+ #pragma unroll
245
+ for (int jj = 0; jj < 4; jj++) {{
246
+ int j = hh * 4 + jj;
247
+ uint32_t e2 = lut2[(cw[j >> 2] >> (8u * uint32_t(j & 3))) & 0xFFu];
248
+ uint32_t r = (rw[j >> 1] >> (16u * uint32_t(j & 1))) & 0xFFFFu;
249
+ pk[jj] = e2 | ((r & 0x80u) << 8) | (r & 0x7Fu) | ((r & 0x8000u) << 16) | ((r & 0x7F00u) << 8);
250
+ }}
251
+ if (f[hh]) {{
252
+ #pragma unroll
253
+ for (int jj = 0; jj < 8; jj++) {{
254
+ if ((f[hh] >> (4u * uint32_t(jj))) & 1u) {{
255
+ uint32_t sh = 7u + 16u * uint32_t(jj & 1);
256
+ pk[jj >> 1] = (pk[jj >> 1] & ~(0xFFu << sh)) | (uint32_t(esc[q]) << sh);
257
+ q++;
258
+ }}
259
+ }}
260
+ }}
261
+ *reinterpret_cast<uint4*>(&Bs[nl * LD + 16 * g + 8 * hh]) = nok ? make_uint4(pk[0], pk[1], pk[2], pk[3]) : make_uint4(0u, 0u, 0u, 0u);
262
+ }}
263
+ }}
264
+ __syncthreads();
265
+ #pragma unroll
266
+ for (int kk = 0; kk < 32; kk += 16) {{
267
+ uint32_t af[{tm}][4], bf[{tn}][2];
268
+ #pragma unroll
269
+ for (int i = 0; i < {tm}; i++) {{
270
+ int r0 = wr + i * 16 + qg;
271
+ af[i][0] = *reinterpret_cast<const uint32_t*>(&As[r0 * LD + kk + 2 * qt]);
272
+ af[i][1] = *reinterpret_cast<const uint32_t*>(&As[(r0 + 8) * LD + kk + 2 * qt]);
273
+ af[i][2] = *reinterpret_cast<const uint32_t*>(&As[r0 * LD + kk + 2 * qt + 8]);
274
+ af[i][3] = *reinterpret_cast<const uint32_t*>(&As[(r0 + 8) * LD + kk + 2 * qt + 8]);
275
+ }}
276
+ #pragma unroll
277
+ for (int j = 0; j < {tn}; j++) {{
278
+ int n0 = wc + j * 8 + qg;
279
+ bf[j][0] = *reinterpret_cast<const uint32_t*>(&Bs[n0 * LD + kk + 2 * qt]);
280
+ bf[j][1] = *reinterpret_cast<const uint32_t*>(&Bs[n0 * LD + kk + 2 * qt + 8]);
281
+ }}
282
+ #pragma unroll
283
+ for (int i = 0; i < {tm}; i++) {{
284
+ #pragma unroll
285
+ for (int j = 0; j < {tn}; j++) {{
286
+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {{%0,%1,%2,%3}}, {{%4,%5,%6,%7}}, {{%8,%9}}, {{%0,%1,%2,%3}};\\n"
287
+ : "+f"(acc[i][j][0]), "+f"(acc[i][j][1]), "+f"(acc[i][j][2]), "+f"(acc[i][j][3])
288
+ : "r"(af[i][0]), "r"(af[i][1]), "r"(af[i][2]), "r"(af[i][3]), "r"(bf[j][0]), "r"(bf[j][1]));
289
+ }}
290
+ }}
291
+ }}
292
+ }}
293
+ #pragma unroll
294
+ for (int i = 0; i < {tm}; i++) {{
295
+ #pragma unroll
296
+ for (int j = 0; j < {tn}; j++) {{
297
+ int c = cb + wc + j * 8 + 2 * qt;
298
+ #pragma unroll
299
+ for (int h = 0; h < 2; h++) {{
300
+ int r = rb + wr + i * 16 + qg + 8 * h;
301
+ if (r < M && c < N) {{ {store} = {conv}(acc[i][j][2 * h]); }}
302
+ if (r < M && c + 1 < N) {{ {store.replace("+ c]", "+ c + 1]")} = {conv}(acc[i][j][2 * h + 1]); }}
303
+ }}
304
+ }}
305
+ }}
306
+ """
307
+
308
+
309
+ STEP_REGS = r'''
310
+ #pragma unroll
311
+ for (int j = @J0; j < @J1; j++) {
312
+ uint32_t b0 = nok ? b0s[j] : 0u, b1 = nok ? b1s[j] : 0u;
313
+ #pragma unroll
314
+ for (int i = 0; i < @MT; i++) {
315
+ const uint16_t* a = A + (16 * i + g) * LDA + 16 * j + 2 * t;
316
+ uint32_t a0 = *reinterpret_cast<const uint32_t*>(a), a1 = *reinterpret_cast<const uint32_t*>(a + 8 * LDA);
317
+ uint32_t a2 = *reinterpret_cast<const uint32_t*>(a + 8), a3 = *reinterpret_cast<const uint32_t*>(a + 8 * LDA + 8);
318
+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
319
+ : "+f"(@ACC[i][0]), "+f"(@ACC[i][1]), "+f"(@ACC[i][2]), "+f"(@ACC[i][3])
320
+ : "r"(a0), "r"(a1), "r"(a2), "r"(a3), "r"(b0), "r"(b1));
321
+ }
322
+ }
323
+ '''
324
+
325
+
326
+ def source_r4_mma_regs(mt: int, split: str, wpb: int = 8, gather: bool = False, slices: int = 1) -> str:
327
+ """The R4 tensor-core GEMM for short inputs (up to 16 mt rows), with the same per-output
328
+ order as source_r4_mma (in-order mma.sync m16n8k16 steps per split-K partition, so the same
329
+ cuBLAS mirror). A block of wpb warps owns 8 wpb weight rows, one warp per 8, for every input
330
+ row (r4_gemm picks wpb so that a narrow matrix still spreads over the GPU's SMs).
331
+ K goes in blocks of 64 weights: the block's input rows for the next 64 are loaded into
332
+ registers and staged in a double-buffered shared tile (one barrier per block); each warp's
333
+ B fragments are decoded straight into registers (the four threads of a row's quad hold one
334
+ step's raw bytes and code words each and exchange them by shuffle; escapes are ordered by a
335
+ prefix sum over the quad), with weight blocks loaded three ahead. Like the matvec kernel, every
336
+ weight is read once. Partition bounds are multiples of 64 (cublas_plan); K % 64 == 0."""
337
+ store = "y[size_t(rg) * N + c]" if split == "none" else "part[size_t(s) * M * N + size_t(rg) * N + c]"
338
+ run_head = ("uint32_t e = idx[rb + seg]; int end = seg + 1; while (end < nrow && idx[rb + end] == e) { end++; }" if gather else "int end = nrow;")
339
+ row_expr = "size_t(e) * RS + R0 + size_t(nok ? n : 0)" if gather else "size_t(nok ? n : 0)"
340
+ conv = "" if split in FLOAT_PARTIALS else "__float2bfloat16_rn"
341
+ rows = 16 * mt
342
+ nthr = 32 * wpb
343
+ xv = rows * 8 # uint4 (8 BF16) per 64-wide input block
344
+ # with slices == 2 (cuBLAS's sliced-K kernels) steps 0, 1 of each 64-wide block go to acc and 2, 3 to acc2
345
+ def step(j0: int, j1: int, acc: str) -> str:
346
+ return STEP_REGS.replace("@J0", str(j0)).replace("@J1", str(j1)).replace("@ACC", acc).replace("@MT", str(mt))
347
+ steps = step(0, 4, "acc") if slices == 1 else step(0, 2, "acc") + step(2, 4, "acc2")
348
+ acc2 = f"float acc2[{mt}][4]; for (int i = 0; i < {mt}; i++) {{ acc2[i][0] = acc2[i][1] = acc2[i][2] = acc2[i][3] = 0.f; }}" if slices == 2 else ""
349
+ v0, v1 = ("(acc[i][2 * h] + acc2[i][2 * h])", "(acc[i][2 * h + 1] + acc2[i][2 * h + 1])") if slices == 2 else ("acc[i][2 * h]", "acc[i][2 * h + 1]")
350
+ per = -(-xv // nthr) # per thread
351
+ return f"""
352
+ constexpr int LDA = 72; // padded staged input row, BF16
353
+ __shared__ __align__(16) uint16_t As[3][{rows} * LDA]; // 3-stage ring of 64-wide input blocks
354
+ __shared__ uint8_t lut[16];
355
+ if (threadIdx.x < 16) {{ lut[threadIdx.x] = tbl[threadIdx.x]; }}
356
+ const uint32_t full = 0xffffffffu;
357
+ uint32_t tid = threadIdx.x, lane = tid & 31u;
358
+ int warp = int(tid >> 5);
359
+ int g = int(lane >> 2), t = int(lane & 3u);
360
+ int q0 = int(lane & ~3u);
361
+ int n0 = (int(blockIdx.x) * {wpb} + warp) * 8;
362
+ int n = n0 + g;
363
+ bool nok = n < N; // warps past N keep running for the barriers, with zero weights
364
+ int s = int(blockIdx.z);
365
+ int kb = kr[s], ke = kr[s + 1];
366
+ int rb = int(blockIdx.y) * {rows}; // this block's input rows: rb .. rb + nrow - 1
367
+ int nrow = min({rows}, M - rb);
368
+ int sh = (t & 1) * 2;
369
+ // input staging with cp.async: thread tid copies uint4 number tid + {nthr} v of a block (row (..) / 8,
370
+ // column 8 ((..) % 8)) straight into the ring; rows past nrow are zero-filled; one commit group per block
371
+ #define COPYX(k64, st) {{ _Pragma("unroll") for (int v = 0; v < {per}; v++) {{ int i = int(tid) + {nthr} * v; int r = i >> 3, c = (i & 7) * 8; \\
372
+ if (i < {xv}) {{ bool ok = r < nrow && (k64) < ke; const __nv_bfloat16* gp = ok ? x + size_t(rb + r) * K + (k64) + c : x; \\
373
+ uint32_t sa = static_cast<uint32_t>(__cvta_generic_to_shared(&As[st][r * LDA + c])); \\
374
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\\n" :: "r"(sa), "l"(gp), "r"(ok ? 16 : 0)); }} }} \\
375
+ asm volatile("cp.async.commit_group;\\n" ::); }}
376
+ #define LOADB(k64, R, C) {{ if (nok && (k64) < ke) {{ R = *reinterpret_cast<const uint4*>(rrow + (k64) + 16 * t); C = *reinterpret_cast<const uint2*>(crow + ((k64) >> 2) + 4 * t); }} \\
377
+ else {{ R = make_uint4(0u, 0u, 0u, 0u); C = make_uint2(0u, 0u); }} }}
378
+ // runs of input rows that share an expert (gathering: slots sorted by expert); one run otherwise
379
+ for (int seg = 0; seg < nrow;) {{
380
+ {run_head}
381
+ size_t row = {row_expr};
382
+ // escape pointer at the partition start: escapes in [0, kb) of this row, split over the quad
383
+ uint32_t c0 = 0;
384
+ if (nok && kb > 0) {{
385
+ int tk = kb >> 7;
386
+ for (int tt = t; tt < tk; tt += 4) {{
387
+ if (flags[row * T + tt]) {{
388
+ const uint4* cw4 = reinterpret_cast<const uint4*>(codes + (row * T + tt) * 32);
389
+ for (int z = 0; z < 4; z++) {{ uint4 u = cw4[z]; uint32_t w[4] = {{u.x, u.y, u.z, u.w}};
390
+ for (int y2 = 0; y2 < 4; y2++) {{ c0 += __popc(w[y2] & (w[y2] >> 1) & (w[y2] >> 2) & (w[y2] >> 3) & 0x11111111u); }} }}
391
+ }}
392
+ }}
393
+ int wpart = (kb & 127) >> 2;
394
+ if (wpart > 0 && flags[row * T + tk]) {{
395
+ const uint16_t* cw = codes + (row * T + tk) * 32;
396
+ for (int z = t; z < wpart; z += 4) {{ uint32_t w = cw[z]; c0 += __popc(w & (w >> 1) & (w >> 2) & (w >> 3) & 0x1111u); }}
397
+ }}
398
+ }}
399
+ c0 += __shfl_xor_sync(full, c0, 1);
400
+ c0 += __shfl_xor_sync(full, c0, 2);
401
+ uint32_t epos = (nok ? row_esc[row] : 0u) + c0;
402
+ const uint16_t* crow = codes + row * T * 32; // the row's code words: word k / 4 holds weights k .. k + 3
403
+ const uint8_t* rrow = raw + row * K;
404
+ float acc[{mt}][4];
405
+ #pragma unroll
406
+ for (int i = 0; i < {mt}; i++) {{ acc[i][0] = acc[i][1] = acc[i][2] = acc[i][3] = 0.f; }}
407
+ {acc2}
408
+ uint4 r_cur, r_nxt, r_nx2; uint2 c_cur, c_nxt, c_nx2;
409
+ LOADB(kb, r_cur, c_cur);
410
+ LOADB(kb + 64, r_nxt, c_nxt);
411
+ LOADB(kb + 128, r_nx2, c_nx2);
412
+ COPYX(kb, 0);
413
+ COPYX(kb + 64, 1);
414
+ int buf = 0;
415
+ for (int k64 = kb; k64 < ke; k64 += 64) {{
416
+ asm volatile("cp.async.wait_group 1;\\n" ::); // this block's copy is done (the next one may still be in flight)
417
+ __syncthreads(); // ... for every thread; and every warp is done with the stage refilled below
418
+ COPYX(k64 + 128, (buf + 2) % 3);
419
+ uint4 br = r_cur; uint2 bc = c_cur;
420
+ r_cur = r_nxt; c_cur = c_nxt;
421
+ r_nxt = r_nx2; c_nxt = c_nx2;
422
+ LOADB(k64 + 192, r_nx2, c_nx2);
423
+ uint32_t cA = (bc.x & 0xFFFFu) | (bc.y << 16), cB = (bc.x >> 16) | (bc.y & 0xFFFF0000u);
424
+ const uint16_t* A = As[buf];
425
+ // gather the block's 4 steps with 12 shuffles: at shuffle k, threads 0, 1 of each quad read
426
+ // step k from lane k (its A-half: code words 0, 2; raw words 0, 2) and threads 2, 3 read step
427
+ // (k + 1) % 4 from lane (k + 1) % 4 (B-half: words 1, 3); each source lane sends the half
428
+ // its readers need
429
+ int qs = int(lane & 3u);
430
+ uint32_t sc[4], sl[4], shh[4];
431
+ #pragma unroll
432
+ for (int k = 0; k < 4; k++) {{
433
+ bool sendA = qs == k, sendB = qs == ((k + 1) & 3);
434
+ uint32_t vc = sendA ? cA : (sendB ? cB : 0u);
435
+ uint32_t vl = sendA ? br.x : (sendB ? br.y : 0u);
436
+ uint32_t vh = sendA ? br.z : (sendB ? br.w : 0u);
437
+ int src = q0 + (t < 2 ? k : ((k + 1) & 3));
438
+ sc[k] = __shfl_sync(full, vc, src);
439
+ sl[k] = __shfl_sync(full, vl, src);
440
+ shh[k] = __shfl_sync(full, vh, src);
441
+ }}
442
+ uint32_t b0s[4], b1s[4], cw[4];
443
+ uint32_t anyesc = 0;
444
+ #pragma unroll
445
+ for (int j = 0; j < 4; j++) {{
446
+ // step j arrived at shuffle j (threads 0, 1) or at shuffle (j + 3) % 4 (threads 2, 3)
447
+ uint32_t cc = t < 2 ? sc[j] : sc[(j + 3) & 3];
448
+ uint32_t rlo = t < 2 ? sl[j] : sl[(j + 3) & 3];
449
+ uint32_t rhi = t < 2 ? shh[j] : shh[(j + 3) & 3];
450
+ cw[j] = cc;
451
+ uint32_t clo = cc & 0xFFFFu, chi = cc >> 16;
452
+ uint32_t c0 = (clo >> (4 * sh)) & 15u, c1 = (clo >> (4 * sh + 4)) & 15u, c2 = (chi >> (4 * sh)) & 15u, c3 = (chi >> (4 * sh + 4)) & 15u;
453
+ anyesc |= (c0 == 15u) | (c1 == 15u) | (c2 == 15u) | (c3 == 15u);
454
+ uint32_t r0b = (rlo >> (8 * sh)) & 255u, r1b = (rlo >> (8 * sh + 8)) & 255u, r2b = (rhi >> (8 * sh)) & 255u, r3b = (rhi >> (8 * sh + 8)) & 255u;
455
+ uint32_t u0 = ((r0b & 0x80u) << 8) | (uint32_t(lut[c0]) << 7) | (r0b & 0x7Fu);
456
+ uint32_t u1 = ((r1b & 0x80u) << 8) | (uint32_t(lut[c1]) << 7) | (r1b & 0x7Fu);
457
+ uint32_t u2 = ((r2b & 0x80u) << 8) | (uint32_t(lut[c2]) << 7) | (r2b & 0x7Fu);
458
+ uint32_t u3 = ((r3b & 0x80u) << 8) | (uint32_t(lut[c3]) << 7) | (r3b & 0x7Fu);
459
+ b0s[j] = u0 | (u1 << 16); b1s[j] = u2 | (u3 << 16);
460
+ }}
461
+ if (__any_sync(full, anyesc)) {{
462
+ // rare: some row has escapes in this block; patch steps in order (escape order = position order)
463
+ #pragma unroll
464
+ for (int j = 0; j < 4; j++) {{
465
+ uint32_t clo = cw[j] & 0xFFFFu, chi = cw[j] >> 16;
466
+ uint32_t c[4] = {{(clo >> (4 * sh)) & 15u, (clo >> (4 * sh + 4)) & 15u, (chi >> (4 * sh)) & 15u, (chi >> (4 * sh + 4)) & 15u}};
467
+ uint32_t nlo = (c[0] == 15u ? 1u : 0u) + (c[1] == 15u ? 1u : 0u), nhi = (c[2] == 15u ? 1u : 0u) + (c[3] == 15u ? 1u : 0u);
468
+ uint32_t ilo = nlo, ihi = nhi, v;
469
+ v = __shfl_up_sync(full, ilo, 1, 4); if (t >= 1) {{ ilo += v; }}
470
+ v = __shfl_up_sync(full, ilo, 2, 4); if (t >= 2) {{ ilo += v; }}
471
+ v = __shfl_up_sync(full, ihi, 1, 4); if (t >= 1) {{ ihi += v; }}
472
+ v = __shfl_up_sync(full, ihi, 2, 4); if (t >= 2) {{ ihi += v; }}
473
+ uint32_t tlo = __shfl_sync(full, ilo, 3, 4), thi = __shfl_sync(full, ihi, 3, 4);
474
+ uint32_t q = epos + ilo - nlo;
475
+ if (c[0] == 15u) {{ b0s[j] = (b0s[j] & ~(0xFFu << 7)) | (uint32_t(esc[q]) << 7); q++; }}
476
+ if (c[1] == 15u) {{ b0s[j] = (b0s[j] & ~(0xFFu << 23)) | (uint32_t(esc[q]) << 23); q++; }}
477
+ q = epos + tlo + ihi - nhi;
478
+ if (c[2] == 15u) {{ b1s[j] = (b1s[j] & ~(0xFFu << 7)) | (uint32_t(esc[q]) << 7); q++; }}
479
+ if (c[3] == 15u) {{ b1s[j] = (b1s[j] & ~(0xFFu << 23)) | (uint32_t(esc[q]) << 23); q++; }}
480
+ epos += tlo + thi;
481
+ }}
482
+ }}
483
+ {steps}
484
+ buf = (buf + 1) % 3;
485
+ }}
486
+ asm volatile("cp.async.wait_group 0;\\n" ::);
487
+ int c = n0 + 2 * t;
488
+ #pragma unroll
489
+ for (int i = 0; i < {mt}; i++) {{
490
+ #pragma unroll
491
+ for (int h = 0; h < 2; h++) {{
492
+ int r = 16 * i + g + 8 * h;
493
+ int rg = rb + r;
494
+ if (r >= seg && r < end && c < N) {{ {store} = {conv}({v0}); }}
495
+ if (r >= seg && r < end && c + 1 < N) {{ {store.replace("+ c]", "+ c + 1]")} = {conv}({v1}); }}
496
+ }}
497
+ }}
498
+ seg = end;
499
+ __syncthreads(); // the next run refills the ring
500
+ }}
501
+ #undef COPYX
502
+ #undef LOADB
503
+ """
504
+
505
+
506
+ BIG_STAGES = {128: 3, 256: 4} # input stages per tile height (dynamic shared memory)
507
+
508
+
509
+ def big_smem(bm: int) -> int:
510
+ return BIG_STAGES[bm] * bm * 64 + 2 * 128 * 64 + 1024
511
+
512
+
513
+ STEP_BIG = r'''
514
+ #pragma unroll
515
+ for (int kk = 0; kk < 2; kk++) {
516
+ uint32_t af[4][4];
517
+ #pragma unroll
518
+ for (int i = 0; i < 4; i++) {
519
+ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(af[i][0]), "=r"(af[i][1]), "=r"(af[i][2]), "=r"(af[i][3]) : "r"(A + (oA[i] ^ (32u * kk))));
520
+ }
521
+ #pragma unroll
522
+ for (int jp = 0; jp < @NJ; jp++) {
523
+ uint32_t b0, b1, b2, b3;
524
+ asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" : "=r"(b0), "=r"(b1), "=r"(b2), "=r"(b3) : "r"(B + (oB[jp] ^ (32u * kk))));
525
+ #pragma unroll
526
+ for (int i = 0; i < 4; i++) {
527
+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
528
+ : "+f"(@ACC[i][2 * jp][0]), "+f"(@ACC[i][2 * jp][1]), "+f"(@ACC[i][2 * jp][2]), "+f"(@ACC[i][2 * jp][3])
529
+ : "r"(af[i][0]), "r"(af[i][1]), "r"(af[i][2]), "r"(af[i][3]), "r"(b0), "r"(b1));
530
+ asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};\n"
531
+ : "+f"(@ACC[i][2 * jp + 1][0]), "+f"(@ACC[i][2 * jp + 1][1]), "+f"(@ACC[i][2 * jp + 1][2]), "+f"(@ACC[i][2 * jp + 1][3])
532
+ : "r"(af[i][0]), "r"(af[i][1]), "r"(af[i][2]), "r"(af[i][3]), "r"(b2), "r"(b3));
533
+ }
534
+ }
535
+ }
536
+ '''
537
+
538
+
539
+ def source_r4_mma_big(split: str, bm: int = 256, slices: int = 1) -> str:
540
+ """The R4 tensor-core GEMM for long inputs, with the same per-output order as the other two
541
+ (in-order mma.sync m16n8k16 steps per split-K partition). A block of 8 warps owns bm input
542
+ rows (128 or 256) by 128 weight rows, each warp a 64 x (128 * 64 / bm) tile, like cuBLAS's
543
+ 256 x 128 kernel, and walks its partition in chunks of 32: inputs come with cp.async into a
544
+ shared ring of BIG_STAGES[bm] stages, two threads per weight row decode 16 weights each into
545
+ a double-buffered shared tile one chunk ahead (raw bytes and code words loaded two chunks
546
+ ahead), and fragments are read with ldmatrix from rows swizzled in 16-byte pieces (no bank
547
+ conflicts). Every address is computed once; one barrier per chunk. Launch rows of blocks
548
+ walk the input tiles first, so blocks sharing a weight tile run together. K % 32 == 0,
549
+ N % 2 == 0."""
550
+ store = "y + size_t(r) * N + c" if split == "none" else "part + size_t(s) * M * N + size_t(r) * N + c"
551
+ if split in FLOAT_PARTIALS:
552
+ put = "*reinterpret_cast<float2*>({p}) = make_float2(acc[i][j][2 * h], acc[i][j][2 * h + 1]);"
553
+ else:
554
+ put = "*reinterpret_cast<__nv_bfloat162*>({p}) = __floats2bfloat162_rn(acc[i][j][2 * h], acc[i][j][2 * h + 1]);"
555
+ put = put.format(p=store)
556
+ wm = bm // 64
557
+ wn = 8 // wm
558
+ nt = 128 // wn // 8
559
+ stages = BIG_STAGES[bm]
560
+ a_bytes = bm * 64
561
+ # with slices == 2 (cuBLAS's sliced-K kernels) chunks alternate between acc and acc2 (32-wide K slices)
562
+ step = lambda acc: STEP_BIG.replace("@NJ", str(nt // 2)).replace("@ACC", acc)
563
+ steps = step("acc") if slices == 1 else " if (((k0 - kb) >> 5) & 1) {\n" + step("acc2") + " } else {\n" + step("acc") + " }\n"
564
+ acc2 = f"float acc2[4][{nt}][4]; for (int i = 0; i < 4; i++) {{ for (int j = 0; j < {nt}; j++) {{ acc2[i][j][0] = acc2[i][j][1] = acc2[i][j][2] = acc2[i][j][3] = 0.f; }} }}" if slices == 2 else ""
565
+ if slices == 2:
566
+ put = put.replace("acc[i][j][2 * h]", "acc[i][j][2 * h] + acc2[i][j][2 * h]").replace("acc[i][j][2 * h + 1]", "acc[i][j][2 * h + 1] + acc2[i][j][2 * h + 1]")
567
+ return f"""
568
+ extern __shared__ __align__(128) uint8_t smem[];
569
+ const uint32_t sA = static_cast<uint32_t>(__cvta_generic_to_shared(smem));
570
+ const uint32_t sB = sA + {stages * a_bytes};
571
+ uint32_t* lut2 = reinterpret_cast<uint32_t*>(smem + {stages * a_bytes + 2 * 128 * 64});
572
+ const uint32_t full = 0xffffffffu;
573
+ uint32_t tid = threadIdx.x, lane = tid & 31u;
574
+ int warp = int(tid >> 5);
575
+ lut2[tid] = (uint32_t(tbl[tid & 15u]) << 7) | (uint32_t(tbl[tid >> 4]) << 23);
576
+ __syncthreads();
577
+ int s = int(blockIdx.z);
578
+ int kb = kr[s], ke = kr[s + 1];
579
+ int rb = int(blockIdx.x) * {bm}, cb = int(blockIdx.y) * 128;
580
+ // byte offset of (row r, 16-byte piece c of 4) in a stage of 64-byte rows, swizzled
581
+ #define SWB(r, c) (uint32_t(r) * 64u + 16u * uint32_t((c) ^ (((r) >> 1) & 3)))
582
+ // decoding role: weight row nl, weights 16 gh .. 16 gh + 15 of each chunk
583
+ int nl = int(tid) >> 1, gh = int(tid) & 1;
584
+ int n = cb + nl;
585
+ bool nok = n < N;
586
+ size_t row = size_t(nok ? n : 0);
587
+ uint32_t cnt0 = 0;
588
+ if (nok && kb > 0) {{
589
+ int tk = kb >> 7;
590
+ for (int t = gh; t < tk; t += 2) {{
591
+ if (flags[row * T + t]) {{
592
+ const uint4* cw4 = reinterpret_cast<const uint4*>(codes + (row * T + t) * 32);
593
+ for (int q = 0; q < 4; q++) {{ uint4 u = cw4[q]; uint32_t w[4] = {{u.x, u.y, u.z, u.w}};
594
+ for (int z = 0; z < 4; z++) {{ cnt0 += __popc(w[z] & (w[z] >> 1) & (w[z] >> 2) & (w[z] >> 3) & 0x11111111u); }} }}
595
+ }}
596
+ }}
597
+ int wpart = (kb & 127) >> 2;
598
+ if (gh == 0 && wpart > 0 && flags[row * T + tk]) {{
599
+ const uint16_t* cw = codes + (row * T + tk) * 32;
600
+ for (int q = 0; q < wpart; q++) {{ uint32_t w = cw[q]; cnt0 += __popc(w & (w >> 1) & (w >> 2) & (w >> 3) & 0x1111u); }}
601
+ }}
602
+ }}
603
+ cnt0 += __shfl_xor_sync(full, cnt0, 1);
604
+ uint32_t epos = (nok ? row_esc[row] : 0u) + cnt0;
605
+ const uint16_t* crow = codes + row * T * 32 + 4 * gh; // word k / 4 holds the codes of weights k .. k + 3
606
+ const uint8_t* rrow = raw + row * K + 16 * gh;
607
+ const uint32_t dB = SWB(nl, 2 * gh); // this thread's two decoded pieces: dB and dB ^ 16
608
+ // input copies: rows (tid >> 2) + 64 v, piece tid & 3
609
+ const int cr = int(tid) >> 2, cpc = int(tid) & 3;
610
+ const uint32_t dA = SWB(cr, cpc);
611
+ const __nv_bfloat16* xg = x + size_t(rb + cr) * K + 8 * cpc;
612
+ #define COPYA(k0, st) {{ _Pragma("unroll") for (int v = 0; v < {wm}; v++) {{ \\
613
+ bool ok = rb + cr + 64 * v < M && (k0) < ke; const __nv_bfloat16* gp = ok ? xg + size_t(64 * v) * K + (k0) : x; \\
614
+ asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;\\n" :: "r"(sA + (st) * {a_bytes}u + dA + 4096u * v), "l"(gp), "r"(ok ? 16 : 0)); }} \\
615
+ asm volatile("cp.async.commit_group;\\n" ::); }}
616
+ #define LOADB(k0, R, C) {{ if (nok && (k0) < ke) {{ R = *reinterpret_cast<const uint4*>(rrow + (k0)); C = *reinterpret_cast<const uint2*>(crow + ((k0) >> 2)); }} \\
617
+ else {{ R = make_uint4(0u, 0u, 0u, 0u); C = make_uint2(0u, 0u); }} }}
618
+ // weights 16 gh .. 16 gh + 15 of row nl into B stage st; escapes in position order (the pair's counts exchanged)
619
+ #define DECODE(R, C, st) {{ uint32_t cw[2] = {{C.x, C.y}}; uint32_t rw[4] = {{R.x, R.y, R.z, R.w}}; uint32_t f[2]; uint32_t cnt = 0; \\
620
+ _Pragma("unroll") for (int z = 0; z < 2; z++) {{ f[z] = cw[z] & (cw[z] >> 1) & (cw[z] >> 2) & (cw[z] >> 3) & 0x11111111u; cnt += __popc(f[z]); }} \\
621
+ uint32_t other = __shfl_xor_sync(full, cnt, 1); uint32_t q = epos + (gh ? other : 0u); epos += cnt + other; \\
622
+ _Pragma("unroll") for (int hh = 0; hh < 2; hh++) {{ uint32_t pk[4]; \\
623
+ _Pragma("unroll") for (int jj = 0; jj < 4; jj++) {{ int j = hh * 4 + jj; uint32_t e2 = lut2[(cw[j >> 2] >> (8u * uint32_t(j & 3))) & 0xFFu]; \\
624
+ uint32_t r2 = __byte_perm(rw[j >> 1], 0u, (j & 1) ? 0x7372u : 0x7170u); \\
625
+ pk[jj] = e2 | ((r2 & 0x00800080u) << 8) | (r2 & 0x007F007Fu); }} \\
626
+ if (f[hh]) {{ _Pragma("unroll") for (int jj = 0; jj < 8; jj++) {{ if ((f[hh] >> (4u * uint32_t(jj))) & 1u) {{ \\
627
+ uint32_t sh = 7u + 16u * uint32_t(jj & 1); pk[jj >> 1] = (pk[jj >> 1] & ~(0xFFu << sh)) | (uint32_t(esc[q]) << sh); q++; }} }} }} \\
628
+ uint4 v4 = nok ? make_uint4(pk[0], pk[1], pk[2], pk[3]) : make_uint4(0u, 0u, 0u, 0u); \\
629
+ asm volatile("st.shared.v4.u32 [%0], {{%1, %2, %3, %4}};\\n" :: "r"(sB + (st) * 8192u + (dB ^ (16u * hh))), "r"(v4.x), "r"(v4.y), "r"(v4.z), "r"(v4.w)); }} }}
630
+ // MMA role: warp tile 64 x {128 // wn} at (wr, wc); ldmatrix offsets for the chunk's first step (the second: ^ 32)
631
+ int wr = (warp / {wn}) * 64, wc = (warp % {wn}) * {128 // wn};
632
+ int qg = int(lane >> 2), qt = int(lane & 3u);
633
+ uint32_t oA[4], oB[{nt // 2}];
634
+ #pragma unroll
635
+ for (int i = 0; i < 4; i++) {{ int r = wr + 16 * i + (int(lane) & 7) + ((int(lane) >> 3) & 1) * 8; oA[i] = SWB(r, int(lane) >> 4); }}
636
+ #pragma unroll
637
+ for (int jp = 0; jp < {nt // 2}; jp++) {{ int r = wc + 16 * jp + ((int(lane) >> 4) & 1) * 8 + (int(lane) & 7); oB[jp] = SWB(r, (int(lane) >> 3) & 1); }}
638
+ float acc[4][{nt}][4];
639
+ #pragma unroll
640
+ for (int i = 0; i < 4; i++) {{
641
+ #pragma unroll
642
+ for (int j = 0; j < {nt}; j++) {{ acc[i][j][0] = acc[i][j][1] = acc[i][j][2] = acc[i][j][3] = 0.f; }}
643
+ }}
644
+ {acc2}
645
+ uint4 rc, rn; uint2 cc, cn;
646
+ LOADB(kb, rc, cc);
647
+ LOADB(kb + 32, rn, cn);
648
+ #pragma unroll
649
+ for (int st = 0; st < {stages - 1}; st++) {{ COPYA(kb + 32 * st, st); }}
650
+ DECODE(rc, cc, 0);
651
+ rc = rn; cc = cn;
652
+ LOADB(kb + 64, rn, cn);
653
+ int a = 0, b = 0;
654
+ for (int k0 = kb; k0 < ke; k0 += 32) {{
655
+ asm volatile("cp.async.wait_group {stages - 2};\\n" ::);
656
+ __syncthreads(); // chunk k0's inputs and weights are in; everyone is done with the stages refilled below
657
+ COPYA(k0 + {32 * (stages - 1)}, (a + {stages - 1}) % {stages});
658
+ if (k0 + 32 < ke) {{ DECODE(rc, cc, b ^ 1); }}
659
+ rc = rn; cc = cn;
660
+ LOADB(k0 + 96, rn, cn);
661
+ const uint32_t A = sA + uint32_t(a) * {a_bytes}u, B = sB + uint32_t(b) * 8192u;
662
+ {steps}
663
+ a = (a + 1) % {stages}; b ^= 1;
664
+ }}
665
+ asm volatile("cp.async.wait_group 0;\\n" ::);
666
+ #pragma unroll
667
+ for (int i = 0; i < 4; i++) {{
668
+ #pragma unroll
669
+ for (int j = 0; j < {nt}; j++) {{
670
+ int c = cb + wc + 8 * j + 2 * qt;
671
+ #pragma unroll
672
+ for (int h = 0; h < 2; h++) {{
673
+ int r = rb + wr + 16 * i + qg + 8 * h;
674
+ if (r < M && c < N) {{ {put} }}
675
+ }}
676
+ }}
677
+ }}
678
+ #undef SWB
679
+ #undef COPYA
680
+ #undef LOADB
681
+ #undef DECODE
682
+ """
683
+
684
+
685
+ SOURCE_SPLIT_REDUCE = """
686
+ // cuBLAS's split-K reduction: partials (BF16 or float32) added in float32 in partition order
687
+ size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x;
688
+ if (i >= size_t(M) * N) { return; }
689
+ float a = 0.f;
690
+ for (int s = 0; s < S; s++) { a += static_cast<float>(part[size_t(s) * M * N + i]); }
691
+ y[i] = __float2bfloat16_rn(a);
692
+ """
693
+
694
+ SOURCE_SPLIT_INPLACE = """
695
+ // cuBLAS's in-place (serial) split-K: partition s adds its float32 sum to the BF16 output
696
+ // left by partitions 0 .. s - 1, rounding to BF16 each time
697
+ size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x;
698
+ if (i >= size_t(M) * N) { return; }
699
+ __nv_bfloat16 o = __float2bfloat16_rn(part[i]);
700
+ for (int s = 1; s < S; s++) { o = __float2bfloat16_rn(static_cast<float>(o) + part[size_t(s) * M * N + i]); }
701
+ y[i] = o;
702
+ """
703
+
704
+ _MMA = {}
705
+ _REDUCE = {}
706
+ MMA_TILES = ((16, (16, 64, 1, 4)), (None, (64, 64, 2, 2))) # (max rows, (bm, bn, wm, wn))
707
+
708
+
709
+ def mma_tile(M: int) -> tuple:
710
+ return next(t for r, t in MMA_TILES if r is None or M <= r)
711
+
712
+
713
+ REGS_MAX_ROWS = 64 # up to this many rows, the register-decoding kernel (all rows in one launch row)
714
+ REGS_MIN_BLOCKS = 376 # fewer warps per block until there are this many blocks (2 per SM of an RTX PRO 6000)
715
+ _BOUNDS = {}
716
+
717
+
718
+ def _bounds(b: tuple) -> mx.array:
719
+ """Split-K bounds as a cached, evaluated device array: a fresh array per call would copy from
720
+ the host each time and can stall the CPU/GPU pipeline."""
721
+ if b not in _BOUNDS:
722
+ _BOUNDS[b] = mx.array(b, dtype=mx.int32)
723
+ mx.eval(_BOUNDS[b])
724
+ return _BOUNDS[b]
725
+
726
+
727
+ def gemm_supported(M: int, N: int, K: int, slices: int = 1) -> bool:
728
+ """Whether r4_gemm's default kernel for this shape can sum in `slices` K slices (the 64 x 64
729
+ shared-memory kernel sums in order only)."""
730
+ return K % 32 == 0 and (slices == 1 or (M <= REGS_MAX_ROWS and K % 64 == 0) or N % 2 == 0)
731
+
732
+
733
+ def r4_gemm(a: dict, x: mx.array, N: int, K: int, bounds: list, split: str = "none", tile: str | tuple | None = None, slices: int = 1) -> mx.array:
734
+ """x [M, K] @ W.T [M, N] with W in R4, bit-identical to MLX's cuBLAS matmul when bounds and
735
+ split are that matmul's split-K partitions and partial type (cublas_plan). K % 32 == 0.
736
+ The kernel: up to REGS_MAX_ROWS rows (K % 64 == 0) the register kernel, else the 128 x 128
737
+ one (N even), else the 64 x 64 shared-memory one; tile ("regs", "big128", "big256" or
738
+ (bm, bn, wm, wn)) forces one, for tests and benchmarks. slices = 2 mirrors cuBLAS's sliced-K
739
+ kernels (cublas_plan.slices), without split-K."""
740
+ M = x.shape[0]
741
+ S = len(bounds) - 1
742
+ split = "none" if S == 1 else split
743
+ T = -(-K // TILE)
744
+ kr = _bounds(tuple(bounds))
745
+ out_shape, out_dtype = ((S, M, N) if S > 1 else (M, N)), (mx.float32 if split in FLOAT_PARTIALS else mx.bfloat16)
746
+ if (tile == "regs" or (tile is None and M <= REGS_MAX_ROWS)) and K % 64 == 0:
747
+ mt = min(4, -(-M // 16))
748
+ gy = -(-M // (16 * mt)) # launch rows of 16 mt inputs (each re-decodes the weights)
749
+ wpb = next(w for w in (8, 4, 2) if w == 2 or -(-N // (8 * w)) * gy * S >= REGS_MIN_BLOCKS)
750
+ key = ("regs", mt, split, wpb, slices)
751
+ if key not in _MMA:
752
+ _MMA[key] = mx.fast.cuda_kernel(
753
+ name=f"binade_cuda_r4_mma_regs{mt}_{split}_w{wpb}{'_s%d' % slices if slices > 1 else ''}",
754
+ input_names=["x", "raw", "codes", "flags", "esc", "tbl", "row_esc", "kr"],
755
+ output_names=["y" if split == "none" else "part"],
756
+ source=source_r4_mma_regs(mt, split, wpb, slices=slices),
757
+ )
758
+ (out,) = _MMA[key](
759
+ inputs=[x, a["raw"], a["codes"], a["flags"], a["esc"], a["table"], a["row_esc"], kr],
760
+ template=[("M", M), ("N", N), ("K", K), ("T", T)],
761
+ grid=(-(-N // (8 * wpb)) * 32 * wpb, gy, S),
762
+ threadgroup=(32 * wpb, 1, 1),
763
+ output_shapes=[out_shape],
764
+ output_dtypes=[out_dtype],
765
+ )
766
+ return out if S == 1 else _split_reduce(out, M, N, S, split)
767
+ if tile is None and N % 2 == 0:
768
+ tile = "big128" # 128 x 128 tiles beat 256 x 128 at every length measured (two blocks per SM)
769
+ if tile in ("big128", "big256"):
770
+ bm = 128 if tile == "big128" else 256
771
+ key = ("big", bm, split, slices)
772
+ if key not in _MMA:
773
+ _MMA[key] = mx.fast.cuda_kernel(
774
+ name=f"binade_cuda_r4_mma_big{bm}_{split}{'_s%d' % slices if slices > 1 else ''}",
775
+ input_names=["x", "raw", "codes", "flags", "esc", "tbl", "row_esc", "kr"],
776
+ output_names=["y" if split == "none" else "part"],
777
+ source=source_r4_mma_big(split, bm, slices),
778
+ shared_memory=big_smem(bm),
779
+ )
780
+ (out,) = _MMA[key](
781
+ inputs=[x, a["raw"], a["codes"], a["flags"], a["esc"], a["table"], a["row_esc"], kr],
782
+ template=[("M", M), ("N", N), ("K", K), ("T", T)],
783
+ grid=(-(-M // bm) * 256, -(-N // 128), S),
784
+ threadgroup=(256, 1, 1),
785
+ output_shapes=[out_shape],
786
+ output_dtypes=[out_dtype],
787
+ )
788
+ return out if S == 1 else _split_reduce(out, M, N, S, split)
789
+ if slices != 1:
790
+ raise ValueError("the 64 x 64 kernel sums K in order only")
791
+ bm, bn, wm, wn = tile or mma_tile(M)
792
+ key = (bm, bn, wm, wn, split)
793
+ if key not in _MMA:
794
+ _MMA[key] = mx.fast.cuda_kernel(
795
+ name=f"binade_cuda_r4_mma_{bm}x{bn}_{wm}x{wn}_{split}",
796
+ input_names=["x", "raw", "codes", "flags", "esc", "tbl", "row_esc", "kr"],
797
+ output_names=["y" if split == "none" else "part"],
798
+ source=source_r4_mma(bm, bn, wm, wn, split),
799
+ )
800
+ (out,) = _MMA[key](
801
+ inputs=[x, a["raw"], a["codes"], a["flags"], a["esc"], a["table"], a["row_esc"], kr],
802
+ template=[("M", M), ("N", N), ("K", K), ("T", T)],
803
+ grid=(-(-N // bn) * 128, -(-M // bm), S),
804
+ threadgroup=(128, 1, 1),
805
+ output_shapes=[out_shape],
806
+ output_dtypes=[out_dtype],
807
+ )
808
+ return out if S == 1 else _split_reduce(out, M, N, S, split)
809
+
810
+
811
+ def r4_gather_mm(a: dict, x: mx.array, idx: mx.array, n: int, rs: int, r0: int, K: int) -> mx.array:
812
+ """[S, n] = rows of x [S, K] times storage rows idx[s] * rs + r0 .. + n, slots sorted by expert:
813
+ bit-identical to MLX's CUDA gather_mm(x, W.swapaxes(-1, -2), idx, sorted_indices=True), which
814
+ runs a CUTLASS grouped GEMM (per expert, m16n8k16 steps along K in order, no split-K) for
815
+ one-row slots. K % 64 == 0."""
816
+ S = int(idx.size)
817
+ per_expert = S / max(1, a["raw"].shape[0] // rs)
818
+ mt = 1 if per_expert <= 16 else 2 if per_expert <= 32 else 4
819
+ wpb = next(w for w in (8, 4, 2) if w == 2 or -(-n // (8 * w)) * -(-S // (16 * mt)) >= REGS_MIN_BLOCKS)
820
+ key = ("gather", mt, wpb)
821
+ if key not in _MMA:
822
+ _MMA[key] = mx.fast.cuda_kernel(
823
+ name=f"binade_cuda_r4_mma_gather{mt}_w{wpb}",
824
+ input_names=["x", "raw", "codes", "flags", "esc", "tbl", "row_esc", "kr", "idx"],
825
+ output_names=["y"],
826
+ source=source_r4_mma_regs(mt, "none", wpb, gather=True),
827
+ )
828
+ (y,) = _MMA[key](
829
+ inputs=[x.reshape(S, K), a["raw"], a["codes"], a["flags"], a["esc"], a["table"], a["row_esc"], _bounds((0, K)), _u32(idx)],
830
+ template=[("M", S), ("N", n), ("K", K), ("T", -(-K // TILE)), ("RS", rs), ("R0", r0)],
831
+ grid=(-(-n // (8 * wpb)) * 32 * wpb, -(-S // (16 * mt)), 1),
832
+ threadgroup=(32 * wpb, 1, 1),
833
+ output_shapes=[(S, n)],
834
+ output_dtypes=[mx.bfloat16],
835
+ )
836
+ return y
837
+
838
+
839
+ def _split_reduce(out: mx.array, M: int, N: int, S: int, split: str) -> mx.array:
840
+ if split not in _REDUCE:
841
+ _REDUCE[split] = mx.fast.cuda_kernel(name=f"binade_cuda_split_reduce_{split}", input_names=["part"], output_names=["y"], source=SOURCE_SPLIT_INPLACE if split == "inplace" else SOURCE_SPLIT_REDUCE)
842
+ (y,) = _REDUCE[split](
843
+ inputs=[out],
844
+ template=[("M", M), ("N", N), ("S", S)],
845
+ grid=(-(-(M * N) // 256) * 256, 1, 1),
846
+ threadgroup=(256, 1, 1),
847
+ output_shapes=[(M, N)],
848
+ output_dtypes=[mx.bfloat16],
849
+ )
850
+ return y
851
+
852
+
853
+ SOURCE_DECODE = """
854
+ // One warp per output row, lane l owning weights 4l..4l+3 of each tile: one 32-bit load of
855
+ // raw bytes and one 8-byte store of four BF16 values per lane and tile (rows of K weights,
856
+ // K % 4 == 0, keep both aligned); exponent table in shared memory.
857
+ __shared__ uint8_t lut[16];
858
+ if (threadIdx.x < 16) { lut[threadIdx.x] = tbl[threadIdx.x]; }
859
+ __syncthreads();
860
+ uint32_t lane = threadIdx.x % 32;
861
+ int orow = int(blockIdx.x) * 8 + int(threadIdx.x / 32);
862
+ if (orow >= N) { return; }
863
+ size_t row = size_t(orow / NB) * RS + R0 + size_t(orow % NB);
864
+ uint32_t epos = row_esc[row];
865
+ const uint32_t* rw = reinterpret_cast<const uint32_t*>(raw + row * K);
866
+ uint2* o = reinterpret_cast<uint2*>(out + size_t(orow) * K);
867
+ for (int t = 0; t < T; t++) {
868
+ bool in = t * 128 + int(lane) * 4 < K;
869
+ uint32_t f = flags[row * T + t];
870
+ uint32_t g4 = uint32_t(codes[(row * T + t) * 32 + lane]);
871
+ uint32_t r = in ? rw[t * 32 + lane] : 0u;
872
+ uint32_t c[4]; uint32_t e[4];
873
+ for (int j = 0; j < 4; j++) { c[j] = (g4 >> (4u * uint32_t(j))) & 15u; e[j] = lut[c[j]]; }
874
+ if (f) {
875
+ uint32_t cnt = 0;
876
+ for (int j = 0; j < 4; j++) { cnt += c[j] == 15u ? 1u : 0u; }
877
+ uint32_t incl = cnt;
878
+ for (int s = 1; s < 32; s <<= 1) { uint32_t v = __shfl_up_sync(0xffffffffu, incl, s); if (lane >= s) incl += v; }
879
+ uint32_t q = epos + incl - cnt;
880
+ for (int j = 0; j < 4; j++) { if (c[j] == 15u) { e[j] = esc[q]; q++; } }
881
+ epos += __shfl_sync(0xffffffffu, incl, 31);
882
+ }
883
+ if (in) {
884
+ uint32_t u[4];
885
+ for (int j = 0; j < 4; j++) {
886
+ uint32_t rj = (r >> (8u * uint32_t(j))) & 0xFFu;
887
+ u[j] = ((rj & 0x80u) << 8) | (e[j] << 7) | (rj & 0x7Fu);
888
+ }
889
+ o[t * 32 + lane] = make_uint2(u[0] | (u[1] << 16), u[2] | (u[3] << 16));
890
+ }
891
+ }
892
+ """
893
+
894
+ _DECODE = []
895
+
896
+
897
+ def r4_decode(raw, codes, flags, esc, table, row_esc, N: int, K: int, nb: int | None = None, rs: int | None = None, r0: int = 0) -> mx.array:
898
+ """BF16 weight [N, K] from R4 arrays; output row r is storage row (r // nb) * rs + r0 + r % nb."""
899
+ if not _DECODE:
900
+ _DECODE.append(
901
+ mx.fast.cuda_kernel(
902
+ name="binade_cuda_r4_decode",
903
+ input_names=["raw", "codes", "flags", "esc", "tbl", "row_esc"],
904
+ output_names=["out"],
905
+ source=SOURCE_DECODE,
906
+ )
907
+ )
908
+ (u,) = _DECODE[0](
909
+ inputs=[raw, codes, flags, esc, table, row_esc],
910
+ template=[("N", N), ("K", K), ("T", -(-K // TILE)), ("NB", nb or N), ("RS", rs or nb or N), ("R0", r0)],
911
+ grid=(-(-N // 8) * 256, 1, 1),
912
+ threadgroup=(256, 1, 1),
913
+ output_shapes=[(N, K)],
914
+ output_dtypes=[mx.bfloat16],
915
+ )
916
+ return u
917
+
918
+
919
+ SOURCE_RICE = """
920
+ uint32_t lane = threadIdx.x % 32;
921
+ int row = int(blockIdx.x) * 8 + int(threadIdx.x / 32);
922
+ if (row >= R) { return; }
923
+ unsigned long long cur = (unsigned long long)roff[row] * 32ull;
924
+ for (int t = 0; t < TN; t++) {
925
+ uint32_t m = meta[row * TN + t];
926
+ uint32_t k = m & 3u;
927
+ uint32_t qmax = m >> 2;
928
+ int n = min(128, K - t * 128);
929
+ uint32_t nv = uint32_t(max(0, min(4, n - int(lane) * 4)));
930
+ uint32_t lo = 0u;
931
+ uint32_t cnt0 = nv * k;
932
+ if (cnt0 > 0u) {
933
+ unsigned long long p = cur + (unsigned long long)(lane * 4u * k);
934
+ uint32_t w = uint32_t(p >> 5), s = uint32_t(p & 31ull);
935
+ lo = bits[w] >> s;
936
+ if (s + cnt0 > 32u) { lo |= bits[w + 1] << (32u - s); }
937
+ lo &= (1u << cnt0) - 1u;
938
+ }
939
+ cur += (unsigned long long)(uint32_t(n) * k);
940
+ uint32_t q[4] = {0u, 0u, 0u, 0u};
941
+ uint32_t alive = (1u << nv) - 1u;
942
+ for (uint32_t j = 0; j < qmax; j++) {
943
+ uint32_t c = __popc(alive);
944
+ uint32_t incl = c;
945
+ for (int o = 1; o < 32; o <<= 1) { uint32_t v = __shfl_up_sync(0xffffffffu, incl, o); if (lane >= o) incl += v; }
946
+ uint32_t pre = incl - c;
947
+ uint32_t tot = __shfl_sync(0xffffffffu, incl, 31);
948
+ uint32_t b = 0u;
949
+ if (c > 0u) {
950
+ unsigned long long p = cur + pre;
951
+ uint32_t w = uint32_t(p >> 5), s = uint32_t(p & 31ull);
952
+ b = bits[w] >> s;
953
+ if (s + c > 32u) { b |= bits[w + 1] << (32u - s); }
954
+ b &= (1u << c) - 1u;
955
+ }
956
+ uint32_t na = 0u, bi = 0u;
957
+ for (uint32_t i = 0; i < 4u; i++) {
958
+ if ((alive >> i) & 1u) { uint32_t v = (b >> bi) & 1u; q[i] += v; na |= v << i; bi++; }
959
+ }
960
+ alive = na;
961
+ cur += tot;
962
+ }
963
+ uint32_t mask = (1u << k) - 1u;
964
+ uint32_t packed = 0u;
965
+ for (uint32_t i = 0; i < 4u; i++) { packed |= ((q[i] << k) | ((lo >> (i * k)) & mask)) << (8u * i); }
966
+ out[((size_t)row * TN + t) * 32 + lane] = packed;
967
+ }
968
+ if (lane == 0) { rend[row] = uint32_t((cur + 31ull) >> 5); }
969
+ """
970
+
971
+ _RICE = []
972
+
973
+
974
+ def rice_ranks(meta: mx.array, bits: mx.array, roff: mx.array, K: int) -> tuple[mx.array, mx.array]:
975
+ """Same contract as rice_kernel.rice_ranks, on CUDA."""
976
+ if not _RICE:
977
+ _RICE.append(
978
+ mx.fast.cuda_kernel(
979
+ name="binade_cuda_rice_ranks",
980
+ input_names=["meta", "bits", "roff"],
981
+ output_names=["out", "rend"],
982
+ source=SOURCE_RICE,
983
+ )
984
+ )
985
+ R = roff.size
986
+ TN = -(-K // TILE)
987
+ u, rend = _RICE[0](
988
+ inputs=[meta, bits, roff],
989
+ template=[("R", R), ("K", K), ("TN", TN)],
990
+ grid=(-(-R // 8) * 256, 1, 1),
991
+ threadgroup=(256, 1, 1),
992
+ output_shapes=[(R * TN * 32,), (R,)],
993
+ output_dtypes=[mx.uint32, mx.uint32],
994
+ )
995
+ return u.view(mx.uint8).reshape(R, TN * TILE), rend