okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1// src/prefill/lat_q3k_down.cu - see include/strata/prefill/lat_q3k_down.hpp. 2// 3// M1 of the q3k latent A stage (q3k_fused/BRIEF.md): the down half, IQ4_NL weights, K = 640, 1280 output rows. 4// It is moe_fused.cu's NVFP4 latent down kernel (latent_kernel<false>, "the latent (edge0)" section) with only the 5// block decode replaced - the same work item (256 output rows of one expert), the same 512-thread block, the same 6// double-buffered staged rows, the same mma.sync m16n8k16 s8 products and the same epilogue: 7// staged weight row (LWPITCH 76): 4 x 16 int8 codes at 16 * s, four fp16 sub-scales at 68 + 2 * s 8// staged activation row (LAPITCH 80): the same 64 codes at 16 * s, then {d0, d1} (its two 32-value blocks' fp16 9// scales) at 64; the H rows the gate/up epilogue writes are already in that order (q8_1_store's), so the down 10// reads them as they are. 11// The mma multiplies word k, byte c of a weight sub-block with word k, byte c of the activation sub-block, so both 12// sides must hold the sub-block's value 4c + k there. 13// 14// The decode. An IQ4_NL block is 18 bytes for 32 values - half d, then uint8 qs[16]: value j (0..15) is qs[j]'s low 15// nibble through kvalues_iq4nl, value j + 16 its high nibble (ggml's dequantize_row_iq4_nl). A 64-value chunk of a 16// row is exactly two such blocks = 36 bytes, the size of an NVFP4 chunk, so the chunk stride (36), raw_load's shape 17// and every stage buffer stay as they are. The block's one d serves both of its 16-value halves (the NVFP4 rows 18// carry a sub-scale per 16 values), so the four sub-scale slots get the two blocks' d's twice each. 19// 20// The expert's blob is read where it is: blob[g] + 704000 + row * 360 for the group's rows, no copy, no gather. 21#include "strata/prefill/lat_q3k_down.hpp" 22 23#include <cuda_fp16.h> 24#include <cuda_runtime.h> 25 26#include "ggml.h" 27 28#define GGML_COMMON_DECL_CUDA 29#define GGML_COMMON_IMPL_CUDA 30#include "ggml-common.h" 31 32#include <algorithm> 33#include <cstdio> 34#include <cstdlib> 35 36namespace strata::prefill { 37namespace { 38 39void dck(cudaError_t e, const char* what) { 40 if (e != cudaSuccess) { 41 std::fprintf(stderr, "lat q3k down: %s: %s\n", what, cudaGetErrorString(e)); 42 std::exit(1); 43 } 44} 45 46// The q3k latent pack's geometry (q3k_fused/BRIEF.md): native_expert_layout(11, 20, 1280, 640). 47constexpr int64_t kNE = 1280; // the down's output rows (ELL) 48constexpr int64_t kFF = 640; // the down's K (n_ff) 49constexpr size_t kDownOff = 704000; // the blob's down section 50constexpr size_t kDRow = 360; // 20 IQ4_NL blocks x 18 B 51constexpr int kChunks = (int) (kFF >> 6); // 10 chunks of 64 values along K 52constexpr int LHQ = kChunks * 80; // a staged H row: 800 B 53 54constexpr int LTHREADS = 512; // as moe_fused.cu's latent kernel 55constexpr int WROWS = 256; // the down rows of one work item 56constexpr int LWPITCH = 76; // a staged weight row 57constexpr int LAPITCH = 80; // a staged activation row 58constexpr int kTileRows = 64; // routed rows (a group's entries) per tile 59constexpr int kItems = (int) (kNE / WROWS); // 5 work items along the output rows 60 61inline size_t lat_smem_bytes() { 62 return (size_t) 2 * WROWS * LWPITCH + (size_t) 2 * kTileRows * LAPITCH + (size_t) kTileRows * 4; 63} 64 65#if !defined(__HIPCC__) 66 67// One 16-value sub-block's 4 code words of 4 qs words (q[m] = values 4m .. 4m + 3, the natural order) permuted into 68// the staged order: out[k]'s byte c is the sub-block's value 4c + k. 69__device__ __forceinline__ void lat_stage_codes(const uint32_t* A, uint32_t (&out)[4]) { 70#pragma unroll 71 for (int k = 0; k < 4; ++k) 72 out[k] = __byte_perm(__byte_perm(A[0], A[1], k | ((k + 4) << 4)), 73 __byte_perm(A[2], A[3], k | ((k + 4) << 4)), 0x5410u); 74} 75 76__global__ void __launch_bounds__(LTHREADS, 1) 77lat_q3k_down_kernel(const uint8_t* const* __restrict__ blob, const int32_t* __restrict__ starts, int n_groups, 78 const uint8_t* __restrict__ act, float* __restrict__ out, int64_t ld, 79 const int32_t* __restrict__ counts, const int32_t* __restrict__ ent_dst) { 80#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 81 extern __shared__ __align__(16) uint8_t smem[]; 82 uint8_t* wst[2] = {smem, smem + WROWS * LWPITCH}; 83 uint8_t* ast[2] = {smem + 2 * WROWS * LWPITCH, smem + 2 * WROWS * LWPITCH + kTileRows * LAPITCH}; 84 int* srow = (int*) (smem + 2 * WROWS * LWPITCH + 2 * kTileRows * LAPITCH); // [64] the act row of each tile row 85 86 const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, mg = lane >> 2, tig = lane & 3; 87 const int wf = warp & 3, nb0 = 16 * (warp >> 2); 88 const int wrow = tid >> 1, whalf = tid & 1; // the weight rows: 2 threads a row, 1 block each 89 const int arow = tid >> 1, ahalf = tid & 1; // the act rows: 128 threads, 2 a row 90 uint32_t wq[4]; // this thread's 16 qs bytes of a chunk 91 uint32_t wd = 0; // the block's d (fp16 bits) 92 uint32_t aq[8], adw = 0; // the chunk's act words / its {d0, d1} 93 const int fb = blockIdx.x; // this launch's 256 output rows of the item 94 for (int g = blockIdx.y; g < n_groups; g += gridDim.y) { 95 const uint8_t* bl = blob[g]; 96 if (bl == nullptr) continue; // an expert of another launch of this layer 97 const int e0 = starts[g]; 98 // the group's row count: counts[] when the caller has it (the engine's flushes are not in group order), 99 // otherwise the next group's start 100 const int e1 = counts != nullptr ? e0 + counts[g] : starts[g + 1]; 101 // A group's 64-row tiles are split over blockIdx.z (the launcher widens z only when the groups alone do not 102 // fill the device): a block row takes the tiles z, z + gridDim.z, ... 103 for (int row0 = e0 + (int) blockIdx.z * kTileRows; row0 < e1; row0 += (int) gridDim.z * kTileRows) { 104 const int nrows = min(kTileRows, e1 - row0); 105 // the tile rows the products read: nb0 = 16 * (warp >> 2) and on0 / on1, so 16-row groups of them - 106 // staging the rows past that is work no lane consumes (a 4-entry group read 64 of them before) 107 const int arows = min(kTileRows, (nrows + 15) & ~15); 108 // this thread's weight row of the item: row WROWS * fb + wrow of the group's 1280 down rows 109 const uint8_t* wsrc = bl + kDownOff + (size_t) (WROWS * fb + wrow) * kDRow; 110 __syncthreads(); // the previous item is done with the buffers 111 if (tid < kTileRows) srow[tid] = row0 + min(tid, nrows - 1); // rows past the tile repeat its last one 112 __syncthreads(); // srow 113 114 auto raw_load = [&](int kb) { 115 // The chunk is 36 B = 9 words and its start is 4-byte aligned (704000, 360 and 36 are); an IQ4_NL 116 // block's qs starts 2 B into it, so a block's 16 qs bytes are NOT word aligned - each thread reads 117 // the 5 aligned words its block's qs spans and shifts the two halves' d out of the first. 118 const uint32_t* w9 = (const uint32_t*) (wsrc + 36 * kb + 4 * (4 * whalf)); 119 const uint32_t b0 = w9[0], b1 = w9[1], b2 = w9[2], b3 = w9[3], b4 = w9[4]; 120 if (whalf) { // block 1: d at bytes 18,19, qs at 20..35 121 wq[0] = b1; wq[1] = b2; wq[2] = b3; wq[3] = b4; 122 wd = b0 >> 16; 123 } else { // block 0: d at bytes 0,1, qs at 2..17 124 wq[0] = (b0 >> 16) | (b1 << 16); 125 wq[1] = (b1 >> 16) | (b2 << 16); 126 wq[2] = (b2 >> 16) | (b3 << 16); 127 wq[3] = (b3 >> 16) | (b4 << 16); 128 wd = b0 & 0xFFFFu; 129 } 130 if (tid < 2 * arows) { 131 const uint32_t* ap = (const uint32_t*) (act + (size_t) srow[arow] * LHQ + (size_t) LAPITCH * kb); 132#pragma unroll 133 for (int i = 0; i < 8; ++i) aq[i] = ap[8 * ahalf + i]; 134 adw = ap[16]; // the chunk's {d0, d1} 135 } 136 }; 137 auto stage_store = [&](int kb) { 138 uint8_t* wr = wst[kb & 1] + (size_t) wrow * LWPITCH; 139 // 32 codes in natural order: q[m] holds values 4m .. 4m + 3, the low nibbles of qs[4m .. 4m + 3] 140 // (values 0..15) then the high ones (16..31); value j is qs[j]'s low nibble, j + 16 its high one 141 uint32_t q[8]; 142#pragma unroll 143 for (int k = 0; k < 4; ++k) { 144 uint32_t lo = 0, hi = 0; 145#pragma unroll 146 for (int c = 0; c < 4; ++c) { 147 const uint32_t byte = (wq[k] >> (8 * c)) & 0xFF; 148 lo |= (uint32_t) (uint8_t) kvalues_iq4nl[byte & 0xF] << (8 * c); 149 hi |= (uint32_t) (uint8_t) kvalues_iq4nl[byte >> 4] << (8 * c); 150 } 151 q[k] = lo; 152 q[4 + k] = hi; 153 } 154 const unsigned short dh = (unsigned short) wd; // the block's d, this chunk's 2 sub-blocks 155#pragma unroll 156 for (int h = 0; h < 2; ++h) { 157 const int s = 2 * whalf + h; 158 uint32_t o[4]; 159 lat_stage_codes(q + 4 * h, o); 160#pragma unroll 161 for (int k = 0; k < 4; ++k) *(uint32_t*) (wr + 16 * s + 4 * k) = o[k]; 162 *(__half*) (wr + 68 + 2 * s) = __ushort_as_half(dh); 163 } 164 if (tid < 2 * arows) { 165 uint8_t* ar = ast[kb & 1] + (size_t) arow * LAPITCH; 166#pragma unroll 167 for (int h = 0; h < 2; ++h) { 168 const int s = 2 * ahalf + h; 169 const uint32_t* wp = &aq[4 * h]; 170#pragma unroll 171 for (int k = 0; k < 4; ++k) *(uint32_t*) (ar + 16 * s + 4 * k) = wp[k]; 172 } 173 *(uint32_t*) (ar + 64) = adw; 174 } 175 }; 176 177 raw_load(0); 178 stage_store(0); 179 if (kChunks > 1) raw_load(1); 180 const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows; 181 float acc[4][2][4]; 182#pragma unroll 183 for (int i = 0; i < 4; ++i) 184#pragma unroll 185 for (int n = 0; n < 2; ++n) 186#pragma unroll 187 for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f; 188 for (int kb = 0; kb < kChunks; ++kb) { 189 __syncthreads(); 190 if (on0) { 191 const uint8_t* wc = wst[kb & 1]; 192 const uint8_t* ac = ast[kb & 1]; 193 for (int s = 0; s < 4; ++s) { 194 uint32_t bq[2]; 195 float dx0[2], dx1[2]; // the OUTPUT rows' (2 tig, 2 tig + 1) own ds 196 for (int n = 0; n < 2; ++n) { 197 if (n == 1 && !on1) break; 198 const uint8_t* ar = ac + (size_t) (nb0 + 8 * n + mg) * LAPITCH; 199 bq[n] = *(const uint32_t*) (ar + 16 * s + 4 * tig); 200 const half2 ds0 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig) * LAPITCH + 64); 201 const half2 ds1 = *(const half2*) (ac + (size_t) (nb0 + 8 * n + 2 * tig + 1) * LAPITCH + 64); 202 dx0[n] = __half2float((s & 2) ? ds0.y : ds0.x); 203 dx1[n] = __half2float((s & 2) ? ds1.y : ds1.x); 204 } 205 for (int i = 0; i < 4; ++i) { 206 const int ra = 64 * wf + 16 * i + mg; 207 const int rb = ra + 8; 208 const uint32_t a0 = *(const uint32_t*) (wc + (size_t) ra * LWPITCH + 16 * s + 4 * tig); 209 const uint32_t a1 = *(const uint32_t*) (wc + (size_t) rb * LWPITCH + 16 * s + 4 * tig); 210 const float da = __half2float(*(const __half*) (wc + (size_t) ra * LWPITCH + 68 + 2 * s)); 211 const float db = __half2float(*(const __half*) (wc + (size_t) rb * LWPITCH + 68 + 2 * s)); 212 for (int n = 0; n < 2; ++n) { 213 if (n == 1 && !on1) break; 214 int d[4] = {0, 0, 0, 0}; 215 asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, " 216 "{%0,%1,%2,%3};\n" 217 : "+r"(d[0]), "+r"(d[1]), "+r"(d[2]), "+r"(d[3]) 218 : "r"(a0), "r"(a1), "r"(bq[n])); 219 acc[i][n][0] += (da * dx0[n]) * (float) d[0]; 220 acc[i][n][1] += (da * dx1[n]) * (float) d[1]; 221 acc[i][n][2] += (db * dx0[n]) * (float) d[2]; 222 acc[i][n][3] += (db * dx1[n]) * (float) d[3]; 223 } 224 } 225 } 226 } 227 __syncthreads(); 228 if (kb + 1 < kChunks) { 229 stage_store(kb + 1); 230 if (kb + 2 < kChunks) raw_load(kb + 2); 231 } 232 } 233 if (!on0) continue; 234 // the expert's s_down (NVFP4's tail) is 1 for a q3k blob (tail_off 0): the products go out as they are 235#pragma unroll 236 for (int i = 0; i < 4; ++i) 237#pragma unroll 238 for (int n = 0; n < 2; ++n) { 239 if (n == 1 && !on1) break; 240#pragma unroll 241 for (int q = 0; q < 4; ++q) { 242 const int r = nb0 + 8 * n + 2 * tig + (q & 1); 243 if (r < nrows) 244 out[(size_t) (ent_dst != nullptr ? ent_dst[row0 + r] : (row0 + r)) * ld + WROWS * fb + 245 (q < 2 ? 64 * wf + 16 * i + mg : 64 * wf + 16 * i + mg + 8)] = acc[i][n][q]; 246 } 247 } 248 } 249 } 250#endif 251} 252 253#endif // !__HIPCC__ 254 255} // namespace 256 257void lat_q3k_down(const uint8_t* const* blob, const int32_t* starts, int n_groups, const void* hq, float* out, 258 int64_t ld, void* stream, const int32_t* counts, const int32_t* ent_dst) { 259 if (n_groups <= 0 || blob == nullptr || starts == nullptr || hq == nullptr || out == nullptr) return; 260#if defined(__HIPCC__) 261 std::fprintf(stderr, "lat q3k down: the latent A stage's kernels are CUDA-only\n"); 262 std::exit(1); 263#else 264 static const bool once = [] { 265 dck(cudaFuncSetAttribute(lat_q3k_down_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, 266 (int) lat_smem_bytes()), "smem"); 267 return true; 268 }(); 269 (void) once; 270 static const int sms = [] { 271 int dev = 0, n = 0; 272 return cudaGetDevice(&dev) == cudaSuccess && cudaDeviceGetAttribute(&n, cudaDevAttrMultiProcessorCount, dev) == 273 cudaSuccess && n > 0 274 ? n 275 : 0; // 0: never widen z (the launch then cannot lose anything) 276 }(); 277 const unsigned gy = (unsigned) std::min(n_groups, 512); 278 // A launch of a few experts (a verify window's, or one big group) has too few (group, 256-row) items to fill 279 // the device: the group's tiles go over blockIdx.z as well. With many groups the extra z blocks would only exit. 280 const unsigned gz = (sms > 0 && (int) (gy * kItems) < sms) ? 8u : 1u; 281 lat_q3k_down_kernel<<<dim3((unsigned) kItems, gy, gz), LTHREADS, lat_smem_bytes(), (cudaStream_t) stream>>>( 282 blob, starts, n_groups, (const uint8_t*) hq, out, ld, counts, ent_dst); 283 dck(cudaGetLastError(), "launch"); 284#endif 285} 286 287} // namespace strata::prefill