okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
09eb82791
main
1// src/prefill/moe_f16_common.cuh - the parts the gfx11 F16 prompt-expert kernels share (STRATA_PF_F16=1): the 2// switch, the work item's width, the int8 activations staged as F16, the WMMA over the token tiles and the two 3// epilogues. moe_f16_kq.cu (the K-quant kernels) and moe_fused_iq.cu (the other native formats) include it. 4// 5// A work item is 128 weight rows (gate/up: the 64 gate and 64 up rows of 64 features; down: 128 output rows) against 6// one 64-row tile of fused::group or two consecutive tiles of one expert; each of the eight waves owns 16 of the 7// weight rows. The F16 WMMA accumulates all of K in F32. The fragment loop and the epilogues' layouts follow gufo's 8// RoutedF16GEMMKernel. 9// 10// Adapted from gufo 97b8645f: src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp (RoutedF16GEMMKernel). 11// MIT License 12// Copyright (c) 2026 gufo contributors 13// Permission is hereby granted, free of charge, to any person obtaining a copy 14// of this software and associated documentation files (the "Software"), to deal 15// in the Software without restriction, including without limitation the rights 16// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 17// copies of the Software, and to permit persons to whom the Software is 18// furnished to do so, subject to the following conditions: 19// The above copyright notice and this permission notice shall be included in all 20// copies or substantial portions of the Software. 21// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 27// SOFTWARE. 28#pragma once 29 30#include <cstdint> 31#include <cstdlib> 32 33#include <cuda_fp16.h> 34#include <cuda_runtime.h> 35 36#include "strata/prefill/moe_fused.hpp" 37 38#if defined(__HIPCC__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || \ 39 defined(__gfx1150__) || defined(__gfx1151__)) 40#define STRATA_F16_DEVICE 1 41#else 42#define STRATA_F16_DEVICE 0 43#endif 44 45namespace strata::prefill::fused::f16 { 46 47constexpr int AB = 80; // activation / H bytes per 64 values: 64 codes, {d0, d1}, {sum0, sum1} 48constexpr int THREADS = 256; 49constexpr int ROWS = 128; // weight rows per work item 50// The widths are the compiled geometry's (kMoeEmbd 2560 and kMoeFF 640 for Flash-Next: 10 gate/up items and 20 down items a tile). 51static_assert(kMoeFF % 64 == 0 && kMoeEmbd % ROWS == 0, "the F16 expert kernels: the expert width must be a multiple of 64 (a gate/up item is 64 features) and the hidden width of 128 (a down item is 128 output rows)"); 52constexpr int GU_NFB = kMoeFF / 64, D_NFB = kMoeEmbd / ROWS; // work items per tile: 64 features, 128 output rows 53constexpr int GU_ACT_LD = kMoeEmbd / 64 * AB, H_LD = kMoeFF / 64 * AB; // bytes per activation / H row 54 55/// STRATA_PF_F16=1 (on top of STRATA_PF_FUSED=1): the covered formats take the F16 kernels on gfx11. 56inline bool requested() { 57 static const bool on = [] { 58 const char* v = std::getenv("STRATA_PF_F16"); 59 return v != nullptr && v[0] == '1'; 60 }(); 61 return on; 62} 63 64/// Two tiles a work item when an expert has a tile's rows or more on average. gfx1151, Q4_K, top 10 over 512 65/// experts, one 128-expert launch, ms (64 / 128): 1024 tokens 1.22 / 1.28, 2048 1.51 / 1.64, 4096 2.73 / 2.48, 8192 66/// 4.76 / 4.59, 16384 9.19 / 8.46; Q5_1 down 2048 1.02 / 1.04, 4096 1.61 / 1.48, 16384 5.29 / 4.83. 67/// STRATA_PF_F16_BN=64|128 forces one. 68inline int pick_bn(int64_t n, int n_expert) { 69 static const int forced = [] { 70 const char* v = std::getenv("STRATA_PF_F16_BN"); 71 const int t = v ? std::atoi(v) : 0; 72 return t == kTileRows || t == 2 * kTileRows ? t : 0; 73 }(); 74 if (forced) return forced; 75 return (double) n / (n_expert > 0 ? n_expert : 1) >= kTileRows ? 2 * kTileRows : kTileRows; 76} 77 78using v16h = __attribute__((__vector_size__(16 * sizeof(_Float16)))) _Float16; 79using v8f = __attribute__((__vector_size__(8 * sizeof(float)))) float; 80 81__device__ __forceinline__ v8f wmma_f16(v16h a, v16h b, v8f c) { 82#if STRATA_F16_DEVICE 83 return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); 84#else 85 __builtin_trap(); 86 return c; 87#endif 88} 89 90/// The work item of block `w`: its tile (fused::group's tables), whether it is the second tile of a pair (the first 91/// takes it), and its rows. Returns false when the block has no work. 92template <int BN, int NFB> 93__device__ __forceinline__ bool work_item(const Batch& b, const int32_t* ts, const int2* tiles, const int32_t* off, int w, 94 int& fb, int& e, int& row0, int& nrows) { 95 static_assert(BN == kTileRows || BN == 2 * kTileRows, "one tile or a pair"); 96 const int t0 = ts[b.e0]; 97 if (w >= (ts[b.e1] - t0) * NFB) return false; 98 const int2 tl = tiles[t0 + w / NFB]; 99 fb = w % NFB; 100 e = tl.x; 101 row0 = tl.y; 102 if (BN > kTileRows && ((t0 + w / NFB - ts[e]) & 1)) return false; 103 nrows = min(BN, off[e + 1] - row0); 104 return true; 105} 106 107/// The int8 activation (or H) rows of a work item, staged as F16 per stage: BN rows x 8 chunks of 8 values, chunk 108/// sub = kb * 4 + quarter, into LDS [sub][row] (stride BN + 1) - the B fragments' layout of the F16 WMMA. A row past 109/// the item's end is zero. 110template <int BN> struct ActStage { 111 static constexpr int FETCH = BN * 8 / THREADS, STRIDE = BN + 1, BYTES = 2 * 4 * STRIDE * 16; 112 const uint8_t* src[FETCH]; 113 int slot[FETCH], sub[FETCH]; 114 uint2 codes[FETCH]; 115 float d[FETCH]; 116 // rows[t]: the row of item row t in `base` (rows of `ld` bytes), or -1 117 __device__ __forceinline__ void init(const uint8_t* base, size_t ld, const int* rows, int tid) { 118#pragma unroll 119 for (int i = 0; i < FETCH; ++i) { 120 const int chunk = tid + i * THREADS, t = chunk >> 3, c = chunk & 7; 121 src[i] = rows[t] >= 0 ? base + (size_t) rows[t] * ld : nullptr; 122 slot[i] = c * STRIDE + t; 123 sub[i] = c; 124 } 125 } 126 __device__ __forceinline__ void fetch(int s) { 127#pragma unroll 128 for (int i = 0; i < FETCH; ++i) { 129 if (src[i] != nullptr) { 130 const uint8_t* p = src[i] + (size_t) s * AB; 131 codes[i] = *reinterpret_cast<const uint2*>(p + 8 * sub[i]); 132 d[i] = *reinterpret_cast<const float*>(p + 64 + 4 * (sub[i] >> 2)); 133 } else { 134 codes[i] = make_uint2(0u, 0u); 135 d[i] = 0.0f; 136 } 137 } 138 } 139 __device__ __forceinline__ void commit(uint4* s_act) const { 140#pragma unroll 141 for (int i = 0; i < FETCH; ++i) { 142 const uint32_t ws[2] = {codes[i].x, codes[i].y}; 143 __half2 h[4]; 144#pragma unroll 145 for (int j = 0; j < 4; ++j) { 146 const uint32_t wd = ws[j >> 1] >> (16 * (j & 1)); 147 const float lo = (float) (int8_t) (wd & 0xFFu), hi = (float) (int8_t) ((wd >> 8) & 0xFFu); 148 h[j] = __floats2half2_rn(lo * d[i], hi * d[i]); 149 } 150 s_act[slot[i]] = make_uint4(__builtin_bit_cast(uint32_t, h[0]), __builtin_bit_cast(uint32_t, h[1]), 151 __builtin_bit_cast(uint32_t, h[2]), __builtin_bit_cast(uint32_t, h[3])); 152 } 153 } 154}; 155 156/// Two F16 WMMAs (K 32) of a wave's 16 weight rows against each live 16-row tile of the staged activations. 157template <int BN> 158__device__ __forceinline__ void mma_tiles(v8f (&acc)[BN / 16], v16h a_lo, v16h a_hi, const uint4* s_act, int kb, int sub_lane, 159 int live_tiles) { 160 constexpr int STRIDE = ActStage<BN>::STRIDE; 161#pragma unroll 162 for (int j = 0; j < BN / 16; ++j) { 163 asm volatile("" ::: "memory"); // one token tile's fragments live at a time (gufo: hoisting spills) 164 if (j >= live_tiles) continue; 165 const uint4* frag = s_act + (kb * 4) * STRIDE + j * 16 + sub_lane; 166 uint4 bq[4]; 167#pragma unroll 168 for (int q = 0; q < 4; ++q) bq[q] = frag[q * STRIDE]; 169 v16h b_lo, b_hi; 170 __builtin_memcpy(&b_lo, &bq[0], 32); 171 __builtin_memcpy(&b_hi, &bq[2], 32); 172 acc[j] = wmma_f16(a_lo, b_lo, acc[j]); 173 acc[j] = wmma_f16(a_hi, b_hi, acc[j]); 174 } 175} 176 177constexpr int GU_EPI_STRIDE = 18, GU_EPI_PLANE = 16 * GU_EPI_STRIDE; 178constexpr int GU_EPI_BYTES = 8 * GU_EPI_PLANE * 4, D_EPI_BYTES = 8 * 256 * 4; 179 180/// Gate/up epilogue (every wave; `lds` at least GU_EPI_BYTES, free): per token tile, each wave's 16 x 16 181/// accumulators as plane [token][row] (waves 0-3 the gate rows, 4-7 the up rows), then a thread per (token, half of 182/// the 64 features): SwiGLU, H as int8 per 32 features with its scale and the codes' sum (native_w11_kernel's H). 183template <int BN> 184__device__ __forceinline__ void gu_epilogue(const v8f (&acc)[BN / 16], uint8_t* lds, int tid, int live_tiles, int nrows, int row0, 185 int fb, uint8_t* __restrict__ out) { 186 const int wave = tid >> 5, lane = tid & 31, sub_lane = lane & 15, half_id = lane >> 4; 187 float* base = reinterpret_cast<float*>(lds); 188 float* scratch = base + wave * GU_EPI_PLANE; 189#pragma unroll 190 for (int j = 0; j < BN / 16; ++j) { 191 if (j >= live_tiles) break; // uniform 192#pragma unroll 193 for (int l = 0; l < 8; ++l) scratch[sub_lane * GU_EPI_STRIDE + 2 * l + half_id] = acc[j][l]; 194 __syncthreads(); 195 if (tid < 32) { 196 const int t = tid >> 1, hh = tid & 1, r = j * 16 + t; 197 if (r < nrows) { 198 float hv[32]; 199 float am = 0.0f; 200#pragma unroll 201 for (int f = 0; f < 32; ++f) { 202 const int ft = 32 * hh + f; 203 const int idx = (ft >> 4) * GU_EPI_PLANE + t * GU_EPI_STRIDE + (ft & 15); 204 const float gt = base[idx], up = base[idx + 4 * GU_EPI_PLANE]; 205 hv[f] = gt / (1.0f + __expf(-gt)) * up; 206 am = fmaxf(am, fabsf(hv[f])); 207 } 208 const float inv = am > 0.0f ? 127.0f / am : 0.0f; 209 uint8_t* o = out + (size_t) (row0 + r) * H_LD + (size_t) fb * AB; 210 uint32_t wd[8] = {}; 211 int csum = 0; 212#pragma unroll 213 for (int f = 0; f < 32; ++f) { 214 const int c = __float2int_rn(hv[f] * inv); 215 csum += c; 216 wd[f >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (f & 3)); 217 } 218 uint4* o4 = reinterpret_cast<uint4*>(o + 32 * hh); 219 o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); 220 o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); 221 *reinterpret_cast<float*>(o + 64 + 4 * hh) = am / 127.0f; 222 *reinterpret_cast<float*>(o + 72 + 4 * hh) = (float) csum; 223 } 224 } 225 __syncthreads(); 226 } 227} 228 229/// Down epilogue (`lds` at least D_EPI_BYTES, free): each wave's 16 x 16 tile through LDS ([token][row]), then 16 230/// consecutive FP32 rows per routed row into dm [routed row][kMoeEmbd]. 231/// D16 (STRATA_PF_DM16): the rows go out as FP16 (saturated at +-65504, kMoeEmbd halves a row, two neighbouring columns in one 4-byte store from the even lane) 232/// for moe_combine16 - half the bytes written here and read there. 233template <int BN, bool D16 = false> 234__device__ __forceinline__ void down_epilogue(const v8f (&acc)[BN / 16], uint8_t* lds, int tid, int live_tiles, int nrows, int row0, 235 int fb, float* __restrict__ dm) { 236 const int wave = tid >> 5, lane = tid & 31, sub_lane = lane & 15, half_id = lane >> 4; 237 float* tile = reinterpret_cast<float*>(lds) + wave * 256; 238 const int r0 = fb * ROWS + wave * 16; 239#pragma unroll 240 for (int j = 0; j < BN / 16; ++j) { 241 if (j >= live_tiles) break; // uniform 242#pragma unroll 243 for (int l = 0; l < 8; ++l) tile[sub_lane * 16 + 2 * l + half_id] = acc[j][l]; 244 __builtin_amdgcn_wave_barrier(); 245#pragma unroll 246 for (int q = 0; q < 8; ++q) { 247 const int flat = q * 32 + lane, t = j * 16 + (flat >> 4); 248 if constexpr (D16) { 249 const float v = fminf(fmaxf(tile[flat], -65504.0f), 65504.0f); 250 const float nx = __shfl_down(v, 1); 251 if (t < nrows && !(flat & 1)) 252 reinterpret_cast<uint32_t*>(reinterpret_cast<uint16_t*>(dm) + (size_t) (row0 + t) * kMoeEmbd + r0 + (flat & 15))[0] = 253 (uint32_t) __half_as_ushort(__float2half(v)) | ((uint32_t) __half_as_ushort(__float2half(nx)) << 16); 254 } else { 255 if (t < nrows) dm[(size_t) (row0 + t) * kMoeEmbd + r0 + (flat & 15)] = tile[flat]; 256 } 257 } 258 __builtin_amdgcn_wave_barrier(); 259 } 260} 261 262} // namespace strata::prefill::fused::f16