okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1// src/prefill/lat_q3k_gu.cu - see include/strata/prefill/lat_q3k_gu.hpp. 2// 3// M2a of the q3k latent A stage (q3k_fused/BRIEF.md): the gate/up half, Q3_K, K = 1280, 640 gate rows + 640 up rows. 4// It is the latent fp4 kernel's work item, mma and epilogue (moe_fused.cu's latent_kernel<true>, 128 features of gate 5// and their up rows as the stage's rows 0-127 / 128-255) with the staged row built from Q3_K instead of NVFP4: 6// staged row (80 B): 4 x 16 int8 codes at 16 * s, four fp32 sub-scales at 64 + 4 * s 7// a lane multiplies word k, byte c of its weight sub-block with word k, byte c of the activation sub-block, so both 8// hold the sub-block's value 4c + k; the sub-block's scale multiplies the whole 16-value product. 9// 10// The decode. block_q3_K (110 B, 256 values): hmask[32], qs[64], scales[12], half d. Value v of the super-block is 11// code(v) = ((qs[B] >> 2t) & 3) - 4 + 4 * ((hmask[B] >> m) & 1) in [-4, 3] 12// scale = d * (sc[s] - 32), s = v / 16, sc = the 6-bit scale of that sub-block 13// with B = 32 * (v / 128) + 16 * ((v / 16) & 1) + (v & 15), t = (v / 32) & 3 and m = t + 4 * (v / 128) - exactly 14// ggml-quants.c's dequantize_row_q3_K (:1305): its 16 sub-blocks per 128-value half, its `shift += 2; m <<= 1`. 15// The 16 6-bit scales come from the 12 scale bytes the same way: sub-block s takes the low (s < 8) or high nibble of 16// byte s & 7 and the two high bits 2 * (s / 4) of byte 8 + (s & 3). 17// A 64-value chunk of a row is four sub-blocks: 32 qs bytes and 32 hmask bytes of one half at ONE 2-bit field. Two 18// threads a row: thread `whalf` takes the two sub-blocks of field j = 2 * (chunk & 1) + whalf. 19// 20// The rows are 550 B apart, so an address inside a row is 4-byte aligned or 2 mod 4: the 16-byte groups are read with 21// one funnel shift (lat_ld4). The reads can reach up to 6 bytes past a row's last scale byte, which is inside the 22// blob (the down section follows the gate/up rows) and never past the blob. 23#include "strata/prefill/lat_q3k_gu.hpp" 24 25#include <cuda_fp16.h> 26#include <cuda_runtime.h> 27 28#include "ggml.h" 29 30#define GGML_COMMON_DECL_CUDA 31#define GGML_COMMON_IMPL_CUDA 32#include "ggml-common.h" 33 34#include <algorithm> 35#include <cstdio> 36#include <cstdlib> 37 38namespace strata::prefill { 39namespace { 40 41void dck(cudaError_t e, const char* what) { 42 if (e != cudaSuccess) { 43 std::fprintf(stderr, "lat q3k gu: %s: %s\n", what, cudaGetErrorString(e)); 44 std::exit(1); 45 } 46} 47 48constexpr int64_t kNE = 1280; // K (ell): 5 Q3_K super-blocks 49constexpr int64_t kFF = 640; // gate/up rows per projection 50constexpr size_t kUpOff = 352000; // native_expert_layout(11, 20, 1280, 640) 51constexpr size_t kGuRow = 550; // 5 x 110 B 52constexpr int kChunks = 20; // 1280 / 64 53constexpr int kItems = 5; // 640 features / 128 a work item 54 55constexpr int LTHREADS = 512; 56constexpr int WROWS = 256; // 128 gate rows + their 128 up rows 57constexpr int LWPITCH = 80; // 4 x 16 codes, 4 fp32 sub-scales 58constexpr int LAPITCH = 80; // 64 activation codes, {d0, d1}, pad 59constexpr int kTileRows = 64; 60constexpr int kXqRow = 1440; // 40 q8_1 blocks of 36 B 61 62inline size_t lat_smem_bytes() { 63 return (size_t) 2 * WROWS * LWPITCH + (size_t) 2 * kTileRows * LAPITCH + (size_t) kTileRows * 4; 64} 65 66#if !defined(__HIPCC__) 67 68// 16 bytes at p as four words; `sh` is 0 or 16, from the row's 2-byte misalignment (550 B rows) 69__device__ __forceinline__ void lat_ld4(const uint8_t* p, int sh, uint32_t (&w)[4]) { 70 const uint32_t* q = (const uint32_t*) (p - (sh >> 3)); 71 w[0] = __funnelshift_r(q[0], q[1], sh); 72 w[1] = __funnelshift_r(q[1], q[2], sh); 73 w[2] = __funnelshift_r(q[2], q[3], sh); 74 w[3] = __funnelshift_r(q[3], q[4], sh); 75} 76 77// One 16-value sub-block's 4 code words (A[m] byte c = the sub-block's value 4m + c) into the staged order: out[k]'s 78// byte c is the sub-block's value 4c + k (the order the staged activations use, so both mma operands agree). 79__device__ __forceinline__ void lat_stage_codes(const uint32_t* A, uint32_t (&out)[4]) { 80#pragma unroll 81 for (int k = 0; k < 4; ++k) 82 out[k] = __byte_perm(__byte_perm(A[0], A[1], k | ((k + 4) << 4)), 83 __byte_perm(A[2], A[3], k | ((k + 4) << 4)), 0x5410u); 84} 85 86// This thread's two sub-blocks of one 64-value chunk, staged. 87struct GuStaged { 88 uint32_t w[2][4]; 89 float sc[2]; 90}; 91 92__device__ __forceinline__ GuStaged lat_gu_decode(const uint8_t* blk, int kb, int whalf) { 93 const int cl = kb & 3; // the chunk inside the 256-value super-block 94 const int half = cl >> 1; // the dequantizer's n = 128 * half 95 const int j = 2 * (cl & 1) + whalf; // the 2-bit field (and, with +4*half, the hmask bit) 96 const int hb = j + 4 * half; // the hmask bit of this thread's two sub-blocks 97 const int sh = 8 * ((int) ((uintptr_t) blk & 3)); 98 uint32_t qg[2][4], hg[2][4], sw[4]; 99 lat_ld4(blk + 32 + 32 * half + 0, sh, qg[0]); // the even sub-block's 16 qs bytes 100 lat_ld4(blk + 32 + 32 * half + 16, sh, qg[1]); // the odd one's 101 // the hmask is NOT advanced across the 128-value halves (ggml reads hm[l] / hm[l + 16] both times, the bit 102 // j + 4 * half picking the half): its two 16-byte groups are 0 and 16 103 lat_ld4(blk + 0, sh, hg[0]); 104 lat_ld4(blk + 16, sh, hg[1]); 105 lat_ld4(blk + 96, sh, sw); // scales[12] then d (and 2 pad bytes) 106 const float d = __half2float(__ushort_as_half((unsigned short) (sw[3] & 0xFFFFu))); 107 GuStaged r; 108#pragma unroll 109 for (int g = 0; g < 2; ++g) { // sub-block s_local = 2 * whalf + g 110 const int s = 4 * cl + 2 * whalf + g; 111 uint32_t nat[4]; 112#pragma unroll 113 for (int m = 0; m < 4; ++m) { 114 const uint32_t lo2 = (qg[g][m] >> (2 * j)) & 0x03030303u; // 2 low bits per value 115 const uint32_t hi1 = (hg[g][m] >> hb) & 0x01010101u; // the high bit -> 4 116 // the -4 offset ggml's vec_dot folds in with a second dp4a, folded into the code here: [0, 7] - 4 = 117 // [-4, 3]. Byte-wise, not a 32-bit subtract: a byte underflow would borrow from its neighbour. 118 nat[m] = __vsub4(lo2 | (4u * hi1), 0x04040404u); 119 } 120 lat_stage_codes(nat, r.w[g]); 121 // the sub-block's 6-bit scale: nibble (low/high per half) of byte s & 7, two high bits of byte 8 + (s & 3) 122 const uint32_t nib_byte = (sw[(s & 7) >> 2] >> (8 * (s & 3))) & 0xFFu; 123 const uint32_t nib = (nib_byte >> (4 * (s >> 3))) & 0xFu; 124 const uint32_t hi2 = (sw[2] >> (8 * (s & 3) + 2 * (s >> 2))) & 3u; 125 r.sc[g] = d * (float) ((int) (nib | (hi2 << 4)) - 32); 126 } 127 return r; 128} 129 130// ---- the kernel: 128 gate rows and their up rows per work item ------------------------------------------------ 131__global__ void __launch_bounds__(LTHREADS, 1) 132lat_q3k_gu_kernel(const uint8_t* const* __restrict__ blob, const int32_t* __restrict__ starts, int n_groups, 133 const uint8_t* __restrict__ xq, float* __restrict__ gate, float* __restrict__ up, int64_t ld, 134 const int32_t* __restrict__ counts, const int32_t* __restrict__ ent_tok) { 135#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 136 extern __shared__ __align__(16) uint8_t smem[]; 137 uint8_t* wst[2] = {smem, smem + WROWS * LWPITCH}; 138 uint8_t* ast[2] = {smem + 2 * WROWS * LWPITCH, smem + 2 * WROWS * LWPITCH + kTileRows * LAPITCH}; 139 int* srow = (int*) (smem + 2 * WROWS * LWPITCH + 2 * kTileRows * LAPITCH); 140 141 const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, mg = lane >> 2, tig = lane & 3; 142 const int wf = warp & 3, nb0 = 16 * (warp >> 2); 143 const int wrow = tid >> 1, whalf = tid & 1; // 2 threads a weight row, one 32-value half each 144 const int arow = tid >> 1, ahalf = tid & 1; 145 146 const int fb = blockIdx.x; // this launch's 128 features of the item 147 for (int g = blockIdx.y; g < n_groups; g += gridDim.y) { 148 const uint8_t* bl = blob[g]; 149 if (bl == nullptr) continue; 150 const int e0 = starts[g]; 151 // the group's row count: counts[] when the caller has it (the engine's flushes are not in group order) 152 const int e1 = counts != nullptr ? e0 + counts[g] : starts[g + 1]; 153 for (int row0 = e0 + (int) blockIdx.z * kTileRows; row0 < e1; row0 += (int) gridDim.z * kTileRows) { 154 const int nrows = min(kTileRows, e1 - row0); 155 const int arows = min(kTileRows, (nrows + 15) & ~15); 156 // the stage's row: gate rows 128 * fb .. , then their up rows 128 rows later 157 const int fr = 128 * fb + (wrow & 127); 158 const uint8_t* wsrc = wrow < 128 ? bl + (size_t) fr * kGuRow : bl + kUpOff + (size_t) fr * kGuRow; 159 __syncthreads(); 160 // the activation row of a tile row: the entry itself, or the token row ent_tok gives it 161 if (tid < kTileRows) { 162 const int er = row0 + min(tid, nrows - 1); 163 srow[tid] = ent_tok != nullptr ? ent_tok[er] : er; 164 } 165 __syncthreads(); 166 167 GuStaged wc[2]; 168 uint32_t aq[8], adw = 0; 169 auto load_chunk = [&](int kb) { 170 const uint8_t* blk = wsrc + 110 * (kb >> 2); 171 wc[kb & 1] = lat_gu_decode(blk, kb, whalf); 172 if (tid < 2 * arows) { 173 // the plain q8_1 row: 72 B a chunk (two 32-value blocks), word 0 of a block is its ds 174 const uint32_t* ap = (const uint32_t*) (xq + (size_t) srow[arow] * kXqRow + (size_t) 72 * kb); 175#pragma unroll 176 for (int i = 0; i < 8; ++i) aq[i] = ap[1 + 9 * ahalf + i]; 177 adw = ap[9 * ahalf]; 178 } 179 }; 180 auto store_chunk = [&](int kb) { 181 uint8_t* wr = wst[kb & 1] + (size_t) wrow * LWPITCH; 182 const GuStaged& w = wc[kb & 1]; 183#pragma unroll 184 for (int gg = 0; gg < 2; ++gg) { 185 const int s = 2 * whalf + gg; 186#pragma unroll 187 for (int k = 0; k < 4; ++k) *(uint32_t*) (wr + 16 * s + 4 * k) = w.w[gg][k]; 188 *(float*) (wr + 64 + 4 * s) = w.sc[gg]; 189 } 190 if (tid < 2 * arows) { 191 uint8_t* ar = ast[kb & 1] + (size_t) arow * LAPITCH; 192#pragma unroll 193 for (int h = 0; h < 2; ++h) { 194 const int s = 2 * ahalf + h; 195 const uint32_t* wp = &aq[4 * h]; 196#pragma unroll 197 for (int k = 0; k < 4; ++k) { 198 const uint32_t p1 = __byte_perm(wp[0], wp[1], k | ((k + 4) << 4)); 199 const uint32_t p2 = __byte_perm(wp[2], wp[3], k | ((k + 4) << 4)); 200 *(uint32_t*) (ar + 16 * s + 4 * k) = __byte_perm(p1, p2, 0x5410u); 201 } 202 } 203 *(__half*) (ar + 64 + 2 * ahalf) = __ushort_as_half((unsigned short) (adw & 0xFFFFu)); 204 } 205 }; 206 207 load_chunk(0); 208 store_chunk(0); 209 if (kChunks > 1) load_chunk(1); 210 const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows; 211 float acc[4][2][4]; 212#pragma unroll 213 for (int i = 0; i < 4; ++i) 214#pragma unroll 215 for (int n = 0; n < 2; ++n) 216#pragma unroll 217 for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f; 218 for (int kb = 0; kb < kChunks; ++kb) { 219 __syncthreads(); 220 if (on0) { 221 const uint8_t* wc8 = wst[kb & 1]; 222 const uint8_t* ac = ast[kb & 1]; 223 for (int s = 0; s < 4; ++s) { 224 uint32_t bq[2]; 225 float dx0[2], dx1[2]; 226 for (int n = 0; n < 2; ++n) { 227 if (n == 1 && !on1) break; 228 const uint8_t* ar = ac + (size_t) (nb0 + 8 * n + mg) * LAPITCH; 229 bq[n] = *(const uint32_t*) (ar + 16 * s + 4 * tig); 230 const half2 ds0 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig) * LAPITCH + 64); 231 const half2 ds1 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig + 1) * LAPITCH + 64); 232 dx0[n] = __half2float((s & 2) ? ds0.y : ds0.x); 233 dx1[n] = __half2float((s & 2) ? ds1.y : ds1.x); 234 } 235 for (int i = 0; i < 4; ++i) { 236 const int ra = 32 * wf + 8 * i + mg; // the gate row (its up row is ra + 128) 237 const int rb = ra + 128; 238 const uint32_t a0 = *(const uint32_t*) (wc8 + (size_t) ra * LWPITCH + 16 * s + 4 * tig); 239 const uint32_t a1 = *(const uint32_t*) (wc8 + (size_t) rb * LWPITCH + 16 * s + 4 * tig); 240 const float da = *(const float*) (wc8 + (size_t) ra * LWPITCH + 64 + 4 * s); 241 const float db = *(const float*) (wc8 + (size_t) rb * LWPITCH + 64 + 4 * s); 242 for (int n = 0; n < 2; ++n) { 243 if (n == 1 && !on1) break; 244 int d[4] = {0, 0, 0, 0}; 245 asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, " 246 "{%0,%1,%2,%3};\n" 247 : "+r"(d[0]), "+r"(d[1]), "+r"(d[2]), "+r"(d[3]) 248 : "r"(a0), "r"(a1), "r"(bq[n])); 249 acc[i][n][0] += (da * dx0[n]) * (float) d[0]; 250 acc[i][n][1] += (da * dx1[n]) * (float) d[1]; 251 acc[i][n][2] += (db * dx0[n]) * (float) d[2]; 252 acc[i][n][3] += (db * dx1[n]) * (float) d[3]; 253 } 254 } 255 } 256 } 257 __syncthreads(); 258 if (kb + 1 < kChunks) { 259 store_chunk(kb + 1); 260 if (kb + 2 < kChunks) load_chunk(kb + 2); 261 } 262 } 263 if (!on0) continue; 264 // the q3k pack has no NVFP4 tail: s_gate = s_up = 1 265#pragma unroll 266 for (int i = 0; i < 4; ++i) 267#pragma unroll 268 for (int n = 0; n < 2; ++n) { 269 if (n == 1 && !on1) break; 270 const int col = 128 * fb + 32 * wf + 8 * i + mg; 271#pragma unroll 272 for (int c = 0; c < 2; ++c) { 273 const int r = nb0 + 8 * n + 2 * tig + c; 274 if (r < nrows) { 275 gate[(size_t) (row0 + r) * ld + col] = acc[i][n][c]; 276 up[(size_t) (row0 + r) * ld + col] = acc[i][n][2 + c]; 277 } 278 } 279 } 280 } 281 } 282#endif 283} 284 285// ---- the decode gate: one row's staged rows, written out ------------------------------------------------ 286__global__ void lat_q3k_gu_dump_kernel(const uint8_t* __restrict__ blob, int row, uint8_t* __restrict__ out) { 287#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 288 const int i = threadIdx.x; // i < 2 * kChunks: (chunk, half) 289 if (i >= 2 * kChunks) return; 290 const int kb = i >> 1, whalf = i & 1; 291 const uint8_t* wsrc = blob + (size_t) row * kGuRow; 292 const GuStaged w = lat_gu_decode(wsrc + 110 * (kb >> 2), kb, whalf); 293 uint8_t* wr = out + (size_t) kb * LWPITCH; 294#pragma unroll 295 for (int gg = 0; gg < 2; ++gg) { 296 const int s = 2 * whalf + gg; 297#pragma unroll 298 for (int k = 0; k < 4; ++k) *(uint32_t*) (wr + 16 * s + 4 * k) = w.w[gg][k]; 299 *(float*) (wr + 64 + 4 * s) = w.sc[gg]; 300 } 301#else 302 (void) blob; (void) row; (void) out; 303#endif 304} 305 306#endif // !__HIPCC__ 307 308int lat_sms() { 309 static const int sms = [] { 310 int dev = 0, n = 0; 311 return cudaGetDevice(&dev) == cudaSuccess && 312 cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && n > 0 313 ? n 314 : 0; 315 }(); 316 return sms; 317} 318 319} // namespace 320 321void lat_q3k_gu(const uint8_t* const* blob, const int32_t* starts, int n_groups, const void* xq, float* gate, 322 float* up, int64_t ld, void* stream, const int32_t* counts, const int32_t* ent_tok) { 323 if (n_groups <= 0 || blob == nullptr || starts == nullptr || xq == nullptr || gate == nullptr || up == nullptr) return; 324#if defined(__HIPCC__) 325 std::fprintf(stderr, "lat q3k gu: the latent A stage's kernels are CUDA-only\n"); 326 std::exit(1); 327#else 328 static const bool once = [] { 329 dck(cudaFuncSetAttribute(lat_q3k_gu_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) lat_smem_bytes()), 330 "smem"); 331 return true; 332 }(); 333 (void) once; 334 const int sms = lat_sms(); 335 const unsigned gy = (unsigned) std::min(n_groups, 512); 336 const unsigned gz = (sms > 0 && (int) (gy * kItems) < sms) ? 8u : 1u; 337 lat_q3k_gu_kernel<<<dim3((unsigned) kItems, gy, gz), LTHREADS, lat_smem_bytes(), (cudaStream_t) stream>>>( 338 blob, starts, n_groups, (const uint8_t*) xq, gate, up, ld, counts, ent_tok); 339 dck(cudaGetLastError(), "launch"); 340#endif 341} 342 343void lat_q3k_gu_dump(const void* blob, int row, void* out, void* stream) { 344 if (blob == nullptr || out == nullptr) return; 345#if defined(__HIPCC__) 346 std::fprintf(stderr, "lat q3k gu: the latent A stage's kernels are CUDA-only\n"); 347 std::exit(1); 348#else 349 lat_q3k_gu_dump_kernel<<<1, 64, 0, (cudaStream_t) stream>>>((const uint8_t*) blob, row, (uint8_t*) out); 350 dck(cudaGetLastError(), "dump launch"); 351#endif 352} 353 354} // namespace strata::prefill