okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
78.3 KiB1479 linesraw
1// src/kernels/cuda/s2_expert_grouped.cu - R4's grouped GPU expert.  Read the header first.
2//
3// THE ARITHMETIC IS `src/kernels/cpu/expert.cpp`'s, over the same bytes, one warp per output row.
4//
5//     sum_j (c_j - 1) * d_w * xhat_j * d_x   ==   d_w * d_x * ( sum_j c_j*xhat_j  -  sum_j xhat_j )
6//
7// Both sums are INT8 x INT8, so both are `__dp4a` - four multiply-accumulates per instruction, exact in
8// integer and with no dequantization inside the loop.  The weight scale `d_w` is fp16 (one per 64 elements)
9// and the activation scale `d_x` is fp16 (one per 32 elements), so the float work is one multiply-add per
10// 32-element chunk rather than one per element.
11//
12// **THE SUMMATION ORDER IS NOT THE CPU's AND CANNOT BE.**  Lane `L` takes chunks `L, L+32, ...` and the
13// partials are reduced through shuffle; the CPU walks every chunk in order with its own accumulator shape.
14// The two agree to float rounding and not to the bit, which is the same contract `s_gemv_parity` carries for
15// the same reason.  `bench/micro/moe_hit_parity.cu` is the check.
16#include "strata/kernels/s2_expert_grouped.hpp"
17#include "strata/core/geometry.hpp"
18#include "strata/kernels/dp4a.hpp"
19#include "strata/kernels/f16_bits.hpp"
20
21#include "strata/kernels/quantize_act.hpp"
22#include "strata/kernels/fuse_decode.hpp"
23#include "strata/kernels/verify_kernels.hpp"
24
25#include <cuda_fp16.h>
26#include <cuda_runtime.h>
27
28#include <atomic>
29#include <cstdint>
30#include <cstdio>
31#include <cstdlib>
32#include <cstring>
33
34namespace strata::kernels {
35namespace {
36
37// THE BLOB'S OWN GEOMETRY, from `include/strata/kernels/cpu/expert.hpp`.  Restated as literals because that
38// header is the CPU path's and this file must not silently follow it if the two ever disagree: the sizes below
39// are what the CPU kernel's indexing computes, and `moe_hit_parity` compares the two end to end.
40constexpr int H = strata::core::kCompiledGeometry.n_embd;
41constexpr int FF = strata::core::kCompiledGeometry.n_ff;
42static_assert(H == strata::core::kCompiledGeometry.n_embd && FF == strata::core::kCompiledGeometry.n_ff, "s2_expert_grouped is compiled for core/geometry.hpp");
43constexpr int QK = 64;                       // Q2_0's group: one fp16 scale per 64 weights
44constexpr int ROW_GU = H / 4;                // 640 B of codes per gate/up row (2 bits per element)
45constexpr int ROW_D = FF / 4;                // 160 B per down row
46constexpr int SC_GU = H / QK;                // 40 fp16 scales per gate/up row
47constexpr int SC_D = FF / QK;                // 10 per down row
48constexpr size_t O_D_CODES = (size_t) 2 * FF * ROW_GU;
49constexpr size_t O_GU_SCALES = O_D_CODES + (size_t) H * ROW_D;
50constexpr size_t O_D_SCALES = O_GU_SCALES + (size_t) 2 * FF * SC_GU * 2;
51
52__device__ __forceinline__ float f16_at(const uint8_t* p) {
53    return __half2float(__ushort_as_half((uint16_t) (p[0] | (p[1] << 8))));
54}
55
56__device__ __forceinline__ void s2_sync_lds() {
57#if defined(__HIP_DEVICE_COMPILE__) && (defined(__gfx1200__) || defined(__gfx1201__))
58    asm volatile("s_wait_dscnt 0x0\n\ts_barrier_signal -1\n\ts_barrier_wait -1" ::: "memory");
59#else
60    __syncthreads();
61#endif
62}
63
64/// **ONE S2 ROW AGAINST A Q8_0 ACTIVATION, WARP-WIDE.**  Every lane accumulates its own float partial over a
65/// strided set of 32-element chunks and the caller reduces; `chunk` indices are absolute so the caller can
66/// start the lane at any offset.
67///
68/// Returns the lane's partial.  `codes` is `n_in/4` bytes and `scales` `n_in/QK` fp16, both for THIS row.
69///
70/// **`x_scales` IS R4.2h AND IT IS OPTIONAL ON PURPOSE.**  When it is non-null the activation's multiplier
71/// comes from an fp32 array instead of the block's fp16 `d`.  The CPU pool multiplies by the fp32
72/// `ActQ::scale` (`cpu/expert.cpp:92`), and the two disagreed by **4.761e-04 relative on 80 of 80 chunks**
73/// (`bench/micro/act_quant_parity.cu`), which is what made a cache hit compute a different expert from a
74/// cache miss.  Null keeps the previous fp16 behaviour **exactly**, so `moe_hit_parity` - which passes no
75/// scales - still measures the kernel it always measured.
76__device__ __forceinline__ float row_dot_s2_q8(const uint8_t* __restrict__ codes,
77                                               const uint8_t* __restrict__ scales,
78                                               const uint8_t* __restrict__ x_q8_0, int n_chunks, int lane,
79                                               const float* __restrict__ x_scales = nullptr) {
80    float acc = 0.0f;
81    for (int c = lane; c < n_chunks; c += 32) {
82        const uint8_t* cb = codes + (size_t) c * 8;             // 8 code bytes = 32 elements
83        const uint8_t* xb = x_q8_0 + (size_t) c * 34;           // one block_q8_0
84        const float dx = x_scales ? x_scales[c] : f16_at(xb);
85        const int8_t* xq = (const int8_t*) (xb + 2);
86
87        // ---- THE CODES, EXPANDED TO ONE BYTE PER ELEMENT, THEN FOUR AT A TIME INTO `dp4a`.
88        //
89        // The packed form is LSB-first: element 4j+k is bits [2k, 2k+2) of code byte j.  `dp4a` needs both
90        // operands as packed int8, so each code byte becomes a word whose four bytes are its four 2-bit
91        // fields - which is exactly `(c & 3) | ((c>>2)&3)<<8 | ((c>>4)&3)<<16 | ((c>>6)&3)<<24`.
92        int s = 0;      // sum of code * x
93        int hx = 0;     // sum of x        - the weight-independent term, as ones * x
94        const int ones = 0x01010101;
95#pragma unroll
96        for (int j = 0; j < 8; ++j) {
97            const unsigned cbyte = cb[j];
98            const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) |
99                                  (((cbyte >> 6) & 3u) << 24));
100            // **`memcpy`, NOT A CAST.**  A `block_q8_0` is 34 BYTES - two of header then 32 of int8 - so the
101            // activation data at offset 2 is never 4-byte aligned, and `*(const int*)(xq + 4*j)` faults with
102            // "misaligned address".  It faulted exactly that way on this kernel's first run.  `memcpy` of a
103            // known 4 bytes compiles to whatever load is legal for the alignment, which is the point of using
104            // it rather than reasoning about which cast happens to work.
105            int xw;
106            memcpy(&xw, xq + 4 * j, 4);
107            s = STRATA_DP4A(cw, xw, s);
108            hx = STRATA_DP4A(ones, xw, hx);
109        }
110        // One weight scale per 64 elements, so per TWO 32-element chunks.
111        const float dw = f16_at(scales + (size_t) (c >> 1) * 2);
112        acc += dw * dx * (float) (s - hx);
113    }
114    return acc;
115}
116
117__device__ __forceinline__ float warp_sum(float v) {
118#pragma unroll
119    for (int off = 16; off > 0; off >>= 1) v += __shfl_down_sync(0xFFFFFFFFu, v, off);
120    return v;
121}
122
123/// GATE AND UP, ONE WARP PER ROW.
124///
125/// **THE ROWS ARE INTERLEAVED AND THE FIRST VERSION OF THIS GOT IT WRONG.**  In the blob, row-SLOT `i` of the
126/// `2*FF` gate/up rows is gate row `i/2` when `i` is even and up row `(i-1)/2` when it is odd - that is what
127/// `O_GU_CODES + (2r)*ROW_GU` and `+ (2r+1)*ROW_GU` mean in `expert.cpp`.  This kernel decoded the correct
128/// code row for slot `i` and then wrote it to output slot `i` of a layout whose first `FF` entries are gate and
129/// whose last `FF` are up, which pairs `silu(gate[r]) * up[r]` with the WRONG `up` for every `r`.  It produced
130/// finite, plausible numbers.  `moe_hit_parity` caught it on the first run, at worst relative error 2.2e+03.
131///
132/// So slot `i` is DECODED from row-slot `i` and WRITTEN to the output slot its parity says it belongs to.
133__global__ void gu_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index,
134                          long long blob_bytes, const uint8_t* __restrict__ x_q8_0,
135                          const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits,
136                          const int32_t* __restrict__ d_count = nullptr,
137                          const int32_t* __restrict__ dst_index = nullptr, int tok_div = 0) {
138    const int warps_per_block = (int) (blockDim.x >> 5);
139    const long long slot = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
140    const long long rows_per_hit = 2LL * FF;
141    const long long total = (long long) n_hits * rows_per_hit;
142    if (slot >= total) return;
143    const int h = (int) (slot / rows_per_hit);
144    if (d_count != nullptr && h >= *d_count) return;     // token graph: capacity layout, device count
145    const int i = (int) (slot % rows_per_hit);
146    const int lane = threadIdx.x & 31;
147
148    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
149    if (tok_div > 0) {   // plan v0.3 P6 verify window: each hit reads its own token's activation
150        const int tok = dst_index[h] / tok_div;
151        x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34;
152        if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32);
153    }
154    const float acc = row_dot_s2_q8(blob + (size_t) i * ROW_GU,
155                                    blob + O_GU_SCALES + (size_t) i * SC_GU * 2, x_q8_0, H / 32, lane, x_scales);
156    const float s = warp_sum(acc);
157    if (lane != 0) return;
158    // ---- THE OUTPUT LAYOUT IS GATE-MAJOR, AND THAT IS NOT COSMETIC.
159    //
160    // The first version wrote `gate_up[h*2FF + {0..FF-1}] = gate` and `[h*2FF + FF..] = up`, i.e. a per-hit
161    // [gate | up] pair, and then called the shared `swiglu_kernel` and `quantize_q8_0` over the whole buffer.
162    // Both of those walk a CONTIGUOUS range, so with more than one hit they read hit 0's UP rows where they
163    // wanted hit 1's GATE rows - finite numbers, wrong expert.  With one hit it would have passed.
164    //
165    // Gate-major removes the mismatch instead of adding a stride to two other kernels: every hit's gate rows
166    // are contiguous from 0, every hit's up rows are contiguous from `n_hits * FF`, and the swiglu's output
167    // lands in the first `n_hits * FF` floats exactly where `quantize_q8_0` reads it.
168    const int r = i >> 1;
169    const size_t base = (i & 1) ? ((size_t) n_hits * FF + (size_t) h * FF) : ((size_t) h * FF);
170    gate_up[base + (size_t) r] = s;
171}
172
173// `silu(gate) * up` lives in `strata/kernels/swiglu.cuh` (the fused kernels call it in their epilogues);
174// the standalone pass it replaced is gone.  The scratch layout is unchanged: `[0, n_pairs)` ends up holding
175// the products, `[n_pairs, 2*n_pairs)` the raw up rows.
176/// `silu(gate) * up`, in place, over a GATE-MAJOR buffer: `[0, n_pairs)` is every hit's gate and
177/// `[n_pairs, 2*n_pairs)` is every hit's up, so hit `h`'s row `r` meets itself at `h*FF + r`.
178///
179/// SiLU on the GATE and multiplied by up - the reading `docs/semantics.md` records, and the one that is wrong
180/// the other way round in a way that still produces a finite number.
181__global__ void swiglu_kernel(float* __restrict__ gate_up, long long n_pairs) {
182    const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
183    if (i >= n_pairs) return;
184    const float g = gate_up[i];
185    const float u = gate_up[n_pairs + i];
186    gate_up[i] = (g / (1.0f + __expf(-g))) * u;
187}
188
189__global__ void swiglu_quantize_q8_0_scaled_kernel(float* __restrict__ gate_up, long long n_pairs,
190                                                   uint8_t* __restrict__ blocks, float* __restrict__ scales) {
191    const long long n_blocks = n_pairs >> 5;
192    const long long b = ((long long) blockIdx.x * blockDim.x + threadIdx.x) >> 5;
193    if (b >= n_blocks) return;
194    const int lane = threadIdx.x & 31;
195    const long long idx = b * 32 + lane;
196    const float g = gate_up[idx];
197    const float u = gate_up[n_pairs + idx];
198    const float xv = (g / (1.0f + __expf(-g))) * u;
199    gate_up[idx] = xv;
200    uint8_t* out = blocks + b * 34;
201
202    float amax = fabsf(xv);
203#pragma unroll
204    for (int off = 16; off > 0; off >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, off));
205    const float s = amax > 0.f ? amax / 127.f : 0.f;
206    const float inv = s > 0.f ? 1.f / s : 0.f;
207    if (lane == 0) {
208        scales[b] = s;
209        const uint16_t d16bits = f16_from_f32(s);
210        out[0] = (uint8_t) (d16bits & 0xFF);
211        out[1] = (uint8_t) (d16bits >> 8);
212    }
213    const float t = xv * inv;
214    const float r = t + (t >= 0.f ? 0.5f : -0.5f);
215    int v = (int) r;
216    v = v < -127 ? -127 : (v > 127 ? 127 : v);
217    out[2 + lane] = (uint8_t) (int8_t) v;
218}
219
220/// DOWN, ONE WARP PER ROW, reading the quantized intermediate the caller produced.
221///
222/// `dst_index[h]` is which row of the shared output buffer hit `h` fills - see the header.  It is the router's
223/// slot, not `h`, and the two differ on every layer where some experts are resident and some are not.
224__global__ void down_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index,
225                            const int32_t* __restrict__ dst_index, long long blob_bytes,
226                            const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales,
227                            float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count = nullptr) {
228    const int warps_per_block = (int) (blockDim.x >> 5);
229    const long long row = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
230    const long long total = (long long) n_hits * H;
231    if (row >= total) return;
232    const int h = (int) (row / H);
233    if (d_count != nullptr && h >= *d_count) return;
234    const int r = (int) (row % H);
235    const int lane = threadIdx.x & 31;
236
237    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
238    const uint8_t* xb = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34;
239    const float acc = row_dot_s2_q8(blob + O_D_CODES + (size_t) r * ROW_D,
240                                    blob + O_D_SCALES + (size_t) r * SC_D * 2, xb, FF / 32, lane,
241                                    h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr);
242    const float s = warp_sum(acc);
243    if (lane == 0) out[(size_t) dst_index[h] * H + r] = s;
244}
245
246// ---- THE SAME INTEGERS FROM FEWER INSTRUCTIONS.  `STRATA_OLD_GROUPED=1` keeps the kernels above.
247//
248// **INSIDE A CHUNK, WHICH CODE MEETS WHICH ACTIVATION IN A `dp4a` WORD IS FREE.**  `s = sum_e code_e * x_e` and
249// `hx = sum_e x_e` are exact integer sums (|s| <= 32 * 3 * 128), so any grouping of the 32 products into words
250// gives the same two integers.  The grouping used here costs no transposition of the codes: `(w >> 2f) & 0x03030303`
251// holds field `f` of each of a code word's four bytes - elements `4b + f`, plus 16 for the second word - so it is
252// the ACTIVATIONS that are regrouped, once per chunk, into
253//
254//     X[4h + f] = { x[16h + f], x[16h + 4 + f], x[16h + 8 + f], x[16h + 12 + f] }
255//
256// a 4x4 byte transpose of each half of the chunk, eight `__byte_perm`.  The kernels above spend seven integer
257// operations per code BYTE and a second `dp4a` chain for `hx` on every row; here a code word costs seven for 16
258// elements and `hx` is summed once per chunk.  `s`, `hx` and the float expression `dw * dx * (float) (s - hx)` are
259// unchanged, so every output is bitwise the previous kernels' - `s2_expert_grouped_parity` checks exactly that.
260
261// fp16 at an even address, one 16-bit load (`f16_at` reads it as two bytes); same value.
262__device__ __forceinline__ float f16_ld(const uint8_t* p) {
263    return __half2float(__ushort_as_half(*(const unsigned short*) p));
264}
265
266// A chunk's two code words as the eight `dp4a` operands that pair with `X[0..7]`: `m[4h + f]` byte `b` is the
267// code of element `16h + 4b + f`.
268__device__ __forceinline__ void expand_codes(uint2 cb, int m[8]) {
269    const unsigned M = 0x03030303u;
270    m[0] = (int) (cb.x & M);
271    m[1] = (int) ((cb.x >> 2) & M);
272    m[2] = (int) ((cb.x >> 4) & M);
273    m[3] = (int) ((cb.x >> 6) & M);
274    m[4] = (int) (cb.y & M);
275    m[5] = (int) ((cb.y >> 2) & M);
276    m[6] = (int) ((cb.y >> 4) & M);
277    m[7] = (int) ((cb.y >> 6) & M);
278}
279
280// The 32 int8 of the `block_q8_0` at `xb` regrouped into `X[0..7]` (see above), and their sum `hx`.
281//
282// **NINE ALIGNED WORD LOADS INSTEAD OF 32 BYTE LOADS.**  The caller guarantees a 4-byte aligned activation row, so
283// chunk `c`'s int8 start at `34c + 2`, i.e. 0 bytes (odd `c`) or 2 bytes (even `c`) into an aligned word; the
284// words are read aligned and funnel-shifted into place.  The ninth word is read only in the 2-byte case, and then
285// it lies inside block `c + 1` of the same row: both row lengths (80 and 20 chunks) are even, so an even chunk is
286// never a row's last.
287__device__ __forceinline__ int load_x_chunk(const uint8_t* __restrict__ xb, int X[8]) {
288    const uint8_t* q = xb + 2;
289    const int off = (int) ((uintptr_t) q & 3);
290    const unsigned* p = (const unsigned*) (q - off);
291    const unsigned sh = (unsigned) off * 8;
292    unsigned v[9];
293#pragma unroll
294    for (int j = 0; j < 8; ++j) v[j] = __ldg(p + j);
295    v[8] = off != 0 ? __ldg(p + 8) : 0u;
296    unsigned n[8];
297    int hx = 0;
298#pragma unroll
299    for (int j = 0; j < 8; ++j) {
300        // natural word j: x[4j .. 4j+3]; a 64-bit shift (sh is 0, 8, 16 or 24) rather than __funnelshift_r, so the same
301        // source needs no CUDA-only intrinsic.
302        n[j] = (unsigned) ((((unsigned long long) v[j + 1] << 32) | v[j]) >> sh);
303        hx = STRATA_DP4A(0x01010101, (int) n[j], hx);
304    }
305#pragma unroll
306    for (int h = 0; h < 2; ++h) {
307        const unsigned t0 = __byte_perm(n[4 * h], n[4 * h + 1], 0x5140);      // a0 b0 a1 b1
308        const unsigned t1 = __byte_perm(n[4 * h], n[4 * h + 1], 0x7362);      // a2 b2 a3 b3
309        const unsigned t2 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x5140);  // c0 d0 c1 d1
310        const unsigned t3 = __byte_perm(n[4 * h + 2], n[4 * h + 3], 0x7362);  // c2 d2 c3 d3
311        X[4 * h + 0] = (int) __byte_perm(t0, t2, 0x5410);                    // a0 b0 c0 d0
312        X[4 * h + 1] = (int) __byte_perm(t0, t2, 0x7632);                    // a1 b1 c1 d1
313        X[4 * h + 2] = (int) __byte_perm(t1, t3, 0x5410);                    // a2 b2 c2 d2
314        X[4 * h + 3] = (int) __byte_perm(t1, t3, 0x7632);                    // a3 b3 c3 d3
315    }
316    return hx;
317}
318
319// `s` for one chunk: the eight expanded code words against the eight regrouped activation words.
320__device__ __forceinline__ int chunk_s(const int m[8], const int X[8]) {
321    int s = 0;
322#pragma unroll
323    for (int j = 0; j < 8; ++j) s = STRATA_DP4A(m[j], X[j], s);
324    return s;
325}
326
327/// `gu_kernel`, new: ONE WARP PER (gate, up) PAIR - row-slots `2r` and `2r + 1`, adjacent in the blob - so each
328/// activation chunk is loaded and regrouped once for both rows.  Per row, the lane's chunks, their order, the float
329/// expression and the shuffle reduction are `row_dot_s2_q8`'s; the outputs land where `gu_kernel` puts them.
330__global__ void gu_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index,
331                               long long blob_bytes, const uint8_t* __restrict__ x_q8_0,
332                               const float* __restrict__ x_scales, float* __restrict__ gate_up, int n_hits,
333                               const int32_t* __restrict__ d_count, const int32_t* __restrict__ dst_index,
334                               int tok_div) {
335    const int warps_per_block = (int) (blockDim.x >> 5);
336    const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
337    const long long total = (long long) n_hits * FF;
338    if (pair >= total) return;
339    const int h = (int) (pair / FF);
340    if (d_count != nullptr && h >= *d_count) return;
341    const int r = (int) (pair % FF);
342    const int lane = threadIdx.x & 31;
343
344    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
345    if (tok_div > 0) {
346        const int tok = dst_index[h] / tok_div;
347        x_q8_0 += (size_t) tok * (size_t) (H / 32) * 34;
348        if (x_scales != nullptr) x_scales += (size_t) tok * (size_t) (H / 32);
349    }
350    const uint8_t* codes = blob + (size_t) (2 * r) * ROW_GU;               // gate row; the up row follows it
351    const uint8_t* scales = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2;
352    float acc_g = 0.0f, acc_u = 0.0f;
353    for (int c = lane; c < H / 32; c += 32) {
354        const uint8_t* xb = x_q8_0 + (size_t) c * 34;
355        const float dx = x_scales ? x_scales[c] : f16_ld(xb);
356        int X[8], m[8];
357        const int hx = load_x_chunk(xb, X);
358        expand_codes(*(const uint2*) (codes + (size_t) c * 8), m);
359        const float dw_g = f16_ld(scales + (size_t) (c >> 1) * 2);
360        acc_g += dw_g * dx * (float) (chunk_s(m, X) - hx);
361        expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m);
362        const float dw_u = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
363        acc_u += dw_u * dx * (float) (chunk_s(m, X) - hx);
364    }
365    const float sg = warp_sum(acc_g);
366    const float su = warp_sum(acc_u);
367    if (lane != 0) return;
368    gate_up[(size_t) h * FF + (size_t) r] = sg;                                // gate-major, as in `gu_kernel`
369    gate_up[(size_t) n_hits * FF + (size_t) h * FF + (size_t) r] = su;
370}
371
372/// `down_kernel`, new: ONE WARP PER PAIR OF ROWS `r, r + 1` of one hit, the intermediate's chunk loaded once for both.
373__global__ void down_pair_kernel(const uint8_t* __restrict__ blob_base, const int32_t* __restrict__ slot_index,
374                                 const int32_t* __restrict__ dst_index, long long blob_bytes,
375                                 const uint8_t* __restrict__ h_q8_0, const float* __restrict__ h_scales,
376                                 float* __restrict__ out, int n_hits, const int32_t* __restrict__ d_count) {
377    const int warps_per_block = (int) (blockDim.x >> 5);
378    const long long pair = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
379    const long long total = (long long) n_hits * (H / 2);
380    if (pair >= total) return;
381    const int h = (int) (pair / (H / 2));
382    if (d_count != nullptr && h >= *d_count) return;
383    const int r = 2 * (int) (pair % (H / 2));
384    const int lane = threadIdx.x & 31;
385
386    const uint8_t* blob = blob_base + (size_t) slot_index[h] * (size_t) blob_bytes;
387    const uint8_t* xrow = h_q8_0 + (size_t) h * (size_t) (FF / 32) * 34;
388    const float* xs = h_scales ? h_scales + (size_t) h * (size_t) (FF / 32) : nullptr;
389    const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
390    const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
391    float acc0 = 0.0f, acc1 = 0.0f;
392    for (int c = lane; c < FF / 32; c += 32) {
393        const uint8_t* xb = xrow + (size_t) c * 34;
394        const float dx = xs ? xs[c] : f16_ld(xb);
395        int X[8], m[8];
396        const int hx = load_x_chunk(xb, X);
397        expand_codes(*(const uint2*) (codes + (size_t) c * 8), m);
398        const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
399        acc0 += dw0 * dx * (float) (chunk_s(m, X) - hx);
400        expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m);
401        const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
402        acc1 += dw1 * dx * (float) (chunk_s(m, X) - hx);
403    }
404    const float s0 = warp_sum(acc0);
405    const float s1 = warp_sum(acc1);
406    if (lane != 0) return;
407    const size_t o = (size_t) dst_index[h] * H + (size_t) r;
408    out[o] = s0;
409    out[o + 1] = s1;
410}
411
412// The CPU subtracts the weight bias after its eight FMA accumulators have been reduced. Moving the
413// subtraction into each integer dot, as the legacy kernel does, changes rounding even with equal scales.
414__global__ void activation_correction_kernel(const uint8_t* q8, const float* scales, float* hx, int chunks) {
415    const int c = blockIdx.x * blockDim.x + threadIdx.x;
416    if (c >= chunks) return;
417    const int8_t* q = (const int8_t*) (q8 + (size_t) c * 34 + 2);
418    int sum = 0;
419    for (int j = 0; j < 32; ++j) sum += q[j];
420    hx[c] = __fmul_rn(scales[c], (float) sum);
421}
422
423__device__ __forceinline__ int dot4(const uint8_t* codes, const int8_t* q) {
424    const unsigned c = *codes;
425    const int cw = (int) ((c & 3u) | (((c >> 2) & 3u) << 8) |
426                          (((c >> 4) & 3u) << 16) | (((c >> 6) & 3u) << 24));
427    int xw;
428    memcpy(&xw, q, sizeof xw);
429    return STRATA_DP4A(cw, xw, 0);
430}
431
432__device__ __forceinline__ float row_dot_cpu_order(const uint8_t* codes, const uint8_t* scales,
433                                                   const uint8_t* xq, const float* xs,
434                                                   const float* hx, int blocks, int lane) {
435    float acc = 0.0f;
436    float corr = 0.0f;
437    for (int b = 0; b < blocks; ++b) {
438        const float d = f16_at(scales + 2 * b);
439        const int lo = dot4(codes + b * 16 + lane,
440                           (const int8_t*) (xq + (size_t) (2 * b) * 34 + 2) + lane * 4);
441        const int hi = dot4(codes + b * 16 + 8 + lane,
442                           (const int8_t*) (xq + (size_t) (2 * b + 1) * 34 + 2) + lane * 4);
443        acc = __fmaf_rn(__fmul_rn(d, xs[2 * b]), (float) lo, acc);
444        acc = __fmaf_rn(__fmul_rn(d, xs[2 * b + 1]), (float) hi, acc);
445        if (lane == 0)
446            corr = __fadd_rn(corr, __fmul_rn(d, __fadd_rn(hx[2 * b], hx[2 * b + 1])));
447    }
448    // _mm_add_ps(low128, high128), then two _mm_hadd_ps. The pair order is 4, 1, 2;
449    // a standard shuffle tree in the order 4, 2, 1 is a different floating-point expression.
450    constexpr unsigned mask = 0xffffffffu;
451    acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 4, 8));
452    acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 1, 8));
453    acc = __fadd_rn(acc, __shfl_down_sync(mask, acc, 2, 8));
454    return __fsub_rn(acc, corr);  // Only lane zero is consumed.
455}
456
457template <bool DOWN>
458__global__ void cpu_order_projection_kernel(const uint8_t* blob_base, const int32_t* slots,
459                                              const int32_t* destinations, long long blob_bytes,
460                                              const uint8_t* xq, const float* xs, const float* hx,
461                                              float* out, int n_hits) {
462    constexpr int rows_per_hit = DOWN ? H : 2 * FF;
463    const int row = blockIdx.x * (blockDim.x / 8) + threadIdx.x / 8;
464    if (row >= n_hits * rows_per_hit) return;
465    const int h = row / rows_per_hit;
466    const int r = row % rows_per_hit;
467    const int lane = threadIdx.x & 7;
468    const uint8_t* blob = blob_base + (size_t) slots[h] * (size_t) blob_bytes;
469    const int chunks_offset = DOWN ? h * (FF / 32) : 0;
470    const uint8_t* codes = DOWN ? blob + O_D_CODES + (size_t) r * ROW_D : blob + (size_t) r * ROW_GU;
471    const uint8_t* scales = DOWN ? blob + O_D_SCALES + (size_t) r * SC_D * 2
472                                 : blob + O_GU_SCALES + (size_t) r * SC_GU * 2;
473    const float value = row_dot_cpu_order(codes, scales, xq + (size_t) chunks_offset * 34,
474                                           xs + chunks_offset, hx + chunks_offset,
475                                           DOWN ? SC_D : SC_GU, lane);
476    if (lane != 0) return;
477    if (DOWN) out[(size_t) destinations[h] * H + r] = value;
478    else out[((r & 1) ? (size_t) n_hits * FF : 0) + (size_t) h * FF + (r >> 1)] = value;
479}
480
481__global__ void cpu_order_swiglu_kernel(float* gu, int pairs) {
482    const int i = blockIdx.x * blockDim.x + threadIdx.x;
483    if (i >= pairs) return;
484    const float g = gu[i];
485    // Accurate fp32 exponential; __expf's approximation would introduce an additional source of error.
486    // CPU/GPU libc last-bit differences are diagnosed separately by the micro, not hidden with FP64 here.
487    const float eg = expf(-g);
488    gu[i] = __fmul_rn(__fdiv_rn(g, __fadd_rn(1.0f, eg)), gu[pairs + i]);
489}
490
491__global__ void cpu_order_quantize_kernel(const float* x, uint8_t* blocks, float* scales,
492                                           float* hx, int chunks) {
493    const int c = blockIdx.x * blockDim.x + threadIdx.x;
494    if (c >= chunks) return;
495    const float* xb = x + c * 32;
496    uint8_t* out = blocks + (size_t) c * 34;
497    float amax = 0.0f;
498    for (int j = 0; j < 32; ++j) amax = fmaxf(amax, fabsf(xb[j]));
499    const float s = amax > 0.0f ? __fdiv_rn(amax, 127.0f) : 0.0f;
500    const float inv = s > 0.0f ? __fdiv_rn(1.0f, s) : 0.0f;
501    scales[c] = s;
502    const uint16_t bits = __half_as_ushort(__float2half_rn(s));
503    out[0] = (uint8_t) bits;
504    out[1] = (uint8_t) (bits >> 8);
505    int sum = 0;
506    for (int j = 0; j < 32; ++j) {
507        const float t = __fmul_rn(xb[j], inv);
508        int v = (int) __fadd_rn(t, t >= 0.0f ? 0.5f : -0.5f);
509        v = v < -127 ? -127 : (v > 127 ? 127 : v);
510        out[2 + j] = (uint8_t) (int8_t) v;
511        sum += v;
512    }
513    hx[c] = __fmul_rn(s, (float) sum);
514}
515
516constexpr int THREADS = 256;
517
518void check(const char* who, void* stream) {
519    const cudaError_t e = cudaGetLastError();
520    if (e != cudaSuccess) {
521        std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e));
522        std::exit(1);
523    }
524    // Deliberately NOT synchronising for a non-null stream: this is called once per layer from a captured
525    // graph's worth of work, and `finish()`'s null-stream sync in `s_gemv.cu` is the pattern that made a whole
526    // round of measurements the driver's cost instead of the kernel's (Memory/ERRORS.md RC-7).
527    (void) stream;
528}
529
530// The previous kernels stay selectable for A/B - `STRATA_OLD_GROUPED=1` in the environment, or
531// `moe_grouped_select_old` (the parity test runs both in one process).  The environment is read once, on first use;
532// the choice is made at each launch, so a captured graph keeps the kernels it was captured with.
533std::atomic<int> g_select_old{-1};
534// Which kernels the last launch of an entry point used: 1 = new, 0 = previous, -1 = none since the last query.
535std::atomic<int> g_last_path{-1};
536
537bool old_kernels() {
538    const int s = g_select_old.load(std::memory_order_relaxed);
539    if (s >= 0) return s != 0;
540    static const bool env = [] {
541        const char* e = std::getenv("STRATA_OLD_GROUPED");
542        return e != nullptr && e[0] == '1';
543    }();
544    return env;
545}
546
547// `STRATA_GROUPED_PAIR_MIN_HITS=N`: the per-hit path keeps the previous one-warp-per-row kernels below N hits of
548// capacity.  The new per-hit kernels launch half the warps (two rows each), so one hit's gate/up is 80 blocks - fewer
549// than an RTX 5090's SMs - and whether that costs time at one to three hits is what `--bench` measures.  Bitwise
550// the same either way; default 0 (always the new kernels).  Ignored while `moe_grouped_select_old` forces a choice.
551long long pair_min_hits() {
552    if (g_select_old.load(std::memory_order_relaxed) >= 0) return 0;
553    static const long long n = [] {
554        const char* e = std::getenv("STRATA_GROUPED_PAIR_MIN_HITS");
555        return e != nullptr ? std::atoll(e) : 0LL;
556    }();
557    return n;
558}
559
560// The new kernels read the activations as aligned words (`load_x_chunk`), so they need 4-byte aligned activation
561// rows - the input's and the intermediate's in `scratch`; the per-hit ones also read a blob's codes as uint2, which
562// needs an 8-byte aligned arena and slot size (the grouped kernels above already did).  Anything else keeps the
563// previous kernels rather than issuing a misaligned load.
564bool new_grouped(const void* x_q8_0, const void* scratch) {
565    const bool fast = !old_kernels() && ((uintptr_t) x_q8_0 & 3) == 0 && ((uintptr_t) scratch & 3) == 0;
566    g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed);
567    return fast;
568}
569
570bool new_hit(const void* blob_base, long long blob_bytes, const void* x_q8_0, const void* scratch, long long cap) {
571    const bool fast = new_grouped(x_q8_0, scratch) && ((uintptr_t) blob_base & 7) == 0 && (blob_bytes & 7) == 0 &&
572                      cap >= pair_min_hits();
573    g_last_path.store(fast ? 1 : 0, std::memory_order_relaxed);
574    return fast;
575}
576
577// The per-hit path's two projections, previous or new kernels (one warp per row, or per pair of rows).
578void launch_hit_gu(bool fast, const uint8_t* blob_base, const int32_t* slot_index, long long blob_bytes,
579                   const uint8_t* x_q8_0, const float* x_scales, float* gate_up, long long cap,
580                   const int32_t* d_count, const int32_t* dst_index, int tok_div, cudaStream_t cs) {
581    const int warps = THREADS / 32;
582    if (fast) {
583        const long long pairs = cap * (long long) FF;
584        gu_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>(
585            blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div);
586    } else {
587        const long long rows = cap * 2LL * FF;
588        gu_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>(
589            blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, (int) cap, d_count, dst_index, tok_div);
590    }
591}
592
593bool swiglu_q8_on() {
594    static const bool on = [] {
595        const char* e = std::getenv("STRATA_S2_SWIGLU_Q8");
596        return e == nullptr || e[0] != '0';
597    }();
598    return on;
599}
600
601void launch_hit_swiglu_q8(bool fast, float* gate_up, uint8_t* h_q8_0, float* h_scales, long long cap,
602                          const float* x_scales, void* stream) {
603    cudaStream_t cs = (cudaStream_t) stream;
604    const long long pairs = cap * (long long) FF;
605    if (fast && x_scales != nullptr && swiglu_q8_on()) {
606        const long long n_blocks = pairs >> 5;
607        const int warps = THREADS / 32;
608        swiglu_quantize_q8_0_scaled_kernel<<<(unsigned) ((n_blocks + warps - 1) / warps), THREADS, 0, cs>>>(
609            gate_up, pairs, h_q8_0, h_scales);
610        check("moe_hit_grouped_s2/swiglu_q8", stream);
611    } else {
612#if defined(STRATA_EXPERIMENTAL_SM60)
613        if (strata::kernels::fuse_decode()) {
614            if (x_scales != nullptr)
615                swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream);
616            else
617                swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream);
618        } else
619#endif
620        {
621            swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs);
622            check("moe_hit_grouped_s2/swiglu", stream);
623            if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, pairs, stream);
624            else quantize_q8_0(gate_up, h_q8_0, pairs, stream);
625        }
626    }
627}
628
629void launch_hit_down(bool fast, const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
630                     long long blob_bytes, const uint8_t* h_q8_0, const float* h_scales, float* out, long long cap,
631                     const int32_t* d_count, cudaStream_t cs) {
632    const int warps = THREADS / 32;
633    if (fast) {
634        const long long pairs = cap * (long long) (H / 2);
635        down_pair_kernel<<<(unsigned) ((pairs + warps - 1) / warps), THREADS, 0, cs>>>(
636            blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count);
637    } else {
638        const long long rows = cap * (long long) H;
639        down_kernel<<<(unsigned) ((rows + warps - 1) / warps), THREADS, 0, cs>>>(
640            blob_base, slot_index, dst_index, blob_bytes, h_q8_0, h_scales, out, (int) cap, d_count);
641    }
642}
643
644}  // namespace
645
646void moe_grouped_select_old(int old) { g_select_old.store(old < 0 ? -1 : (old != 0 ? 1 : 0)); }
647
648int moe_grouped_last_path() { return g_last_path.exchange(-1, std::memory_order_relaxed); }
649
650uint64_t moe_hit_grouped_scratch_bytes(int64_t n_hits, int64_t n_embd, int64_t n_ff) {
651    if (n_hits <= 0) return 0;
652    const uint64_t gu = (uint64_t) n_hits * (uint64_t) (2 * n_ff) * 4;
653    const uint64_t q8 = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 34;
654    // R4.2h: the fp32 scales for the INTERMEDIATE's own quantization, one per 32-element chunk per hit.
655    const uint64_t hs = (uint64_t) n_hits * (uint64_t) (n_ff / 32) * 4;
656    const uint64_t xh = (uint64_t) (n_embd / 32) * 4;
657    return ((gu + 15) & ~15ull) + ((q8 + 15) & ~15ull) + 2 * ((hs + 15) & ~15ull) +
658           ((xh + 15) & ~15ull);
659}
660
661void moe_hit_grouped_s2(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
662                        int64_t n_hits, int64_t blob_bytes, const uint8_t* x_q8_0, void* scratch, float* out,
663                        void* stream, const float* x_scales) {
664    if (n_hits <= 0) return;
665    cudaStream_t cs = (cudaStream_t) stream;
666    const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, n_hits);
667
668    const uint64_t gu_bytes = ((uint64_t) n_hits * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
669    const uint64_t q8_bytes = ((uint64_t) n_hits * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
670    float* gate_up = (float*) scratch;
671    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
672    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
673
674    // 1. gate + up, one launch for every row of every hit.
675    {
676        launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, n_hits, nullptr, nullptr,
677                      0, cs);
678        check("moe_hit_grouped_s2/gu", stream);
679    }
680    // 2-3. silu(gate) * up and Q8_0 quantization of the intermediate (fused when fast && x_scales != nullptr).
681    launch_hit_swiglu_q8(fast, gate_up, h_q8_0, h_scales, n_hits, x_scales, stream);
682    // 4. down.
683    {
684        launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
685                        x_scales != nullptr ? h_scales : nullptr, out, n_hits, nullptr, cs);
686        check("moe_hit_grouped_s2/down", stream);
687    }
688}
689
690namespace {
691// Plan v0.3 P4 token graph: which of this layer's routed experts are resident, decided ON THE DEVICE from the
692// static residency row, so no host step sits between the ring and the hit kernels.  One warp; k <= 32.
693__global__ void hit_select_kernel(const int32_t* __restrict__ ids, const int32_t* __restrict__ res_row, int k,
694                                  int n_expert, int32_t* __restrict__ slot, int32_t* __restrict__ dst,
695                                  int32_t* __restrict__ count) {
696    const int lane = threadIdx.x;
697    int s = -1;
698    if (lane < k) {
699        const int e = ids[lane];
700        if (e >= 0 && e < n_expert) s = res_row[e];
701    }
702    const unsigned hit = __ballot_sync(0xffffffffu, s >= 0);
703    if (s >= 0) {
704        const int at = __popc(hit & ((1u << lane) - 1u));
705        slot[at] = s;
706        dst[at] = lane;
707    }
708    if (lane == 0) *count = __popc(hit);
709}
710
711// Plan v0.3 P6: the same for up to 128 routed entries (a verify window of T tokens x k): four warps, ballots
712// compacted in entry order.
713__global__ void hit_select_multi_kernel(const int32_t* __restrict__ ids, const int32_t* __restrict__ res_row, int n,
714                                        int n_expert, int32_t* __restrict__ slot, int32_t* __restrict__ dst,
715                                        int32_t* __restrict__ count) {
716    __shared__ int warp_count[4];
717    const int i = threadIdx.x, lane = i & 31, warp = i >> 5;
718    int s = -1;
719    if (i < n) {
720        const int e = ids[i];
721        if (e >= 0 && e < n_expert) s = res_row[e];
722    }
723    const unsigned hit = __ballot_sync(0xffffffffu, s >= 0);
724    if (lane == 0) warp_count[warp] = __popc(hit);
725    s2_sync_lds();
726    int before = 0;
727    for (int w = 0; w < warp; ++w) before += warp_count[w];
728    if (s >= 0) {
729        const int at = before + __popc(hit & ((1u << lane) - 1u));
730        slot[at] = s;
731        dst[at] = i;
732    }
733    if (i == 0) *count = warp_count[0] + warp_count[1] + warp_count[2] + warp_count[3];
734}
735
736__global__ void add_hits_kernel(float* __restrict__ parts, const float* __restrict__ hit_out,
737                                const int32_t* __restrict__ dst, const int32_t* __restrict__ count, int n_embd) {
738    const int h = blockIdx.y;
739    if (h >= *count) return;
740    const size_t row = (size_t) dst[h] * (size_t) n_embd;
741    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n_embd; i += gridDim.x * blockDim.x)
742        parts[row + i] += hit_out[row + i];
743}
744}  // namespace
745
746void moe_hit_select(const int32_t* ids, const int32_t* res_row, int k, int n_expert, int32_t* slot, int32_t* dst,
747                    int32_t* count, void* stream) {
748    if (k < 1 || k > 32) { std::fprintf(stderr, "moe_hit_select: k must be 1..32\n"); std::exit(1); }
749    hit_select_kernel<<<1, 32, 0, (cudaStream_t) stream>>>(ids, res_row, k, n_expert, slot, dst, count);
750    check("moe_hit_select", stream);
751}
752
753void moe_hit_grouped_s2_dev(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
754                            const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0,
755                            void* scratch, float* out, void* stream, const float* x_scales) {
756    if (cap <= 0) return;
757    cudaStream_t cs = (cudaStream_t) stream;
758    const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap);
759    const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
760    const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
761    float* gate_up = (float*) scratch;
762    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
763    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
764    {
765        launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, nullptr, 0,
766                      cs);
767        check("moe_hit_grouped_s2_dev/gu", stream);
768    }
769    launch_hit_swiglu_q8(fast, gate_up, h_q8_0, h_scales, cap, x_scales, stream);
770    {
771        launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
772                        x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
773        check("moe_hit_grouped_s2_dev/down", stream);
774    }
775}
776
777void moe_hit_select_multi(const int32_t* ids, const int32_t* res_row, int n, int n_expert, int32_t* slot, int32_t* dst,
778                          int32_t* count, void* stream) {
779    if (n < 1 || n > 128) { std::fprintf(stderr, "moe_hit_select_multi: n must be 1..128\n"); std::exit(1); }
780    hit_select_multi_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, res_row, n, n_expert, slot, dst, count);
781    check("moe_hit_select_multi", stream);
782}
783
784void moe_hit_grouped_s2_multi(const uint8_t* blob_base, const int32_t* slot_index, const int32_t* dst_index,
785                              const int32_t* d_count, int64_t cap, int64_t blob_bytes, const uint8_t* x_q8_0,
786                              const float* x_scales, int k_per_token, void* scratch, float* out, void* stream) {
787    if (cap <= 0) return;
788    cudaStream_t cs = (cudaStream_t) stream;
789    const bool fast = new_hit(blob_base, blob_bytes, x_q8_0, scratch, cap);
790    const uint64_t gu_bytes = ((uint64_t) cap * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
791    const uint64_t q8_bytes = ((uint64_t) cap * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
792    float* gate_up = (float*) scratch;
793    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
794    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
795    {
796        launch_hit_gu(fast, blob_base, slot_index, blob_bytes, x_q8_0, x_scales, gate_up, cap, d_count, dst_index,
797                      k_per_token, cs);
798        check("moe_hit_grouped_s2_multi/gu", stream);
799    }
800    launch_hit_swiglu_q8(fast, gate_up, h_q8_0, h_scales, cap, x_scales, stream);
801    {
802        launch_hit_down(fast, blob_base, slot_index, dst_index, blob_bytes, h_q8_0,
803                        x_scales != nullptr ? h_scales : nullptr, out, cap, d_count, cs);
804        check("moe_hit_grouped_s2_multi/down", stream);
805    }
806}
807
808namespace {
809// Plan v0.3 P6: experts GROUPED - one blob pointer per group (a VRAM slot or a mapped host blob read over PCIe),
810// every entry of the group (a token routed to that expert) computed from ONE read of each row.  Per entry the
811// arithmetic is `row_dot_s2_q8`'s, chunk by chunk in the same lane order, so every entry is bitwise the per-entry
812// hit kernel's.
813constexpr int GU_CHUNKS = (H / 32 + 31) / 32;   // 3: chunks of a gate/up row per lane (80 chunks / 32 lanes)
814constexpr int GMAX = 8;                          // entries per group (tokens routed to one expert in a window)
815// a group holds one entry per token of the window routed to its expert, and a kernel keeps at most GMAX of them
816// (`min(..., GMAX)`): a longer group would drop entries without a word.  A window of 9..16 rows can route more tokens
817// than that to one expert, so `moe_grouped_s2` takes the window's largest group and runs the kernel again with
818// SKIP = GMAX over the entries from the GMAX-th on (the staging is GMAX entries wide in shared memory: 51 KB at 16
819// would not compile on CUDA, whose static limit is 48 KB).  Every entry's output is its own dot products, so the
820// passes are bitwise the one wide pass; SKIP = 0 is the kernel as it was.
821constexpr int kGroupPasses = (kVerifyMaxT + GMAX - 1) / GMAX;
822static_assert(kGroupPasses * GMAX >= kVerifyMaxT, "a verify window's group can exceed the passes' entries");
823constexpr int GU_ROWS = 32;                      // gate/up rows per block: 4 per warp
824constexpr int D_ROWS = 64;                       // down rows per block: 8 per warp
825
826// One activation chunk's contribution, `row_dot_s2_q8`'s inner body with the 32 int8 of the chunk already in
827// aligned words: same dp4a sequence, same float expression, so the result is bitwise the per-entry kernel's.
828__device__ __forceinline__ float chunk_dot(uint2 cb, const int* xw, float dw, float dx) {
829    const uint8_t* cbytes = (const uint8_t*) &cb;
830    int s = 0, hx = 0;
831    const int ones = 0x01010101;
832#pragma unroll
833    for (int j = 0; j < 8; ++j) {
834        const unsigned cbyte = cbytes[j];
835        const int cw = (int) ((cbyte & 3u) | (((cbyte >> 2) & 3u) << 8) | (((cbyte >> 4) & 3u) << 16) |
836                              (((cbyte >> 6) & 3u) << 24));
837        s = STRATA_DP4A(cw, xw[j], s);
838        hx = STRATA_DP4A(ones, xw[j], hx);
839    }
840    return dw * dx * (float) (s - hx);
841}
842
843// Gate/up: a block = GU_ROWS rows of ONE group.  The group's activations (each entry's token row of x_q8_0 and
844// its fp32 scales) are staged once into shared memory as aligned words; each warp then walks its rows, loading
845// each lane's code chunks once and dotting them with every entry.
846template <int SKIP>
847__global__ void __launch_bounds__(256) gu_grouped_kernel(const unsigned long long* __restrict__ grp_ptr,
848                                                         const int32_t* __restrict__ grp_start,
849                                                         const int32_t* __restrict__ n_groups,
850                                                         const int32_t* __restrict__ ent_tok,
851                                                         const uint8_t* __restrict__ x_q8_0,
852                                                         const float* __restrict__ x_scales,
853                                                         float* __restrict__ gate_up, int cap_entries) {
854    __shared__ int xs_q[GMAX][H / 4];          // the entries' int8 activations as words (2560 B each)
855    __shared__ float xs_d[GMAX][H / 32];
856    const int g = blockIdx.y;
857    if (g >= *n_groups) return;
858    const int e0 = grp_start[g] + SKIP, ne = min(grp_start[g + 1] - e0, GMAX);
859    if (SKIP > 0 && ne <= 0) return;
860    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
861    for (int i = t; i < ne * (H / 32); i += blockDim.x) {
862        const int k = i / (H / 32), c = i - k * (H / 32);
863        const uint8_t* xb = x_q8_0 + (size_t) ent_tok[e0 + k] * (size_t) (H / 32) * 34 + (size_t) c * 34;
864        xs_d[k][c] = x_scales ? x_scales[(size_t) ent_tok[e0 + k] * (H / 32) + c] : f16_at(xb);
865        const int8_t* q = (const int8_t*) (xb + 2);
866#pragma unroll
867        for (int w = 0; w < 8; ++w) {
868            int v;
869            memcpy(&v, q + 4 * w, 4);
870            xs_q[k][c * 8 + w] = v;
871        }
872    }
873    s2_sync_lds();
874    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
875    const int row0 = blockIdx.x * GU_ROWS;
876    for (int rr = warp; rr < GU_ROWS; rr += 8) {
877        const int i = row0 + rr;
878        const uint8_t* codes = blob + (size_t) i * ROW_GU;
879        const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2;
880        uint2 cb[GU_CHUNKS];
881        float dw[GU_CHUNKS];
882#pragma unroll
883        for (int q = 0; q < GU_CHUNKS; ++q) {
884            const int c = lane + 32 * q;
885            if (c < H / 32) {
886                cb[q] = *(const uint2*) (codes + (size_t) c * 8);
887                dw[q] = f16_at(scales + (size_t) (c >> 1) * 2);
888            }
889        }
890        for (int k = 0; k < ne; ++k) {
891            float acc = 0.0f;
892#pragma unroll
893            for (int q = 0; q < GU_CHUNKS; ++q) {
894                const int c = lane + 32 * q;
895                if (c >= H / 32) break;
896                acc += chunk_dot(cb[q], &xs_q[k][c * 8], dw[q], xs_d[k][c]);
897            }
898            const float sum = warp_sum(acc);
899            if (lane == 0) {
900                const int e = e0 + k, r = i >> 1;
901                const size_t base = (i & 1) ? ((size_t) cap_entries * FF + (size_t) e * FF) : ((size_t) e * FF);
902                gate_up[base + (size_t) r] = sum;
903            }
904        }
905    }
906}
907
908// Down: a block = D_ROWS rows of ONE group; the entries' quantized intermediates staged once.  A down row is 20
909// chunks, so lanes 0..19 each hold one chunk, as in the per-entry kernel.
910template <int SKIP>
911__global__ void __launch_bounds__(256) down_grouped_kernel(const unsigned long long* __restrict__ grp_ptr,
912                                                           const int32_t* __restrict__ grp_start,
913                                                           const int32_t* __restrict__ n_groups,
914                                                           const int32_t* __restrict__ ent_dst,
915                                                           const uint8_t* __restrict__ h_q8_0,
916                                                           const float* __restrict__ h_scales,
917                                                           float* __restrict__ out) {
918    __shared__ int hs_q[GMAX][FF / 4];
919    __shared__ float hs_d[GMAX][FF / 32];
920    const int g = blockIdx.y;
921    if (g >= *n_groups) return;
922    const int e0 = grp_start[g] + SKIP, ne = min(grp_start[g + 1] - e0, GMAX);
923    if (SKIP > 0 && ne <= 0) return;
924    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
925    for (int i = t; i < ne * (FF / 32); i += blockDim.x) {
926        const int k = i / (FF / 32), c = i - k * (FF / 32);
927        const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) (FF / 32) * 34 + (size_t) c * 34;
928        hs_d[k][c] = h_scales ? h_scales[(size_t) (e0 + k) * (FF / 32) + c] : f16_at(xb);
929        const int8_t* q = (const int8_t*) (xb + 2);
930#pragma unroll
931        for (int w = 0; w < 8; ++w) {
932            int v;
933            memcpy(&v, q + 4 * w, 4);
934            hs_q[k][c * 8 + w] = v;
935        }
936    }
937    s2_sync_lds();
938    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
939    const int row0 = blockIdx.x * D_ROWS;
940    for (int rr = warp; rr < D_ROWS; rr += 8) {
941        const int r = row0 + rr;
942        const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
943        const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
944        const int c = lane;
945        uint2 cb = make_uint2(0, 0);
946        float dw = 0.0f;
947        if (c < FF / 32) {
948            cb = *(const uint2*) (codes + (size_t) c * 8);
949            dw = f16_at(scales + (size_t) (c >> 1) * 2);
950        }
951        for (int k = 0; k < ne; ++k) {
952            float acc = 0.0f;
953            if (c < FF / 32) acc += chunk_dot(cb, &hs_q[k][c * 8], dw, hs_d[k][c]);
954            const float sum = warp_sum(acc);
955            if (lane == 0) out[(size_t) ent_dst[e0 + k] * H + r] = sum;
956        }
957    }
958}
959
960// ---- The grouped kernels with the staged activations laid out for the reads.
961//
962// **THE LAYOUT ABOVE IS AN 8-WAY BANK CONFLICT.**  `xs_q[k][c * 8 + j]` puts lane `L`'s word `j` at `8L + j`, so
963// lanes `L, L + 4, L + 8, ...` share a bank on every one of the chunk's eight reads; and `chunk_dot` recomputes
964// `hx`, which depends on the entry alone, for every row.  Here the staging writes, once per (entry, chunk):
965//
966//     xs_w[j][k * NC + c]   word j of the regrouped chunk (`load_x_chunk`), so lanes read consecutive words
967//     xs_dh[k * NC + c]     (dx, hx) - one 64-bit read per chunk instead of a float and eight `dp4a`
968//
969// Word-major, the staging writes are consecutive as well (the flat index `i` IS `k * NC + c`), so neither side
970// conflicts and no padding is needed.  Each warp takes its rows TWO at a time (adjacent rows: gate `r` and up `r`,
971// or down rows `r, r + 1`), so every shared read serves both; the codes of both are expanded once per row, not
972// once per entry.  Per (row, entry) the lane's chunks, their order, the float expression and the shuffle
973// reduction are the kernels' above, so every output is bitwise theirs.
974
975// Stages chunk `i = k * NC + c` of a group: its regrouped words at `xs_w[j * STRIDE + i]` and (dx, hx) at `xs_dh[i]`.
976template <int STRIDE>
977__device__ __forceinline__ void stage_chunk(const uint8_t* __restrict__ xb, float dx, int* xs_w, int2* xs_dh, int i) {
978    int X[8];
979    const int hx = load_x_chunk(xb, X);
980#pragma unroll
981    for (int j = 0; j < 8; ++j) xs_w[j * STRIDE + i] = X[j];
982    xs_dh[i] = make_int2(__float_as_int(dx), hx);
983}
984
985template <int SKIP, int MAX_E = GMAX>
986__global__ void __launch_bounds__(256) gu_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr,
987                                                           const int32_t* __restrict__ grp_start,
988                                                           const int32_t* __restrict__ n_groups,
989                                                           const int32_t* __restrict__ ent_tok,
990                                                           const uint8_t* __restrict__ x_q8_0,
991                                                           const float* __restrict__ x_scales,
992                                                           float* __restrict__ gate_up, int cap_entries) {
993    constexpr int NC = H / 32;
994    __shared__ int xs_w[8 * MAX_E * NC];
995    __shared__ int2 xs_dh[MAX_E * NC];
996    const int g = blockIdx.y;
997    if (g >= *n_groups) return;
998    const int e0 = grp_start[g] + SKIP, ne = min(grp_start[g + 1] - e0, GMAX);
999    if (ne <= 0) return;
1000    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1001    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
1002    const int row0 = blockIdx.x * GU_ROWS;                 // even: a pair is always (gate r, up r)
1003    if constexpr (MAX_E == 1) {
1004        for (int k = 0; k < ne; ++k) {
1005            if (k > 0) s2_sync_lds();
1006            if (t < NC) {
1007                const int tok = ent_tok[e0 + k];
1008                const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) t * 34;
1009                const float dx = x_scales ? x_scales[(size_t) tok * NC + t] : f16_ld(xb);
1010                stage_chunk<NC>(xb, dx, xs_w, xs_dh, t);
1011            }
1012            s2_sync_lds();
1013#pragma unroll 1
1014            for (int pp = warp; pp < GU_ROWS / 2; pp += 8) {
1015                const int i = row0 + 2 * pp;
1016                const uint8_t* codes = blob + (size_t) i * ROW_GU;
1017                const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2;
1018                float acc0 = 0.0f, acc1 = 0.0f;
1019#pragma unroll
1020                for (int q = 0; q < GU_CHUNKS; ++q) {
1021                    const int c = lane + 32 * q;
1022                    if (c < NC) {
1023                        int m0[8], m1[8], X[8];
1024                        expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0);
1025                        expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m1);
1026                        const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
1027                        const float dw1 = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
1028#pragma unroll
1029                        for (int j = 0; j < 8; ++j) X[j] = xs_w[j * NC + c];
1030                        const int2 dh = xs_dh[c];
1031                        const float dx = __int_as_float(dh.x);
1032                        acc0 += dw0 * dx * (float) (chunk_s(m0, X) - dh.y);
1033                        acc1 += dw1 * dx * (float) (chunk_s(m1, X) - dh.y);
1034                    }
1035                }
1036                const float s0 = warp_sum(acc0);
1037                const float s1 = warp_sum(acc1);
1038                if (lane == 0) {
1039                    const int e = e0 + k, r = i >> 1;
1040                    gate_up[(size_t) e * FF + (size_t) r] = s0;
1041                    gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1;
1042                }
1043            }
1044        }
1045    } else {
1046        for (int i = t; i < ne * NC; i += blockDim.x) {
1047            const int k = i / NC, c = i - k * NC;
1048            const int tok = ent_tok[e0 + k];
1049            const uint8_t* xb = x_q8_0 + (size_t) tok * (size_t) NC * 34 + (size_t) c * 34;
1050            const float dx = x_scales ? x_scales[(size_t) tok * NC + c] : f16_ld(xb);
1051            stage_chunk<MAX_E * NC>(xb, dx, xs_w, xs_dh, i);
1052        }
1053        s2_sync_lds();
1054        for (int pp = warp; pp < GU_ROWS / 2; pp += 8) {
1055            const int i = row0 + 2 * pp;
1056            const uint8_t* codes = blob + (size_t) i * ROW_GU;
1057            const uint8_t* scales = blob + O_GU_SCALES + (size_t) i * SC_GU * 2;
1058            int m0[GU_CHUNKS][8], m1[GU_CHUNKS][8];
1059            float dw0[GU_CHUNKS], dw1[GU_CHUNKS];
1060#pragma unroll
1061            for (int q = 0; q < GU_CHUNKS; ++q) {
1062                const int c = lane + 32 * q;
1063                if (c < NC) {
1064                    expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0[q]);
1065                    expand_codes(*(const uint2*) (codes + ROW_GU + (size_t) c * 8), m1[q]);
1066                    dw0[q] = f16_ld(scales + (size_t) (c >> 1) * 2);
1067                    dw1[q] = f16_ld(scales + SC_GU * 2 + (size_t) (c >> 1) * 2);
1068                }
1069            }
1070            for (int k = 0; k < ne; ++k) {
1071                float acc0 = 0.0f, acc1 = 0.0f;
1072#pragma unroll
1073                for (int q = 0; q < GU_CHUNKS; ++q) {
1074                    const int c = lane + 32 * q;
1075                    if (c >= NC) break;
1076                    const int at = k * NC + c;
1077                    int X[8];
1078#pragma unroll
1079                    for (int j = 0; j < 8; ++j) X[j] = xs_w[j * (MAX_E * NC) + at];
1080                    const int2 dh = xs_dh[at];
1081                    const float dx = __int_as_float(dh.x);
1082                    acc0 += dw0[q] * dx * (float) (chunk_s(m0[q], X) - dh.y);
1083                    acc1 += dw1[q] * dx * (float) (chunk_s(m1[q], X) - dh.y);
1084                }
1085                const float s0 = warp_sum(acc0);
1086                const float s1 = warp_sum(acc1);
1087                if (lane == 0) {
1088                    const int e = e0 + k, r = i >> 1;
1089                    gate_up[(size_t) e * FF + (size_t) r] = s0;
1090                    gate_up[(size_t) cap_entries * FF + (size_t) e * FF + (size_t) r] = s1;
1091                }
1092            }
1093        }
1094    }
1095}
1096
1097template <int SKIP, int MAX_E = GMAX>
1098__global__ void __launch_bounds__(256) down_grouped_t_kernel(const unsigned long long* __restrict__ grp_ptr,
1099                                                             const int32_t* __restrict__ grp_start,
1100                                                             const int32_t* __restrict__ n_groups,
1101                                                             const int32_t* __restrict__ ent_dst,
1102                                                             const uint8_t* __restrict__ h_q8_0,
1103                                                             const float* __restrict__ h_scales,
1104                                                             float* __restrict__ out) {
1105    constexpr int NC = FF / 32;
1106    __shared__ int hs_w[8 * MAX_E * NC];
1107    __shared__ int2 hs_dh[MAX_E * NC];
1108    const int g = blockIdx.y;
1109    if (g >= *n_groups) return;
1110    const int e0 = grp_start[g] + SKIP, ne = min(grp_start[g + 1] - e0, GMAX);
1111    if (ne <= 0) return;
1112    const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
1113    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
1114    const int row0 = blockIdx.x * D_ROWS;
1115    if constexpr (MAX_E == 1) {
1116        for (int k = 0; k < ne; ++k) {
1117            if (k > 0) s2_sync_lds();
1118            if (t < NC) {
1119                const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) t * 34;
1120                const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + t] : f16_ld(xb);
1121                stage_chunk<NC>(xb, dx, hs_w, hs_dh, t);
1122            }
1123            s2_sync_lds();
1124            for (int pp = warp; pp < D_ROWS / 2; pp += 8) {
1125                const int r = row0 + 2 * pp;
1126                const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
1127                const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
1128                const int c = lane;
1129                float acc0 = 0.0f, acc1 = 0.0f;
1130                if (c < NC) {
1131                    int m0[8], m1[8], X[8];
1132                    expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0);
1133                    expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m1);
1134                    const float dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
1135                    const float dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
1136#pragma unroll
1137                    for (int j = 0; j < 8; ++j) X[j] = hs_w[j * NC + c];
1138                    const int2 dh = hs_dh[c];
1139                    const float dx = __int_as_float(dh.x);
1140                    acc0 += dw0 * dx * (float) (chunk_s(m0, X) - dh.y);
1141                    acc1 += dw1 * dx * (float) (chunk_s(m1, X) - dh.y);
1142                }
1143                const float s0 = warp_sum(acc0);
1144                const float s1 = warp_sum(acc1);
1145                if (lane == 0) {
1146                    const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r;
1147                    out[o] = s0;
1148                    out[o + 1] = s1;
1149                }
1150            }
1151        }
1152    } else {
1153        for (int i = t; i < ne * NC; i += blockDim.x) {
1154            const int k = i / NC, c = i - k * NC;
1155            const uint8_t* xb = h_q8_0 + (size_t) (e0 + k) * (size_t) NC * 34 + (size_t) c * 34;
1156            const float dx = h_scales ? h_scales[(size_t) (e0 + k) * NC + c] : f16_ld(xb);
1157            stage_chunk<MAX_E * NC>(xb, dx, hs_w, hs_dh, i);
1158        }
1159        s2_sync_lds();
1160        for (int pp = warp; pp < D_ROWS / 2; pp += 8) {
1161            const int r = row0 + 2 * pp;
1162            const uint8_t* codes = blob + O_D_CODES + (size_t) r * ROW_D;
1163            const uint8_t* scales = blob + O_D_SCALES + (size_t) r * SC_D * 2;
1164            const int c = lane;                                // lanes 0..19 hold one chunk each, as above
1165            int m0[8], m1[8];
1166            float dw0 = 0.0f, dw1 = 0.0f;
1167            if (c < NC) {
1168                expand_codes(*(const uint2*) (codes + (size_t) c * 8), m0);
1169                expand_codes(*(const uint2*) (codes + ROW_D + (size_t) c * 8), m1);
1170                dw0 = f16_ld(scales + (size_t) (c >> 1) * 2);
1171                dw1 = f16_ld(scales + SC_D * 2 + (size_t) (c >> 1) * 2);
1172            }
1173            for (int k = 0; k < ne; ++k) {
1174                float acc0 = 0.0f, acc1 = 0.0f;
1175                if (c < NC) {
1176                    const int at = k * NC + c;
1177                    int X[8];
1178#pragma unroll
1179                    for (int j = 0; j < 8; ++j) X[j] = hs_w[j * (MAX_E * NC) + at];
1180                    const int2 dh = hs_dh[at];
1181                    const float dx = __int_as_float(dh.x);
1182                    acc0 += dw0 * dx * (float) (chunk_s(m0, X) - dh.y);
1183                    acc1 += dw1 * dx * (float) (chunk_s(m1, X) - dh.y);
1184                }
1185                const float s0 = warp_sum(acc0);
1186                const float s1 = warp_sum(acc1);
1187                if (lane == 0) {
1188                    const size_t o = (size_t) ent_dst[e0 + k] * H + (size_t) r;
1189                    out[o] = s0;
1190                    out[o + 1] = s1;
1191                }
1192            }
1193        }
1194    }
1195}
1196}  // namespace
1197
1198namespace {
1199// Plan v0.3 P6: groups built on the device when every expert is resident at `base + id * blob` (the MTP layer):
1200// one block of 128 threads, groups in first-appearance order, entries of a group in routing order.
1201__global__ void group_resident_kernel(const int32_t* __restrict__ ids, int n, int k_per_tok, const uint8_t* base,
1202                                      long long blob, unsigned long long* __restrict__ grp_ptr,
1203                                      int32_t* __restrict__ grp_start, int32_t* __restrict__ counts,
1204                                      int32_t* __restrict__ ent_dst, int32_t* __restrict__ ent_tok) {
1205    __shared__ int e_s[128], first_s[128], size_s[128], gidx_s[128], gstart_s[129];
1206    const int i = threadIdx.x;
1207    const int e = i < n ? ids[i] : -1;
1208    e_s[i] = e;
1209    s2_sync_lds();
1210    int first = i, rank = 0, size = 0;
1211    if (i < n) {
1212        for (int j = 0; j < i; ++j)
1213            if (e_s[j] == e) { if (first == i) first = j; ++rank; }
1214        if (first == i)
1215            for (int j = i; j < n; ++j) size += e_s[j] == e;
1216    }
1217    first_s[i] = first;
1218    size_s[i] = (i < n && first == i) ? size : 0;
1219    s2_sync_lds();
1220    if (i == 0) {
1221        int gi = 0, acc = 0;
1222        for (int j = 0; j < n; ++j)
1223            if (first_s[j] == j) {
1224                gidx_s[j] = gi;
1225                gstart_s[gi] = acc;
1226                grp_ptr[gi] = (unsigned long long) (base + (size_t) e_s[j] * (size_t) blob);
1227                grp_start[gi] = acc;
1228                acc += size_s[j];
1229                ++gi;
1230            }
1231        grp_start[gi] = acc;
1232        counts[0] = gi;
1233        counts[1] = acc;
1234    }
1235    s2_sync_lds();
1236    if (i < n) {
1237        const int at = gstart_s[gidx_s[first]] + rank;
1238        ent_dst[at] = i;
1239        ent_tok[at] = i / k_per_tok;
1240    }
1241}
1242}  // namespace
1243
1244void moe_group_resident(const int32_t* ids, int n, int k_per_tok, const uint8_t* base, int64_t blob,
1245                        unsigned long long* grp_ptr, int32_t* grp_start, int32_t* counts, int32_t* ent_dst,
1246                        int32_t* ent_tok, void* stream) {
1247    if (n < 1 || n > 128) { std::fprintf(stderr, "moe_group_resident: n must be 1..128\n"); std::exit(1); }
1248    group_resident_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ids, n, k_per_tok, base, (long long) blob, grp_ptr,
1249                                                               grp_start, counts, ent_dst, ent_tok);
1250    check("moe_group_resident", stream);
1251}
1252
1253static void grouped_s2_impl(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
1254                            const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
1255                            const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream,
1256                            int max_group) {
1257    if (cap_groups <= 0 || cap_entries <= 0) return;
1258    if (max_group < 1 || max_group > kGroupPasses * GMAX) {
1259        std::fprintf(stderr, "moe_grouped_s2: a group of %d entries, at most %d\n", max_group, kGroupPasses * GMAX);
1260        std::exit(1);
1261    }
1262    // a group of more than GMAX entries (a window of 9..16 rows, wide builds only): the entries from the GMAX-th on, too
1263    constexpr bool kWide = kGroupPasses > 1;
1264    const bool second = kWide && max_group > GMAX;
1265    cudaStream_t cs = (cudaStream_t) stream;
1266    const uint64_t gu_bytes = ((uint64_t) cap_entries * (uint64_t) (2 * FF) * 4 + 15) & ~15ull;
1267    const uint64_t q8_bytes = ((uint64_t) cap_entries * (uint64_t) (FF / 32) * 34 + 15) & ~15ull;
1268    float* gate_up = (float*) scratch;
1269    uint8_t* h_q8_0 = (uint8_t*) scratch + gu_bytes;
1270    float* h_scales = (float*) ((uint8_t*) scratch + gu_bytes + q8_bytes);
1271    const bool fast = new_grouped(x_q8_0, scratch);
1272    const bool single_entry = cap_entries <= 16 && !second;   // (second: a group of more than GMAX entries)
1273    {
1274        const dim3 grid((unsigned) (2 * FF / GU_ROWS), (unsigned) cap_groups);
1275        if (fast) {
1276            if (single_entry)   // #3264: one entry a group (the MTP draft's single token): 3 KB of shared memory instead of 25 KB
1277                gu_grouped_t_kernel<0, 1><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales,
1278                                                                gate_up, (int) cap_entries);
1279            else
1280                gu_grouped_t_kernel<0><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales,
1281                                                             gate_up, (int) cap_entries);
1282            if constexpr (kWide)
1283                if (second)
1284                    gu_grouped_t_kernel<GMAX><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales,
1285                                                                    gate_up, (int) cap_entries);
1286        } else {
1287            gu_grouped_kernel<0><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales, gate_up,
1288                                                       (int) cap_entries);
1289            if constexpr (kWide)
1290                if (second)
1291                    gu_grouped_kernel<GMAX><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_tok, x_q8_0, x_scales,
1292                                                                  gate_up, (int) cap_entries);
1293        }
1294        check("moe_grouped_s2/gu", stream);
1295    }
1296    // #783 PR-k (stuchapin909): SwiGLU and the scaled Q8_0 quantize of its result in one kernel (gate_up still gets the
1297    // activation written back, so the parity checks read the same buffer); STRATA_S2_SWIGLU_Q8=0 keeps the two launches
1298    static_assert(FF % 32 == 0, "the fused SwiGLU + Q8_0 kernel works in whole 32-value blocks");
1299    if (fast && x_scales != nullptr && swiglu_q8_on()) {
1300        const long long pairs = cap_entries * (long long) FF;
1301        const long long n_blocks = pairs >> 5;
1302        const int warps = THREADS / 32;
1303        swiglu_quantize_q8_0_scaled_kernel<<<(unsigned) ((n_blocks + warps - 1) / warps), THREADS, 0, cs>>>(
1304            gate_up, pairs, h_q8_0, h_scales);
1305        check("moe_grouped_s2/swiglu_q8", stream);
1306    } else {
1307        const long long pairs = cap_entries * (long long) FF;
1308#if defined(STRATA_EXPERIMENTAL_SM60)
1309        if (strata::kernels::fuse_decode()) {
1310        if (x_scales != nullptr)
1311            swilu_quantize_q8_0_scaled(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, h_scales, stream);
1312        else
1313            swilu_quantize_q8_0(gate_up, gate_up + pairs, gate_up, pairs, 1, h_q8_0, stream);
1314        } else
1315#endif
1316        {
1317        swiglu_kernel<<<(unsigned) ((pairs + THREADS - 1) / THREADS), THREADS, 0, cs>>>(gate_up, pairs);
1318        check("moe_grouped_s2/swiglu", stream);
1319        if (x_scales != nullptr) quantize_q8_0_scaled(gate_up, h_q8_0, h_scales, cap_entries * (int64_t) FF, stream);
1320        else quantize_q8_0(gate_up, h_q8_0, cap_entries * (int64_t) FF, stream);
1321        }
1322    }
1323    {
1324        const dim3 grid((unsigned) (H / D_ROWS), (unsigned) cap_groups);
1325        const float* hs = x_scales != nullptr ? h_scales : nullptr;
1326        if (fast) {
1327            if (single_entry)
1328                down_grouped_t_kernel<0, 1><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out);
1329            else
1330                down_grouped_t_kernel<0><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out);
1331            if constexpr (kWide)
1332                if (second) down_grouped_t_kernel<GMAX><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out);
1333        } else {
1334            down_grouped_kernel<0><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out);
1335            if constexpr (kWide)
1336                if (second) down_grouped_kernel<GMAX><<<grid, 256, 0, cs>>>(grp_ptr, grp_start, n_groups, ent_dst, h_q8_0, hs, out);
1337        }
1338        check("moe_grouped_s2/down", stream);
1339    }
1340}
1341
1342void moe_grouped_s2(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
1343                    const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
1344                    const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream) {
1345    grouped_s2_impl(grp_ptr, grp_start, n_groups, ent_dst, ent_tok, cap_groups, cap_entries, x_q8_0, x_scales, scratch, out, stream,
1346                    GMAX);
1347}
1348
1349#if STRATA_VERIFY_MAX_T > 8
1350void moe_grouped_s2_wide(const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
1351                         const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries,
1352                         const uint8_t* x_q8_0, const float* x_scales, void* scratch, float* out, void* stream,
1353                         int max_group) {
1354    grouped_s2_impl(grp_ptr, grp_start, n_groups, ent_dst, ent_tok, cap_groups, cap_entries, x_q8_0, x_scales, scratch, out, stream,
1355                    max_group);
1356}
1357#endif
1358
1359__global__ void add_hits_mapped_kernel(float* __restrict__ parts, const float* __restrict__ hit_out,
1360                                        const volatile float* __restrict__ ymiss, const int32_t* __restrict__ dst,
1361                                        const int32_t* __restrict__ count, const volatile uint32_t* __restrict__ wait_flag,
1362                                        uint32_t wait_value, int n_embd, int64_t rows_total) {
1363    // LATENT-CUT-A: wait_flag + copy_rows_from_mapped + moe_hit_add fused. The grid walks ALL
1364    // routed rows r (one block per row, like the copy kernel). Row r in dst (the GPU's share):
1365    // parts[r] = 0 + hit_out[r] (the copy kernel zeroed it, moe_hit_add added hit - one
1366    // rounding, kept here as the single add). Row r NOT in dst (the CPU pool's):
1367    // parts[r] = ymiss[r] (the copy stored it; the add kernel then left it - hit_out is zero
1368    // on those rows only if the U stage wrote none, so we add hit_out[r] the same way the old
1369    // moe_hit_add did NOT: it only walked dst. Faithful: store ymiss, no hit add).
1370    if (threadIdx.x == 0) {   // 143-amdk: the wait folded into every row block (as the original)
1371        while (*wait_flag < wait_value) strata_spin_pause();
1372        __threadfence_system();
1373    }
1374    __syncthreads();
1375    const int r = blockIdx.x;   // the routed position: m_ymiss is indexed by it
1376    __shared__ int hit;
1377    if (threadIdx.x == 0) {
1378        int h = 0;
1379        const int c = *count;
1380        for (int i = 0; i < c; ++i) h |= dst[i] == r;
1381        hit = h;
1382    }
1383    __syncthreads();
1384    float* p = parts + (int64_t) r * (int64_t) n_embd;
1385    if (hit) {
1386        // the GPU's own row: zero then add the hit (the old two-step exactly: copy zeroed, add added)
1387        for (int i = threadIdx.x; i < n_embd; i += blockDim.x)
1388            p[i] = hit_out[(int64_t) r * (int64_t) n_embd + i];
1389    } else {
1390        // the CPU pool's row: store the mapped row (the copy kernel's store), no hit add
1391        const volatile float* ym = ymiss + (int64_t) r * (int64_t) n_embd;
1392        for (int i = threadIdx.x; i < n_embd; i += blockDim.x)
1393            p[i] = ym[i];
1394    }
1395}
1396
1397void moe_hit_add(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap,
1398                 int64_t n_embd, void* stream) {
1399    if (cap <= 0) return;
1400    const dim3 grid((unsigned) ((n_embd + 255) / 256 < 8 ? (n_embd + 255) / 256 : 8), (unsigned) cap);
1401    add_hits_kernel<<<grid, 256, 0, (cudaStream_t) stream>>>(parts, hit_out, dst, count, (int) n_embd);
1402    check("moe_hit_add", stream);
1403}
1404
1405// knife-0: the u0 path's GPU-row write is an ASSIGNMENT (add_hits_mapped_kernel: p[i] = hit_out[r*H+i]), not an add:
1406// in the latent branch nothing writes parts for those rows before the merge (the VRAM share writes hit_out, the PCIe
1407// share lat_yl_grp), so an add there keeps the previous window's stale rows (a wrong first token).
1408__global__ void set_hits_kernel(float* __restrict__ parts, const float* __restrict__ hit_out,
1409                                const int32_t* __restrict__ dst, const int32_t* __restrict__ count, int n_embd) {
1410    const int h = blockIdx.y;
1411    if (h >= *count) return;
1412    const size_t row = (size_t) dst[h] * (size_t) n_embd;
1413    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n_embd; i += gridDim.x * blockDim.x)
1414        parts[row + i] = hit_out[row + i];
1415}
1416void moe_hit_set(float* parts, const float* hit_out, const int32_t* dst, const int32_t* count, int64_t cap,
1417                 int64_t n_embd, void* stream) {
1418    if (cap <= 0) return;
1419    const dim3 grid((unsigned) ((n_embd + 255) / 256 < 8 ? (n_embd + 255) / 256 : 8), (unsigned) cap);
1420    set_hits_kernel<<<grid, 256, 0, (cudaStream_t) stream>>>(parts, hit_out, dst, count, (int) n_embd);
1421    check("moe_hit_set", stream);
1422}
1423
1424void moe_hit_add_mapped(float* parts, const float* hit_out, const volatile float* ymiss, const int32_t* dst,
1425                        const int32_t* count, int64_t cap, int64_t n_embd, const volatile uint32_t* wait_flag,
1426                        uint32_t wait_value, void* stream) {
1427    // LATENT-CUT-A: the fused replacement of wait_flag_ge + copy_rows_from_mapped + moe_hit_add.
1428    // Grid: one block per ROUTED row (cap = n*K), 128 threads - the copy kernel's shape.
1429    if (cap <= 0) return;
1430    add_hits_mapped_kernel<<<(unsigned) cap, 128, 0, (cudaStream_t) stream>>>(parts, hit_out, ymiss, dst, count,
1431                                                                               wait_flag, wait_value, (int) n_embd, cap);
1432    check("moe_hit_add_mapped", stream);
1433}
1434
1435void moe_hit_grouped_s2_cpu_order(const uint8_t* blob_base, const int32_t* slot_index,
1436                                 const int32_t* dst_index, int64_t n_hits, int64_t blob_bytes,
1437                                 const uint8_t* x_q8_0, void* scratch, float* out, void* stream,
1438                                 const float* x_scales, float* gate_up_trace) {
1439    if (n_hits <= 0) return;
1440    if (x_scales == nullptr) {
1441        std::fprintf(stderr, "moe_hit_grouped_s2_cpu_order requires fp32 activation scales\n");
1442        std::exit(1);
1443    }
1444    cudaStream_t cs = (cudaStream_t) stream;
1445    const uint64_t gu_bytes = ((uint64_t) n_hits * 2 * FF * 4 + 15) & ~15ull;
1446    const uint64_t q8_bytes = ((uint64_t) n_hits * (FF / 32) * 34 + 15) & ~15ull;
1447    const uint64_t scale_bytes = ((uint64_t) n_hits * (FF / 32) * 4 + 15) & ~15ull;
1448    float* gu = (float*) scratch;
1449    uint8_t* hq = (uint8_t*) scratch + gu_bytes;
1450    float* hs = (float*) (hq + q8_bytes);
1451    float* hh = (float*) ((uint8_t*) hs + scale_bytes);
1452    float* xh = (float*) ((uint8_t*) hh + scale_bytes);
1453    activation_correction_kernel<<<(H / 32 + THREADS - 1) / THREADS, THREADS, 0, cs>>>(
1454        x_q8_0, x_scales, xh, H / 32);
1455    check("cpu_order/input_correction", stream);
1456    const int rows_per_block = THREADS / 8;
1457    cpu_order_projection_kernel<false><<<(unsigned) ((n_hits * 2 * FF + rows_per_block - 1) / rows_per_block),
1458                                            THREADS, 0, cs>>>(
1459        blob_base, slot_index, dst_index, blob_bytes, x_q8_0, x_scales, xh, gu, (int) n_hits);
1460    check("cpu_order/gate_up", stream);
1461    if (gate_up_trace != nullptr &&
1462        cudaMemcpyAsync(gate_up_trace, gu, (size_t) n_hits * 2 * FF * sizeof(float),
1463                        cudaMemcpyDeviceToDevice, cs) != cudaSuccess) {
1464        std::fprintf(stderr, "cpu_order/gate_up_trace copy failed\n");
1465        std::exit(1);
1466    }
1467    cpu_order_swiglu_kernel<<<(unsigned) ((n_hits * FF + THREADS - 1) / THREADS), THREADS, 0, cs>>>(
1468        gu, (int) n_hits * FF);
1469    check("cpu_order/swiglu", stream);
1470    cpu_order_quantize_kernel<<<(unsigned) ((n_hits * (FF / 32) + THREADS - 1) / THREADS), THREADS, 0, cs>>>(
1471        gu, hq, hs, hh, (int) n_hits * (FF / 32));
1472    check("cpu_order/intermediate_quantize", stream);
1473    cpu_order_projection_kernel<true><<<(unsigned) ((n_hits * H + rows_per_block - 1) / rows_per_block),
1474                                           THREADS, 0, cs>>>(
1475        blob_base, slot_index, dst_index, blob_bytes, hq, hs, hh, out, (int) n_hits);
1476    check("cpu_order/down", stream);
1477}
1478
1479}  // namespace strata::kernels