okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
41.2 KiB967 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// src/kernels/cuda/exl3_legacy.cu - v1.1.8's EXL3 decode kernels, kept for NVIDIA GPUs before sm_80 (V100, T4,
4// RTX 20): #180's decode kernels run the tiles on the tensor cores from sm_80 on, and their CUDA-core fallback was
5// slower here than these (a V100 with EXL3-3.05bpw: decode 4.9 -> 4.4 tok/s).  exl3.cu's mv / moe_gate_up / moe_down
6// / win_experts / prepare / several_ok call these on such a GPU (STRATA_GLM_EXL3_DECODE=legacy|new picks one on any
7// GPU); the prompt path is exl3.cu's on every GPU.  The code below is v1.1.8's as it was, the prompt path's kernels
8// left out.
9//
10// The codebooks and the trellis window arithmetic follow exllamav3 (MIT, turboderp - exllamav3_ext/quant/
11// codebook.cuh, exl3_dq.cuh, hadamard_inner.cuh); the kernels around them are shaped for this engine's decode:
12//
13//   * a block owns 128 outputs (8 tiles - exactly one output rotation block) over a slice of at most 4096 inputs;
14//     its 8 warps take the slice's 16-row tile rows in turn, each staging the row's 8 tiles in shared memory with
15//     coalesced loads and decoding 8 weights per lane (one fragment: 2 columns x 4 rows), F32 accumulation;
16//   * the input rotation runs per block on the slice it reads (F32 or q8_1 in, FP16 in shared memory), so the
17//     engine's activation buffers are used as they are;
18//   * a matrix with more than 4096 inputs, or too few output blocks to fill the device, splits its inputs over
19//     blocks: the partial sums go to a per-stream scratch and the LAST block of an output block adds them up in
20//     split order (deterministic) and runs the output rotation.
21#if !defined(STRATA_USE_HIP)   // (AMD runs exl3.cu's kernels; EXL3 does not run there anyway)
22#include "strata/dsv41/exl3.hpp"
23
24#include <cuda_fp16.h>
25#include <cuda_runtime.h>
26
27#include <algorithm>
28#include <atomic>
29#include <cstdio>
30#include <map>
31#include <mutex>
32#include <utility>
33
34namespace strata::dsv41k::exl3::legacy {
35namespace {
36
37constexpr int kThreads = 256, kWarps = 8;
38constexpr int kCols = 128;                // outputs per block: 8 tiles, one rotation block
39constexpr int kMaxKR = 4096;              // inputs per block (the rotated slice lives in shared memory)
40constexpr float kHad = 0.088388347648f;   // 1 / sqrt(128)
41
42struct Q81 {   // the engine's q8_1 block (ggml block_q8_1): d, sum, 32 int8
43    __half2 ds;
44    int8_t qs[32];
45};
46
47std::atomic<int> g_launch_errors{0};
48void launch_check(const char* what) {
49    const cudaError_t e = cudaGetLastError();
50    if (e != cudaSuccess) {
51        std::fprintf(stderr, "exl3 %s: %s\n", what, cudaGetErrorString(e));
52        g_launch_errors.fetch_add(1, std::memory_order_relaxed);
53    }
54}
55
56// ---------------------------------------------------------------- the codebooks
57__device__ __forceinline__ uint32_t bytesum_plus(uint32_t x, uint32_t acc) {
58#if defined(STRATA_USE_HIP)
59    return acc + (x & 0xffu) + ((x >> 8) & 0xffu) + ((x >> 16) & 0xffu) + (x >> 24);
60#else
61    return __dp4a(x, 0x01010101u, acc);
62#endif
63}
64
65// two states -> two values, FP16 arithmetic as exllamav3's decode_3inst_2 (the tensor-core kernels take the half2)
66template <int cb>
67__device__ __forceinline__ __half2 decode2h(uint32_t s0, uint32_t s1) {
68    if constexpr (cb == 2) {
69        const uint32_t a = bytesum_plus(s0 * 0x83DCD12Du, 0x6400u);
70        const uint32_t b = bytesum_plus(s1 * 0x83DCD12Du, 0x6400u);
71        const __half2 h = __halves2half2(__ushort_as_half((unsigned short) a), __ushort_as_half((unsigned short) b));
72        return __hfma2(h, __half2half2(__ushort_as_half(0x1eee)), __half2half2(__ushort_as_half(0xc931)));
73    } else {
74        uint32_t x0 = cb == 1 ? s0 * 0xCBAC1FEDu : s0 * 89226354u + 64248484u;
75        uint32_t x1 = cb == 1 ? s1 * 0xCBAC1FEDu : s1 * 89226354u + 64248484u;
76        x0 = (x0 & 0x8fff8fffu) ^ 0x3b603b60u;
77        x1 = (x1 & 0x8fff8fffu) ^ 0x3b603b60u;
78        const __half2 lo = __halves2half2(__ushort_as_half((unsigned short) (x0 & 0xffffu)),
79                                          __ushort_as_half((unsigned short) (x1 & 0xffffu)));
80        const __half2 hi = __halves2half2(__ushort_as_half((unsigned short) (x0 >> 16)),
81                                          __ushort_as_half((unsigned short) (x1 >> 16)));
82        return __hadd2(lo, hi);
83    }
84}
85template <int cb>
86__device__ __forceinline__ float2 decode2(uint32_t s0, uint32_t s1) {
87    return __half22float2(decode2h<cb>(s0, s1));
88}
89
90// step p's state: the 16-bit window ending at bit (p + 1) K of the tile's MSB-first bit stream (w: its 8 K words),
91// wrapping around the tile (the + 256 K keeps the start non-negative)
92template <int K>
93__device__ __forceinline__ uint32_t state_at(const uint32_t* w, int p) {
94    constexpr int W = 8 * K;
95    const int b1 = (p + 1 + 256) * K;
96    const int i1 = (b1 - 1) >> 5, i0 = (b1 - 16) >> 5;
97    const int sh = ((i1 + 1) << 5) - b1;
98    const uint64_t m = ((uint64_t) w[i0 % W] << 32) | (uint64_t) w[i1 % W];
99    return (uint32_t) (m >> sh) & 0xffffu;
100}
101
102// lane's 8 steps (lane * 8 + j): v[j] sits at tile row (lane & 3) * 2 + (j & 1) + 8 (j >> 1 & 1), column
103// (lane >> 2) + 8 (j >> 2)
104template <int K, int cb>
105__device__ __forceinline__ void decode8(const uint32_t* w, int lane, float* v) {
106    const int p0 = lane * 8;
107#pragma unroll
108    for (int j = 0; j < 8; j += 2) {
109        const float2 d = decode2<cb>(state_at<K>(w, p0 + j), state_at<K>(w, p0 + j + 1));
110        v[j] = d.x;
111        v[j + 1] = d.y;
112    }
113}
114
115// ---------------------------------------------------------------- the rotation
116// the 128-point transform of the 128 values a warp holds 4 per lane (value lane * 4 + i), over sqrt(128)
117__device__ __forceinline__ void had128(float* v, int lane) {
118    const float s0 = v[0] + v[1], d0 = v[0] - v[1], s1 = v[2] + v[3], d1 = v[2] - v[3];
119    v[0] = s0 + s1;
120    v[1] = d0 + d1;
121    v[2] = s0 - s1;
122    v[3] = d0 - d1;
123#pragma unroll
124    for (int m = 1; m < 32; m <<= 1) {
125#pragma unroll
126        for (int i = 0; i < 4; ++i) {
127            const float o = __shfl_xor_sync(0xffffffffu, v[i], m);
128            v[i] = (lane & m) ? o - v[i] : v[i] + o;
129        }
130    }
131#pragma unroll
132    for (int i = 0; i < 4; ++i) v[i] *= kHad;
133}
134
135__device__ __forceinline__ float h2f(uint16_t b) { return __half2float(__ushort_as_half(b)); }
136
137// xs[i] = H(x * suh)[k0 + i] for i < kr (kr % 128 == 0); x from xf (F32) or xq (q8_1); every warp of the block
138__device__ void rotate_in(const float* __restrict__ xf, const Q81* __restrict__ xq, const uint16_t* __restrict__ suh,
139                          int k0, int kr, __half* xs) {
140    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
141    for (int c = warp; c < kr / 128; c += kWarps) {
142        const int base = k0 + c * 128 + lane * 4;
143        float v[4];
144        if (xf != nullptr) {
145#pragma unroll
146            for (int i = 0; i < 4; ++i) v[i] = xf[base + i];
147        } else {
148            const Q81* b = xq + base / 32;
149            const float d = __low2float(b->ds);
150#pragma unroll
151            for (int i = 0; i < 4; ++i) v[i] = d * (float) b->qs[base % 32 + i];
152        }
153#pragma unroll
154        for (int i = 0; i < 4; ++i) v[i] *= h2f(suh[base + i]);
155        had128(v, lane);
156#pragma unroll
157        for (int i = 0; i < 4; ++i) xs[c * 128 + lane * 4 + i] = __float2half_rn(v[i]);
158    }
159}
160
161// ---------------------------------------------------------------- the block GEMV
162// a lane's 4 weights of one column times the activation's 4 inputs, added to a: the rounding spelled out, so the
163// one-activation and the several-activation GEMVs (block_gemv, block_gemv_n) give each activation the same bits
164__device__ __forceinline__ float dot4_acc(float a, const float* v, float x0, float x1, float x2, float x3) {
165    return __fadd_rn(a, __fmaf_rn(v[3], x3, __fmaf_rn(v[2], x2, __fmaf_rn(v[1], x1, __fmul_rn(v[0], x0)))));
166}
167
168// red[c] (c < 128) = sum over the 16-row slices [ks0, ks1) of x' . W'[:, tc0 * 16 + c], x' = xs from slice ks0 on.
169// tr: the matrix's first tile, ld tiles per slice row.  stage: kWarps * 64 K words, red: kWarps * 128 floats.
170// Ends with a __syncthreads (red[0..127] complete).
171template <int K, int cb>
172__device__ void block_gemv(const uint32_t* __restrict__ tr, int ld, int tc0, int ks0, int ks1, const __half* xs,
173                           uint32_t* stage, float* red) {
174    constexpr int W = 8 * K, TW = 8 * W;
175    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
176    uint32_t* st = stage + warp * TW;
177    float acc[8][2];
178#pragma unroll
179    for (int t = 0; t < 8; ++t) acc[t][0] = acc[t][1] = 0.0f;
180    const int kk = (lane & 3) * 2;
181    for (int ks = ks0 + warp; ks < ks1; ks += kWarps) {
182        const uint32_t* src = tr + ((size_t) ks * ld + tc0) * W;
183        __syncwarp();
184#pragma unroll
185        for (int i = lane; i < TW; i += 32) st[i] = src[i];
186        __syncwarp();
187        const __half* xk = xs + (ks - ks0) * 16;
188        const float x0 = __half2float(xk[kk]), x1 = __half2float(xk[kk + 1]);
189        const float x2 = __half2float(xk[kk + 8]), x3 = __half2float(xk[kk + 9]);
190#pragma unroll
191        for (int t = 0; t < 8; ++t) {
192            float v[8];
193            decode8<K, cb>(st + t * W, lane, v);
194            acc[t][0] = dot4_acc(acc[t][0], v, x0, x1, x2, x3);
195            acc[t][1] = dot4_acc(acc[t][1], v + 4, x0, x1, x2, x3);
196        }
197    }
198    // the 4 lanes of one lane / 4 hold the same two columns of every tile
199#pragma unroll
200    for (int t = 0; t < 8; ++t)
201#pragma unroll
202        for (int c = 0; c < 2; ++c) {
203            acc[t][c] += __shfl_xor_sync(0xffffffffu, acc[t][c], 1);
204            acc[t][c] += __shfl_xor_sync(0xffffffffu, acc[t][c], 2);
205        }
206    if ((lane & 3) == 0)
207#pragma unroll
208        for (int t = 0; t < 8; ++t) {
209            red[warp * kCols + t * 16 + (lane >> 2)] = acc[t][0];
210            red[warp * kCols + t * 16 + 8 + (lane >> 2)] = acc[t][1];
211        }
212    __syncthreads();
213    if (threadIdx.x < kCols) {
214        float s = 0.0f;
215#pragma unroll
216        for (int w = 0; w < kWarps; ++w) s += red[w * kCols + threadIdx.x];
217        red[threadIdx.x] = s;
218    }
219    __syncthreads();
220}
221
222// block_gemv for nc activations at once (nc <= kNC; activation c's rotated slice at xs + c * kMaxKR): each lane decodes
223// its 8 weights of a tile once and adds them into every activation's sums - as exllamav3's small-m GEMV and fused MoE
224// kernels share a tile's decode among the rows of an MMA, but with block_gemv's own F32 arithmetic, so outc[c * 128 +
225// i] (i < 128) is bit for bit block_gemv's red[i] for activation c alone.  Ends with a __syncthreads.
226constexpr int kNC = 4;
227template <int K, int cb>
228__device__ void block_gemv_n(const uint32_t* __restrict__ tr, int ld, int tc0, int ks0, int ks1, const __half* xs,
229                             int nc, uint32_t* stage, float* red, float* outc) {
230    constexpr int W = 8 * K, TW = 8 * W;
231    const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
232    uint32_t* st = stage + warp * TW;
233    float acc[kNC][8][2];
234#pragma unroll
235    for (int c = 0; c < kNC; ++c)
236#pragma unroll
237        for (int t = 0; t < 8; ++t) acc[c][t][0] = acc[c][t][1] = 0.0f;
238    const int kk = (lane & 3) * 2;
239    for (int ks = ks0 + warp; ks < ks1; ks += kWarps) {
240        const uint32_t* src = tr + ((size_t) ks * ld + tc0) * W;
241        __syncwarp();
242#pragma unroll
243        for (int i = lane; i < TW; i += 32) st[i] = src[i];
244        __syncwarp();
245        float x[kNC][4];
246#pragma unroll
247        for (int c = 0; c < kNC; ++c) {
248            const __half* xk = xs + c * kMaxKR + (ks - ks0) * 16;
249            if (c < nc) {
250                x[c][0] = __half2float(xk[kk]);
251                x[c][1] = __half2float(xk[kk + 1]);
252                x[c][2] = __half2float(xk[kk + 8]);
253                x[c][3] = __half2float(xk[kk + 9]);
254            }
255        }
256#pragma unroll
257        for (int t = 0; t < 8; ++t) {
258            float v[8];
259            decode8<K, cb>(st + t * W, lane, v);
260#pragma unroll
261            for (int c = 0; c < kNC; ++c)
262                if (c < nc) {
263                    acc[c][t][0] = dot4_acc(acc[c][t][0], v, x[c][0], x[c][1], x[c][2], x[c][3]);
264                    acc[c][t][1] = dot4_acc(acc[c][t][1], v + 4, x[c][0], x[c][1], x[c][2], x[c][3]);
265                }
266        }
267    }
268    // per activation, block_gemv's reduction
269#pragma unroll
270    for (int c = 0; c < kNC; ++c) {
271        if (c >= nc) break;
272#pragma unroll
273        for (int t = 0; t < 8; ++t)
274#pragma unroll
275            for (int h = 0; h < 2; ++h) {
276                acc[c][t][h] += __shfl_xor_sync(0xffffffffu, acc[c][t][h], 1);
277                acc[c][t][h] += __shfl_xor_sync(0xffffffffu, acc[c][t][h], 2);
278            }
279        if ((lane & 3) == 0)
280#pragma unroll
281            for (int t = 0; t < 8; ++t) {
282                red[warp * kCols + t * 16 + (lane >> 2)] = acc[c][t][0];
283                red[warp * kCols + t * 16 + 8 + (lane >> 2)] = acc[c][t][1];
284            }
285        __syncthreads();
286        if (threadIdx.x < kCols) {
287            float s = 0.0f;
288#pragma unroll
289            for (int w = 0; w < kWarps; ++w) s += red[w * kCols + threadIdx.x];
290            outc[c * kCols + threadIdx.x] = s;
291        }
292        __syncthreads();
293    }
294}
295
296// one warp: y[c] = alpha * (H(red) * svh)[c] + bias[c] for the block's 128 outputs
297__device__ __forceinline__ void epilogue(const float* red, const uint16_t* svh, float alpha, const float* bias,
298                                         float* y) {
299    const int lane = threadIdx.x & 31;
300    float v[4];
301#pragma unroll
302    for (int i = 0; i < 4; ++i) v[i] = red[lane * 4 + i];
303    had128(v, lane);
304#pragma unroll
305    for (int i = 0; i < 4; ++i) {
306        const int c = lane * 4 + i;
307        y[c] = __fmaf_rn(__fmul_rn(alpha, v[i]), h2f(svh[c]), bias != nullptr ? bias[c] : 0.0f);
308    }
309}
310
311// ---------------------------------------------------------------- mv
312struct KJob {
313    const uint32_t* tr;
314    const uint16_t* suh;
315    const uint16_t* svh;
316    const float* xf;
317    const Q81* xq;
318    float* y;
319    const float* bias;
320    float* part;       // S x n partial sums (S > 1); mv_n_kernel: nc x S x n
321    unsigned* cnt;     // n / 128 counters, zero between launches
322    float alpha;
323    int k, n, ld, S, kr;
324    int nc;            // mv_n_kernel: the activations (1..kNC), xf / xq / y advanced by these per activation
325    size_t xf_cs, xq_cs, y_cs;   // (floats, bytes, floats)
326};
327struct KBatch {
328    KJob j[kMaxMvJobs];
329    int blk_end[kMaxMvJobs];
330    int n;
331};
332
333// the dynamic shared memory of the several-activation kernels (mv_n_kernel, win_gu_kernel, win_down_kernel):
334// red[kWarps][128] outc[kNC][128] gu[2][kNC][128] (F32), stage[kWarps * 64 K] (words), xs[kNC][kMaxKR] (FP16) - up to
335// 58 KB, past the 48 KB a launch gets without asking (set_smem)
336constexpr size_t smem_n_bytes(int K) {
337    return (size_t) (kWarps * kCols + kNC * kCols + 2 * kNC * kCols) * 4 + (size_t) kWarps * 64 * K * 4 +
338           (size_t) kNC * kMaxKR * 2;
339}
340struct SmemN {
341    float *red, *outc, *gu;
342    uint32_t* stage;
343    __half* xs;
344};
345template <int K>
346__device__ __forceinline__ SmemN smem_n(unsigned char* p) {
347    SmemN s;
348    s.red = (float*) p;
349    s.outc = s.red + kWarps * kCols;
350    s.gu = s.outc + kNC * kCols;
351    s.stage = (uint32_t*) (s.gu + 2 * kNC * kCols);
352    s.xs = (__half*) (s.stage + kWarps * 64 * K);
353    return s;
354}
355
356template <int K, int cb>
357__global__ void __launch_bounds__(kThreads) mv_kernel(const KBatch b) {
358    __shared__ __half xs[kMaxKR];
359    __shared__ uint32_t stage[kWarps * 64 * K];
360    __shared__ float red[kWarps * kCols];
361    __shared__ int last;
362    int ji = 0;
363    while ((int) blockIdx.x >= b.blk_end[ji]) ++ji;
364    const KJob& J = b.j[ji];
365    const int local = (int) blockIdx.x - (ji > 0 ? b.blk_end[ji - 1] : 0);
366    const int g = local / J.S, sp = local % J.S;
367    const int k0 = sp * J.kr, k1 = min(J.k, k0 + J.kr);
368    rotate_in(J.xf, J.xq, J.suh, k0, k1 - k0, xs);
369    __syncthreads();
370    block_gemv<K, cb>(J.tr, J.ld, g * 8, k0 / 16, k1 / 16, xs, stage, red);
371    const int warp = threadIdx.x >> 5;
372    if (J.S == 1) {
373        if (warp == 0)
374            epilogue(red, J.svh + g * kCols, J.alpha, J.bias != nullptr ? J.bias + g * kCols : nullptr,
375                     J.y + g * kCols);
376        return;
377    }
378    if (threadIdx.x < kCols) J.part[(size_t) sp * J.n + g * kCols + threadIdx.x] = red[threadIdx.x];
379    __threadfence();
380    __syncthreads();
381    if (threadIdx.x == 0) last = atomicAdd(&J.cnt[g], 1u) == (unsigned) (J.S - 1);
382    __syncthreads();
383    if (!last) return;
384    __threadfence();
385    if (threadIdx.x < kCols) {
386        float s = 0.0f;
387        for (int i = 0; i < J.S; ++i) s += *(volatile const float*) &J.part[(size_t) i * J.n + g * kCols + threadIdx.x];
388        red[threadIdx.x] = s;
389    }
390    __syncthreads();
391    if (warp == 0)
392        epilogue(red, J.svh + g * kCols, J.alpha, J.bias != nullptr ? J.bias + g * kCols : nullptr, J.y + g * kCols);
393    if (threadIdx.x == 0) J.cnt[g] = 0u;
394}
395
396// mv_kernel for a job's nc activations at once (a verify window's tokens): the same input split, the weights read and
397// decoded once for all of them (block_gemv_n), each activation's partials and sums in mv_kernel's order - every
398// activation's y is mv_kernel's for it alone, bit for bit
399template <int K, int cb>
400__global__ void __launch_bounds__(kThreads) mv_n_kernel(const KBatch b) {
401    extern __shared__ __align__(16) unsigned char smem_raw[];
402    const SmemN sm = smem_n<K>(smem_raw);
403    __shared__ int last;
404    int ji = 0;
405    while ((int) blockIdx.x >= b.blk_end[ji]) ++ji;
406    const KJob& J = b.j[ji];
407    const int local = (int) blockIdx.x - (ji > 0 ? b.blk_end[ji - 1] : 0);
408    const int g = local / J.S, sp = local % J.S;
409    const int k0 = sp * J.kr, k1 = min(J.k, k0 + J.kr);
410    for (int c = 0; c < J.nc; ++c)
411        rotate_in(J.xf != nullptr ? J.xf + c * J.xf_cs : nullptr,
412                  J.xq != nullptr ? (const Q81*) ((const uint8_t*) J.xq + c * J.xq_cs) : nullptr, J.suh, k0, k1 - k0,
413                  sm.xs + c * kMaxKR);
414    __syncthreads();
415    block_gemv_n<K, cb>(J.tr, J.ld, g * 8, k0 / 16, k1 / 16, sm.xs, J.nc, sm.stage, sm.red, sm.outc);
416    const int warp = threadIdx.x >> 5;
417    const float* bias = J.bias != nullptr ? J.bias + g * kCols : nullptr;
418    if (J.S == 1) {
419        if (warp < J.nc)
420            epilogue(sm.outc + warp * kCols, J.svh + g * kCols, J.alpha, bias, J.y + warp * J.y_cs + g * kCols);
421        return;
422    }
423    if (threadIdx.x < kCols)
424        for (int c = 0; c < J.nc; ++c)
425            J.part[((size_t) c * J.S + sp) * J.n + g * kCols + threadIdx.x] = sm.outc[c * kCols + threadIdx.x];
426    __threadfence();
427    __syncthreads();
428    if (threadIdx.x == 0) last = atomicAdd(&J.cnt[g], 1u) == (unsigned) (J.S - 1);
429    __syncthreads();
430    if (!last) return;
431    __threadfence();
432    if (threadIdx.x < kCols)
433        for (int c = 0; c < J.nc; ++c) {
434            float s = 0.0f;
435            for (int i = 0; i < J.S; ++i)
436                s += *(volatile const float*) &J.part[((size_t) c * J.S + i) * J.n + g * kCols + threadIdx.x];
437            sm.outc[c * kCols + threadIdx.x] = s;
438        }
439    __syncthreads();
440    if (warp < J.nc) epilogue(sm.outc + warp * kCols, J.svh + g * kCols, J.alpha, bias, J.y + warp * J.y_cs + g * kCols);
441    if (threadIdx.x == 0) J.cnt[g] = 0u;
442}
443
444// ---------------------------------------------------------------- the routed experts
445struct KMoe {
446    const unsigned long long* plan_ptr;
447    const float* plan_w;
448    const float* cpu_part;
449    const int* cpu_flag;
450    const float* x;
451    float* h;            // [k][n_ff]
452    const float* sh_out;
453    float* out;
454    float* part;         // [k][n_embd]
455    unsigned* cnt;       // n_embd / 128
456    size_t suh[3], svh[3], tr[3];
457    int k, n_embd, n_ff;
458    float limit;
459};
460
461// the pieces the token's experts (moe_*_kernel) and a window's grouped experts (win_*_kernel) share, so each window
462// token gets the token path's bits: one warp's output block of 128 (H, then svh) ...
463__device__ __forceinline__ void block_out(const float* red, const uint16_t* svh, float* dst) {
464    const int lane = threadIdx.x & 31;
465    float v[4];
466#pragma unroll
467    for (int i = 0; i < 4; ++i) v[i] = red[lane * 4 + i];
468    had128(v, lane);
469#pragma unroll
470    for (int i = 0; i < 4; ++i) dst[lane * 4 + i] = __fmul_rn(v[i], h2f(svh[lane * 4 + i]));
471}
472// ... the clamped swiglu ...
473__device__ __forceinline__ float swiglu(float gv, float uv, float limit) {
474    if (limit > 0.0f) {
475        gv = fminf(gv, limit);
476        uv = fminf(fmaxf(uv, -limit), limit);
477    }
478    return __fmul_rn(__fdiv_rn(gv, __fadd_rn(1.0f, expf(-gv))), uv);
479}
480// ... and one output's sum: the experts' rows in plan order (p[i]: expert i's, 0 for one not on the device), the CPU
481// lane's part when flagged (cpu_part: null when not), the shared expert's row (sh: 0 without one)
482__device__ __forceinline__ float combine(const float* plan_w, const float* p, int k, const float* cpu_part, float sh) {
483    float m = 0.0f;
484    for (int i = 0; i < k; ++i) m = __fmaf_rn(plan_w[i], p[i], m);
485    if (cpu_part != nullptr) m = __fadd_rn(m, *cpu_part);
486    return __fadd_rn(m, sh);
487}
488
489// grid (n_ff / 128, k): expert blockIdx.y's gate and up for 128 h values, then the clamped swiglu
490template <int K, int cb>
491__global__ void __launch_bounds__(kThreads) moe_gate_up_kernel(const KMoe a) {
492    __shared__ __half xs[2][kMaxKR];
493    __shared__ uint32_t stage[kWarps * 64 * K];
494    __shared__ float red[kWarps * kCols];
495    __shared__ float gu[2][kCols];
496    const int ei = blockIdx.y, g = blockIdx.x;
497    const unsigned long long ptr = a.plan_ptr[ei];
498    if (ptr == 0ull) return;
499    const uint8_t* blob = (const uint8_t*) ptr;
500    const int warp = threadIdx.x >> 5;
501    for (int r = 0; r < 2; ++r) rotate_in(a.x, nullptr, (const uint16_t*) (blob + a.suh[r]), 0, a.n_embd, xs[r]);
502    __syncthreads();
503    for (int r = 0; r < 2; ++r) {
504        block_gemv<K, cb>((const uint32_t*) (blob + a.tr[r]), a.n_ff / 16, g * 8, 0, a.n_embd / 16, xs[r], stage, red);
505        if (warp == 0) block_out(red, (const uint16_t*) (blob + a.svh[r]) + g * kCols, gu[r]);
506        __syncthreads();
507    }
508    if (threadIdx.x < kCols)
509        a.h[(size_t) ei * a.n_ff + g * kCols + threadIdx.x] = swiglu(gu[0][threadIdx.x], gu[1][threadIdx.x], a.limit);
510}
511
512// grid (n_embd / 128, k): expert blockIdx.y's down rows for 128 outputs; the last block of each output block adds
513// the experts up in plan order (as the engine's moe_down), then the CPU lane's part and the shared expert
514template <int K, int cb>
515__global__ void __launch_bounds__(kThreads) moe_down_kernel(const KMoe a) {
516    __shared__ __half xs[kMaxKR];
517    __shared__ uint32_t stage[kWarps * 64 * K];
518    __shared__ float red[kWarps * kCols];
519    __shared__ int last;
520    const int ei = blockIdx.y, g = blockIdx.x;
521    const unsigned long long ptr = a.plan_ptr[ei];
522    const int warp = threadIdx.x >> 5;
523    float* part = a.part + (size_t) ei * a.n_embd + g * kCols;
524    if (ptr != 0ull) {
525        const uint8_t* blob = (const uint8_t*) ptr;
526        rotate_in(a.h + (size_t) ei * a.n_ff, nullptr, (const uint16_t*) (blob + a.suh[2]), 0, a.n_ff, xs);
527        __syncthreads();
528        block_gemv<K, cb>((const uint32_t*) (blob + a.tr[2]), a.n_embd / 16, g * 8, 0, a.n_ff / 16, xs, stage, red);
529        if (warp == 0) block_out(red, (const uint16_t*) (blob + a.svh[2]) + g * kCols, part);
530    } else if (threadIdx.x < kCols) {
531        part[threadIdx.x] = 0.0f;
532    }
533    __threadfence();
534    __syncthreads();
535    if (threadIdx.x == 0) last = atomicAdd(&a.cnt[g], 1u) == (unsigned) (a.k - 1);
536    __syncthreads();
537    if (!last) return;
538    __threadfence();
539    if (threadIdx.x < kCols) {
540        const int r = g * kCols + threadIdx.x;
541        float p[8];
542        for (int i = 0; i < a.k; ++i) p[i] = *(volatile const float*) &a.part[(size_t) i * a.n_embd + r];
543        a.out[r] = combine(a.plan_w, p, a.k, a.cpu_flag != nullptr && *a.cpu_flag ? a.cpu_part + r : nullptr,
544                           a.sh_out != nullptr ? a.sh_out[r] : 0.0f);
545    }
546    if (threadIdx.x == 0) a.cnt[g] = 0u;
547}
548
549// ---------------------------------------------------------------- a verify window's routed experts
550// gf::moe_win_experts' grouping (group g: one expert, its blob at grp_ptr[g]; its entries e = t * 8 + i at
551// grp_ent[grp_start[g] ..)), each group's weights read and decoded once for up to kNC of its tokens at a time (as
552// exllamav3's fused MoE runs a run of slots that picked one expert as the rows of one MMA tile), with the token
553// path's arithmetic per entry: every token's output is moe_gate_up + moe_down's for it alone, bit for bit
554struct KWin {
555    const unsigned long long* grp_ptr;
556    const int *grp_start, *grp_ent, *n_groups;
557    const unsigned long long* plan_ptr;
558    const float* plan_w;
559    const float* cpu_part;
560    const int* cpu_flag;
561    const float* x;
562    size_t x_stride;
563    float* h;            // [T * 8][n_ff]
564    float* part;         // [T * 8][n_embd]
565    const float* sh_out; // [T][n_embd]
566    float* out;
567    size_t out_stride;
568    size_t suh[3], svh[3], tr[3];
569    int k, n_embd, n_ff;
570    float limit;
571};
572
573// grid (n_ff / 128, groups at most): group blockIdx.y's gate and up for 128 h values of each entry, the clamped swiglu
574template <int K, int cb>
575__global__ void __launch_bounds__(kThreads) win_gu_kernel(const KWin a) {
576    extern __shared__ __align__(16) unsigned char smem_raw[];
577    const SmemN sm = smem_n<K>(smem_raw);
578    const int grp = blockIdx.y, g = blockIdx.x;
579    if (grp >= *a.n_groups) return;
580    const uint8_t* blob = (const uint8_t*) a.grp_ptr[grp];
581    const int warp = threadIdx.x >> 5;
582    const int m1 = a.grp_start[grp + 1];
583    for (int m0 = a.grp_start[grp]; m0 < m1; m0 += kNC) {
584        const int nc = min(kNC, m1 - m0);
585        for (int r = 0; r < 2; ++r) {
586            for (int c = 0; c < nc; ++c)
587                rotate_in(a.x + (size_t) (a.grp_ent[m0 + c] >> 3) * a.x_stride, nullptr,
588                          (const uint16_t*) (blob + a.suh[r]), 0, a.n_embd, sm.xs + c * kMaxKR);
589            __syncthreads();
590            block_gemv_n<K, cb>((const uint32_t*) (blob + a.tr[r]), a.n_ff / 16, g * 8, 0, a.n_embd / 16, sm.xs, nc,
591                                sm.stage, sm.red, sm.outc);
592            if (warp < nc)
593                block_out(sm.outc + warp * kCols, (const uint16_t*) (blob + a.svh[r]) + g * kCols,
594                          sm.gu + (r * kNC + warp) * kCols);
595            __syncthreads();
596        }
597        if (threadIdx.x < kCols)
598            for (int c = 0; c < nc; ++c)
599                a.h[(size_t) a.grp_ent[m0 + c] * a.n_ff + g * kCols + threadIdx.x] =
600                    swiglu(sm.gu[c * kCols + threadIdx.x], sm.gu[(kNC + c) * kCols + threadIdx.x], a.limit);
601        __syncthreads();
602    }
603}
604
605// grid (n_embd / 128, groups at most): group blockIdx.y's down rows for 128 outputs of each entry into its part rows
606template <int K, int cb>
607__global__ void __launch_bounds__(kThreads) win_down_kernel(const KWin a) {
608    extern __shared__ __align__(16) unsigned char smem_raw[];
609    const SmemN sm = smem_n<K>(smem_raw);
610    const int grp = blockIdx.y, g = blockIdx.x;
611    if (grp >= *a.n_groups) return;
612    const uint8_t* blob = (const uint8_t*) a.grp_ptr[grp];
613    const int warp = threadIdx.x >> 5;
614    const int m1 = a.grp_start[grp + 1];
615    for (int m0 = a.grp_start[grp]; m0 < m1; m0 += kNC) {
616        const int nc = min(kNC, m1 - m0);
617        for (int c = 0; c < nc; ++c)
618            rotate_in(a.h + (size_t) a.grp_ent[m0 + c] * a.n_ff, nullptr, (const uint16_t*) (blob + a.suh[2]), 0,
619                      a.n_ff, sm.xs + c * kMaxKR);
620        __syncthreads();
621        block_gemv_n<K, cb>((const uint32_t*) (blob + a.tr[2]), a.n_embd / 16, g * 8, 0, a.n_ff / 16, sm.xs, nc,
622                            sm.stage, sm.red, sm.outc);
623        if (warp < nc)
624            block_out(sm.outc + warp * kCols, (const uint16_t*) (blob + a.svh[2]) + g * kCols,
625                      a.part + (size_t) a.grp_ent[m0 + warp] * a.n_embd + g * kCols);
626        __syncthreads();
627    }
628}
629
630// grid (n_embd / 128, T): each token's outputs, moe_down_kernel's combine (an entry off the device adds 0)
631__global__ void __launch_bounds__(kCols) win_combine_kernel(const KWin a) {
632    const int t = blockIdx.y, r = blockIdx.x * kCols + threadIdx.x;
633    float p[8];
634    for (int i = 0; i < a.k; ++i) {
635        const int e = t * 8 + i;
636        p[i] = a.plan_ptr[e] != 0ull ? a.part[(size_t) e * a.n_embd + r] : 0.0f;
637    }
638    a.out[(size_t) t * a.out_stride + r] =
639        combine(a.plan_w + t * 8, p, a.k, a.cpu_flag[t] ? a.cpu_part + (size_t) t * a.n_embd + r : nullptr,
640                a.sh_out != nullptr ? a.sh_out[(size_t) t * a.n_embd + r] : 0.0f);
641}
642
643// ---------------------------------------------------------------- dispatch
644// F(K, cb) for K 1..8 and the three codebooks
645template <template <int, int> class F, typename... A>
646bool dispatch(int K, int cb, A&&... args) {
647#define EXL3_CASE(KK)                                                    \
648    case KK:                                                             \
649        if (cb == 2) F<KK, 2>::run(std::forward<A>(args)...);            \
650        else if (cb == 1) F<KK, 1>::run(std::forward<A>(args)...);       \
651        else F<KK, 0>::run(std::forward<A>(args)...);                    \
652        return true;
653    switch (K) {
654        EXL3_CASE(1) EXL3_CASE(2) EXL3_CASE(3) EXL3_CASE(4) EXL3_CASE(5) EXL3_CASE(6) EXL3_CASE(7) EXL3_CASE(8)
655        default: return false;
656    }
657#undef EXL3_CASE
658}
659
660template <int K, int cb> struct RunMv {
661    static void run(const KBatch& b, int blocks, cudaStream_t s) { mv_kernel<K, cb><<<blocks, kThreads, 0, s>>>(b); }
662};
663template <int K, int cb> struct RunMvN {
664    static void run(const KBatch& b, int blocks, cudaStream_t s) {
665        mv_n_kernel<K, cb><<<blocks, kThreads, smem_n_bytes(K), s>>>(b);
666    }
667};
668template <int K, int cb> struct RunWin {
669    static void run(const KWin& a, int groups, cudaStream_t s) {
670        win_gu_kernel<K, cb><<<dim3((unsigned) (a.n_ff / kCols), (unsigned) groups), kThreads, smem_n_bytes(K), s>>>(a);
671    }
672};
673template <int K, int cb> struct RunWinDown {
674    static void run(const KWin& a, int groups, cudaStream_t s) {
675        win_down_kernel<K, cb><<<dim3((unsigned) (a.n_embd / kCols), (unsigned) groups), kThreads, smem_n_bytes(K),
676                                 s>>>(a);
677    }
678};
679template <int K, int cb> struct AllowSmemN {
680    static void run() {
681        const int b = (int) smem_n_bytes(K);
682        cudaFuncSetAttribute(mv_n_kernel<K, cb>, cudaFuncAttributeMaxDynamicSharedMemorySize, b);
683        cudaFuncSetAttribute(win_gu_kernel<K, cb>, cudaFuncAttributeMaxDynamicSharedMemorySize, b);
684        cudaFuncSetAttribute(win_down_kernel<K, cb>, cudaFuncAttributeMaxDynamicSharedMemorySize, b);
685    }
686};
687template <int K, int cb> struct RunGU {
688    static void run(const KMoe& a, cudaStream_t s) {
689        moe_gate_up_kernel<K, cb><<<dim3((unsigned) (a.n_ff / kCols), (unsigned) a.k), kThreads, 0, s>>>(a);
690    }
691};
692template <int K, int cb> struct RunDown {
693    static void run(const KMoe& a, cudaStream_t s) {
694        moe_down_kernel<K, cb><<<dim3((unsigned) (a.n_embd / kCols), (unsigned) a.k), kThreads, 0, s>>>(a);
695    }
696};
697// ---------------------------------------------------------------- per-stream scratch
698constexpr size_t kPartFloats = (size_t) 2 << 20;   // split partials: 8 MB
699constexpr size_t kCounters = 16384;
700constexpr size_t kHFloats = (size_t) 8 * 8192;     // the experts' h
701struct Scratch {
702    float* part = nullptr;
703    unsigned* cnt = nullptr;
704    float* h = nullptr;
705};
706std::mutex g_mu;
707std::map<std::pair<int, cudaStream_t>, Scratch> g_scratch;
708
709Scratch* scratch(cudaStream_t s) {
710    int dev = 0;
711    cudaGetDevice(&dev);
712    std::lock_guard<std::mutex> lk(g_mu);
713    auto it = g_scratch.find({dev, s});
714    if (it != g_scratch.end()) return &it->second;
715    cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone;
716    if (cudaStreamIsCapturing(s, &cs) == cudaSuccess && cs != cudaStreamCaptureStatusNone) {
717        std::fprintf(stderr, "exl3: scratch for a stream first seen inside a graph capture (call exl3::prepare)\n");
718        return nullptr;
719    }
720    Scratch sc;
721    if (cudaMalloc(&sc.part, kPartFloats * sizeof(float)) != cudaSuccess ||
722        cudaMalloc(&sc.cnt, kCounters * sizeof(unsigned)) != cudaSuccess ||
723        cudaMalloc(&sc.h, kHFloats * sizeof(float)) != cudaSuccess ||
724        cudaMemsetAsync(sc.cnt, 0, kCounters * sizeof(unsigned), s) != cudaSuccess) {
725        std::fprintf(stderr, "exl3: scratch did not allocate\n");
726        return nullptr;
727    }
728    cudaStreamSynchronize(s);
729    return &(g_scratch[{dev, s}] = sc);
730}
731
732int sm_count() {
733    int dev = 0, sms = 0;
734    cudaGetDevice(&dev);
735    cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
736    return std::max(1, sms);
737}
738
739// the several-activation kernels may use smem_n_bytes of shared memory: asked once per device (prepare, before a graph
740// capture; else at the first such launch).  A device that cannot give a block that much (48 KB GPUs) runs one
741// activation at a time instead
742constexpr int kMaxDev = 64;
743std::atomic<int> g_smem_n[kMaxDev];   // 0 not asked, 1 allowed, 2 refused
744bool allow_smem_n() {
745    int dev = 0;
746    cudaGetDevice(&dev);
747    if (dev < 0 || dev >= kMaxDev) return false;
748    const int st = g_smem_n[dev].load(std::memory_order_acquire);
749    if (st != 0) return st == 1;
750    std::lock_guard<std::mutex> lk(g_mu);
751    if (g_smem_n[dev].load(std::memory_order_relaxed) != 0) return g_smem_n[dev].load() == 1;
752    int optin = 0;
753    cudaDeviceGetAttribute(&optin, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev);
754    bool ok = (size_t) optin >= smem_n_bytes(8);
755    if (ok) {
756        for (int K = 1; K <= 8; ++K)
757            for (int cb = 0; cb <= 2; ++cb) dispatch<AllowSmemN>(K, cb);
758        ok = cudaGetLastError() == cudaSuccess;
759    }
760    if (!ok)
761        std::fprintf(stderr, "exl3: CUDA%d gives a block %d bytes of shared memory, the several-activation kernels "
762                             "need %zu - a verify window's tokens run one at a time there\n", dev, optin,
763                     smem_n_bytes(8));
764    g_smem_n[dev].store(ok ? 1 : 2, std::memory_order_release);
765    return ok;
766}
767
768// mv's input split for m: S blocks of kr inputs per output block, at most kMaxKR inputs a block and about two blocks
769// per SM (the same for every activation count: mv_kernel and mv_n_kernel sum each activation alike)
770void mv_split(const Mat& m, int sms, int& S, int& kr) {
771    const int groups = m.n / kCols;
772    S = (m.k + kMaxKR - 1) / kMaxKR;
773    while (groups * S < 2 * sms && m.k / (S * 2) >= 256) S *= 2;
774    kr = ((m.k + S - 1) / S + 127) / 128 * 128;
775    S = (m.k + kr - 1) / kr;
776}
777
778}  // namespace
779
780int launch_errors() { return g_launch_errors.load(std::memory_order_relaxed); }
781
782bool prepare(cudaStream_t s) {
783    if (scratch(s) == nullptr) return false;
784    (void) allow_smem_n();
785    return true;
786}
787
788bool several_ok() { return allow_smem_n(); }
789
790bool mv(const MvJob* jobs, int n, cudaStream_t s) {
791    if (n <= 0 || n > kMaxMvJobs) return false;
792    Scratch* sc = scratch(s);
793    if (sc == nullptr) return false;
794    const int sms = sm_count();
795    // the launch units: a job of one activation is mv_kernel's, a job of several mv_n_kernel's in runs of up to kNC
796    // (one mv_kernel unit an activation where the device lacks the shared memory)
797    struct Unit {
798        int j, c0, nc;
799    };
800    Unit units[kMaxMvJobs * kMaxMvCols];
801    int nu = 0;
802    bool several = false;
803    for (int j = 0; j < n; ++j) several = several || jobs[j].ncol > 1;
804    const int run = several && allow_smem_n() ? kNC : 1;
805    for (int j = 0; j < n; ++j) {
806        const Mat& m = *jobs[j].m;
807        if (!supported(m) || jobs[j].y == nullptr || (jobs[j].xf == nullptr && jobs[j].xq == nullptr) ||
808            jobs[j].ncol < 1 || jobs[j].ncol > kMaxMvCols) {
809            std::fprintf(stderr, "exl3 mv: job %d unsupported (k %d n %d K %d cb %d, %d activations)\n", j, m.k, m.n,
810                         m.K, m.cb, jobs[j].ncol);
811            return false;
812        }
813        for (int c0 = 0; c0 < jobs[j].ncol; c0 += run) units[nu++] = {j, c0, std::min(run, jobs[j].ncol - c0)};
814    }
815    bool done[sizeof(units) / sizeof(units[0])] = {};
816    for (int i = 0; i < nu; ++i) {
817        if (done[i]) continue;
818        const Mat& m0 = *jobs[units[i].j].m;
819        const bool multi = units[i].nc > 1;
820        // a launch: the units of one (K, codebook, kernel), as many as KBatch and the split scratch take (the next
821        // launch on the stream may use the scratch again: this one's last blocks are done with it by then)
822        KBatch b{};
823        int blocks = 0, nb = 0;
824        size_t part_at = 0, cnt_at = 0;
825        for (int u = i; u < nu && nb < kMaxMvJobs; ++u) {
826            const MvJob& job = jobs[units[u].j];
827            const Mat& m = *job.m;
828            if (done[u] || m.K != m0.K || m.cb != m0.cb || (units[u].nc > 1) != multi) continue;
829            const int c0 = units[u].c0, nc = units[u].nc, groups = m.n / kCols;
830            int S = 1, kr = 0;
831            mv_split(m, sms, S, kr);
832            const size_t need = S > 1 ? (size_t) S * m.n * nc : 0;
833            if (S > 1 && (part_at + need > kPartFloats || cnt_at + (size_t) groups > kCounters)) {
834                if (nb > 0) continue;   // the next launch
835                std::fprintf(stderr, "exl3 mv: scratch too small for k %d n %d (%d activations)\n", m.k, m.n, nc);
836                return false;
837            }
838            done[u] = true;
839            KJob& J = b.j[nb];
840            J.tr = m.trellis;
841            J.suh = m.suh;
842            J.svh = m.svh;
843            J.xf = job.xf != nullptr ? job.xf + c0 * job.xf_cs : nullptr;
844            J.xq = job.xq != nullptr ? (const Q81*) ((const uint8_t*) job.xq + c0 * job.xq_cs) : nullptr;
845            J.y = job.y + c0 * job.y_cs;
846            J.bias = job.bias;
847            J.alpha = job.alpha;
848            J.k = m.k;
849            J.n = m.n;
850            J.ld = m.ld > 0 ? m.ld : m.n / 16;
851            J.S = S;
852            J.kr = kr;
853            J.part = sc->part + part_at;
854            J.cnt = sc->cnt + cnt_at;
855            J.nc = nc;
856            J.xf_cs = job.xf_cs;
857            J.xq_cs = job.xq_cs;
858            J.y_cs = job.y_cs;
859            part_at += need;
860            if (S > 1) cnt_at += (size_t) groups;
861            blocks += groups * S;
862            b.blk_end[nb++] = blocks;
863        }
864        b.n = nb;
865        if (!(multi ? dispatch<RunMvN>(m0.K, m0.cb, b, blocks, s) : dispatch<RunMv>(m0.K, m0.cb, b, blocks, s)))
866            return false;
867    }
868    launch_check("mv");
869    return true;
870}
871
872static bool moe_args(const MoeArgs& a, KMoe& m, cudaStream_t s) {
873    Scratch* sc = scratch(s);
874    if (sc == nullptr) return false;
875    if (a.k < 1 || a.k > 8 || a.n_embd % kCols != 0 || a.n_ff % kCols != 0 || a.n_embd > kMaxKR ||
876        a.n_ff > kMaxKR || (size_t) a.k * a.n_ff > kHFloats || (size_t) a.k * a.n_embd > kPartFloats ||
877        (size_t) (a.n_embd / kCols) > kCounters) {
878        std::fprintf(stderr, "exl3 moe: geometry not covered (k %d n_embd %d n_ff %d)\n", a.k, a.n_embd, a.n_ff);
879        return false;
880    }
881    m = KMoe{};
882    m.plan_ptr = a.plan_ptr;
883    m.plan_w = a.plan_w;
884    m.cpu_part = a.cpu_part;
885    m.cpu_flag = a.cpu_flag;
886    m.h = sc->h;
887    m.part = sc->part;
888    m.cnt = sc->cnt;
889    for (int r = 0; r < 3; ++r) {
890        m.suh[r] = a.lay.suh[r];
891        m.svh[r] = a.lay.svh[r];
892        m.tr[r] = a.lay.trellis[r];
893    }
894    m.k = a.k;
895    m.n_embd = a.n_embd;
896    m.n_ff = a.n_ff;
897    m.limit = a.limit;
898    return true;
899}
900
901void moe_gate_up(const MoeArgs& a, const float* x, float* h, cudaStream_t s) {
902    KMoe m;
903    if (!moe_args(a, m, s)) return;
904    if (a.lay.K[0] != a.lay.K[1]) {
905        std::fprintf(stderr, "exl3 moe_gate_up: gate K %d != up K %d\n", a.lay.K[0], a.lay.K[1]);
906        return;
907    }
908    m.x = x;
909    if (h != nullptr) m.h = h;
910    if (!dispatch<RunGU>(a.lay.K[0], a.lay.cb, m, s)) std::fprintf(stderr, "exl3 moe_gate_up: K %d\n", a.lay.K[0]);
911    launch_check("moe_gate_up");
912}
913
914void moe_down(const MoeArgs& a, const float* h, const float* sh_out, float* out, cudaStream_t s) {
915    KMoe m;
916    if (!moe_args(a, m, s)) return;
917    if (h != nullptr) m.h = const_cast<float*>(h);
918    m.sh_out = sh_out;
919    m.out = out;
920    if (!dispatch<RunDown>(a.lay.K[2], a.lay.cb, m, s)) std::fprintf(stderr, "exl3 moe_down: K %d\n", a.lay.K[2]);
921    launch_check("moe_down");
922}
923
924bool win_experts(const WinArgs& a, cudaStream_t s) {
925    if (a.T < 1 || a.k < 1 || a.k > 8 || a.n_embd % kCols != 0 || a.n_ff % kCols != 0 || a.n_embd > kMaxKR ||
926        a.n_ff > kMaxKR || a.lay.K[0] != a.lay.K[1] || a.h == nullptr || a.part == nullptr || a.out == nullptr) {
927        std::fprintf(stderr, "exl3 win_experts: not covered (T %d k %d n_embd %d n_ff %d, gate K %d up K %d)\n", a.T,
928                     a.k, a.n_embd, a.n_ff, a.lay.K[0], a.lay.K[1]);
929        return false;
930    }
931    if (!allow_smem_n()) return false;
932    KWin w{};
933    w.grp_ptr = a.grp_ptr;
934    w.grp_start = a.grp_start;
935    w.grp_ent = a.grp_ent;
936    w.n_groups = a.n_groups;
937    w.plan_ptr = a.plan_ptr;
938    w.plan_w = a.plan_w;
939    w.cpu_part = a.cpu_part;
940    w.cpu_flag = a.cpu_flag;
941    w.x = a.x;
942    w.x_stride = a.x_stride;
943    w.h = a.h;
944    w.part = a.part;
945    w.sh_out = a.sh_out;
946    w.out = a.out;
947    w.out_stride = a.out_stride;
948    for (int r = 0; r < 3; ++r) {
949        w.suh[r] = a.lay.suh[r];
950        w.svh[r] = a.lay.svh[r];
951        w.tr[r] = a.lay.trellis[r];
952    }
953    w.k = a.k;
954    w.n_embd = a.n_embd;
955    w.n_ff = a.n_ff;
956    w.limit = a.limit;
957    const int groups = a.T * a.k;   // at most (the blocks past the real count return at once)
958    if (!dispatch<RunWin>(a.lay.K[0], a.lay.cb, w, groups, s) ||
959        !dispatch<RunWinDown>(a.lay.K[2], a.lay.cb, w, groups, s))
960        return false;
961    win_combine_kernel<<<dim3((unsigned) (a.n_embd / kCols), (unsigned) a.T), kCols, 0, s>>>(w);
962    launch_check("win_experts");
963    return true;
964}
965
966}  // namespace strata::dsv41k::exl3::legacy
967#endif