okami.mom/strata

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

waveringanafix partial rows and column scales in latent D projections14dd31524

main
84.9 KiB1599 linesraw
1// src/prefill/moe_fused.cu - see include/strata/prefill/moe_fused.hpp (#136: the Q2_0 pack's prompt experts on
2// Strata's own int8 tensor-core kernels, with the grouping on the GPU).
3//
4// The arithmetic.  A Q2_0 block is 64 weights w = d_w * (q - 1), q in 0..3, four codes per byte, weight j of a block
5// in byte j / 4 at bits 2 * (j % 4).  An activation block of 32 values is x = d_x * a with a = round(x / d_x) in
6// -127..127.  Over one 32-value half-block
7//     sum w x = d_w * d_x * (sum q a - sum a),
8// so the int8 product takes the codes as they are (0..3 is a valid s8) and the offset is the activations' own sum,
9// stored with the block.  The dot product (|sum q a| <= 32 * 3 * 127 < 2^22) becomes a float exactly with one
10// integer add: as_float(0x4B400000 + dot) = 1.5 * 2^23 + dot, and the block stores c = -(1.5 * 2^23 + sum a), so
11// as_float(0x4B400000 + dot) + c = dot - sum a with no rounding.  Per output and 64-block that is
12//     acc += d_w * (d_x0 * t0 + d_x1 * t1)        (t = dot - sum a of each half)
13// - two integer adds, two float adds and three multiply-adds.
14//
15// The K order.  mma.sync m16n8k32 takes four consecutive k of a row (A) or column (B) per register.  Four consecutive
16// weights are one code byte; four codes of one register instead come from the same 2-bit field of four consecutive
17// bytes - (word >> 2t) & 0x03030303 holds weights t, t+4, t+8, t+12 of a 16-weight word.  So the kernels use that order
18// for the k of a half-block: mma k index 16h + 4t + j stands for weight (and activation) 16h + t + 4j.  The
19// activations are stored in it (perm32), and a lane's two B registers (h = 0 and 1) are adjacent: one 8-byte load.
20#include "strata/prefill/moe_fused.hpp"
21#include "strata/kernels/gfx_arch.hpp"
22#include "strata/core/emulate.hpp"
23#include "strata/kernels/q8_1_finite.hpp"
24
25#include <cuda_fp16.h>
26#include <cuda_runtime.h>
27
28// moe_fused_q3k: moe_fused.cu, COPIED WHOLE, with the q3k pack's two quantized routes in place of NVFP4 - Q3_K
29// gate/up and IQ4_NL down - decoded by the functions lat_q3k_gu.cu / lat_q3k_down.cu carry (verified against a host
30// dequantization to 1e-7 and against native_expert_grouped to 1e-7).  Nothing else changed except: this namespace
31// (fused -> fused_q3k, so both files can live in one binary), the two exports' names, and LWPITCH (76 -> 80) - a
32// Q3_K sub-block's scale is d * (sc - 32) and is kept in fp32 (an fp16 stage would round it by 5e-4 relative); with
33// fp32 the staged row is bit for bit the one lat_q3k_gu.cu writes.
34#define GGML_COMMON_DECL_CUDA
35#define GGML_COMMON_IMPL_CUDA
36#include "ggml-common.h"   // kvalues_iq4nl, block_q8_1
37
38#include <algorithm>
39#include <cstdio>
40#include <cstdlib>
41#include <cstring>
42#include <mutex>
43
44namespace strata::prefill::fused_q3k {
45
46using namespace fused;   // WideBatch, LatentGeom, group_bytes, ... (this file is moe_fused.cu's)
47namespace {
48
49void ck(cudaError_t e, const char* what) {
50    if (e != cudaSuccess) {
51        std::fprintf(stderr, "prefill fused experts: %s: %s\n", what, cudaGetErrorString(e));
52        std::exit(1);
53    }
54}
55
56constexpr int AB = 80;                  // activation bytes per 64 values: 64 codes, then {d0, c0, d1, c1}
57constexpr int MAGIC = 0x4B400000;       // the bits of 1.5 * 2^23
58constexpr float MAGICF = 12582912.0f;
59// The Strata Q2_0 blob (moe_mmq.cu strata_q2_kernel, kernels.cu blob_dequant_kernel): gate/up codes [1280][640 B]
60// (rows interleaved: gate of feature f at row 2f, its up at 2f + 1), down codes [2560][160 B], gate/up scales
61// [1280][40] fp16, down scales [2560][10] fp16.
62constexpr size_t O_GU_CODES = 0, O_D_CODES = (size_t) 1280 * 640, O_GU_SC = O_D_CODES + (size_t) 2560 * 160,
63                 O_D_SC = O_GU_SC + (size_t) 1280 * 40 * 2;
64constexpr int THREADS = 512;            // 16 warps: 4 along the weight rows (64 each) x 4 along the tile rows (16 each)
65constexpr int WROWS = 256;              // weight rows per work item: 128 features of gate/up, or 256 outputs of down
66constexpr int STAGES = 4;               // cp.async pipeline depth, one 64-weight block of K per stage
67constexpr int STAGE_BYTES = WROWS * 16 + kTileRows * AB;
68constexpr size_t smem_bytes(bool gu) {
69    return (size_t) WROWS * (gu ? 40 : 10) * 2 + STAGES * STAGE_BYTES + kTileRows * 4;
70}
71
72// the stored position of value k of a 32-value half-block (see "The K order")
73__host__ __device__ __forceinline__ int perm32(int k) { return 8 * (k & 3) + 4 * (k >> 4) + ((k & 15) >> 2); }
74// where value k of a 32-value half-block is stored: perm32 for the CUDA kernel; on HIP the gfx11 WMMA kernel's order
75// (value 4b + t of a 16-value word at 4t + b: see expert_w11_kernel)
76__host__ __device__ __forceinline__ int act_pos(int k) {
77#if defined(__HIPCC__)
78    return (k & 16) | ((k & 3) << 2) | ((k >> 2) & 3);
79#else
80    return perm32(k);
81#endif
82}
83
84struct Tables {
85    int32_t *cnt, *off, *fill, *ts;      // per expert: rows, first row (E + 1), placement cursor, first tile (E + 1)
86    int2* tiles;                         // {expert, first row}, in expert order
87};
88size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; }
89Tables tables(void* scratch, int n_expert) {
90    int32_t* p = (int32_t*) scratch;
91    return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1,
92            (int2*) ((uint8_t*) scratch + tiles_at(n_expert))};
93}
94
95// ---- activations: one warp per 64 values
96__global__ void quant_act_kernel(const float* __restrict__ x, int64_t nblk, uint8_t* __restrict__ xa) {
97    const int64_t w = (int64_t) blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32;
98    const int lane = threadIdx.x & 31;
99    if (w >= nblk) return;
100    const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane];
101    float a0 = fabsf(v0), a1 = fabsf(v1);
102#pragma unroll
103    for (int o = 16; o > 0; o >>= 1) {
104        a0 = fmaxf(a0, __shfl_xor_sync(0xffffffffu, a0, o));
105        a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o));
106    }
107    const int q0 = a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0;
108    const int q1 = a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0;
109    int s0 = q0, s1 = q1;
110#pragma unroll
111    for (int o = 16; o > 0; o >>= 1) {
112        s0 += __shfl_xor_sync(0xffffffffu, s0, o);
113        s1 += __shfl_xor_sync(0xffffffffu, s1, o);
114    }
115    uint8_t* out = xa + w * AB;
116    out[act_pos(lane)] = (uint8_t) (int8_t) q0;
117    out[32 + act_pos(lane)] = (uint8_t) (int8_t) q1;
118    if (lane == 0)
119        *(float4*) (out + 64) = make_float4(a0 / 127.0f, -(MAGICF + (float) s0), a1 / 127.0f, -(MAGICF + (float) s1));
120}
121
122// ---- grouping: counts, offsets and tiles, placement
123__global__ void count_kernel(const int32_t* __restrict__ ids, int64_t n, int E, int32_t* __restrict__ cnt) {
124    extern __shared__ int32_t hist[];
125    for (int e = threadIdx.x; e < E; e += blockDim.x) hist[e] = 0;
126    __syncthreads();
127    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
128        const int e = ids[i];
129        if ((unsigned) e < (unsigned) E) atomicAdd(&hist[e], 1);
130    }
131    __syncthreads();
132    for (int e = threadIdx.x; e < E; e += blockDim.x)
133        if (hist[e]) atomicAdd(&cnt[e], hist[e]);
134}
135
136// exclusive prefix sum over the block (blockDim a multiple of 32); *total = the block's sum
137__device__ int block_excl_sum(int v, int* total, int* sh) {
138    const int lane = threadIdx.x & 31, w = threadIdx.x >> 5, nw = blockDim.x >> 5;
139    int x = v;
140#pragma unroll
141    for (int o = 1; o < 32; o <<= 1) {
142        const int y = __shfl_up_sync(0xffffffffu, x, o);
143        if (lane >= o) x += y;
144    }
145    if (lane == 31) sh[w] = x;
146    __syncthreads();
147    if (w == 0) {
148        int s = lane < nw ? sh[lane] : 0;
149#pragma unroll
150        for (int o = 1; o < 32; o <<= 1) {
151            const int y = __shfl_up_sync(0xffffffffu, s, o);
152            if (lane >= o) s += y;
153        }
154        sh[lane] = s;
155    }
156    __syncthreads();
157    const int r = x - v + (w > 0 ? sh[w - 1] : 0);
158    *total = sh[nw - 1];
159    __syncthreads();   // sh is reused by the next call
160    return r;
161}
162
163// one block, a thread per expert (E <= 1024)
164__global__ void scan_kernel(Tables tb, int E) {
165    __shared__ int sh[32];
166    const int e = threadIdx.x;
167    const int c = e < E ? tb.cnt[e] : 0, nt = (c + kTileRows - 1) / kTileRows;
168    int rows = 0, tiles = 0;
169    const int o = block_excl_sum(c, &rows, sh), to = block_excl_sum(nt, &tiles, sh);
170    if (e < E) {
171        tb.off[e] = o;
172        tb.fill[e] = o;
173        tb.ts[e] = to;
174        for (int i = 0; i < nt; ++i) tb.tiles[to + i] = make_int2(e, o + i * kTileRows);
175    }
176    if (e == 0) {
177        tb.off[E] = rows;
178        tb.ts[E] = tiles;
179    }
180}
181
182__global__ void place_kernel(const int32_t* __restrict__ ids, int64_t n, int k, int E, Tables tb,
183                             int32_t* __restrict__ slot, int32_t* __restrict__ src) {
184    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
185    if (i >= n) return;
186    const int e = ids[i];
187    if ((unsigned) e >= (unsigned) E) { slot[i] = 0; return; }   // (the router never writes one)
188    const int p = atomicAdd(&tb.fill[e], 1);
189    slot[i] = p;
190    src[p] = (int32_t) (i / k);
191}
192
193// ---- the expert products
194#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
195__device__ __forceinline__ void cp16(void* dst, const void* src) {
196    asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)),
197                 "l"(src));
198}
199__device__ __forceinline__ void cp4(void* dst, const void* src) {
200    asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)),
201                 "l"(src));
202}
203__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
204template <int N> __device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); }
205// d = A (16 x 32 s8, row) * B (32 x 8 s8, col), int32, from zero
206__device__ __forceinline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
207    asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n"
208        : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3])
209        : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(0));
210}
211#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
212// Turing (STRATA_PF_FUSED_SM75): no cp.async - the stages are filled by plain copies (the same bytes; the barriers
213// around them stay) - and no m16n8k32 with s8 operands: it is four m8n8k16, rows g / g + 8 by k 0-15 / 16-31 (the
214// m16n8k32 fragments: a[0] / a[1] rows g / g + 8 at k 4 tig.., a[2] / a[3] the same at k 16 + 4 tig.., b0 / b1 the
215// two k halves).  The int32 sums are exact in any order: the same d as the sm_80 instruction.
216__device__ __forceinline__ void cp16(void* dst, const void* src) { *(uint4*) dst = __ldg((const uint4*) src); }
217__device__ __forceinline__ void cp4(void* dst, const void* src) { *(uint32_t*) dst = __ldg((const uint32_t*) src); }
218__device__ __forceinline__ void cp_commit() {}
219template <int N> __device__ __forceinline__ void cp_wait() {}
220__device__ __forceinline__ void mma8_s8(int& c0, int& c1, uint32_t a, uint32_t b) {
221    asm("mma.sync.aligned.m8n8k16.row.col.s32.s8.s8.s32 {%0,%1}, {%2}, {%3}, {%0,%1};\n"
222        : "+r"(c0), "+r"(c1) : "r"(a), "r"(b));
223}
224__device__ __forceinline__ void mma_s8(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) {
225    d[0] = d[1] = d[2] = d[3] = 0;
226    mma8_s8(d[0], d[1], a[0], b0);
227    mma8_s8(d[0], d[1], a[2], b1);
228    mma8_s8(d[2], d[3], a[1], b0);
229    mma8_s8(d[2], d[3], a[3], b1);
230}
231#endif
232
233// One work item = (tile of up to 64 routed rows of expert e, a block of 256 weight rows); a persistent grid walks
234// the batch's items (their count is on the device).  GU: gate/up rows of 128 features against the rows' tokens'
235// activations (`act` per token, 2560 values), SwiGLU, H to int8 per 32 features into `out` (per row, 640 values).
236// !GU: down rows (256 outputs) against H (`act` per row), FP32 into `dm` per row.
237// Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, its gate rows as mma rows 0-7 and
238// its up rows as 8-15, so a lane holds gate and up of one feature: SwiGLU in registers), tile rows 16 wt.. as two n8.
239template <bool GU>
240__global__ void __launch_bounds__(THREADS, 1)
241expert_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src,
242              uint8_t* __restrict__ out, float* __restrict__ dm) {
243#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750
244    constexpr int NKB = GU ? 40 : 10;                 // 64-weight blocks along K
245    constexpr int NFB = GU ? 5 : 10;                  // weight-row blocks per tile
246    constexpr int CODE_LD = GU ? 640 : 160;           // code bytes per weight row
247    constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;
248    constexpr int ACT_LD = NKB * AB;                  // bytes per activation row: 3200 (a token), 800 (a row's H)
249    constexpr unsigned M2 = 0x03030303u;
250    extern __shared__ __align__(16) uint8_t smem[];
251    const __half* wsc = (const __half*) smem;                     // [256][NKB] the work item's weight scales
252    uint8_t* stages = smem + WROWS * NKB * 2;                     // [STAGES] x {codes [256][16], act [64][AB]}
253    int* srow = (int*) (stages + STAGES * STAGE_BYTES);           // [64] the activation row of each tile row
254
255    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3;
256    const int wf = warp & 3, nb0 = 16 * (warp >> 2);
257    int ra[4], rb[4];                                             // the local weight rows of mma rows g and g + 8
258#pragma unroll
259    for (int i = 0; i < 4; ++i) {
260        if (GU) { ra[i] = 2 * (32 * wf + 8 * i + g); rb[i] = ra[i] + 1; }
261        else { ra[i] = 64 * wf + 16 * i + g; rb[i] = ra[i] + 8; }
262    }
263    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
264    for (int w = blockIdx.x; w < nwork; w += gridDim.x) {
265        const int2 tl = tb.tiles[t0 + w / NFB];
266        const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);
267        const uint8_t* blob = b.blob[e - b.e0];
268        const int rbase = fb * WROWS;
269        __syncthreads();                                          // the previous item is done with the buffers
270        if (tid < kTileRows) {
271            const int r = row0 + min(tid, nrows - 1);             // rows past the tile's end repeat its last one
272            srow[tid] = GU ? src[r] : r;
273        }
274        for (int c = tid; c < WROWS * 5; c += THREADS) {          // the scales: 5 x 16 B (GU) or 5 x 4 B a row
275            const int r = c / 5, q = c % 5;
276            if (GU) cp16(smem + r * 80 + q * 16, blob + O_SC + (size_t) (rbase + r) * 80 + q * 16);
277            else cp4(smem + r * 20 + q * 4, blob + O_SC + (size_t) (rbase + r) * 20 + q * 4);
278        }
279        __syncthreads();                                          // srow
280        auto load = [&](int kb) {
281            uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;
282            if (tid < WROWS) cp16(st + tid * 16, blob + O_CODES + (size_t) (rbase + tid) * CODE_LD + kb * 16);
283            const int a = tid - (THREADS - kTileRows * 5);        // the last 320 threads: 64 rows x 5 x 16 B
284            if (a >= 0) {
285                const int r = a / 5, q = a % 5;
286                cp16(st + WROWS * 16 + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + kb * AB + q * 16);
287            }
288        };
289#pragma unroll
290        for (int s = 0; s < STAGES - 1; ++s) {
291            if (s < NKB) load(s);
292            cp_commit();
293        }
294        // a warp whose rows are all past the tile's end only takes part in the loads
295        const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
296        float acc[4][2][4];
297#pragma unroll
298        for (int i = 0; i < 4; ++i)
299#pragma unroll
300            for (int n = 0; n < 2; ++n)
301#pragma unroll
302                for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
303        for (int kb = 0; kb < NKB; ++kb) {
304            cp_wait<STAGES - 2>();
305            __syncthreads();
306            if (kb + STAGES - 1 < NKB) load(kb + STAGES - 1);
307            cp_commit();
308            if (!on0) continue;
309            const uint8_t* st = stages + (kb % STAGES) * STAGE_BYTES;
310            const uint8_t* sa = st + WROWS * 16;
311            uint2 bq[2][2];                                       // [n8 tile][half]: the B registers
312            float4 sc[2][2];                                      // [n8 tile][column 2 tig + c]: {d0, c0, d1, c1}
313#pragma unroll
314            for (int n = 0; n < 2; ++n) {
315                if (n == 1 && !on1) break;
316                const uint8_t* r = sa + (nb0 + 8 * n + g) * AB + 8 * tig;
317                bq[n][0] = *(const uint2*) r;
318                bq[n][1] = *(const uint2*) (r + 32);
319                sc[n][0] = *(const float4*) (sa + (nb0 + 8 * n + 2 * tig) * AB + 64);
320                sc[n][1] = *(const float4*) (sa + (nb0 + 8 * n + 2 * tig + 1) * AB + 64);
321            }
322#pragma unroll
323            for (int i = 0; i < 4; ++i) {
324                const uint4 ca = *(const uint4*) (st + ra[i] * 16), cb = *(const uint4*) (st + rb[i] * 16);
325                const float da = __half2float(wsc[ra[i] * NKB + kb]), db = __half2float(wsc[rb[i] * NKB + kb]);
326                const int s = 2 * tig;
327                const uint32_t a0[4] = {(ca.x >> s) & M2, (cb.x >> s) & M2, (ca.y >> s) & M2, (cb.y >> s) & M2};
328                const uint32_t a1[4] = {(ca.z >> s) & M2, (cb.z >> s) & M2, (ca.w >> s) & M2, (cb.w >> s) & M2};
329#pragma unroll
330                for (int n = 0; n < 2; ++n) {
331                    if (n == 1 && !on1) break;
332                    int d0[4], d1[4];
333                    mma_s8(d0, a0, bq[n][0].x, bq[n][0].y);
334                    mma_s8(d1, a1, bq[n][1].x, bq[n][1].y);
335#pragma unroll
336                    for (int q = 0; q < 4; ++q) {
337                        const float4 z = sc[n][q & 1];
338                        const float u0 = __int_as_float(MAGIC + d0[q]) + z.y, u1 = __int_as_float(MAGIC + d1[q]) + z.w;
339                        acc[i][n][q] = fmaf(q < 2 ? da : db, fmaf(z.z, u1, z.x * u0), acc[i][n][q]);
340                    }
341                }
342            }
343        }
344        if (!on0) continue;
345        if (GU) {
346            // SwiGLU of feature 32 wf + 8 i + g (lane g of m tile i), tile rows nb0 + 8 n + 2 tig + c; H to int8 per
347            // row over the warp's 32 features (= one 32-value half-block of the down product's K)
348            const int blk = 4 * fb + wf;
349#pragma unroll
350            for (int n = 0; n < 2; ++n) {
351                if (n == 1 && !on1) break;
352#pragma unroll
353                for (int c = 0; c < 2; ++c) {
354                    float h[4], am = 0.0f;
355#pragma unroll
356                    for (int i = 0; i < 4; ++i) {
357                        const float gt = acc[i][n][c], up = acc[i][n][2 + c];
358                        h[i] = gt / (1.0f + __expf(-gt)) * up;
359                        am = fmaxf(am, fabsf(h[i]));
360                    }
361#pragma unroll
362                    for (int o = 4; o < 32; o <<= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o));
363                    const float inv = am > 0.0f ? 127.0f / am : 0.0f;
364                    int qv[4], sum = 0;
365#pragma unroll
366                    for (int i = 0; i < 4; ++i) { qv[i] = __float2int_rn(h[i] * inv); sum += qv[i]; }
367#pragma unroll
368                    for (int o = 4; o < 32; o <<= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
369                    const int r = nb0 + 8 * n + 2 * tig + c;
370                    if (r < nrows) {
371                        uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB;
372                        const int hh = blk & 1;
373#pragma unroll
374                        for (int i = 0; i < 4; ++i) o[32 * hh + perm32(8 * i + g)] = (uint8_t) (int8_t) qv[i];
375                        if (g == 0) *(float2*) (o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum));
376                    }
377                }
378            }
379        } else {
380#pragma unroll
381            for (int i = 0; i < 4; ++i)
382#pragma unroll
383                for (int n = 0; n < 2; ++n) {
384                    if (n == 1 && !on1) break;
385#pragma unroll
386                    for (int q = 0; q < 4; ++q) {
387                        const int r = nb0 + 8 * n + 2 * tig + (q & 1);
388                        if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + (q < 2 ? ra[i] : rb[i])] = acc[i][n][q];
389                    }
390                }
391        }
392    }
393#endif
394}
395
396#if defined(__HIPCC__)
397// ---- Aurora (S23): the same products on gfx11 (RDNA3 / RDNA3.5) matrix cores, v_wmma_i32_16x16x16_iu8 (wave32).
398// Fragments (gfx11): A lane l holds the 16 k of row l % 16 (lanes 16..31 repeat lanes 0..15), B lane l the 16 k of
399// column l % 16, C/D lane l holds D[2i + l / 16][l % 16], i = 0..7.  A = 16 weight rows, B = 16 tile rows (tokens):
400// a lane's eight results are eight weight rows of ONE tile row, whose activation scales it already holds.
401// The K order of a 16-weight word (one k-step): A register t = (word >> 2t) & 0x03030303 holds weights t, t+4, t+8,
402// t+12, so k index p = 4t + b stands for weight 4b + t; the activations are stored in that order (act_pos).  The
403// integer dot of each 32-value half (two k-steps) is exact and the epilogue is the CUDA kernel's, so the numbers are
404// those of expert_kernel (another K order inside exact integer sums).
405// No LDS staging: a wave reads its weight rows (16 B per row and 64-weight block) and its tile rows' activation
406// blocks (80 B) straight from global memory (L2: an expert's rows are read by every tile, a token's by every weight
407// block), one block ahead in registers; the work item's weight scales go to LDS once.
408#if defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || defined(__gfx1103__) || defined(__gfx1150__) || defined(__gfx1151__)
409#define STRATA_FUSED_W11 1
410#else
411#define STRATA_FUSED_W11 0
412#endif
413typedef int w11_i4 __attribute__((ext_vector_type(4)));
414typedef int w11_i8 __attribute__((ext_vector_type(8)));
415constexpr int W_ROWS = 128;                       // weight rows per work item (GU: 64 features = one H block)
416constexpr int W_THREADS = 256;                    // 8 waves: 4 along the weight rows (32 each) x 2 along the tile (32)
417
418__device__ __forceinline__ w11_i8 wmma_iu8(w11_i4 a, w11_i4 b, w11_i8 c) {
419#if STRATA_FUSED_W11
420    return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(false, a, true, b, c, false);
421#else
422    __builtin_trap();
423    return c;
424#endif
425}
426
427template <bool GU>
428__global__ void __launch_bounds__(W_THREADS)
429expert_w11_kernel(const Batch b, const Tables tb, const uint8_t* __restrict__ act, const int32_t* __restrict__ src,
430                  uint8_t* __restrict__ out, float* __restrict__ dm) {
431#if STRATA_FUSED_W11
432    constexpr int NKB = GU ? 40 : 10;                 // 64-weight blocks along K
433    constexpr int NFB = (GU ? 1280 : 2560) / W_ROWS;  // work items per tile
434    constexpr int CODE_LD = GU ? 640 : 160;           // code bytes per weight row
435    constexpr size_t O_CODES = GU ? O_GU_CODES : O_D_CODES, O_SC = GU ? O_GU_SC : O_D_SC;
436    constexpr int ACT_LD = NKB * AB;                  // bytes per activation row
437    constexpr unsigned M2 = 0x03030303u;
438    __shared__ __align__(16) uint16_t wsc[W_ROWS * NKB];        // the item's weight scales (fp16), [row][kb]
439    __shared__ int srow[kTileRows];
440    __shared__ float hs[GU ? kTileRows : 1][GU ? 65 : 1];      // GU: H of the item's 64 features, [tile row][feature]
441    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
442    const int wm = wave & 3, wn = wave >> 2, l16 = lane & 15, hi = lane >> 4;
443    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
444    for (int w = blockIdx.x; w < nwork; w += gridDim.x) {
445        const int2 tl = tb.tiles[t0 + w / NFB];
446        const int fb = w % NFB, e = tl.x, row0 = tl.y, nrows = min(kTileRows, tb.off[e + 1] - row0);
447        const uint8_t* blob = b.blob[e - b.e0];
448        const int rbase = fb * W_ROWS;
449        __syncthreads();                                          // the previous item is done with srow / wsc / hs
450        if (tid < kTileRows) {
451            const int r = row0 + min(tid, nrows - 1);             // rows past the tile's end repeat its last one
452            srow[tid] = GU ? src[r] : r;
453        }
454        {
455            const uint4* s4 = reinterpret_cast<const uint4*>(blob + O_SC + (size_t) rbase * NKB * 2);
456            for (int i = tid; i < W_ROWS * NKB / 8; i += W_THREADS) reinterpret_cast<uint4*>(wsc)[i] = s4[i];
457        }
458        __syncthreads();
459        const bool on = 32 * wn < nrows;                          // a wave past the tile's rows only stages
460        float acc[2][2][8];
461#pragma unroll
462        for (int mt = 0; mt < 2; ++mt)
463#pragma unroll
464            for (int nt = 0; nt < 2; ++nt)
465#pragma unroll
466                for (int i = 0; i < 8; ++i) acc[mt][nt][i] = 0.0f;
467        if (on) {
468            const uint8_t* arow[2];
469            const uint8_t* brow[2];
470#pragma unroll
471            for (int mt = 0; mt < 2; ++mt) arow[mt] = blob + O_CODES + (size_t) (rbase + 32 * wm + 16 * mt + l16) * CODE_LD;
472#pragma unroll
473            for (int nt = 0; nt < 2; ++nt) brow[nt] = act + (size_t) srow[32 * wn + 16 * nt + l16] * ACT_LD;
474            uint4 ac[2], bq[2][4];
475            float4 bs[2];
476            auto fetch = [&](int kb, uint4 (&a)[2], uint4 (&q)[2][4], float4 (&s)[2]) {
477#pragma unroll
478                for (int mt = 0; mt < 2; ++mt) a[mt] = *reinterpret_cast<const uint4*>(arow[mt] + kb * 16);
479#pragma unroll
480                for (int nt = 0; nt < 2; ++nt) {
481                    const uint4* p = reinterpret_cast<const uint4*>(brow[nt] + kb * AB);
482                    q[nt][0] = p[0]; q[nt][1] = p[1]; q[nt][2] = p[2]; q[nt][3] = p[3];
483                    s[nt] = *reinterpret_cast<const float4*>(brow[nt] + kb * AB + 64);
484                }
485            };
486            fetch(0, ac, bq, bs);
487            for (int kb = 0; kb < NKB; ++kb) {
488                uint4 nac[2], nbq[2][4];
489                float4 nbs[2];
490                if (kb + 1 < NKB) fetch(kb + 1, nac, nbq, nbs);
491                w11_i8 c[2][2][2];                                // [half][mt][nt]
492#pragma unroll
493                for (int h = 0; h < 2; ++h)
494#pragma unroll
495                    for (int mt = 0; mt < 2; ++mt)
496#pragma unroll
497                        for (int nt = 0; nt < 2; ++nt) c[h][mt][nt] = w11_i8{0, 0, 0, 0, 0, 0, 0, 0};
498#pragma unroll
499                for (int ks = 0; ks < 4; ++ks) {                  // k-step = 16-weight word ks of the block
500                    w11_i4 A[2];
501#pragma unroll
502                    for (int mt = 0; mt < 2; ++mt) {
503                        const unsigned wd = ks == 0 ? ac[mt].x : ks == 1 ? ac[mt].y : ks == 2 ? ac[mt].z : ac[mt].w;
504                        A[mt] = w11_i4{(int) (wd & M2), (int) ((wd >> 2) & M2), (int) ((wd >> 4) & M2),
505                                       (int) ((wd >> 6) & M2)};
506                    }
507#pragma unroll
508                    for (int nt = 0; nt < 2; ++nt) {
509                        const uint4 q = bq[nt][ks];
510                        const w11_i4 B = w11_i4{(int) q.x, (int) q.y, (int) q.z, (int) q.w};
511#pragma unroll
512                        for (int mt = 0; mt < 2; ++mt) c[ks >> 1][mt][nt] = wmma_iu8(A[mt], B, c[ks >> 1][mt][nt]);
513                    }
514                }
515                // the epilogue: per 64-weight block acc += d_w * (d_x0 * (dot0 - sum0) + d_x1 * (dot1 - sum1))
516#pragma unroll
517                for (int mt = 0; mt < 2; ++mt) {
518                    float dw[8];
519#pragma unroll
520                    for (int i = 0; i < 8; ++i) {
521                        const int m = 32 * wm + 16 * mt + 2 * i + hi;
522                        dw[i] = __half2float(__ushort_as_half(wsc[m * NKB + kb]));
523                    }
524#pragma unroll
525                    for (int nt = 0; nt < 2; ++nt) {
526                        const float4 z = bs[nt];
527#pragma unroll
528                        for (int i = 0; i < 8; ++i) {
529                            const float u0 = __int_as_float(MAGIC + c[0][mt][nt][i]) + z.y;
530                            const float u1 = __int_as_float(MAGIC + c[1][mt][nt][i]) + z.w;
531                            acc[mt][nt][i] = fmaf(dw[i], fmaf(z.z, u1, z.x * u0), acc[mt][nt][i]);
532                        }
533                    }
534                }
535                if (kb + 1 < NKB) {
536#pragma unroll
537                    for (int mt = 0; mt < 2; ++mt) ac[mt] = nac[mt];
538#pragma unroll
539                    for (int nt = 0; nt < 2; ++nt) {
540                        bs[nt] = nbs[nt];
541#pragma unroll
542                        for (int j = 0; j < 4; ++j) bq[nt][j] = nbq[nt][j];
543                    }
544                }
545            }
546        }
547        if constexpr (GU) {
548            // SwiGLU: row 2f is feature f's gate (lanes 0..15), 2f + 1 its up (lanes 16..31) - the same (mt, i)
549            if (on) {
550#pragma unroll
551                for (int mt = 0; mt < 2; ++mt)
552#pragma unroll
553                    for (int nt = 0; nt < 2; ++nt)
554#pragma unroll
555                        for (int i = 0; i < 8; ++i) {
556                            const float up = __shfl_xor_sync(0xffffffffu, acc[mt][nt][i], 16);
557                            const float gt = acc[mt][nt][i];
558                            if (hi == 0) hs[32 * wn + 16 * nt + l16][16 * wm + 8 * mt + i] = gt / (1.0f + __expf(-gt)) * up;
559                        }
560            }
561            __syncthreads();
562            // H block fb (features 64 fb .. 64 fb + 63) to int8: a thread per (tile row, half)
563            if (tid < 2 * kTileRows) {
564                const int r = tid >> 1, hh = tid & 1;
565                if (r < nrows) {
566                    float am = 0.0f;
567#pragma unroll 8
568                    for (int j = 0; j < 32; ++j) am = fmaxf(am, fabsf(hs[r][32 * hh + j]));
569                    const float inv = am > 0.0f ? 127.0f / am : 0.0f;
570                    uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB;
571                    int sum = 0;
572                    uint32_t wd[8] = {};
573#pragma unroll
574                    for (int j = 0; j < 32; ++j) {
575                        const int qv = __float2int_rn(hs[r][32 * hh + j] * inv);
576                        sum += qv;
577                        const int p = act_pos(j);
578                        wd[p >> 2] |= (uint32_t) (uint8_t) (int8_t) qv << (8 * (p & 3));
579                    }
580                    uint4* o4 = reinterpret_cast<uint4*>(o + 32 * hh);
581                    o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]);
582                    o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]);
583                    *reinterpret_cast<float2*>(o + 64 + 8 * hh) = make_float2(am / 127.0f, -(MAGICF + (float) sum));
584                }
585            }
586        } else if (on) {
587#pragma unroll
588            for (int mt = 0; mt < 2; ++mt)
589#pragma unroll
590                for (int nt = 0; nt < 2; ++nt) {
591                    const int r = 32 * wn + 16 * nt + l16;
592                    if (r < nrows) {
593                        float* d = dm + (size_t) (row0 + r) * 2560 + rbase + 32 * wm + 16 * mt + hi;
594#pragma unroll
595                        for (int i = 0; i < 8; ++i) d[2 * i] = acc[mt][nt][i];
596                    }
597                }
598        }
599    }
600#else
601    __builtin_trap();
602#endif
603}
604#endif  // __HIPCC__
605
606unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); }
607
608struct DevInfo {
609    bool done = false;
610    int cc = 0, sms = 0, occ_gu = 0, occ_d = 0;
611};
612std::mutex g_mu;
613DevInfo g_dev[32];
614
615#if defined(__HIPCC__)
616// Resident blocks per multiprocessor for the gfx11 WMMA prompt-expert kernels' persistent grids.  HIP counts a gfx11
617// WGP (two CUs, which these kernels use as one in the default WGP mode) as one multiprocessor, and the occupancy query
618// answers 1 block for these kernels where 2 run side by side - so the grid was half the GPU's room.  gfx1151 (20
619// WGPs), 8192 tokens x top 10, IQ3_S / IQ4_NL, one layer: 1 block per WGP 60.7 ms, 2 44.7, 3 49.9, 4 45.2 (the same
620// work items and arithmetic: the results do not change).  STRATA_PF_OCC=N sets the blocks per WGP (an experiment knob).
621static int wgp_blocks(int occ) {
622    static const int env = [] {
623        const char* v = std::getenv("STRATA_PF_OCC");
624        return v != nullptr ? std::atoi(v) : 0;
625    }();
626    return env > 0 ? env : 2 * std::max(occ, 1);
627}
628#endif
629const DevInfo& dev_info() {
630    int dev = 0;
631    cudaGetDevice(&dev);
632    std::lock_guard<std::mutex> lk(g_mu);
633    DevInfo& d = g_dev[dev & 31];
634    if (d.done) return d;
635    d.done = true;
636#if defined(STRATA_HIP_GFX906)
637    // gfx906 reports compute capability 9.0 through HIP, but the mma.sync bodies above are CUDA sm_80+ only and
638    // empty in a hipcc build: never available here (the prompt path keeps its own expert GEMMs)
639    return d;
640#elif defined(__HIPCC__)
641    {   // gfx11 (RDNA3 / RDNA3.5) with this build's code for it: the WMMA kernels
642        cudaDeviceProp prop;
643        cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
644        hipFuncAttributes fa{};
645        if (cudaGetDeviceProperties(&prop, dev) != cudaSuccess || !strata::kernels::gfx_arch_is_gfx11_wmma(prop.gcnArchName) ||
646            hipFuncGetAttributes(&fa, reinterpret_cast<const void*>(expert_w11_kernel<true>)) != hipSuccess) {
647            cudaGetLastError();
648            return d;
649        }
650        if (hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_w11_kernel<true>, W_THREADS, 0) != hipSuccess ||
651            hipOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_w11_kernel<false>, W_THREADS, 0) != hipSuccess)
652            d.occ_gu = d.occ_d = 0;
653        d.cc = d.occ_gu >= 1 && d.occ_d >= 1 ? 80 : 0;
654        cudaGetLastError();
655        return d;
656    }
657#else
658    int major = 0, minor = 0;
659    cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
660    cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
661    cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
662    d.cc = 10 * strata::cc_major_of(major) + strata::cc_minor_of(minor);   // STRATA_EMULATE_CC counts (tests)
663    // Turing (sm_75): the same kernels with plain copies and m8n8k16 MMAs, opt-in (STRATA_PF_FUSED_SM75=1)
664    static const bool sm75 = [] { const char* v = std::getenv("STRATA_PF_FUSED_SM75"); return v != nullptr && v[0] == '1'; }();
665    if (d.cc < 75 || (d.cc < 80 && !sm75)) { d.cc = d.cc < 80 ? 0 : d.cc; return d; }
666    // the device code of this card's arch must have the kernels (a build without an sm_75+ target has an empty body)
667    cudaFuncAttributes fa{};
668    if (cudaFuncGetAttributes(&fa, expert_kernel<true>) != cudaSuccess || fa.ptxVersion < (d.cc >= 80 ? 80 : 75)) {
669        cudaGetLastError();
670        d.cc = 0;
671        return d;
672    }
673    ck(cudaFuncSetAttribute(expert_kernel<true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem_bytes(true)),
674       "smem gu");
675    ck(cudaFuncSetAttribute(expert_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem_bytes(false)),
676       "smem down");
677    cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, expert_kernel<true>, THREADS, smem_bytes(true));
678    cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, expert_kernel<false>, THREADS, smem_bytes(false));
679    if (d.occ_gu < 1 || d.occ_d < 1) d.cc = 0;                   // does not fit this card: the MMQ path
680    cudaGetLastError();
681#endif
682    return d;
683}
684
685// ---- latent (edge0): the latent pack's A stage - the NVFP4 native blobs on this file's fused batch structure.
686// The blob is the native layout of native_expert_layout(40, 40, ELL, I): [gate rows | up rows | down rows] of
687// raw GGUF blocks, then the NVFP4 tail {s_gate, s_up, s_down, 0} (the expert's global scales).  A 64-value NVFP4
688// block is 4 UE4M3 sub-scales (one per 16 values) and 32 bytes of E2M1 codes; a sub-block's first 8 values sit in
689// the low nibbles of its 8 code bytes, the last 8 in the high nibbles (vec_dot_nvfp4_q8_1's order).  Doubled, the
690// E2M1 values are the ints 0, +-1, +-2, +-3, +-4, +-6, +-8, +-12 (kvalues_fp4), so a 16-value sub-block is an
691// exact s8 x s8 dot on mma.sync m16n8k16, its UE4M3 scale (halved, as ue4m3_to_f32_half decodes it) applied with
692// the activation block's own fp16 scale in the epilogue - the same terms as the native path's vec_dot, another
693// summation order.  The activations are the xl rows' own q8_1 blocks (quantize_q8_1_rows: the same codes and
694// fp16 scales native_expert_grouped reads), staged into shared memory with each sub-block's 16 codes permuted so
695// that a lane's fragment is one aligned word; the H the gate/up epilogue writes is the same q8_1 quantization as
696// q8_1_store (the amax, the d = amax / 127 and the code rounding, bit for bit) in that permuted layout, and the
697// down kernel reads it back the same way.  STRATA_LATENT_FUSED=0 in prefill.cpp keeps native_expert_grouped.
698constexpr int LTHREADS = 512;             // as the Q2_0 kernel: 4 warps along the weight rows x 4 along the tile
699constexpr int LSTAGES = 2;                // the decode / permute stages (plain loads: the bytes go through registers)
700constexpr int LWPITCH = 76;               // a decoded weight row of a stage: 64 int8 codes, 4 fp16 sub-scales, pad
701constexpr int LAPITCH = 80;               // a staged activation row: 16 codes per sub-block, {d0, d1} fp16, pad
702inline size_t lat_smem_bytes() {
703    return (size_t) LSTAGES * WROWS * LWPITCH + (size_t) LSTAGES * kTileRows * LAPITCH + (size_t) kTileRows * 4;
704}
705
706#if !defined(__HIPCC__)
707
708// iq_kernels.cu's ue4m3_to_f32_half: the UE4M3 value halved (kvalues_fp4 holds the E2M1 values doubled)
709__device__ __forceinline__ float lat_ue4m3_half(const uint8_t x) {
710    if (x == 0 || x == 0x7F) return 0.0f;
711    const uint32_t exp = (x >> 3) & 0xF, man = x & 0x7;
712    return exp == 0 ? (float) man * 0.0009765625f : __uint_as_float(((exp + 119u) << 23) | (man << 20));
713}
714
715// the four nibbles of `q` (one code per byte) to the four doubled-E2M1 bytes (kvalues_fp4)
716__device__ __forceinline__ uint32_t lat_kv4(const uint32_t q) {
717    // a byte_perm selector is only 16 bits: the four per-byte codes (value in bits 0-2, sign in
718    // bit 3 of each byte of q) must be gathered into the selector's four nibbles first - nibble
719    // i = q byte i's code. (Passing q & 0x07070707 as the selector left bytes 2-3 of q unused:
720    // only the low two bytes of a 32-bit value form the four selector nibbles.)
721    const uint32_t sel = (q & 0x00000007u) | ((q & 0x00000700u) >> 4) | ((q & 0x00070000u) >> 8) |
722                         ((q & 0x07000000u) >> 12);
723    const uint32_t pl = __byte_perm(0x03020100u, 0x0C080604u, sel);   // {0, 1, 2, 3} {4, 6, 8, 12}
724    const uint32_t ph = __byte_perm(0xFDFEFF00u, 0xF4F8FAFCu, sel);   // their negatives
725    // the final selector, still 16 bits: nibble i = i (pl side), or i + 4 (the ph side) when q
726    // byte i's sign bit is set - the sign bits land on nibble i's bit 2 (value 4)
727    const uint32_t sg = ((q & 0x00000008u) >> 1) | ((q & 0x00000800u) >> 5) |
728                        ((q & 0x00080000u) >> 9) | ((q & 0x08000000u) >> 13);
729    return __byte_perm(pl, ph, 0x3210u | sg);
730}
731
732// One 16-value sub-block's 8 code bytes (w0 = bytes 0-3, w1 = bytes 4-7; the first 8 values in the low nibbles,
733// the last 8 in the high ones) decoded and permuted into out[0..3]: out[k]'s bytes hold values k, 4+k, 8+k and
734// 12+k - the word a lane reads at 4 * its tig for the mma's k fragments.
735__device__ __forceinline__ void lat_decode_sub(const uint32_t w0, const uint32_t w1, uint32_t (&out)[4]) {
736    const uint32_t lo0 = w0 & 0x0F0F0F0Fu, lo1 = w1 & 0x0F0F0F0Fu, hi0 = (w0 >> 4) & 0x0F0F0F0Fu,
737                   hi1 = (w1 >> 4) & 0x0F0F0F0Fu;
738#pragma unroll
739    for (int k = 0; k < 4; ++k) {
740        const uint32_t lo = __byte_perm(__byte_perm(lo0, lo1, k | ((k + 4) << 4)),
741                                        __byte_perm(hi0, hi1, k | ((k + 4) << 4)), 0x5410u);
742        out[k] = lat_kv4(lo);
743    }
744}
745
746// d += A (16 x 16 s8, row) * B (16 x 8 s8, col), int32
747__device__ __forceinline__ void mma_s8_k16(int (&d)[4], const uint32_t a0, const uint32_t a1, const uint32_t b0) {
748    asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%0,%1,%2,%3};\n"
749        : "+r"(d[0]), "+r"(d[1]), "+r"(d[2]), "+r"(d[3])
750        : "r"(a0), "r"(a1), "r"(b0));
751}
752
753// q8_1_store's quantized value (iq_kernels.cu divides as a unit without --use_fast_math does: div.rn)
754__device__ __forceinline__ int8_t lat_q8(const float xi, const float d, const float amax) {
755    if (amax == 0.0f) return 0;
756    const float q = roundf(__fdiv_rn(xi, d));
757    return (int8_t) (q > 127.0f ? 127.0f : q < -127.0f ? -127.0f : q);
758}
759
760// One work item = (a tile of up to 64 routed rows of expert e, a block of the geometry's weight rows); a
761// persistent grid walks the batch's items.  GU: gate feature f's row (blob row f) and its up row (up_off + f) as
762// the mma tile's rows g and g + 8 (SwiGLU in registers), the item's 128 features against the rows' entries' q8_1
763// activations, H quantized as q8_1_store into `hbuf`.  !GU: 256 down rows (256 outputs) against H, FP32 into
764// `dm' per row, the expert's s_down on the store.  The mma runs per 16-value sub-block (the UE4M3 granularity):
765// the decoded weight codes and the staged activation codes share the permuted layout above, so both fragments
766// are one aligned word per lane.
767
768// ---- the q3k routes' decoders (lat_q3k_gu.cu's and lat_q3k_down.cu's, verbatim) ---------------------------------
769// 16 bytes at p as four words; `sh` is 0 or 16, from a row's 2-byte misalignment (a Q3_K row is 550 B)
770__device__ __forceinline__ void lat_ld4(const uint8_t* p, int sh, uint32_t (&w)[4]) {
771    const uint32_t* q = (const uint32_t*) (p - (sh >> 3));
772    w[0] = __funnelshift_r(q[0], q[1], sh);
773    w[1] = __funnelshift_r(q[1], q[2], sh);
774    w[2] = __funnelshift_r(q[2], q[3], sh);
775    w[3] = __funnelshift_r(q[3], q[4], sh);
776}
777
778// One 16-value sub-block's 4 natural-order code words into the staged order: out[k]'s byte c is the value 4c + k.
779__device__ __forceinline__ void lat_stage_codes(const uint32_t* A, uint32_t (&out)[4]) {
780#pragma unroll
781    for (int k = 0; k < 4; ++k)
782        out[k] = __byte_perm(__byte_perm(A[0], A[1], k | ((k + 4) << 4)),
783                             __byte_perm(A[2], A[3], k | ((k + 4) << 4)), 0x5410u);
784}
785
786// one thread's two sub-blocks of a 64-value chunk, staged: the codes and the sub-block scales (fp32)
787struct LatDec {
788    uint32_t w[2][4];
789    float sc[2];
790};
791
792// Q3_K: 110 B a 256-value super-block, a 64-value chunk is four sub-blocks; thread `whalf` takes the two of the
793// 2-bit field j = 2 * (chunk & 1) + whalf.  ggml-quants.c's dequantize_row_q3_K: hm is not advanced across the
794// 128-value halves (the bit j + 4 * half picks one), and the -4 offset is folded into the code, byte-wise.
795__device__ __forceinline__ LatDec lat_gu_decode(const uint8_t* blk, int kb, int whalf) {
796    const int cl = kb & 3;
797    const int half = cl >> 1;
798    const int j = 2 * (cl & 1) + whalf;
799    const int hb = j + 4 * half;
800    const int sh = 8 * ((int) ((uintptr_t) blk & 3));
801    uint32_t qg[2][4], hg[2][4], sw[4];
802    lat_ld4(blk + 32 + 32 * half + 0, sh, qg[0]);
803    lat_ld4(blk + 32 + 32 * half + 16, sh, qg[1]);
804    lat_ld4(blk + 0, sh, hg[0]);
805    lat_ld4(blk + 16, sh, hg[1]);
806    lat_ld4(blk + 96, sh, sw);                        // scales[12], then d (and 2 pad bytes)
807    const float d = __half2float(__ushort_as_half((unsigned short) (sw[3] & 0xFFFFu)));
808    LatDec r;
809#pragma unroll
810    for (int g = 0; g < 2; ++g) {
811        const int s = 4 * cl + 2 * whalf + g;
812        uint32_t nat[4];
813#pragma unroll
814        for (int m = 0; m < 4; ++m) {
815            const uint32_t lo2 = (qg[g][m] >> (2 * j)) & 0x03030303u;
816            const uint32_t hi1 = (hg[g][m] >> hb) & 0x01010101u;
817            nat[m] = __vsub4(lo2 | (4u * hi1), 0x04040404u);   // [0, 7] - 4 = [-4, 3], byte-wise
818        }
819        lat_stage_codes(nat, r.w[g]);
820        const uint32_t nib_byte = (sw[(s & 7) >> 2] >> (8 * (s & 3))) & 0xFFu;
821        const uint32_t nib = (nib_byte >> (4 * (s >> 3))) & 0xFu;
822        const uint32_t hi2 = (sw[2] >> (8 * (s & 3) + 2 * (s >> 2))) & 3u;
823        r.sc[g] = d * (float) ((int) (nib | (hi2 << 4)) - 32);
824    }
825    return r;
826}
827
828// IQ4_NL: 18 B a 32-value block (half d, qs[16]); a 64-value chunk is two blocks, thread `whalf` takes one.  Its qs
829// starts 2 B into the block, so the 5 aligned words the block spans are read and the 16 qs bytes shifted out.
830__device__ __forceinline__ LatDec lat_dn_decode(const uint8_t* chunk, int whalf) {
831    const uint32_t* w9 = (const uint32_t*) (chunk + 4 * (4 * whalf));
832    const uint32_t b0 = w9[0], b1 = w9[1], b2 = w9[2], b3 = w9[3], b4 = w9[4];
833    uint32_t wq[4], wd;
834    if (whalf) {
835        wq[0] = b1; wq[1] = b2; wq[2] = b3; wq[3] = b4;
836        wd = b0 >> 16;
837    } else {
838        wq[0] = (b0 >> 16) | (b1 << 16);
839        wq[1] = (b1 >> 16) | (b2 << 16);
840        wq[2] = (b2 >> 16) | (b3 << 16);
841        wq[3] = (b3 >> 16) | (b4 << 16);
842        wd = b0 & 0xFFFFu;
843    }
844    uint32_t q[8];
845#pragma unroll
846    for (int k = 0; k < 4; ++k) {
847        uint32_t lo = 0, hi = 0;
848#pragma unroll
849        for (int c = 0; c < 4; ++c) {
850            const uint32_t byte = (wq[k] >> (8 * c)) & 0xFF;
851            lo |= (uint32_t) (uint8_t) kvalues_iq4nl[byte & 0xF] << (8 * c);
852            hi |= (uint32_t) (uint8_t) kvalues_iq4nl[byte >> 4] << (8 * c);
853        }
854        q[k] = lo;
855        q[4 + k] = hi;
856    }
857    LatDec r;
858    const float d = __half2float(__ushort_as_half((unsigned short) wd));
859#pragma unroll
860    for (int h = 0; h < 2; ++h) {
861        lat_stage_codes(q + 4 * h, r.w[h]);
862        r.sc[h] = d;
863    }
864    return r;
865}
866
867template <bool GU>
868__global__ void __launch_bounds__(LTHREADS, 1)
869latent_kernel_q3k(const WideBatch b, const Tables tb, const LatentGeom g, const uint8_t* __restrict__ act,
870              const int32_t* __restrict__ src, uint8_t* __restrict__ hbuf, float* __restrict__ dm) {
871#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
872    const int NCH = GU ? (int) (g.ell >> 6) : (int) (g.iff >> 6);   // 64-value chunks along K (28 / 10)
873    // the work items along the output rows, from the geometry: GU covers 128 gate/up rows an item (n_ff / 128), the
874    // down 256 output rows an item (ell / 256).  1280 gives 5 / 5, 1792 gives 5 / 7 - the same numbers v5's fp4
875    // kernel carried as constants.
876    const int NFB = GU ? (int) (g.iff / 128) : (int) (g.ell >> 8);
877    const size_t apitch = GU ? (size_t) (g.ell / 32) * 36 : (size_t) (g.iff >> 6) * LAPITCH;
878    const int achunk = GU ? 72 : LAPITCH;                           // a staged row's source chunk (72 / 80 bytes)
879    const size_t hpitch = (size_t) (g.iff >> 6) * LAPITCH;          // an H row (10 chunks of 80)
880    extern __shared__ __align__(16) uint8_t smem[];
881    uint8_t* wst[2] = {smem, smem + WROWS * LWPITCH};
882    uint8_t* ast[2] = {smem + 2 * WROWS * LWPITCH, smem + 2 * WROWS * LWPITCH + kTileRows * LAPITCH};
883    int* srow = (int*) (smem + 2 * WROWS * LWPITCH + 2 * kTileRows * LAPITCH);   // [64] the act row of each tile row
884
885    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, mg = lane >> 2, tig = lane & 3;
886    const int wf = warp & 3, nb0 = 16 * (warp >> 2);
887    const int wrow = tid >> 1, whalf = tid & 1;                     // the weight rows: 2 threads a row, 2 subs each
888    const int arow = tid >> 1, ahalf = tid & 1;                     // the act rows: threads 0..127, 2 a row
889    LatDec wdec;                                                    // the next chunk's decoded weight (this thread's
890                                                                    // two sub-blocks: the codes and their scales)
891    uint32_t aq[8];                                                 // the next chunk's raw activation bytes
892    uint32_t adw = 0;                                               // its act ds word
893
894    const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB;
895    for (int w = blockIdx.x; w < nwork; w += gridDim.x) {
896        const int2 tl = tb.tiles[t0 + w / NFB];
897        const int fb = w % NFB, e = tl.x, row0 = tl.y;
898        // the latent grouping's off[] is a permutation (the resident experts' block comes first, then the staged
899        // ones), so a tile's rows end at off[e] + cnt[e] - never at off[e + 1], which crosses a block boundary
900        const int nrows = min(kTileRows, tb.cnt[e] - (row0 - tb.off[e]));
901        const uint8_t* blob = b.blob[e - b.e0];
902        if (blob == nullptr) continue;   // an expert of another launch of this layer: this batch has no blob for it
903        // this thread's weight row of the item (GU: gate rows 0..127, up rows 128..255 of the stage)
904        const uint8_t* wsrc;
905        if (GU) wsrc = wrow < 128 ? blob + (size_t) (128 * fb + wrow) * g.gu_row
906                                  : blob + g.up_off + (size_t) (128 * fb + wrow - 128) * g.gu_row;
907        else wsrc = blob + g.down_off + (size_t) (256 * fb + wrow) * g.d_row;
908        // the expert's global scales (the NVFP4 tail; 1 without one)
909        float s_gate = 1.0f, s_up = 1.0f, s_down = 1.0f;
910        if (g.tail_off) {
911            const float* tail = (const float*) (blob + g.tail_off);
912            s_gate = tail[0];
913            s_up = tail[1];
914            s_down = tail[2];
915        }
916        __syncthreads();                                              // the previous item is done with the buffers
917        if (tid < kTileRows) {
918            const int r = row0 + min(tid, nrows - 1);                // rows past the tile's end repeat its last one
919            srow[tid] = GU ? src[r] : r;
920        }
921        __syncthreads();                                              // srow
922
923        auto raw_load = [&](int kb) {
924            // the weight: Q3_K's 110-byte super-blocks (a 64-value chunk is a quarter of one) or IQ4_NL's 18-byte
925            // blocks (a chunk is two), decoded into registers here so the staged row below is a plain copy
926            if (GU) wdec = lat_gu_decode(wsrc + 110 * (kb >> 2), kb, whalf);
927            else wdec = lat_dn_decode(wsrc + 36 * kb, whalf);
928            if (tid < 2 * kTileRows) {
929                const uint32_t* ap = (const uint32_t*) (act + (size_t) srow[arow] * apitch + (size_t) achunk * kb);
930#pragma unroll
931                for (int i = 0; i < 8; ++i) aq[i] = ap[GU ? 1 + 9 * ahalf + i : 8 * ahalf + i];
932                adw = ap[GU ? 9 * ahalf : 16];   // GU: the block's ds word; !GU: the row's {d0, d1}
933            }
934        };
935        auto stage_store = [&](int kb) {
936            uint8_t* wr = wst[kb & 1] + (size_t) wrow * LWPITCH;
937#pragma unroll
938            for (int h = 0; h < 2; ++h) {
939                const int s = 2 * whalf + h;
940#pragma unroll
941                for (int k = 0; k < 4; ++k) *(uint32_t*) (wr + 16 * s + 4 * k) = wdec.w[h][k];
942                *(__half*) (wr + 68 + 2 * s) = __float2half(wdec.sc[h]);   // v5's row layout, fp16 sub-scales
943            }
944            if (tid < 2 * kTileRows) {
945                uint8_t* ar = ast[kb & 1] + (size_t) arow * LAPITCH;
946#pragma unroll
947                for (int h = 0; h < 2; ++h) {
948                    const int s = 2 * ahalf + h;
949                    const uint32_t* wp = &aq[4 * h];
950#pragma unroll
951                    for (int k = 0; k < 4; ++k) {
952                        if (GU) {
953                            const uint32_t p1 = __byte_perm(wp[0], wp[1], k | ((k + 4) << 4));
954                            const uint32_t p2 = __byte_perm(wp[2], wp[3], k | ((k + 4) << 4));
955                            *(uint32_t*) (ar + 16 * s + 4 * k) = __byte_perm(p1, p2, 0x5410u);
956                        } else {
957                            *(uint32_t*) (ar + 16 * s + 4 * k) = wp[k];
958                        }
959                    }
960                }
961                if (GU) *(__half*) (ar + 64 + 2 * ahalf) = __ushort_as_half((unsigned short) (adw & 0xFFFF));
962                else *(uint32_t*) (ar + 64) = adw;
963            }
964        };
965
966        raw_load(0);
967        stage_store(0);
968        if (NCH > 1) raw_load(1);
969        const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
970        float acc[4][2][4];
971#pragma unroll
972        for (int i = 0; i < 4; ++i)
973#pragma unroll
974            for (int n = 0; n < 2; ++n)
975#pragma unroll
976                for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
977        for (int kb = 0; kb < NCH; ++kb) {
978            __syncthreads();
979            if (on0) {
980                const uint8_t* wc = wst[kb & 1];
981                const uint8_t* ac = ast[kb & 1];
982                for (int s = 0; s < 4; ++s) {
983                    uint32_t bq[2];
984                    float dx0[2], dx1[2];               // the OUTPUT rows' (2 tig, 2 tig + 1) own ds
985                    for (int n = 0; n < 2; ++n) {
986                        if (n == 1 && !on1) break;
987                        const uint8_t* ar = ac + (size_t) (nb0 + 8 * n + mg) * LAPITCH;
988                        bq[n] = *(const uint32_t*) (ar + 16 * s + 4 * tig);
989                        const half2 ds0 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig) * LAPITCH + 64);
990                        const half2 ds1 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig + 1) * LAPITCH + 64);
991                        dx0[n] = __half2float((s & 2) ? ds0.y : ds0.x);
992                        dx1[n] = __half2float((s & 2) ? ds1.y : ds1.x);
993                    }
994                    for (int i = 0; i < 4; ++i) {
995                        const int ra = GU ? 32 * wf + 8 * i + mg : 64 * wf + 16 * i + mg;
996                        const int rb = GU ? ra + 128 : ra + 8;
997                        const uint32_t a0 = *(const uint32_t*) (wc + (size_t) ra * LWPITCH + 16 * s + 4 * tig);
998                        const uint32_t a1 = *(const uint32_t*) (wc + (size_t) rb * LWPITCH + 16 * s + 4 * tig);
999                        const float da = __half2float(*(const __half*) (wc + (size_t) ra * LWPITCH + 68 + 2 * s));
1000                        const float db = __half2float(*(const __half*) (wc + (size_t) rb * LWPITCH + 68 + 2 * s));
1001                        for (int n = 0; n < 2; ++n) {
1002                            if (n == 1 && !on1) break;
1003                            int d[4] = {0, 0, 0, 0};
1004                            mma_s8_k16(d, a0, a1, bq[n]);
1005                            acc[i][n][0] += (da * dx0[n]) * (float) d[0];
1006                            acc[i][n][1] += (da * dx1[n]) * (float) d[1];
1007                            acc[i][n][2] += (db * dx0[n]) * (float) d[2];
1008                            acc[i][n][3] += (db * dx1[n]) * (float) d[3];
1009                        }
1010                    }
1011                }
1012            }
1013            __syncthreads();
1014            if (kb + 1 < NCH) {
1015                stage_store(kb + 1);
1016                if (kb + 2 < NCH) raw_load(kb + 2);
1017            }
1018        }
1019        if (!on0) continue;
1020        if (GU) {
1021            // SwiGLU of feature 32 * (4 * fb + wf) + 8 i + mg (lane mg of m tile i), tile rows nb0 + 8 n + 2 tig + c;
1022            // H to q8_1 as q8_1_store (the amax over the warp's 32 features, d = amax / 127, the code rounding)
1023            const int blk = 4 * fb + wf;
1024            for (int n = 0; n < 2; ++n) {
1025                if (n == 1 && !on1) break;
1026                for (int c = 0; c < 2; ++c) {
1027                    float h[4], am = 0.0f;
1028#pragma unroll
1029                    for (int i = 0; i < 4; ++i) {
1030                        const float gt = acc[i][n][c] * s_gate, up = acc[i][n][2 + c] * s_up;
1031                        h[i] = __fmul_rn(__fdiv_rn(gt, 1.0f + __expf(-gt)), up);
1032                        am = fmaxf(am, fabsf(h[i]));
1033                    }
1034                    am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 16));
1035                    am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 8));
1036                    am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, 4));
1037                    const float d = strata::kernels::q8_1_finite(__fdiv_rn(am, 127.0f));
1038                    const int r = nb0 + 8 * n + 2 * tig + c;
1039                    if (r < nrows) {
1040                        uint8_t* o = hbuf + (size_t) (row0 + r) * hpitch + (size_t) (blk >> 1) * LAPITCH;
1041                        const int hh = blk & 1;
1042#pragma unroll
1043                        for (int i = 0; i < 4; ++i) {
1044                            const int v = 8 * i + mg;
1045                            o[16 * (2 * hh + (v >> 4)) + 4 * (v & 3) + ((v & 15) >> 2)] = (uint8_t) lat_q8(h[i], d, am);
1046                        }
1047                        if (mg == 0) *(__half*) (o + 64 + 2 * hh) = __float2half(d);
1048                    }
1049                }
1050            }
1051        } else {
1052#pragma unroll
1053            for (int i = 0; i < 4; ++i)
1054#pragma unroll
1055                for (int n = 0; n < 2; ++n) {
1056                    if (n == 1 && !on1) break;
1057#pragma unroll
1058                    for (int q = 0; q < 4; ++q) {
1059                        const int r = nb0 + 8 * n + 2 * tig + (q & 1);
1060                        if (r < nrows)
1061                            dm[(size_t) (row0 + r) * g.ell + 256 * fb +
1062                               (q < 2 ? 64 * wf + 16 * i + mg : 64 * wf + 16 * i + mg + 8)] = acc[i][n][q] * s_down;
1063                    }
1064                }
1065        }
1066    }
1067#endif
1068}
1069
1070#endif  // !__HIPCC__
1071
1072
1073// ---- latent (edge0): the D and U dense projections on the same fused structure.  Both are Q8_0 weight rows x
1074// q8_1 activation rows - a 32-value block of each side is one exact s8 x s8 dot on mma.m16n8k16 (two sub-blocks
1075// share the Q8_0 block's fp16 scale, staged into all four sub-scale slots), the block scales applied in the
1076// epilogue per sub-block: the same terms as iq_mmvq(8)'s and latent_u_k's dp4a dots, another summation order.
1077// D (latent_dense_kernel<true>): the layer input's q8_1 rows [M = T, K = N] against all G*ell weight rows, the
1078// FP32 products quantized straight to the xl rows' own q8_1 blocks (q8_1_store bit for bit: the warp's amax and
1079// sum, d = amax / 127, the code rounding) - the xl FP32 round trip of iq_mmvq + quantize_q8_1_rows never runs.
1080// U (<false>): each entry's ylq row against its label's H weight rows (the entries bucketed by label on the
1081// host, one tile list per group), FP32 into Dm.
1082template <bool DU>
1083__global__ void __launch_bounds__(LTHREADS, 1)
1084latent_dense_kernel(const uint8_t* __restrict__ w, const uint8_t* __restrict__ xq,
1085                    const int32_t* __restrict__ rows, const int32_t* __restrict__ goff,
1086                    void* __restrict__ outq, float* __restrict__ outf,
1087                    int K, int64_t ell, int G, int H, int n_groups, int64_t M, int nwork, int fmt,
1088                    const float* __restrict__ inv) {   // the Q3_K pack's 1/s (nullptr: none)
1089#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800
1090    const int NCH = K >> 6;                       // 64-value chunks along K (40 for D, 28 for U)
1091    const int NFB = DU ? (int) ((size_t) G * ell >> 8) : H >> 8;   // 256-output items per tile (56 / 10)
1092    const size_t wrowb = (size_t) (K / 32) * (fmt == 4 ? 18 : 34);  // Q4DU: a Q8_0 (34) or Q4_0 (18) weight row
1093    const size_t apitch = (size_t) (K / 32) * 36; // a q8_1 activation row
1094    const int eblk = (int) (ell >> 5);            // q8_1 blocks in an xl row (56)
1095    const int ipg = (int) (ell >> 8);             // the item rows per output group (7)
1096    extern __shared__ __align__(16) uint8_t smem[];
1097    uint8_t* wst[2] = {smem, smem + WROWS * LWPITCH};
1098    uint8_t* ast[2] = {smem + 2 * WROWS * LWPITCH, smem + 2 * WROWS * LWPITCH + kTileRows * LAPITCH};
1099    int* srow = (int*) (smem + 2 * WROWS * LWPITCH + 2 * kTileRows * LAPITCH);   // [64] the act row of each tile row
1100
1101    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, mg = lane >> 2, tig = lane & 3;
1102    const int wf = warp & 3, nb0 = 16 * (warp >> 2);
1103    const int wrow = tid >> 1, whalf = tid & 1;                     // the weight rows: 2 threads a row, a block each
1104    const int arow = tid >> 1, ahalf = tid & 1;                     // the act rows: threads 0..127, 2 a row
1105    uint32_t wq[8], aq[8];                                          // the next chunk's raw bytes
1106    uint32_t adw = 0;                                               // the act ds word
1107    __half wd16;                                                    // the weight block's scale
1108
1109    for (int w_ = blockIdx.x; w_ < nwork; w_ += gridDim.x) {
1110        const int fb = w_ % NFB, t = w_ / NFB;
1111        int base, nrows;
1112        const uint8_t* wsec;
1113        if (DU) {
1114            base = 64 * t;
1115            nrows = min(kTileRows, (int) (M - base));
1116            wsec = w;
1117        } else {
1118            int g = 0, tb = 0;
1119            while (g < n_groups) {
1120                const int nt = (goff[g + 1] - goff[g] + 63) >> 6;
1121                if (t < tb + nt) break;
1122                tb += nt;
1123                ++g;
1124            }
1125            if (g >= n_groups) continue;
1126            base = goff[g] + 64 * (t - tb);
1127            nrows = min(kTileRows, goff[g + 1] - base);
1128            wsec = w + (size_t) g * (size_t) H * wrowb;
1129        }
1130        const uint8_t* wsrc = wsec + (size_t) (256 * fb + wrow) * wrowb;
1131        __syncthreads();                                              // the previous item is done with the buffers
1132        if (tid < kTileRows) {
1133            const int r = base + min(tid, nrows - 1);                // rows past the tile's end repeat its last one
1134            srow[tid] = DU ? r : rows[r];
1135        }
1136        __syncthreads();                                              // srow
1137
1138        auto raw_load = [&](int kb) {
1139            // Q4DU fmt 4: one Q4_0 block {fp16 d; uint8 nib[16]} - element j in byte j's low nibble, j+16
1140            // in its high one, value (code - 8).  Expanded to the SAME 32-int8 qs layout as Q8_0 (wq byte
1141            // order = elements 4j..4j+3), so stage_store and the mma chain below are shared verbatim; the
1142            // centred codes are the exact integer form of iq_kernels.cu's q4_0_centred.
1143            if (fmt == 4) {
1144            const unsigned short* bp = (const unsigned short*) (wsrc + 18 * (2 * kb + whalf));
1145            wd16 = __ushort_as_half(bp[0]);
1146            const uint8_t* nbp = (const uint8_t*) (bp + 1);
1147#pragma unroll
1148            for (int j = 0; j < 8; ++j) {
1149                uint32_t v = 0;
1150#pragma unroll
1151                for (int k = 0; k < 4; ++k) {
1152                    const int p = 4 * j + k;   // element p of the block
1153                    // p < 16: byte p's low nibble; p >= 16: byte (p-16)'s high nibble
1154                    const int code = (p < 16) ? (nbp[p] & 0xF) : ((nbp[p - 16] >> 4) & 0xF);
1155                    v |= ((uint32_t) ((code - 8) & 0xFF)) << (8 * k);   // centred, masked
1156                }
1157                wq[j] = v;
1158            }
1159            } else {
1160            // one Q8_0 block: {fp16 d; int8 qs[32]} - the qs words assembled from ushort pairs (a block is only
1161            // 2-byte aligned within its row)
1162            const unsigned short* bp = (const unsigned short*) (wsrc + 34 * (2 * kb + whalf));
1163            wd16 = __ushort_as_half(bp[0]);
1164#pragma unroll
1165            for (int j = 0; j < 8; ++j) wq[j] = (uint32_t) bp[1 + 2 * j] | ((uint32_t) bp[2 + 2 * j] << 16);
1166            }
1167            if (tid < 2 * kTileRows) {
1168                const uint32_t* ap = (const uint32_t*) (xq + (size_t) srow[arow] * apitch + (size_t) (72 * kb));
1169#pragma unroll
1170                for (int i = 0; i < 8; ++i) aq[i] = ap[1 + 9 * ahalf + i];
1171                adw = ap[9 * ahalf];                                 // the block's ds word (d in the low half)
1172            }
1173        };
1174        auto stage_store = [&](int kb) {
1175            uint8_t* wr = wst[kb & 1] + (size_t) wrow * LWPITCH;
1176#pragma unroll
1177            for (int h = 0; h < 2; ++h) {                             // this block's two 16-value sub-blocks
1178                const int s = 2 * whalf + h;
1179                const uint32_t* wp = &wq[4 * h];
1180#pragma unroll
1181                for (int k = 0; k < 4; ++k) {
1182                    const uint32_t p1 = __byte_perm(wp[0], wp[1], k | ((k + 4) << 4));
1183                    const uint32_t p2 = __byte_perm(wp[2], wp[3], k | ((k + 4) << 4));
1184                    *(uint32_t*) (wr + 16 * s + 4 * k) = __byte_perm(p1, p2, 0x5410u);
1185                }
1186            }
1187            // the Q8_0 block's one scale covers both its sub-blocks - but only THIS thread's
1188            // two slots: whalf 0 stages block 2kb (slots 68/70), whalf 1 block 2kb+1 (72/74).
1189            // (all four slots as before was a write race that lost the second block's scale)
1190            *(__half*) (wr + 68 + 4 * whalf) = wd16;
1191            *(__half*) (wr + 70 + 4 * whalf) = wd16;
1192            if (tid < 2 * kTileRows) {
1193                uint8_t* ar = ast[kb & 1] + (size_t) arow * LAPITCH;
1194#pragma unroll
1195                for (int h = 0; h < 2; ++h) {
1196                    const int s = 2 * ahalf + h;
1197                    const uint32_t* wp = &aq[4 * h];
1198#pragma unroll
1199                    for (int k = 0; k < 4; ++k) {
1200                        const uint32_t p1 = __byte_perm(wp[0], wp[1], k | ((k + 4) << 4));
1201                        const uint32_t p2 = __byte_perm(wp[2], wp[3], k | ((k + 4) << 4));
1202                        *(uint32_t*) (ar + 16 * s + 4 * k) = __byte_perm(p1, p2, 0x5410u);
1203                    }
1204                }
1205                *(__half*) (ar + 64 + 2 * ahalf) = __ushort_as_half((unsigned short) (adw & 0xFFFF));
1206            }
1207        };
1208
1209        raw_load(0);
1210        stage_store(0);
1211        if (NCH > 1) raw_load(1);
1212        const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows;
1213        float acc[4][2][4];
1214#pragma unroll
1215        for (int i = 0; i < 4; ++i)
1216#pragma unroll
1217            for (int n = 0; n < 2; ++n)
1218#pragma unroll
1219                for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f;
1220        for (int kb = 0; kb < NCH; ++kb) {
1221            __syncthreads();
1222            if (on0) {
1223                const uint8_t* wc = wst[kb & 1];
1224                const uint8_t* ac = ast[kb & 1];
1225                for (int s = 0; s < 4; ++s) {
1226                    uint32_t bq[2];
1227                    float dx0[2], dx1[2];               // the OUTPUT rows' (2 tig, 2 tig + 1) own ds
1228                    for (int n = 0; n < 2; ++n) {
1229                        if (n == 1 && !on1) break;
1230                        const uint8_t* ar = ac + (size_t) (nb0 + 8 * n + mg) * LAPITCH;
1231                        bq[n] = *(const uint32_t*) (ar + 16 * s + 4 * tig);
1232                        const half2 ds0 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig) * LAPITCH + 64);
1233                        const half2 ds1 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig + 1) * LAPITCH + 64);
1234                        dx0[n] = __half2float((s & 2) ? ds0.y : ds0.x);
1235                        dx1[n] = __half2float((s & 2) ? ds1.y : ds1.x);
1236                    }
1237                    for (int i = 0; i < 4; ++i) {
1238                        const int ra = 64 * wf + 16 * i + mg, rb = ra + 8;
1239                        const uint32_t a0 = *(const uint32_t*) (wc + (size_t) ra * LWPITCH + 16 * s + 4 * tig);
1240                        const uint32_t a1 = *(const uint32_t*) (wc + (size_t) rb * LWPITCH + 16 * s + 4 * tig);
1241                        const float da = __half2float(*(const __half*) (wc + (size_t) ra * LWPITCH + 68 + 2 * s));
1242                        const float db = __half2float(*(const __half*) (wc + (size_t) rb * LWPITCH + 68 + 2 * s));
1243                        for (int n = 0; n < 2; ++n) {
1244                            if (n == 1 && !on1) break;
1245                            int d[4] = {0, 0, 0, 0};
1246                            mma_s8_k16(d, a0, a1, bq[n]);
1247                            acc[i][n][0] += (da * dx0[n]) * (float) d[0];
1248                            acc[i][n][1] += (da * dx1[n]) * (float) d[1];
1249                            acc[i][n][2] += (db * dx0[n]) * (float) d[2];
1250                            acc[i][n][3] += (db * dx1[n]) * (float) d[3];
1251                        }
1252                    }
1253                }
1254            }
1255            __syncthreads();
1256            if (kb + 1 < NCH) {
1257                stage_store(kb + 1);
1258                if (kb + 2 < NCH) raw_load(kb + 2);
1259            }
1260        }
1261        if (!on0) continue;
1262        if (DU) {
1263            // the warp's 64 outputs are two q8_1 blocks of the (token, group) xl row: quantized as q8_1_store
1264            // (the amax and the sum over the block's 32 values, d = amax / 127, the code rounding, ds = {d, sum})
1265            const int g_out = fb / ipg, rr = fb % ipg;               // the output group, the item within it
1266            const size_t xrowb = (size_t) eblk * 36;                 // an xlq row
1267            // the pack's shared column scale: the experts' gate/up rows were packed as A*diag(s), so the xl rows
1268            // they read must be xl/s.  acc[i][n][q] is column 32*(8*rr+2*wf+(i>>1)) + 16*(i&1) + 8*(q>>1) + mg of
1269            // the group's ell; the coefficients are precomputed because each column serves two tokens (n, q&1).
1270            float cs[4][2];
1271#pragma unroll
1272            for (int i = 0; i < 4; ++i)
1273#pragma unroll
1274                for (int q = 0; q < 2; ++q) {
1275                    const int j = 32 * (8 * rr + 2 * wf + (i >> 1)) + 16 * (i & 1) + 8 * q + mg;
1276                    cs[i][q] = inv ? inv[j] : 1.0f;
1277                }
1278            for (int n = 0; n < 2; ++n) {
1279                if (n == 1 && !on1) break;
1280                for (int qc = 0; qc < 2; ++qc) {
1281                    const int r_t = nb0 + 8 * n + 2 * tig + qc;      // the token's tile row
1282                    // Shuffle groups stay within one token row; absent rows must not be named.
1283                    const unsigned mask = __ballot_sync(0xffffffffu, r_t < nrows);
1284                    if (r_t >= nrows) continue;
1285                    const int t_tok = srow[r_t];
1286                    uint8_t* xrow = (uint8_t*) outq + (size_t) (t_tok * G + g_out) * xrowb;
1287                    for (int b = 0; b < 2; ++b) {                    // the two 32-value blocks of the warp
1288                        float am = 0.0f, sm = 0.0f;
1289#pragma unroll
1290                        for (int h = 0; h < 2; ++h) {
1291                            am = fmaxf(am, fabsf(acc[2 * b + h][n][qc] * cs[2 * b + h][0]));
1292                            am = fmaxf(am, fabsf(acc[2 * b + h][n][2 + qc] * cs[2 * b + h][1]));
1293                            sm += acc[2 * b + h][n][qc] * cs[2 * b + h][0] +
1294                                  acc[2 * b + h][n][2 + qc] * cs[2 * b + h][1];
1295                        }
1296                        am = fmaxf(am, __shfl_xor_sync(mask, am, 16));
1297                        am = fmaxf(am, __shfl_xor_sync(mask, am, 8));
1298                        am = fmaxf(am, __shfl_xor_sync(mask, am, 4));
1299                        sm += __shfl_xor_sync(mask, sm, 16);
1300                        sm += __shfl_xor_sync(mask, sm, 8);
1301                        sm += __shfl_xor_sync(mask, sm, 4);
1302                        const float d = strata::kernels::q8_1_finite(__fdiv_rn(am, 127.0f));
1303                        uint8_t* ob = xrow + (size_t) (8 * rr + 2 * wf + b) * 36;
1304#pragma unroll
1305                        for (int h = 0; h < 2; ++h) {
1306                            ob[4 + 16 * h + mg] = (uint8_t) lat_q8(acc[2 * b + h][n][qc] * cs[2 * b + h][0], d, am);
1307                            ob[4 + 16 * h + 8 + mg] =
1308                                (uint8_t) lat_q8(acc[2 * b + h][n][2 + qc] * cs[2 * b + h][1], d, am);
1309                        }
1310                        if (mg == 0) *(half2*) ob = strata::kernels::q8_1_ds(d, sm);
1311                    }
1312                }
1313            }
1314        } else {
1315#pragma unroll
1316            for (int i = 0; i < 4; ++i)
1317#pragma unroll
1318                for (int n = 0; n < 2; ++n) {
1319                    if (n == 1 && !on1) break;
1320#pragma unroll
1321                    for (int q = 0; q < 4; ++q) {
1322                        const int r_t = nb0 + 8 * n + 2 * tig + (q & 1);
1323                        if (r_t < nrows)
1324                            outf[(size_t) srow[r_t] * H + 256 * fb + 64 * wf + 16 * i + mg + 8 * (q >> 1)] =
1325                                acc[i][n][q];
1326                    }
1327                }
1328        }
1329    }
1330#endif
1331}
1332
1333// ---- the U-stage's group tables, built on the device (a mid-layer pinned h2d waits behind the blob prefetch's
1334// DMA queue - 20-30 ms a layer once stream_all's prefetch runs deep, while these three tiny launches cost ~50 us).
1335// goff[0..n_groups] ends up holding the per-group run ends (0 then the exclusive prefix of the counts), rows[0..n)
1336// the entry indices bucketed by their expert's label; cursors is n_groups + 1 scratch for the scatter.
1337__global__ void lat_u_count_k(const int32_t* __restrict__ ids, const int32_t* __restrict__ labels,
1338                              int64_t n, int n_groups, int32_t* __restrict__ goff) {
1339    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
1340        const int32_t e = ids[i];
1341        atomicAdd(&goff[1 + (e >= 0 ? labels[e] : 0) % n_groups], 1);
1342    }
1343}
1344__global__ void lat_u_prefix_k(int32_t* goff, int32_t* cursors, int n_groups) {
1345    int acc = 0;
1346    for (int g = 0; g < n_groups; ++g) {
1347        cursors[g] = acc;
1348        acc += goff[g + 1];
1349        goff[g + 1] = acc;
1350    }
1351    cursors[n_groups] = acc;
1352}
1353__global__ void lat_u_scatter_k(const int32_t* __restrict__ ids, const int32_t* __restrict__ labels,
1354                                int64_t n, int n_groups, int32_t* __restrict__ cursors,
1355                                int32_t* __restrict__ rows) {
1356    for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) gridDim.x * blockDim.x) {
1357        const int32_t e = ids[i];
1358        const int g = (e >= 0 ? labels[e] : 0) % n_groups;
1359        rows[atomicAdd(&cursors[g], 1)] = (int32_t) i;
1360    }
1361}
1362
1363struct LatentDevInfo {
1364    bool checked = false, ok = false;
1365    int sms = 0, occ_gu = 0, occ_d = 0, occ_dd = 0, occ_du = 0;
1366};
1367std::mutex g_lat_mu;
1368LatentDevInfo g_lat_dev[32];
1369
1370const LatentDevInfo& lat_dev() {
1371    int dev = 0;
1372    cudaGetDevice(&dev);
1373    std::lock_guard<std::mutex> lk(g_lat_mu);
1374    LatentDevInfo& d = g_lat_dev[dev & 31];
1375    if (!d.checked) {
1376        d.checked = true;
1377#if !defined(__HIPCC__)
1378        int major = 0, minor = 0;
1379        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
1380        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
1381        cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev);
1382        if (10 * major + minor < 80) return d;    // the s8 mma of m16n8k16
1383        cudaFuncAttributes fa{};
1384        if (cudaFuncGetAttributes(&fa, latent_kernel_q3k<true>) != cudaSuccess || fa.ptxVersion < 80) {
1385            cudaGetLastError();
1386            return d;
1387        }
1388        ck(cudaFuncSetAttribute(latent_kernel_q3k<true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) lat_smem_bytes()),
1389           "latent smem gu");
1390        ck(cudaFuncSetAttribute(latent_kernel_q3k<false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) lat_smem_bytes()),
1391           "latent smem down");
1392        ck(cudaFuncSetAttribute(latent_dense_kernel<true>, cudaFuncAttributeMaxDynamicSharedMemorySize,
1393                                (int) lat_smem_bytes()), "latent dense smem d");
1394        ck(cudaFuncSetAttribute(latent_dense_kernel<false>, cudaFuncAttributeMaxDynamicSharedMemorySize,
1395                                (int) lat_smem_bytes()), "latent dense smem u");
1396        cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_gu, latent_kernel_q3k<true>, LTHREADS, lat_smem_bytes());
1397        cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_d, latent_kernel_q3k<false>, LTHREADS, lat_smem_bytes());
1398        cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_dd, latent_dense_kernel<true>, LTHREADS, lat_smem_bytes());
1399        cudaOccupancyMaxActiveBlocksPerMultiprocessor(&d.occ_du, latent_dense_kernel<false>, LTHREADS, lat_smem_bytes());
1400        cudaGetLastError();
1401        d.ok = d.occ_gu >= 1 && d.occ_d >= 1 && d.occ_dd >= 1 && d.occ_du >= 1;
1402#endif
1403    }
1404    return d;
1405}
1406
1407}  // namespace
1408
1409bool built() { return true; }
1410bool available() { return dev_info().cc >= 75; }
1411// 0.1.36: on by default for the Q2_0 pack (+13-23% prompts on an RTX 5070; teacher-forced against the FP16 path as
1412// close as MMQ at 8K and closer at 32K: phaseA-tests s18-tf); STRATA_PF_FUSED=0 keeps MMQ.  The native packs' kernels
1413// (moe_fused_iq) stay opt-in: STRATA_PF_FUSED=1 (requested()).
1414bool enabled() {
1415    static const bool env = [] {
1416        const char* v = std::getenv("STRATA_PF_FUSED");
1417#if defined(__HIPCC__)
1418        return v != nullptr && v[0] == '1';   // Aurora: the gfx11 WMMA kernels are opt-in (STRATA_PF_FUSED=1)
1419#else
1420        return v == nullptr || v[0] != '0';
1421#endif
1422    }();
1423    return env && available();
1424}
1425bool requested() {
1426    static const bool env = [] {
1427        const char* v = std::getenv("STRATA_PF_FUSED");
1428        return v != nullptr && v[0] == '1';
1429    }();
1430    return env && available();
1431}
1432
1433size_t act_bytes(int64_t rows, int64_t cols) { return (size_t) rows * (size_t) (cols / 64) * AB; }
1434size_t group_bytes(int64_t n, int n_expert) {
1435    return tiles_at(n_expert) + ((size_t) (n + kTileRows - 1) / kTileRows + (size_t) n_expert) * sizeof(int2);
1436}
1437
1438void quantize_act(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) {
1439    if (rows <= 0) return;
1440    const int64_t nblk = rows * (cols / 64);
1441    quant_act_kernel<<<blocks(nblk, 8), 256, 0, (cudaStream_t) stream>>>(x, nblk, (uint8_t*) xa);
1442    ck(cudaGetLastError(), "quantize_act");
1443}
1444
1445void group(const int32_t* ids, int64_t n, int k, int n_expert, void* scratch, int32_t* slot, int32_t* src,
1446           void* stream) {
1447    if (n_expert < 1 || n_expert > 1024) {
1448        std::fprintf(stderr, "prefill fused experts: %d experts (the grouping takes 1 to 1024)\n", n_expert);
1449        std::exit(1);
1450    }
1451    const cudaStream_t s = (cudaStream_t) stream;
1452    const Tables tb = tables(scratch, n_expert);
1453    ck(cudaMemsetAsync(tb.cnt, 0, (size_t) n_expert * 4, s), "group memset");
1454    if (n > 0) {
1455        const unsigned nb = std::min<unsigned>(blocks(n, 1024), 4u * (unsigned) std::max(dev_info().sms, 1));
1456        count_kernel<<<nb, 1024, (size_t) n_expert * 4, s>>>(ids, n, n_expert, tb.cnt);
1457    }
1458    scan_kernel<<<1, (unsigned) ((n_expert + 31) / 32 * 32), 0, s>>>(tb, n_expert);
1459    if (n > 0) place_kernel<<<blocks(n, 256), 256, 0, s>>>(ids, n, k, n_expert, tb, slot, src);
1460    ck(cudaGetLastError(), "group");
1461}
1462
1463void experts(const Batch& b, int n_expert, int64_t n, const void* scratch, const void* xa, const int32_t* src,
1464             void* ha, float* dm, void* stream) {
1465    if (b.e1 <= b.e0 || n <= 0) return;
1466    const DevInfo& d = dev_info();
1467    const cudaStream_t s = (cudaStream_t) stream;
1468    const Tables tb = tables(const_cast<void*>(scratch), n_expert);
1469    // the most tiles the batch can have: every row in it, plus a partial tile per expert
1470    const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
1471#if defined(__HIPCC__)
1472    const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * (1280 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_gu));
1473    const unsigned g_d = (unsigned) std::min<int64_t>(tiles * (2560 / W_ROWS), (int64_t) d.sms * wgp_blocks(d.occ_d));
1474    expert_w11_kernel<true><<<g_gu, W_THREADS, 0, s>>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha, nullptr);
1475    expert_w11_kernel<false><<<g_d, W_THREADS, 0, s>>>(b, tb, (const uint8_t*) ha, src, nullptr, dm);
1476#else
1477    const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * 5, (int64_t) d.sms * d.occ_gu);
1478    const unsigned g_d = (unsigned) std::min<int64_t>(tiles * 10, (int64_t) d.sms * d.occ_d);
1479    expert_kernel<true><<<g_gu, THREADS, smem_bytes(true), s>>>(b, tb, (const uint8_t*) xa, src, (uint8_t*) ha,
1480                                                                nullptr);
1481    expert_kernel<false><<<g_d, THREADS, smem_bytes(false), s>>>(b, tb, (const uint8_t*) ha, src, nullptr, dm);
1482#endif
1483    ck(cudaGetLastError(), "experts");
1484}
1485
1486bool latent_fused_available() { return lat_dev().ok; }
1487
1488size_t latent_group_bytes(int64_t n, int n_expert) { return group_bytes(n, n_expert); }
1489
1490size_t latent_h_off(int64_t n, int n_expert) { return (group_bytes(n, n_expert) + 255) & ~(size_t) 255; }
1491
1492size_t latent_scratch_bytes(int64_t n, int n_expert, int64_t iff) {
1493    return latent_h_off(n, n_expert) + (size_t) n * (size_t) (iff >> 6) * LAPITCH;
1494}
1495
1496// the tables experts_latent_q3k reads: the layer's whole grouping (the per-expert entry counts and offsets of the
1497// host grouping, the 64-row tile list in expert id order) in the layout of `group`'s scratch.  `fill` stays zero:
1498// the latent entries are already grouped by the host, no placement runs.
1499void group_latent(const int32_t* cnt, const int32_t* off, int n_expert, void* host, size_t bytes) {
1500    std::memset(host, 0, bytes);
1501    int32_t* p = (int32_t*) host;
1502    int32_t* cnt_d = p;
1503    int32_t* off_d = p + n_expert;
1504    int32_t* ts_d = p + 3 * n_expert + 1;
1505    int2* tiles = (int2*) ((uint8_t*) host + tiles_at(n_expert));
1506    for (int e = 0; e < n_expert; ++e) cnt_d[e] = cnt[e];
1507    for (int e = 0; e <= n_expert; ++e) off_d[e] = off[e];
1508    int t = 0;
1509    for (int e = 0; e < n_expert; ++e) {
1510        ts_d[e] = t;
1511        const int c = cnt[e], nt = (c + kTileRows - 1) / kTileRows;
1512        for (int i = 0; i < nt; ++i) tiles[t + i] = make_int2(e, off[e] + i * kTileRows);
1513        t += nt;
1514    }
1515    ts_d[n_expert] = t;
1516}
1517
1518// The batch's products on the latent geometry: gate/up from `xa` (the xl rows' q8_1 blocks, [rows][ell] of
1519// 36-byte blocks) through the rows `src` of the tables (src[row] = that entry's xl row), SwiGLU, H as q8_1 into
1520// `hbuf` (n rows of latent_h_off-sized scratch), down into `dm` [n][ell] FP32 at the tables' rows.  `n` bounds the
1521// launch grid.  The blobs are the native NVFP4 layout `g` describes; an expert of the tables without a blob in
1522// `b` (it belongs to another launch of the same layer) is skipped.
1523void experts_latent_q3k(const WideBatch& b, const LatentGeom& g, int n_expert, int64_t n, const void* scratch,
1524                    const void* xa, const int32_t* src, void* hbuf, float* dm, void* stream) {
1525    if (b.e1 <= b.e0 || n <= 0) return;
1526    const LatentDevInfo& d = lat_dev();
1527    if (!d.ok) {
1528        std::fprintf(stderr, "prefill fused experts (latent): the kernels are not available on this device\n");
1529        std::exit(1);
1530    }
1531    const cudaStream_t s = (cudaStream_t) stream;
1532    const Tables tb = tables(const_cast<void*>(scratch), n_expert);
1533    // the most tiles the batch can have: every row in it, plus a partial tile per expert
1534    const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0);
1535    const int64_t nfb_gu = (int64_t) std::max<int64_t>(1, (int64_t) (g.iff / 128));
1536    const int64_t nfb_d = (int64_t) std::max<int64_t>(1, (int64_t) (g.ell >> 8));
1537    const unsigned g_gu = (unsigned) std::min<int64_t>(tiles * nfb_gu, (int64_t) d.sms * d.occ_gu);
1538    const unsigned g_d = (unsigned) std::min<int64_t>(tiles * nfb_d, (int64_t) d.sms * d.occ_d);
1539    latent_kernel_q3k<true><<<g_gu, LTHREADS, lat_smem_bytes(), s>>>(b, tb, g, (const uint8_t*) xa, src,
1540                                                                 (uint8_t*) hbuf, nullptr);
1541    ck(cudaGetLastError(), "experts_latent_q3k gu");
1542    latent_kernel_q3k<false><<<g_d, LTHREADS, lat_smem_bytes(), s>>>(b, tb, g, (const uint8_t*) hbuf, src, nullptr, dm);
1543    ck(cudaGetLastError(), "experts_latent_q3k down");
1544    ck(cudaGetLastError(), "experts_latent_q3k");
1545}
1546
1547// The latent D projection on the fused dense kernel: the layer input's q8_1 rows [M = T, K = N] (`xq`,
1548// quantize_q8_1_rows of the mixed rows) against the layer's G*ell Q8_0 weight rows (`w`, the dense pack's D
1549// section), the products quantized to the xl rows' own q8_1 blocks in `outq` (row t*G + g) - the FP32 xl round
1550// trip of iq_mmvq + quantize_q8_1_rows never runs.
1551void latent_dense_d(const void* w, const void* xq, int64_t M, int K, int G, int64_t ell, void* outq, void* stream,
1552                     int fmt, const float* inv) {
1553    const LatentDevInfo& d = lat_dev();
1554    if (!d.ok) {
1555        std::fprintf(stderr, "prefill fused experts (latent dense): the kernels are not available on this device\n");
1556        std::exit(1);
1557    }
1558    const cudaStream_t s = (cudaStream_t) stream;
1559    const int64_t nwork = ((M + kTileRows - 1) / kTileRows) * (int64_t) (((size_t) G * ell) >> 8);
1560    const unsigned grid = (unsigned) std::min<int64_t>(nwork, (int64_t) d.sms * d.occ_dd);
1561    latent_dense_kernel<true><<<grid, LTHREADS, lat_smem_bytes(), s>>>(
1562        (const uint8_t*) w, (const uint8_t*) xq, nullptr, nullptr, outq, nullptr, K, ell, G, 0, 0, M, nwork,
1563        fmt, inv);
1564    ck(cudaGetLastError(), "latent_dense_d");
1565}
1566
1567// The latent U projection: each entry's ylq row (`xq`, [M = T*K, K = ELL]) against its label's H Q8_0 weight
1568// rows (`w`, the dense pack's U section, n_groups groups of H rows).  The entries are bucketed by their label
1569// on the host: `goff` [n_groups + 1] the per-group run in `rows` [M] (the entry index list), both in device
1570// memory; `nwork` the tile-item count that bounds the launch grid.  FP32 into `out` [M, H].
1571void latent_dense_u(const void* w, const void* yq, const int32_t* rows, const int32_t* goff, int n_groups,
1572                    int64_t nwork, int64_t M, int K, int H, float* out, void* stream, int fmt) {
1573    const LatentDevInfo& d = lat_dev();
1574    if (!d.ok) {
1575        std::fprintf(stderr, "prefill fused experts (latent dense): the kernels are not available on this device\n");
1576        std::exit(1);
1577    }
1578    const cudaStream_t s = (cudaStream_t) stream;
1579    const unsigned grid = (unsigned) std::min<int64_t>(nwork, (int64_t) d.sms * d.occ_du);
1580    latent_dense_kernel<false><<<grid, LTHREADS, lat_smem_bytes(), s>>>(
1581        (const uint8_t*) w, (const uint8_t*) yq, rows, goff, nullptr, out, K, 0, 0, H, n_groups, M, nwork,
1582        fmt, nullptr);
1583    ck(cudaGetLastError(), "latent_dense_u");
1584}
1585
1586// The U tables on the device: goff[0..n_groups] (the per-group run ends), rows[0..n) (the entries bucketed by
1587// their expert's label), cursors (n_groups + 1 scratch) - all from ids[] and labels[] that are already resident.
1588// The caller bounds the launch grid without the counts: ceil(n / 64) + n_groups tiles cover every split.
1589void latent_dense_u_tables(const int32_t* ids, const int32_t* labels, int64_t n, int n_groups, int32_t* goff,
1590                           int32_t* cursors, int32_t* rows, void* stream) {
1591    const cudaStream_t s = (cudaStream_t) stream;
1592    ck(cudaMemsetAsync(goff, 0, (size_t) (n_groups + 1) * 4, s), "latent u tables memset");
1593    lat_u_count_k<<<64, 256, 0, s>>>(ids, labels, n, n_groups, goff);
1594    lat_u_prefix_k<<<1, 1, 0, s>>>(goff, cursors, n_groups);
1595    lat_u_scatter_k<<<64, 256, 0, s>>>(ids, labels, n, n_groups, cursors, rows);
1596    ck(cudaGetLastError(), "latent_dense_u_tables");
1597}
1598
1599}  // namespace strata::prefill::fused_q3k