okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0408f0921
main
1// q36_kernels.cuh - decode kernels of the Qwen3.6 engine (q36_engine.cu), written to give the SAME BITS as the shared 2// kernels they replace (native_small_mmvq_kernel, k_moe_out, k_add_rms, k_group, native_quantize_q8_1) with a layout that 3// keeps more bytes in flight and fewer launches. Every kernel here is checked bit for bit against the old one on the 4// real activations (STRATA_Q36_VERIFY=1, --no-graph). 5#pragma once 6 7#include "strata/kernels/dp4a.hpp" 8#include "strata/kernels/q8_1_finite.hpp" 9 10#include <cuda_fp16.h> 11#include <cuda_runtime.h> 12 13#include <cfloat> 14#include <cmath> 15#include <cstdint> 16 17namespace q36k { 18 19struct QB { // a q8_1 activation block (what native_quantize_q8_1 writes) 20 half2 ds; 21 int8_t qs[32]; 22}; 23static_assert(sizeof(QB) == 36, "q8_1 block"); 24 25__device__ __forceinline__ float wsum(float x) { 26#pragma unroll 27 for (int o = 16; o > 0; o >>= 1) x += __shfl_xor_sync(0xffffffffu, x, o, 32); 28 return x; 29} 30__device__ __forceinline__ float wmax(float x) { 31#pragma unroll 32 for (int o = 16; o > 0; o >>= 1) x = fmaxf(x, __shfl_xor_sync(0xffffffffu, x, o, 32)); 33 return x; 34} 35__device__ __forceinline__ float sigm(float v) { return 1.0f / (1.0f + expf(-v)); } 36 37// The shared CUDA kernels these ones replace (native_mmvq.cu, native_router.cu) are compiled with --use_fast_math (CMakeLists.txt); 38// this file is not, so on CUDA the division and the exponential they use are spelled out as the instructions that flag selects 39// (div.approx.ftz, rcp.approx.ftz, ex2.approx.ftz via __expf). HIP builds have no such flag: plain operators. 40#if defined(__CUDACC__) && !defined(__HIPCC__) 41__device__ __forceinline__ float fdiv_fm(float a, float b) { 42 float r; 43 asm("div.approx.ftz.f32 %0, %1, %2;" : "=f"(r) : "f"(a), "f"(b)); 44 return r; 45} 46__device__ __forceinline__ float frcp_fm(float a) { 47 float r; 48 asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(a)); 49 return r; 50} 51__device__ __forceinline__ float fexp_fm(float a) { return __expf(a); } 52#else 53__device__ __forceinline__ float fdiv_fm(float a, float b) { return a / b; } 54__device__ __forceinline__ float frcp_fm(float a) { return 1.0f / a; } 55__device__ __forceinline__ float fexp_fm(float a) { return expf(a); } 56#endif 57 58/// One lane's element `v` of a 32-element q8_1 block (the warp is the block): native_quantize_q8_1_kernel's body. 59/// `y` points at the row's blocks, `i` is the element index within the row. 60__device__ __forceinline__ void q8_store(QB* __restrict__ y, int i, float v, int lane) { 61 const float amax = wmax(fabsf(v)); 62 const float sum = wsum(v); 63 const float d = strata::kernels::q8_1_finite(fdiv_fm(amax, 127.0f)); 64 int8_t q = 0; // strata::kernels::q8_1_quant with the division of the fast-math TU 65 if (amax != 0.0f) { 66 const float qf = roundf(fdiv_fm(v, d)); 67 q = (int8_t) (qf > 127.0f ? 127.0f : qf < -127.0f ? -127.0f : qf); 68 } 69 y[i >> 5].qs[lane] = q; 70 if (lane == 0) y[i >> 5].ds = strata::kernels::q8_1_ds(d, sum); 71} 72 73/// A Q8_0 row (GGUF blocks of 34 bytes, or the qs / d planes with PK) against NC activation columns, with the arithmetic of 74/// native_small_mmvq_kernel / native_mmvq_multi_kernel's exact layout: the 4 warps of the old block are the 4 partial sums 75/// P_w of one lane here (block kbx = 8 w + lane / 4 + 32 j, ints 2 (lane % 4) and +1), added in warp order, then the xor 76/// tree. One warp per row, every load of a lane issued before the first dot (NJ = ceil(nb / 32) terms per partial). 77/// res[c] = the row's value for column c in every lane. 78template <int NC, int NJ, bool PK> 79__device__ __forceinline__ void q8_row_dot(const uint8_t* __restrict__ w, const half* __restrict__ dpl, const QB* __restrict__ x, 80 int row, int nb, int lane, float (&res)[NC]) { 81 const int kqs = 2 * (lane & 3); 82 const int kb0 = lane >> 2; 83 int v0[4][NJ], v1[4][NJ]; 84 float d0[4][NJ]; 85 bool ok[4][NJ]; 86#pragma unroll 87 for (int p = 0; p < 4; ++p) 88#pragma unroll 89 for (int j = 0; j < NJ; ++j) { 90 const int kbx = kb0 + 8 * p + 32 * j; 91 ok[p][j] = kbx < nb; 92 if (!ok[p][j]) continue; 93 const size_t blk = (size_t) row * nb + kbx; 94 if (PK) { 95 const int* q = reinterpret_cast<const int*>(w + blk * 32) + kqs; 96 v0[p][j] = q[0]; 97 v1[p][j] = q[1]; 98 d0[p][j] = __half2float(dpl[blk]); 99 } else { 100 const uint16_t* b = reinterpret_cast<const uint16_t*>(w + blk * 34); 101 d0[p][j] = __half2float(__ushort_as_half(b[0])); 102 v0[p][j] = (int) b[1 + 2 * kqs] | ((int) b[2 + 2 * kqs] << 16); 103 v1[p][j] = (int) b[3 + 2 * kqs] | ((int) b[4 + 2 * kqs] << 16); 104 } 105 } 106 float P[NC][4]; 107#pragma unroll 108 for (int c = 0; c < NC; ++c) 109#pragma unroll 110 for (int p = 0; p < 4; ++p) { 111 float t = 0.f; 112#pragma unroll 113 for (int j = 0; j < NJ; ++j) { 114 if (!ok[p][j]) continue; 115 const QB* xb = x + (size_t) c * nb + kb0 + 8 * p + 32 * j; 116 const int* u = reinterpret_cast<const int*>(xb->qs); 117 int sumi = 0; 118 sumi = STRATA_DP4A(v0[p][j], u[kqs], sumi); 119 sumi = STRATA_DP4A(v1[p][j], u[kqs + 1], sumi); 120 const float d1 = __low2float(xb->ds); 121 t += d0[p][j] * d1 * float(sumi); 122 } 123 P[c][p] = t; 124 } 125#pragma unroll 126 for (int c = 0; c < NC; ++c) { 127 float t = P[c][0]; 128 t += P[c][1]; 129 t += P[c][2]; 130 t += P[c][3]; 131 res[c] = wsum(t); 132 } 133} 134 135/// y[c][row] = W[row] . x[c], NC columns, 8 rows (warps) per 256-thread block. 136template <int NC, int NJ, bool PK> 137__global__ void __launch_bounds__(256) k_q8_rows(const uint8_t* __restrict__ w, const half* __restrict__ dpl, 138 const QB* __restrict__ x, float* __restrict__ y, int nb, int n_out) { 139 const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; 140 const int stride = gridDim.x * (blockDim.x >> 5); // a grid-stride loop over the rows (see launch_q8_rows) 141 for (int row = blockIdx.x * (blockDim.x >> 5) + warp; row < n_out; row += stride) { 142 float res[NC]; 143 q8_row_dot<NC, NJ, PK>(w, dpl, x, row, nb, lane, res); 144 if (lane == 0) 145#pragma unroll 146 for (int c = 0; c < NC; ++c) y[(size_t) c * n_out + row] = res[c]; 147 } 148} 149 150template <int NC, int NJ, bool PK> 151inline void launch_q8_rows_t(const void* w, const half* dpl, const void* x, float* y, int nb, int n_out, int warps, int max_warps, 152 cudaStream_t s) { 153 const int rows = n_out < max_warps ? n_out : max_warps; 154 k_q8_rows<NC, NJ, PK><<<(unsigned) ((rows + warps - 1) / warps), warps * 32, 0, s>>>(static_cast<const uint8_t*>(w), dpl, 155 static_cast<const QB*>(x), y, nb, n_out); 156} 157 158template <int NC, int NJ, bool PK> 159/// At most 1024 warps in the grid, a grid-stride loop over the rows beyond: a 2048-row product took 21 us on gfx1201 as 2048 warps and 160/// 5.2 us as 1024 (a grid above 32768 threads is several times slower there; the same rows, the same sums). 161inline void launch_q8_rows(const void* w, const half* dpl, const void* x, float* y, int nb, int n_out, cudaStream_t s) { 162 launch_q8_rows_t<NC, NJ, PK>(w, dpl, x, y, nb, n_out, 8, 1024, s); 163} 164 165/// The shared expert's gate and up products and SwiGLU + q8_1 in one launch: 32 rows (one q8_1 block of h) per 1024-thread 166/// block, warp w computing gate row and up row 32 b + w, then warp 0 applying native_swiglu_quantize_q8_1_kernel's body to 167/// the 32 pairs. Column c of the h image is at hq + c * (n_out / 32). n_out % 32 == 0. 168template <int NC, int NJ, bool PK> 169__global__ void __launch_bounds__(1024) k_sh_gu(const uint8_t* __restrict__ wg, const half* __restrict__ dg, const uint8_t* __restrict__ wu, 170 const half* __restrict__ du, const QB* __restrict__ x, QB* __restrict__ hq, 171 int nb, int n_out) { 172 __shared__ float g[NC][32], u[NC][32]; 173 const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; 174 const int row = blockIdx.x * 32 + warp; 175 float rg[NC], ru[NC]; 176 q8_row_dot<NC, NJ, PK>(wg, dg, x, row, nb, lane, rg); 177 q8_row_dot<NC, NJ, PK>(wu, du, x, row, nb, lane, ru); 178 if (lane == 0) 179#pragma unroll 180 for (int c = 0; c < NC; ++c) { 181 g[c][warp] = rg[c]; 182 u[c][warp] = ru[c]; 183 } 184 __syncthreads(); 185 if (warp == 0) { 186#pragma unroll 187 for (int c = 0; c < NC; ++c) { 188 const float gi = g[c][lane]; 189 const float xi = __fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), u[c][lane]); 190 q8_store(hq + (size_t) c * (n_out >> 5), blockIdx.x * 32 + lane, xi, lane); 191 } 192 } 193} 194 195/// k_add_rms (x += y; h = rms(x) * w, one block of 256 per row) and the q8_1 image of h in the same launch. 196__global__ void __launch_bounds__(256) k_add_rms_q(float* x, const float* y, const float* w, float* h, QB* hq, int n, float eps) { 197 __shared__ float sh[256]; 198 float* xr = x + (size_t) blockIdx.x * n; 199 const float* yr = y + (size_t) blockIdx.x * n; 200 float* hr = h + (size_t) blockIdx.x * n; 201 QB* qr = hq + (size_t) blockIdx.x * (n >> 5); 202 float s = 0.f; 203 for (int i = threadIdx.x; i < n; i += 256) { 204 const float v = xr[i] + yr[i]; 205 xr[i] = v; 206 s += v * v; 207 } 208 sh[threadIdx.x] = s; 209 __syncthreads(); 210 for (int o = 128; o > 0; o >>= 1) { 211 if ((int) threadIdx.x < o) sh[threadIdx.x] += sh[threadIdx.x + o]; 212 __syncthreads(); 213 } 214 const float r = rsqrtf(sh[0] / (float) n + eps); 215 for (int i = threadIdx.x; i < n; i += 256) { 216 const float hv = __fmul_rn(__fmul_rn(xr[i], r), w[i]); // no FMA with the quantizer's sums: the old h was stored first 217 hr[i] = hv; 218 q8_store(qr, i, ((volatile float*) hr)[i], threadIdx.x & 31); // the stored value, as the standalone quantizer reads it 219 } 220} 221 222/// k_moe_out for T <= 8 rows (decode, verify windows) with n <= 2048 and n % 256 == 0: 1024 threads per row instead of 256 223/// (the elements' loads in parallel), the squares summed per old thread (element t, t + 256, ... in order) and the 224/// 256-wide tree as before: the same bits. x += sum_k w_k part_k (+ gate * shared); h = rms(x) * wn; with hq the q8_1 225/// image of h as well (the next layer's input). 226__global__ void __launch_bounds__(1024) k_moe_out_small(float* x, const float* parts, const int32_t* prow, const float* wts, 227 int K_, const float* shared, const float* sgate, int sg_stride, 228 const float* wn, float* h, int n, float eps, QB* hq = nullptr) { 229 __shared__ float vv[2048]; 230 __shared__ float sh[256]; 231 __shared__ const float* pk[16]; 232 const int t = blockIdx.x; 233 float* xr = x + (size_t) t * n; 234 if (threadIdx.x < K_) pk[threadIdx.x] = parts + (size_t) (prow ? prow[t * K_ + threadIdx.x] : t * K_ + threadIdx.x) * n; 235 __syncthreads(); 236 const float* wr = wts + (size_t) t * K_; 237 const float gs = sigm(sgate[(size_t) t * sg_stride]); 238 for (int i = threadIdx.x; i < n; i += 1024) { 239 float acc = wr[0] * pk[0][i]; 240 for (int k = 1; k < K_; ++k) acc = fmaf(wr[k], pk[k][i], acc); 241 acc += gs * shared[(size_t) t * n + i]; 242 const float v = xr[i] + acc; 243 xr[i] = v; 244 vv[i] = v; 245 } 246 if (wn == nullptr) return; 247 __syncthreads(); 248 if (threadIdx.x < 256) { 249 float s = 0.f; 250 for (int i = threadIdx.x; i < n; i += 256) s += vv[i] * vv[i]; 251 sh[threadIdx.x] = s; 252 } 253 __syncthreads(); 254 for (int s = 128; s > 0; s >>= 1) { 255 if ((int) threadIdx.x < s) sh[threadIdx.x] += sh[threadIdx.x + s]; 256 __syncthreads(); 257 } 258 const float r = rsqrtf(sh[0] / (float) n + eps); 259 for (int i = threadIdx.x; i < n; i += 1024) { 260 const float hv = __fmul_rn(__fmul_rn(vv[i], r), wn[i]); 261 h[(size_t) t * n + i] = hv; 262 if (hq) q8_store(hq + (size_t) t * (n >> 5), i, ((volatile float*) h)[(size_t) t * n + i], threadIdx.x & 31); 263 } 264} 265 266/// k_group / k_group_hy for n_ent <= 64 entries: one block of 64 threads ranks each entry by (expert id, entry) in 267/// parallel instead of one thread walking all the experts; the same group / entry arrays. HY: only the entries whose 268/// expert has a VRAM slot (slot_of >= 0), the group's blob at blobs + slot * blob. 269template <bool HY> 270__global__ void k_group_small(const int32_t* ids, int n_ent, int K_, const int32_t* slot_of, const uint8_t* blobs, 271 unsigned long long blob, unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups, 272 int32_t* ent_dst, int32_t* ent_tok) { 273 __shared__ int sid[64]; 274 const int e = threadIdx.x; 275 const int id = e < n_ent ? ids[e] : 0; 276 const bool valid = e < n_ent && (!HY || slot_of[id] >= 0); 277 int rank = 0; 278 if (valid) { 279 for (int e2 = 0; e2 < n_ent; ++e2) { 280 const int id2 = ids[e2]; 281 if (HY && slot_of[id2] < 0) continue; 282 if (id2 < id || (id2 == id && e2 < e)) ++rank; 283 } 284 ent_dst[rank] = e; 285 ent_tok[rank] = e / K_; 286 sid[rank] = id; 287 } 288 __syncthreads(); 289 int nv = 0; 290 for (int e2 = 0; e2 < n_ent; ++e2) nv += (!HY || slot_of[ids[e2]] >= 0) ? 1 : 0; 291 if (valid && (rank == 0 || sid[rank - 1] != sid[rank])) { 292 int g = 0; 293 for (int q = 1; q < rank; ++q) g += sid[q - 1] != sid[q] ? 1 : 0; 294 g += rank > 0 ? 1 : 0; 295 grp_ptr[g] = (unsigned long long) (blobs + (size_t) (HY ? slot_of[id] : id) * blob); 296 grp_start[g] = rank; 297 } 298 if (e == 0) { 299 int G = nv > 0 ? 1 : 0; 300 for (int q = 1; q < nv; ++q) G += sid[q - 1] != sid[q] ? 1 : 0; 301 grp_start[G] = nv; 302 *n_groups = G; 303 } 304} 305 306/// route_topk<256, 8> (native_router.cu, copied: the same expressions) for n_tok <= 8 tokens (one warp each) and, in the same 307/// launch, k_group_small's grouping of the picks. block (32, 8). HY as k_group_small. 308template <bool HY> 309__global__ void __launch_bounds__(256) k_route_group(const float* __restrict__ logits, int32_t* __restrict__ ids, 310 float* __restrict__ weights, int n_tok, int ld, const int32_t* slot_of, 311 const uint8_t* blobs, unsigned long long blob, 312 unsigned long long* grp_ptr, int32_t* grp_start, int32_t* n_groups, 313 int32_t* ent_dst, int32_t* ent_tok) { 314 constexpr int NE = 256, K = 8, V = NE / 32; 315 __shared__ int sids[64], sid[64]; 316 const int tk = threadIdx.y; 317 const int lane = threadIdx.x; 318 if (tk < n_tok) { 319 const float* lg = logits + (size_t) tk * ld; 320 float values[V]; 321#pragma unroll 322 for (int i = 0; i < V; ++i) values[i] = lg[lane + i * 32]; 323 float maximum = -INFINITY; 324#pragma unroll 325 for (int i = 0; i < V; ++i) maximum = max(maximum, values[i]); 326 maximum = wmax(maximum); 327 float sum = 0.0f; 328#pragma unroll 329 for (int i = 0; i < V; ++i) { 330 values[i] = fexp_fm(values[i] - maximum); 331 sum += values[i]; 332 } 333 const float reciprocal = frcp_fm(wsum(sum)); 334#pragma unroll 335 for (int i = 0; i < V; ++i) { 336 values[i] *= reciprocal; 337 if (__isnanf(values[i])) values[i] = -FLT_MAX; 338 } 339 float selected = 0.0f, selected_sum = 0.0f; 340 for (int rank = 0; rank < K; ++rank) { 341 float best = values[0]; 342 int expert = lane; 343#pragma unroll 344 for (int i = 1; i < V; ++i) { 345 if (values[i] > best) { best = values[i]; expert = lane + i * 32; } 346 } 347#pragma unroll 348 for (int mask = 16; mask; mask >>= 1) { 349 const float other = __shfl_xor_sync(0xffffffffu, best, mask, 32); 350 const int other_id = __shfl_xor_sync(0xffffffffu, expert, mask, 32); 351 if (other > best || (other == best && other_id < expert)) { best = other; expert = other_id; } 352 } 353 if ((expert & 31) == lane) { 354 values[expert / 32] = -INFINITY; 355 ids[(size_t) tk * K + rank] = expert; 356 sids[tk * K + rank] = expert; 357 selected_sum += best; 358 } 359 if (rank == lane) selected = best; 360 } 361 selected_sum = max(wsum(selected_sum), 6.103515625e-5f); 362 const float inverse_selected_sum = frcp_fm(selected_sum); 363 if (lane < K) weights[(size_t) tk * K + lane] = selected * inverse_selected_sum; 364 } 365 __syncthreads(); 366 const int n_ent = n_tok * K; 367 const int e = tk * 32 + lane; // 0 .. 255: the entries are the first n_ent threads 368 const int id = e < n_ent ? sids[e] : 0; 369 const bool valid = e < n_ent && (!HY || slot_of[id] >= 0); 370 int rank = 0; 371 if (valid) { 372 for (int e2 = 0; e2 < n_ent; ++e2) { 373 const int id2 = sids[e2]; 374 if (HY && slot_of[id2] < 0) continue; 375 if (id2 < id || (id2 == id && e2 < e)) ++rank; 376 } 377 ent_dst[rank] = e; 378 ent_tok[rank] = e / K; 379 sid[rank] = id; 380 } 381 __syncthreads(); 382 int nv = 0; 383 for (int e2 = 0; e2 < n_ent; ++e2) nv += (!HY || slot_of[sids[e2]] >= 0) ? 1 : 0; 384 if (valid && (rank == 0 || sid[rank - 1] != sid[rank])) { 385 int g = 0; 386 for (int q = 1; q < rank; ++q) g += sid[q - 1] != sid[q] ? 1 : 0; 387 g += rank > 0 ? 1 : 0; 388 grp_ptr[g] = (unsigned long long) (blobs + (size_t) (HY ? slot_of[id] : id) * blob); 389 grp_start[g] = rank; 390 } 391 if (e == 0) { 392 int G = nv > 0 ? 1 : 0; 393 for (int q = 1; q < nv; ++q) G += sid[q - 1] != sid[q] ? 1 : 0; 394 grp_start[G] = nv; 395 *n_groups = G; 396 } 397} 398 399} // namespace q36k