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