okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
09eb82791
main
1// src/prefill/moe_f16_kq.cu - see moe_f16_kq.hpp. gfx11 only (opt-in STRATA_PF_F16=1 with STRATA_PF_FUSED_KQ=1). 2// 3// gufo's routed-expert kernels for the K-quants, on Strata's tables, int8 activations and H (the work item, the 4// activation staging and the epilogues are moe_f16_common.cuh's): 5// - gate/up (Q4_K, Q5_K): the weight codes stay packed in LDS (one 32-byte nibble group per row and stage) and 6// each wave turns its own 16 rows into F16 right after the LDS read: w = q * (d sc) - dmin m as one packed FMA; 7// - down (Q5_1): a K block's 16 code bytes and its high-bit word in LDS, w = q d + m per wave. 8// The output differs from native_w11_kernel's (F16 weights instead of int8 sub-blocks), like STRATA_PF_FUSED_KQ's 9// does from the MMQ path. 10// 11// Adapted from gufo 97b8645f: src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp 12// (RoutedF16GEMMKernel and its helpers). 13// MIT License 14// Copyright (c) 2026 gufo contributors 15// Permission is hereby granted, free of charge, to any person obtaining a copy 16// of this software and associated documentation files (the "Software"), to deal 17// in the Software without restriction, including without limitation the rights 18// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 19// copies of the Software, and to permit persons to whom the Software is 20// furnished to do so, subject to the following conditions: 21// The above copyright notice and this permission notice shall be included in all 22// copies or substantial portions of the Software. 23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 28// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 29// SOFTWARE. 30#include "moe_f16_kq.hpp" 31 32#include "moe_f16_common.cuh" 33 34#include "ggml.h" 35 36#include <algorithm> 37 38namespace strata::prefill::fused::f16kq { 39namespace { 40 41using namespace f16; 42 43constexpr int T_Q4_K = GGML_TYPE_Q4_K, T_Q5_K = GGML_TYPE_Q5_K; 44constexpr int GU_NS = kMoeEmbd / 64, D_NS = kMoeFF / 64; // stages of 64 values (the compiled geometry's: 40 and 10 for Flash-Next) 45constexpr int FEAT = 64; // features (gate rows = up rows) per gate/up item 46 47// Byte i of the 16-byte K-quant block header (d, dmin, scales[12]). 48__device__ __forceinline__ uint32_t header_byte(const uint4& h, uint32_t i) { 49 const uint32_t word = i < 4 ? h.x : i < 8 ? h.y : i < 12 ? h.z : h.w; 50 return (word >> (8U * (i & 3U))) & 0xFFU; 51} 52// Bit s of each of the four bytes of w, packed into bits 0-3. 53__device__ __forceinline__ uint32_t gather_bit(uint32_t w, int s) { return (((w >> s) & 0x01010101U) * 0x01020408U) >> 24U; } 54// Bits 0-3 of `bits` to bit 4 of each byte. 55__device__ __forceinline__ uint32_t spread_high_bits(uint32_t bits) { return (__umul24(bits, 0x00204081U) & 0x01010101U) << 4U; } 56 57constexpr uint32_t HALF_MAGIC = 0x64646464U; // the high bytes of 1024.0 as F16 58// Four code bytes (< 32) to four halves: 1024 + q exactly, minus 1024, then q * scale + bias. 59__device__ __forceinline__ void codes_to_halves(uint32_t codes, __half2 magic, __half2 scale2, __half2 bias2, __half2& lo, 60 __half2& hi) { 61#if STRATA_F16_DEVICE 62 const uint32_t p0 = __builtin_amdgcn_perm(codes, HALF_MAGIC, 0x01050004U); 63 const uint32_t p1 = __builtin_amdgcn_perm(codes, HALF_MAGIC, 0x03070206U); 64 lo = __hfma2(__hadd2(__builtin_bit_cast(__half2, p0), magic), scale2, bias2); 65 hi = __hfma2(__hadd2(__builtin_bit_cast(__half2, p1), magic), scale2, bias2); 66#else 67 (void) codes; (void) magic; (void) scale2; (void) bias2; lo = hi = __half2{}; 68#endif 69} 70 71// Gate/up (Q4_K / Q5_K): code rows 0..63 are the item's gate rows, 64..127 its up rows; a thread pair per row. 72template <int WT, int BN> 73__global__ void __launch_bounds__(THREADS) gate_up_kernel(const Batch b, const NativeGeom geo, const int32_t* __restrict__ ts, 74 const int2* __restrict__ tiles, const int32_t* __restrict__ off, 75 const uint8_t* __restrict__ act, const int32_t* __restrict__ src, 76 uint8_t* __restrict__ out) { 77#if STRATA_F16_DEVICE 78 constexpr bool Q5K = WT == T_Q5_K; 79 constexpr int BLOCK_CHUNKS = Q5K ? 11 : 9; // 16-byte chunks per 256-value block 80 constexpr int CODE_CHUNK = Q5K ? 3 : 1; // the first chunk of qs 81 // LDS (bytes): codes ROWS x 2 chunks (swizzled); Q5_K's high bits and the (scale, bias) half2 per row and K 82 // block; the activations. The epilogue reuses the front. 83 constexpr int CODE_BYTES = ROWS * 2 * 16; 84 constexpr int HIGH_BYTES = Q5K ? 2 * ROWS * 4 : 0; 85 constexpr int SCALE_BYTES = 2 * ROWS * 4; 86 constexpr int STAGE_BYTES = CODE_BYTES + HIGH_BYTES + SCALE_BYTES + ActStage<BN>::BYTES; 87 static_assert(GU_EPI_BYTES <= STAGE_BYTES, "the epilogue fits the stage"); 88 __shared__ __attribute__((aligned(16))) uint8_t lds[STAGE_BYTES]; 89 __shared__ int srow[BN]; 90 auto* s_codes = reinterpret_cast<uint4*>(lds); 91 auto* s_high = reinterpret_cast<uint32_t*>(lds + CODE_BYTES); 92 auto* s_scale = reinterpret_cast<uint32_t*>(lds + CODE_BYTES + HIGH_BYTES); 93 auto* s_act = reinterpret_cast<uint4*>(lds + CODE_BYTES + HIGH_BYTES + SCALE_BYTES); 94 95 const int tid = threadIdx.x, wave = tid >> 5, sub_lane = tid & 15; 96 const int f_c = tid & 1; // this thread's chunk (and K block) of its weight row 97 const auto swizzle = [](int row, int c) { return row * 2 + (c ^ ((row >> 2) & 1)); }; 98 const __half2 magic = __floats2half2_rn(-1024.0f, -1024.0f); 99 100 int fb, e, row0, nrows; 101 if (!work_item<BN, GU_NFB>(b, ts, tiles, off, blockIdx.x, fb, e, row0, nrows)) return; 102 const int live_tiles = (nrows + 15) / 16; 103 const uint8_t* blob = b.blob[e - b.e0]; 104 if (tid < BN) srow[tid] = tid < nrows ? src[row0 + tid] : -1; 105 __syncthreads(); 106 107 const uint8_t* f_ptr = blob + ((tid >> 1) >= FEAT ? geo.up_off : 0) + (size_t) (fb * FEAT + ((tid >> 1) & (FEAT - 1))) * geo.gu_row; 108 uint4 f_header = make_uint4(0u, 0u, 0u, 0u), f_codes, f_qh[2] = {}; 109 uint4 code_cache[4]; // the block's four nibble groups, this thread's chunk of each 110 uint32_t f_high = 0; 111 int f_sb32 = 0; 112 ActStage<BN> as; 113 as.init(act, GU_ACT_LD, srow, tid); // the tokens' activation rows 114 115 const auto fetch_stage = [&](int s) { 116 const int kb0 = 2 * s; 117 const uint4* blk = reinterpret_cast<const uint4*>(f_ptr) + (kb0 / 8) * BLOCK_CHUNKS; 118 if (kb0 % 8 == 0) { // a new 256-value block every four stages 119 f_header = blk[0]; 120#pragma unroll 121 for (int group = 0; group < 4; ++group) code_cache[group] = blk[CODE_CHUNK + group * 2 + f_c]; 122 if constexpr (Q5K) { 123 f_qh[0] = blk[1]; 124 f_qh[1] = blk[2]; 125 } 126 } 127 const int sb32 = (kb0 % 8) + f_c; 128 { 129 const int group = sb32 / 2; // uniform across the wave 130 const uint32_t low = 0u - (group & 1u), high = 0u - ((group >> 1u) & 1u); 131 const auto select = [](uint32_t a, uint32_t bb, uint32_t mask) { 132 uint32_t value; 133 asm("v_cndmask_b32_e64 %0, %1, %2, %3" : "=v"(value) : "v"(a), "v"(bb), "s"(mask)); 134 return value; 135 }; 136 const uint4 &c0 = code_cache[0], &c1 = code_cache[1], &c2 = code_cache[2], &c3 = code_cache[3]; 137 f_codes = make_uint4(select(select(c0.x, c1.x, low), select(c2.x, c3.x, low), high), 138 select(select(c0.y, c1.y, low), select(c2.y, c3.y, low), high), 139 select(select(c0.z, c1.z, low), select(c2.z, c3.z, low), high), 140 select(select(c0.w, c1.w, low), select(c2.w, c3.w, low), high)); 141 } 142 f_sb32 = sb32; 143 if constexpr (Q5K) { 144 const uint32_t qh[8] = {f_qh[0].x, f_qh[0].y, f_qh[0].z, f_qh[0].w, f_qh[1].x, f_qh[1].y, f_qh[1].z, f_qh[1].w}; 145 uint32_t hb = 0; 146#pragma unroll 147 for (int i = 0; i < 8; ++i) hb |= gather_bit(qh[i], sb32) << (4 * i); 148 f_high = hb; 149 } 150 as.fetch(s); 151 }; 152 153 const auto commit_stage = [&]() { 154 const int row = tid >> 1; 155 s_codes[swizzle(row, f_c)] = f_codes; 156 if constexpr (Q5K) s_high[f_c * ROWS + row] = f_high; 157 const int sb32 = f_sb32; 158 uint32_t sc, mn; 159 if (sb32 < 4) { 160 sc = header_byte(f_header, 4 + sb32) & 0x3FU; 161 mn = header_byte(f_header, 8 + sb32) & 0x3FU; 162 } else { 163 sc = (header_byte(f_header, 8 + sb32) & 0x0FU) | ((header_byte(f_header, sb32) >> 6U) << 4U); 164 mn = (header_byte(f_header, 8 + sb32) >> 4U) | ((header_byte(f_header, 4 + sb32) >> 6U) << 4U); 165 } 166 const __half2 dm = __builtin_bit_cast(__half2, f_header.x); 167 const float scale = __low2float(dm) * (float) sc, offset = __high2float(dm) * (float) mn; 168 s_scale[f_c * ROWS + row] = __builtin_bit_cast(uint32_t, __floats2half2_rn(scale, -offset)); 169 as.commit(s_act); 170 }; 171 172 v8f acc[BN / 16]; 173#pragma unroll 174 for (int j = 0; j < BN / 16; ++j) acc[j] = v8f{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; 175 176 const auto compute_stage = [&]() { 177 const int row = wave * 16 + sub_lane; // waves 0-3: gate rows, 4-7: the matching up rows 178 const uint4 raw0 = s_codes[swizzle(row, 0)], raw1 = s_codes[swizzle(row, 1)]; 179#pragma unroll 180 for (int kb = 0; kb < 2; ++kb) { 181 const __half2 sb = __builtin_bit_cast(__half2, s_scale[kb * ROWS + row]); 182 const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb); 183 // elements 0-15 of K block 2s + kb are the low (kb = 0) or high (kb = 1) nibbles of chunk 0, 16-31 of chunk 1 184 const unsigned shift = 4U * (unsigned) kb; 185 const uint32_t words[8] = {raw0.x, raw0.y, raw0.z, raw0.w, raw1.x, raw1.y, raw1.z, raw1.w}; 186 const uint32_t hb = Q5K ? s_high[kb * ROWS + row] : 0U; 187 __half2 h[16]; 188#pragma unroll 189 for (int i = 0; i < 8; ++i) { 190 uint32_t nib = (words[i] >> shift) & 0x0F0F0F0FU; 191 if constexpr (Q5K) nib |= spread_high_bits((hb >> (4 * i)) & 0xFU); 192 codes_to_halves(nib, magic, scale2, bias2, h[2 * i], h[2 * i + 1]); 193 } 194 v16h a_lo, a_hi; 195 __builtin_memcpy(&a_lo, &h[0], 32); 196 __builtin_memcpy(&a_hi, &h[8], 32); 197 mma_tiles<BN>(acc, a_lo, a_hi, s_act, kb, sub_lane, live_tiles); 198 } 199 }; 200 201 fetch_stage(0); 202 for (int s = 0; s < GU_NS; ++s) { 203 commit_stage(); 204 __syncthreads(); 205 if (s + 1 < GU_NS) fetch_stage(s + 1); 206 compute_stage(); 207 __syncthreads(); 208 } 209 gu_epilogue<BN>(acc, lds, tid, live_tiles, nrows, row0, fb, out); 210#else 211 (void) b; (void) geo; (void) ts; (void) tiles; (void) off; (void) act; (void) src; (void) out; 212 __builtin_trap(); 213#endif 214} 215 216// Q5_1 down: 128 of the kMoeEmbd output rows against a tile's (or pair's) H rows, K = kMoeFF in kMoeFF / 64 stages; the routed rows' 217// FP32 outputs in `dm` (native_w11_kernel<T_Q5_1, false>'s). 218template <int BN, bool D16 = false> 219__global__ void __launch_bounds__(THREADS) down_kernel(const Batch b, const NativeGeom geo, const int32_t* __restrict__ ts, 220 const int2* __restrict__ tiles, const int32_t* __restrict__ off, 221 const uint8_t* __restrict__ h, float* __restrict__ dm) { 222#if STRATA_F16_DEVICE 223 constexpr int CODE_BYTES = ROWS * 2 * 16, HIGH_BYTES = 2 * ROWS * 4, SCALE_BYTES = 2 * ROWS * 4; 224 constexpr int STAGE_BYTES = CODE_BYTES + HIGH_BYTES + SCALE_BYTES + ActStage<BN>::BYTES; 225 static_assert(D_EPI_BYTES <= STAGE_BYTES, "the epilogue fits the stage"); 226 __shared__ __attribute__((aligned(16))) uint8_t lds[STAGE_BYTES]; 227 __shared__ int srow[BN]; 228 auto* s_codes = reinterpret_cast<uint4*>(lds); 229 auto* s_high = reinterpret_cast<uint32_t*>(lds + CODE_BYTES); 230 auto* s_scale = reinterpret_cast<uint32_t*>(lds + CODE_BYTES + HIGH_BYTES); 231 auto* s_act = reinterpret_cast<uint4*>(lds + CODE_BYTES + HIGH_BYTES + SCALE_BYTES); 232 233 const int tid = threadIdx.x, wave = tid >> 5, sub_lane = tid & 15; 234 const int f_c = tid & 1; // this thread's K block of its weight row 235 const auto swizzle = [](int row, int c) { return row * 2 + (c ^ ((row >> 2) & 1)); }; 236 const __half2 magic = __floats2half2_rn(-1024.0f, -1024.0f); 237 238 int fb, e, row0, nrows; 239 if (!work_item<BN, D_NFB>(b, ts, tiles, off, blockIdx.x, fb, e, row0, nrows)) return; 240 const int live_tiles = (nrows + 15) / 16; 241 if (tid < BN) srow[tid] = tid < nrows ? row0 + tid : -1; // H is indexed by the routed row 242 __syncthreads(); 243 244 const uint2* f_ptr = reinterpret_cast<const uint2*>(b.blob[e - b.e0] + geo.down_off + (size_t) (fb * ROWS + (tid >> 1)) * geo.d_row); 245 uint4 f_codes; 246 uint32_t f_high = 0, f_dm = 0; 247 ActStage<BN> as; 248 as.init(h, H_LD, srow, tid); 249 const auto fetch_stage = [&](int s) { 250 const uint2* words = f_ptr + (2 * s + f_c) * 3; // block_q5_1: {d, m}, qh, qs[16] 251 const uint2 w0 = words[0], w1 = words[1], w2 = words[2]; 252 f_codes = make_uint4(w1.x, w1.y, w2.x, w2.y); 253 f_high = w0.y; 254 f_dm = w0.x; 255 as.fetch(s); 256 }; 257 const auto commit_stage = [&]() { 258 const int row = tid >> 1; 259 s_codes[swizzle(row, f_c)] = f_codes; 260 s_high[f_c * ROWS + row] = f_high; 261 s_scale[f_c * ROWS + row] = f_dm; // the half2 (d, m): w = q d + m 262 as.commit(s_act); 263 }; 264 v8f acc[BN / 16]; 265#pragma unroll 266 for (int j = 0; j < BN / 16; ++j) acc[j] = v8f{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; 267 const auto compute_stage = [&]() { 268 const int row = wave * 16 + sub_lane; 269 const uint4 raw[2] = {s_codes[swizzle(row, 0)], s_codes[swizzle(row, 1)]}; 270#pragma unroll 271 for (int kb = 0; kb < 2; ++kb) { 272 const __half2 sb = __builtin_bit_cast(__half2, s_scale[kb * ROWS + row]); 273 const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb); 274 // elements 0-15 are the low nibbles of the 16 code bytes, 16-31 the high, plus bit j of the high-bit word 275 const uint32_t words[4] = {raw[kb].x, raw[kb].y, raw[kb].z, raw[kb].w}; 276 const uint32_t hb = s_high[kb * ROWS + row]; 277 __half2 hh[16]; 278#pragma unroll 279 for (int i = 0; i < 4; ++i) { 280 const uint32_t lo = (words[i] & 0x0F0F0F0FU) | spread_high_bits((hb >> (4 * i)) & 0xFU); 281 const uint32_t hi = ((words[i] >> 4U) & 0x0F0F0F0FU) | spread_high_bits((hb >> (16 + 4 * i)) & 0xFU); 282 codes_to_halves(lo, magic, scale2, bias2, hh[2 * i], hh[2 * i + 1]); 283 codes_to_halves(hi, magic, scale2, bias2, hh[8 + 2 * i], hh[8 + 2 * i + 1]); 284 } 285 v16h a_lo, a_hi; 286 __builtin_memcpy(&a_lo, &hh[0], 32); 287 __builtin_memcpy(&a_hi, &hh[8], 32); 288 mma_tiles<BN>(acc, a_lo, a_hi, s_act, kb, sub_lane, live_tiles); 289 } 290 }; 291 fetch_stage(0); 292 for (int s = 0; s < D_NS; ++s) { 293 commit_stage(); 294 __syncthreads(); 295 if (s + 1 < D_NS) fetch_stage(s + 1); 296 compute_stage(); 297 __syncthreads(); 298 } 299 down_epilogue<BN, D16>(acc, lds, tid, live_tiles, nrows, row0, fb, dm); 300#else 301 (void) b; (void) geo; (void) ts; (void) tiles; (void) off; (void) h; (void) dm; 302 __builtin_trap(); 303#endif 304} 305 306} // namespace 307 308bool covers(int gu_type) { return gu_type == T_Q4_K || gu_type == T_Q5_K; } 309 310bool covers_down(int d_type) { return d_type == GGML_TYPE_Q5_1; } 311 312void gate_up(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t n, 313 int n_expert, int64_t work_bound, const uint8_t* act, const int32_t* src, uint8_t* out, cudaStream_t s) { 314 // one block per work item, the grid the batch's bound (gufo's launch: the hardware balances the blocks; the items 315 // of a tile are consecutive, so they meet its activations in L2) 316 const unsigned grid = (unsigned) std::max<int64_t>(1, work_bound * GU_NFB); 317 const bool q5k = g.gu_type == T_Q5_K; 318 if (pick_bn(n, n_expert) == 2 * kTileRows) { 319 if (q5k) gate_up_kernel<T_Q5_K, 2 * kTileRows><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, act, src, out); 320 else gate_up_kernel<T_Q4_K, 2 * kTileRows><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, act, src, out); 321 } else { 322 if (q5k) gate_up_kernel<T_Q5_K, kTileRows><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, act, src, out); 323 else gate_up_kernel<T_Q4_K, kTileRows><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, act, src, out); 324 } 325} 326 327void down(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t n, int n_expert, 328 int64_t work_bound, const uint8_t* h, float* dm, cudaStream_t s, bool d16) { 329 const unsigned grid = (unsigned) std::max<int64_t>(1, work_bound * D_NFB); 330 if (pick_bn(n, n_expert) == 2 * kTileRows) { 331 if (d16) down_kernel<2 * kTileRows, true><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, h, dm); 332 else down_kernel<2 * kTileRows><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, h, dm); 333 } else { 334 if (d16) down_kernel<kTileRows, true><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, h, dm); 335 else down_kernel<kTileRows><<<grid, THREADS, 0, s>>>(b, g, ts, tiles, off, h, dm); 336 } 337} 338 339} // namespace strata::prefill::fused::f16kq