diff --git a/src/prefill/moe_f16_common.cuh b/src/prefill/moe_f16_common.cuh new file mode 100644 index 00000000..cde99444 --- /dev/null +++ b/src/prefill/moe_f16_common.cuh @@ -0,0 +1,250 @@ +// src/prefill/moe_f16_common.cuh - the parts the gfx11 F16 prompt-expert kernels share (STRATA_PF_F16=1): the +// switch, the work item's width, the int8 activations staged as F16, the WMMA over the token tiles and the two +// epilogues. moe_f16_kq.cu (the K-quant kernels) and moe_fused_iq.cu (the other native formats) include it. +// +// A work item is 128 weight rows (gate/up: the 64 gate and 64 up rows of 64 features; down: 128 output rows) against +// one 64-row tile of fused::group or two consecutive tiles of one expert; each of the eight waves owns 16 of the +// weight rows. The F16 WMMA accumulates all of K in F32. The fragment loop and the epilogues' layouts follow gufo's +// RoutedF16GEMMKernel. +// +// Adapted from gufo 97b8645f: src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp (RoutedF16GEMMKernel). +// MIT License +// Copyright (c) 2026 gufo contributors +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. +#pragma once + +#include +#include + +#include +#include + +#include "strata/prefill/moe_fused.hpp" + +#if defined(__HIPCC__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || \ + defined(__gfx1150__) || defined(__gfx1151__)) +#define STRATA_F16_DEVICE 1 +#else +#define STRATA_F16_DEVICE 0 +#endif + +namespace strata::prefill::fused::f16 { + +constexpr int AB = 80; // activation / H bytes per 64 values: 64 codes, {d0, d1}, {sum0, sum1} +constexpr int THREADS = 256; +constexpr int ROWS = 128; // weight rows per work item +constexpr int GU_NFB = 640 / 64, D_NFB = 2560 / ROWS; // work items per tile: 64 features, 128 output rows +constexpr int GU_ACT_LD = 2560 / 64 * AB, H_LD = 640 / 64 * AB; // bytes per activation / H row + +/// STRATA_PF_F16=1 (on top of STRATA_PF_FUSED=1): the covered formats take the F16 kernels on gfx11. +inline bool requested() { + static const bool on = [] { + const char* v = std::getenv("STRATA_PF_F16"); + return v != nullptr && v[0] == '1'; + }(); + return on; +} + +/// Two tiles a work item when an expert has a tile's rows or more on average. gfx1151, Q4_K, top 10 over 512 +/// 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 +/// 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. +/// STRATA_PF_F16_BN=64|128 forces one. +inline int pick_bn(int64_t n, int n_expert) { + static const int forced = [] { + const char* v = std::getenv("STRATA_PF_F16_BN"); + const int t = v ? std::atoi(v) : 0; + return t == kTileRows || t == 2 * kTileRows ? t : 0; + }(); + if (forced) return forced; + return (double) n / (n_expert > 0 ? n_expert : 1) >= kTileRows ? 2 * kTileRows : kTileRows; +} + +using v16h = __attribute__((__vector_size__(16 * sizeof(_Float16)))) _Float16; +using v8f = __attribute__((__vector_size__(8 * sizeof(float)))) float; + +__device__ __forceinline__ v8f wmma_f16(v16h a, v16h b, v8f c) { +#if STRATA_F16_DEVICE + return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); +#else + __builtin_trap(); + return c; +#endif +} + +/// The work item of block `w`: its tile (fused::group's tables), whether it is the second tile of a pair (the first +/// takes it), and its rows. Returns false when the block has no work. +template +__device__ __forceinline__ bool work_item(const Batch& b, const int32_t* ts, const int2* tiles, const int32_t* off, int w, + int& fb, int& e, int& row0, int& nrows) { + static_assert(BN == kTileRows || BN == 2 * kTileRows, "one tile or a pair"); + const int t0 = ts[b.e0]; + if (w >= (ts[b.e1] - t0) * NFB) return false; + const int2 tl = tiles[t0 + w / NFB]; + fb = w % NFB; + e = tl.x; + row0 = tl.y; + if (BN > kTileRows && ((t0 + w / NFB - ts[e]) & 1)) return false; + nrows = min(BN, off[e + 1] - row0); + return true; +} + +/// The int8 activation (or H) rows of a work item, staged as F16 per stage: BN rows x 8 chunks of 8 values, chunk +/// sub = kb * 4 + quarter, into LDS [sub][row] (stride BN + 1) - the B fragments' layout of the F16 WMMA. A row past +/// the item's end is zero. +template struct ActStage { + static constexpr int FETCH = BN * 8 / THREADS, STRIDE = BN + 1, BYTES = 2 * 4 * STRIDE * 16; + const uint8_t* src[FETCH]; + int slot[FETCH], sub[FETCH]; + uint2 codes[FETCH]; + float d[FETCH]; + // rows[t]: the row of item row t in `base` (rows of `ld` bytes), or -1 + __device__ __forceinline__ void init(const uint8_t* base, size_t ld, const int* rows, int tid) { +#pragma unroll + for (int i = 0; i < FETCH; ++i) { + const int chunk = tid + i * THREADS, t = chunk >> 3, c = chunk & 7; + src[i] = rows[t] >= 0 ? base + (size_t) rows[t] * ld : nullptr; + slot[i] = c * STRIDE + t; + sub[i] = c; + } + } + __device__ __forceinline__ void fetch(int s) { +#pragma unroll + for (int i = 0; i < FETCH; ++i) { + if (src[i] != nullptr) { + const uint8_t* p = src[i] + (size_t) s * AB; + codes[i] = *reinterpret_cast(p + 8 * sub[i]); + d[i] = *reinterpret_cast(p + 64 + 4 * (sub[i] >> 2)); + } else { + codes[i] = make_uint2(0u, 0u); + d[i] = 0.0f; + } + } + } + __device__ __forceinline__ void commit(uint4* s_act) const { +#pragma unroll + for (int i = 0; i < FETCH; ++i) { + const uint32_t ws[2] = {codes[i].x, codes[i].y}; + __half2 h[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const uint32_t wd = ws[j >> 1] >> (16 * (j & 1)); + const float lo = (float) (int8_t) (wd & 0xFFu), hi = (float) (int8_t) ((wd >> 8) & 0xFFu); + h[j] = __floats2half2_rn(lo * d[i], hi * d[i]); + } + s_act[slot[i]] = make_uint4(__builtin_bit_cast(uint32_t, h[0]), __builtin_bit_cast(uint32_t, h[1]), + __builtin_bit_cast(uint32_t, h[2]), __builtin_bit_cast(uint32_t, h[3])); + } + } +}; + +/// Two F16 WMMAs (K 32) of a wave's 16 weight rows against each live 16-row tile of the staged activations. +template +__device__ __forceinline__ void mma_tiles(v8f (&acc)[BN / 16], v16h a_lo, v16h a_hi, const uint4* s_act, int kb, int sub_lane, + int live_tiles) { + constexpr int STRIDE = ActStage::STRIDE; +#pragma unroll + for (int j = 0; j < BN / 16; ++j) { + asm volatile("" ::: "memory"); // one token tile's fragments live at a time (gufo: hoisting spills) + if (j >= live_tiles) continue; + const uint4* frag = s_act + (kb * 4) * STRIDE + j * 16 + sub_lane; + uint4 bq[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) bq[q] = frag[q * STRIDE]; + v16h b_lo, b_hi; + __builtin_memcpy(&b_lo, &bq[0], 32); + __builtin_memcpy(&b_hi, &bq[2], 32); + acc[j] = wmma_f16(a_lo, b_lo, acc[j]); + acc[j] = wmma_f16(a_hi, b_hi, acc[j]); + } +} + +constexpr int GU_EPI_STRIDE = 18, GU_EPI_PLANE = 16 * GU_EPI_STRIDE; +constexpr int GU_EPI_BYTES = 8 * GU_EPI_PLANE * 4, D_EPI_BYTES = 8 * 256 * 4; + +/// Gate/up epilogue (every wave; `lds` at least GU_EPI_BYTES, free): per token tile, each wave's 16 x 16 +/// accumulators as plane [token][row] (waves 0-3 the gate rows, 4-7 the up rows), then a thread per (token, half of +/// the 64 features): SwiGLU, H as int8 per 32 features with its scale and the codes' sum (native_w11_kernel's H). +template +__device__ __forceinline__ void gu_epilogue(const v8f (&acc)[BN / 16], uint8_t* lds, int tid, int live_tiles, int nrows, int row0, + int fb, uint8_t* __restrict__ out) { + const int wave = tid >> 5, lane = tid & 31, sub_lane = lane & 15, half_id = lane >> 4; + float* base = reinterpret_cast(lds); + float* scratch = base + wave * GU_EPI_PLANE; +#pragma unroll + for (int j = 0; j < BN / 16; ++j) { + if (j >= live_tiles) break; // uniform +#pragma unroll + for (int l = 0; l < 8; ++l) scratch[sub_lane * GU_EPI_STRIDE + 2 * l + half_id] = acc[j][l]; + __syncthreads(); + if (tid < 32) { + const int t = tid >> 1, hh = tid & 1, r = j * 16 + t; + if (r < nrows) { + float hv[32]; + float am = 0.0f; +#pragma unroll + for (int f = 0; f < 32; ++f) { + const int ft = 32 * hh + f; + const int idx = (ft >> 4) * GU_EPI_PLANE + t * GU_EPI_STRIDE + (ft & 15); + const float gt = base[idx], up = base[idx + 4 * GU_EPI_PLANE]; + hv[f] = gt / (1.0f + __expf(-gt)) * up; + am = fmaxf(am, fabsf(hv[f])); + } + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + uint8_t* o = out + (size_t) (row0 + r) * H_LD + (size_t) fb * AB; + uint32_t wd[8] = {}; + int csum = 0; +#pragma unroll + for (int f = 0; f < 32; ++f) { + const int c = __float2int_rn(hv[f] * inv); + csum += c; + wd[f >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (f & 3)); + } + uint4* o4 = reinterpret_cast(o + 32 * hh); + o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); + o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); + *reinterpret_cast(o + 64 + 4 * hh) = am / 127.0f; + *reinterpret_cast(o + 72 + 4 * hh) = (float) csum; + } + } + __syncthreads(); + } +} + +/// Down epilogue (`lds` at least D_EPI_BYTES, free): each wave's 16 x 16 tile through LDS ([token][row]), then 16 +/// consecutive FP32 rows per routed row into dm [routed row][2560]. +template +__device__ __forceinline__ void down_epilogue(const v8f (&acc)[BN / 16], uint8_t* lds, int tid, int live_tiles, int nrows, int row0, + int fb, float* __restrict__ dm) { + const int wave = tid >> 5, lane = tid & 31, sub_lane = lane & 15, half_id = lane >> 4; + float* tile = reinterpret_cast(lds) + wave * 256; + const int r0 = fb * ROWS + wave * 16; +#pragma unroll + for (int j = 0; j < BN / 16; ++j) { + if (j >= live_tiles) break; // uniform +#pragma unroll + for (int l = 0; l < 8; ++l) tile[sub_lane * 16 + 2 * l + half_id] = acc[j][l]; + __builtin_amdgcn_wave_barrier(); +#pragma unroll + for (int q = 0; q < 8; ++q) { + const int flat = q * 32 + lane, t = j * 16 + (flat >> 4); + if (t < nrows) dm[(size_t) (row0 + t) * 2560 + r0 + (flat & 15)] = tile[flat]; + } + __builtin_amdgcn_wave_barrier(); + } +} + +} // namespace strata::prefill::fused::f16 diff --git a/src/prefill/moe_f16_kq.cu b/src/prefill/moe_f16_kq.cu index 2634d9c6..824b8cce 100644 --- a/src/prefill/moe_f16_kq.cu +++ b/src/prefill/moe_f16_kq.cu @@ -1,18 +1,12 @@ -// src/prefill/moe_f16_kq.cu - see moe_f16_kq.hpp. gfx11 only (opt-in STRATA_PF_F16_KQ=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). // -// The paired gate/up kernel of gufo's routed experts, on Strata's tables, int8 activations and H: -// - one work item is 64 features of one expert (its 64 gate and 64 up rows, BM = 128) against one 64-row tile of -// fused::group, K = 2560 in 40 stages of 64 values; -// - the weight codes stay packed in LDS (one 32-byte Q4_K nibble group per row and stage) and each wave turns its -// own 16 rows into F16 right after the LDS read: w = q * (d sc) - dmin m as one packed FMA, so the F16 matrix -// core accumulates the whole K in F32 with no per-block epilogue; -// - the activations are native_w11_kernel's int8 blocks, staged in LDS as F16 (a * d_x, one product each), shared -// by every wave; -// - the epilogue applies SwiGLU and writes H as int8 per 32 features (with the codes' sum), the form the existing -// down kernels read. -// Q5_1 down takes the same structure (down_kernel): H staged as F16, the codes and high bits packed in LDS, FP32 -// outputs at the routed rows. The output differs from native_w11_kernel's (F16 weights instead of int8 sub-blocks), -// like STRATA_PF_FUSED_KQ's does from the MMQ path. +// gufo's routed-expert kernels for the K-quants, on Strata's tables, int8 activations and H (the work item, the +// activation staging and the epilogues are moe_f16_common.cuh's): +// - gate/up (Q4_K, Q5_K): the weight codes stay packed in LDS (one 32-byte nibble group per row and stage) and +// each wave turns its own 16 rows into F16 right after the LDS read: w = q * (d sc) - dmin m as one packed FMA; +// - down (Q5_1): a K block's 16 code bytes and its high-bit word in LDS, w = q d + m per wave. +// The output differs from native_w11_kernel's (F16 weights instead of int8 sub-blocks), like STRATA_PF_FUSED_KQ's +// does from the MMQ path. // // Adapted from gufo 97b8645f: src/models/qwen38_flash_next/kernels/rocm/kernels.hip.cpp // (RoutedF16GEMMKernel and its helpers). @@ -35,46 +29,20 @@ // SOFTWARE. #include "moe_f16_kq.hpp" -#include +#include "moe_f16_common.cuh" #include "ggml.h" #include -#include -#include -#include namespace strata::prefill::fused::f16kq { namespace { +using namespace f16; + constexpr int T_Q4_K = GGML_TYPE_Q4_K, T_Q5_K = GGML_TYPE_Q5_K; -constexpr int AB = 80; // activation / H bytes per 64 values: 64 codes, {d0, d1}, {sum0, sum1} -constexpr int K_GU = 2560; // n_embd -constexpr int NS = K_GU / 64; // stages -constexpr int ACT_LD = NS * AB; // bytes per activation row -constexpr int FEAT = 64; // features (gate rows = up rows) per work item -constexpr int NFB = 640 / FEAT; // work items per tile -constexpr int BM = 2 * FEAT; // code rows in LDS: gate 0..63, up 64..127 -constexpr int THREADS = 256; - -#if defined(__HIPCC__) && (defined(__gfx1100__) || defined(__gfx1101__) || defined(__gfx1102__) || \ - defined(__gfx1150__) || defined(__gfx1151__)) -#define STRATA_F16KQ_DEVICE 1 -#else -#define STRATA_F16KQ_DEVICE 0 -#endif - -using v16h = __attribute__((__vector_size__(16 * sizeof(_Float16)))) _Float16; -using v8f = __attribute__((__vector_size__(8 * sizeof(float)))) float; - -__device__ __forceinline__ v8f wmma_f16(v16h a, v16h b, v8f c) { -#if STRATA_F16KQ_DEVICE - return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); -#else - __builtin_trap(); - return c; -#endif -} +constexpr int GU_NS = 2560 / 64, D_NS = 640 / 64; // stages of 64 values +constexpr int FEAT = 64; // features (gate rows = up rows) per gate/up item // Byte i of the 16-byte K-quant block header (d, dmin, scales[12]). __device__ __forceinline__ uint32_t header_byte(const uint4& h, uint32_t i) { @@ -90,7 +58,7 @@ constexpr uint32_t HALF_MAGIC = 0x64646464U; // the high bytes of 1024.0 as F1 // Four code bytes (< 32) to four halves: 1024 + q exactly, minus 1024, then q * scale + bias. __device__ __forceinline__ void codes_to_halves(uint32_t codes, __half2 magic, __half2 scale2, __half2 bias2, __half2& lo, __half2& hi) { -#if STRATA_F16KQ_DEVICE +#if STRATA_F16_DEVICE const uint32_t p0 = __builtin_amdgcn_perm(codes, HALF_MAGIC, 0x01050004U); const uint32_t p1 = __builtin_amdgcn_perm(codes, HALF_MAGIC, 0x03070206U); lo = __hfma2(__hadd2(__builtin_bit_cast(__half2, p0), magic), scale2, bias2); @@ -100,97 +68,23 @@ __device__ __forceinline__ void codes_to_halves(uint32_t codes, __half2 magic, _ #endif } -// The int8 activation (or H) rows of a work item, staged as F16 per stage: BN rows x 8 chunks of 8 values, chunk -// sub = kb * 4 + quarter, into LDS [sub][row] (stride BN + 1) - the B fragments' layout of the F16 WMMA. A row past -// the item's end is zero. -template struct ActStage { - static constexpr int FETCH = BN * 8 / THREADS, STRIDE = BN + 1, BYTES = 2 * 4 * STRIDE * 16; - const uint8_t* src[FETCH]; - int slot[FETCH], sub[FETCH]; - uint2 codes[FETCH]; - float d[FETCH]; - // rows[t]: the row of item row t in `base` (rows of `ld` bytes), or -1 - __device__ __forceinline__ void init(const uint8_t* base, size_t ld, const int* rows, int tid) { -#pragma unroll - for (int i = 0; i < FETCH; ++i) { - const int chunk = tid + i * THREADS, t = chunk >> 3, c = chunk & 7; - src[i] = rows[t] >= 0 ? base + (size_t) rows[t] * ld : nullptr; - slot[i] = c * STRIDE + t; - sub[i] = c; - } - } - __device__ __forceinline__ void fetch(int s) { -#pragma unroll - for (int i = 0; i < FETCH; ++i) { - if (src[i] != nullptr) { - const uint8_t* p = src[i] + (size_t) s * AB; - codes[i] = *reinterpret_cast(p + 8 * sub[i]); - d[i] = *reinterpret_cast(p + 64 + 4 * (sub[i] >> 2)); - } else { - codes[i] = make_uint2(0u, 0u); - d[i] = 0.0f; - } - } - } - __device__ __forceinline__ void commit(uint4* s_act) const { -#pragma unroll - for (int i = 0; i < FETCH; ++i) { - const uint32_t ws[2] = {codes[i].x, codes[i].y}; - __half2 h[4]; -#pragma unroll - for (int j = 0; j < 4; ++j) { - const uint32_t wd = ws[j >> 1] >> (16 * (j & 1)); - const float lo = (float) (int8_t) (wd & 0xFFu), hi = (float) (int8_t) ((wd >> 8) & 0xFFu); - h[j] = __floats2half2_rn(lo * d[i], hi * d[i]); - } - s_act[slot[i]] = make_uint4(__builtin_bit_cast(uint32_t, h[0]), __builtin_bit_cast(uint32_t, h[1]), - __builtin_bit_cast(uint32_t, h[2]), __builtin_bit_cast(uint32_t, h[3])); - } - } -}; - -// Two F16 WMMAs (K 32) of a wave's 16 weight rows against each live 16-row tile of the staged activations. -template -__device__ __forceinline__ void mma_tiles(v8f (&acc)[BN / 16], v16h a_lo, v16h a_hi, const uint4* s_act, int kb, int sub_lane, - int live_tiles) { - constexpr int STRIDE = ActStage::STRIDE; -#pragma unroll - for (int j = 0; j < BN / 16; ++j) { - asm volatile("" ::: "memory"); // one token tile's fragments live at a time (gufo: hoisting spills) - if (j >= live_tiles) continue; - const uint4* frag = s_act + (kb * 4) * STRIDE + j * 16 + sub_lane; - uint4 bq[4]; -#pragma unroll - for (int q = 0; q < 4; ++q) bq[q] = frag[q * STRIDE]; - v16h b_lo, b_hi; - __builtin_memcpy(&b_lo, &bq[0], 32); - __builtin_memcpy(&b_hi, &bq[2], 32); - acc[j] = wmma_f16(a_lo, b_lo, acc[j]); - acc[j] = wmma_f16(a_hi, b_hi, acc[j]); - } -} - -// BN: tokens per work item, fused::group's 64-row tile or two consecutive tiles of one expert (128) +// 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. template __global__ void __launch_bounds__(THREADS) gate_up_kernel(const Batch b, const NativeGeom geo, const int32_t* __restrict__ ts, const int2* __restrict__ tiles, const int32_t* __restrict__ off, const uint8_t* __restrict__ act, const int32_t* __restrict__ src, uint8_t* __restrict__ out) { -#if STRATA_F16KQ_DEVICE - static_assert(BN == kTileRows || BN == 2 * kTileRows, "one tile or a pair"); +#if STRATA_F16_DEVICE constexpr bool Q5K = WT == T_Q5_K; - constexpr int TOK_TILES = BN / 16; constexpr int BLOCK_CHUNKS = Q5K ? 11 : 9; // 16-byte chunks per 256-value block constexpr int CODE_CHUNK = Q5K ? 3 : 1; // the first chunk of qs - // LDS (bytes): codes BM rows x 2 chunks (swizzled); Q5_K's high bits and the (scale, bias) half2 per row and K - // block; the activations [kb][quarter][token][16 B], one slot of padding per quarter plane. The epilogue reuses - // the front for eight 16 x 18 float planes. - constexpr int CODE_BYTES = BM * 2 * 16; - constexpr int HIGH_BYTES = Q5K ? 2 * BM * 4 : 0; - constexpr int SCALE_BYTES = 2 * BM * 4; + // LDS (bytes): codes ROWS x 2 chunks (swizzled); Q5_K's high bits and the (scale, bias) half2 per row and K + // block; the activations. The epilogue reuses the front. + constexpr int CODE_BYTES = ROWS * 2 * 16; + constexpr int HIGH_BYTES = Q5K ? 2 * ROWS * 4 : 0; + constexpr int SCALE_BYTES = 2 * ROWS * 4; constexpr int STAGE_BYTES = CODE_BYTES + HIGH_BYTES + SCALE_BYTES + ActStage::BYTES; - constexpr int EPI_STRIDE = 18, EPI_PLANE = 16 * EPI_STRIDE; - static_assert(8 * EPI_PLANE * 4 <= STAGE_BYTES, "the epilogue planes fit the stage"); + static_assert(GU_EPI_BYTES <= STAGE_BYTES, "the epilogue fits the stage"); __shared__ __attribute__((aligned(16))) uint8_t lds[STAGE_BYTES]; __shared__ int srow[BN]; auto* s_codes = reinterpret_cast(lds); @@ -198,192 +92,137 @@ __global__ void __launch_bounds__(THREADS) gate_up_kernel(const Batch b, const N auto* s_scale = reinterpret_cast(lds + CODE_BYTES + HIGH_BYTES); auto* s_act = reinterpret_cast(lds + CODE_BYTES + HIGH_BYTES + SCALE_BYTES); - const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31, sub_lane = lane & 15, half_id = lane >> 4; + const int tid = threadIdx.x, wave = tid >> 5, sub_lane = tid & 15; const int f_c = tid & 1; // this thread's chunk (and K block) of its weight row const auto swizzle = [](int row, int c) { return row * 2 + (c ^ ((row >> 2) & 1)); }; const __half2 magic = __floats2half2_rn(-1024.0f, -1024.0f); - // One work item per block, the grid the batch's bound (gufo's launch: the hardware balances the blocks; the - // NFB items of a tile are consecutive, so they meet its activations in L2) - const int t0 = ts[b.e0], w = blockIdx.x; - if (w >= (ts[b.e1] - t0) * NFB) return; - { - const int2 tl = tiles[t0 + w / NFB]; - const int fb = w % NFB, e = tl.x, row0 = tl.y; - if (BN > kTileRows && ((t0 + w / NFB - ts[e]) & 1)) return; // the second tile of a pair: its first takes it - const int nrows = min(BN, off[e + 1] - row0); - const int live_tok_tiles = (nrows + 15) / 16; - const uint8_t* blob = b.blob[e - b.e0]; - if (tid < BN) srow[tid] = tid < nrows ? src[row0 + tid] : -1; - __syncthreads(); + int fb, e, row0, nrows; + if (!work_item(b, ts, tiles, off, blockIdx.x, fb, e, row0, nrows)) return; + const int live_tiles = (nrows + 15) / 16; + const uint8_t* blob = b.blob[e - b.e0]; + if (tid < BN) srow[tid] = tid < nrows ? src[row0 + tid] : -1; + __syncthreads(); - // Weight fetch: row tid / 2 of the code plane (gate rows, then up rows), chunk f_c. - const uint8_t* f_ptr = blob + ((tid >> 1) >= FEAT ? geo.up_off : 0) + - (size_t) (fb * FEAT + ((tid >> 1) & (FEAT - 1))) * geo.gu_row; - uint4 f_header = make_uint4(0u, 0u, 0u, 0u), f_codes, f_qh[2] = {}; - uint4 code_cache[4]; // the block's four nibble groups, this thread's chunk of each - uint32_t f_high = 0; - int f_sb32 = 0; - ActStage as; - as.init(act, ACT_LD, srow, tid); // the tokens' activation rows + const uint8_t* f_ptr = blob + ((tid >> 1) >= FEAT ? geo.up_off : 0) + (size_t) (fb * FEAT + ((tid >> 1) & (FEAT - 1))) * geo.gu_row; + uint4 f_header = make_uint4(0u, 0u, 0u, 0u), f_codes, f_qh[2] = {}; + uint4 code_cache[4]; // the block's four nibble groups, this thread's chunk of each + uint32_t f_high = 0; + int f_sb32 = 0; + ActStage as; + as.init(act, GU_ACT_LD, srow, tid); // the tokens' activation rows - const auto fetch_stage = [&](int s) { - const int kb0 = 2 * s; - const uint4* blk = reinterpret_cast(f_ptr) + (kb0 / 8) * BLOCK_CHUNKS; - if (kb0 % 8 == 0) { // a new 256-value block every four stages - f_header = blk[0]; + const auto fetch_stage = [&](int s) { + const int kb0 = 2 * s; + const uint4* blk = reinterpret_cast(f_ptr) + (kb0 / 8) * BLOCK_CHUNKS; + if (kb0 % 8 == 0) { // a new 256-value block every four stages + f_header = blk[0]; #pragma unroll - for (int group = 0; group < 4; ++group) code_cache[group] = blk[CODE_CHUNK + group * 2 + f_c]; - if constexpr (Q5K) { - f_qh[0] = blk[1]; - f_qh[1] = blk[2]; - } - } - const int sb32 = (kb0 % 8) + f_c; - { - const int group = sb32 / 2; // uniform across the wave - const uint32_t low = 0u - (group & 1u), high = 0u - ((group >> 1u) & 1u); - const auto select = [](uint32_t a, uint32_t bb, uint32_t mask) { - uint32_t value; - asm("v_cndmask_b32_e64 %0, %1, %2, %3" : "=v"(value) : "v"(a), "v"(bb), "s"(mask)); - return value; - }; - const uint4 &c0 = code_cache[0], &c1 = code_cache[1], &c2 = code_cache[2], &c3 = code_cache[3]; - f_codes = make_uint4(select(select(c0.x, c1.x, low), select(c2.x, c3.x, low), high), - select(select(c0.y, c1.y, low), select(c2.y, c3.y, low), high), - select(select(c0.z, c1.z, low), select(c2.z, c3.z, low), high), - select(select(c0.w, c1.w, low), select(c2.w, c3.w, low), high)); - } - f_sb32 = sb32; + for (int group = 0; group < 4; ++group) code_cache[group] = blk[CODE_CHUNK + group * 2 + f_c]; if constexpr (Q5K) { - 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}; - uint32_t hb = 0; -#pragma unroll - for (int i = 0; i < 8; ++i) hb |= gather_bit(qh[i], sb32) << (4 * i); - f_high = hb; + f_qh[0] = blk[1]; + f_qh[1] = blk[2]; } - as.fetch(s); - }; - - const auto commit_stage = [&]() { - const int row = tid >> 1; - s_codes[swizzle(row, f_c)] = f_codes; - if constexpr (Q5K) s_high[f_c * BM + row] = f_high; - const int sb32 = f_sb32; - uint32_t sc, mn; - if (sb32 < 4) { - sc = header_byte(f_header, 4 + sb32) & 0x3FU; - mn = header_byte(f_header, 8 + sb32) & 0x3FU; - } else { - sc = (header_byte(f_header, 8 + sb32) & 0x0FU) | ((header_byte(f_header, sb32) >> 6U) << 4U); - mn = (header_byte(f_header, 8 + sb32) >> 4U) | ((header_byte(f_header, 4 + sb32) >> 6U) << 4U); - } - const __half2 dm = __builtin_bit_cast(__half2, f_header.x); - const float scale = __low2float(dm) * (float) sc, offset = __high2float(dm) * (float) mn; - s_scale[f_c * BM + row] = __builtin_bit_cast(uint32_t, __floats2half2_rn(scale, -offset)); - as.commit(s_act); - }; - - v8f acc[TOK_TILES]; -#pragma unroll - for (int j = 0; j < TOK_TILES; ++j) acc[j] = v8f{0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; - - const auto compute_stage = [&]() { - const int row = wave * 16 + sub_lane; // waves 0-3: gate rows, 4-7: the matching up rows - const uint4 raw0 = s_codes[swizzle(row, 0)], raw1 = s_codes[swizzle(row, 1)]; -#pragma unroll - for (int kb = 0; kb < 2; ++kb) { - const __half2 sb = __builtin_bit_cast(__half2, s_scale[kb * BM + row]); - const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb); - // 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 - const unsigned shift = 4U * (unsigned) kb; - const uint32_t words[8] = {raw0.x, raw0.y, raw0.z, raw0.w, raw1.x, raw1.y, raw1.z, raw1.w}; - const uint32_t hb = Q5K ? s_high[kb * BM + row] : 0U; - __half2 h[16]; -#pragma unroll - for (int i = 0; i < 8; ++i) { - uint32_t nib = (words[i] >> shift) & 0x0F0F0F0FU; - if constexpr (Q5K) nib |= spread_high_bits((hb >> (4 * i)) & 0xFU); - codes_to_halves(nib, magic, scale2, bias2, h[2 * i], h[2 * i + 1]); - } - v16h a_lo, a_hi; - __builtin_memcpy(&a_lo, &h[0], 32); - __builtin_memcpy(&a_hi, &h[8], 32); - mma_tiles(acc, a_lo, a_hi, s_act, kb, sub_lane, live_tok_tiles); - } - }; - - fetch_stage(0); - for (int s = 0; s < NS; ++s) { - commit_stage(); - __syncthreads(); - if (s + 1 < NS) fetch_stage(s + 1); - compute_stage(); - __syncthreads(); } - - // Epilogue per token tile: each wave's 16 x 16 accumulators as plane [token][row] (gate planes 0-3, up 4-7), - // then a thread per (token, half of the 64 features): SwiGLU, int8 per 32 with the codes' sum. - float* base = reinterpret_cast(lds); - float* scratch = base + wave * EPI_PLANE; -#pragma unroll - for (int j = 0; j < TOK_TILES; ++j) { - if (j >= live_tok_tiles) break; // uniform -#pragma unroll - for (int l = 0; l < 8; ++l) scratch[sub_lane * EPI_STRIDE + 2 * l + half_id] = acc[j][l]; - __syncthreads(); - if (tid < 32) { - const int t = tid >> 1, hh = tid & 1, r = j * 16 + t; - if (r < nrows) { - float hv[32]; - float am = 0.0f; -#pragma unroll - for (int f = 0; f < 32; ++f) { - const int ft = 32 * hh + f; - const int idx = (ft >> 4) * EPI_PLANE + t * EPI_STRIDE + (ft & 15); - const float gt = base[idx], up = base[idx + 4 * EPI_PLANE]; - hv[f] = gt / (1.0f + __expf(-gt)) * up; - am = fmaxf(am, fabsf(hv[f])); - } - const float inv = am > 0.0f ? 127.0f / am : 0.0f; - uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (size_t) fb * AB; - uint32_t wd[8] = {}; - int csum = 0; -#pragma unroll - for (int f = 0; f < 32; ++f) { - const int c = __float2int_rn(hv[f] * inv); - csum += c; - wd[f >> 2] |= (uint32_t) (uint8_t) (int8_t) c << (8 * (f & 3)); - } - uint4* o4 = reinterpret_cast(o + 32 * hh); - o4[0] = make_uint4(wd[0], wd[1], wd[2], wd[3]); - o4[1] = make_uint4(wd[4], wd[5], wd[6], wd[7]); - *reinterpret_cast(o + 64 + 4 * hh) = am / 127.0f; - *reinterpret_cast(o + 72 + 4 * hh) = (float) csum; - } - } - __syncthreads(); + const int sb32 = (kb0 % 8) + f_c; + { + const int group = sb32 / 2; // uniform across the wave + const uint32_t low = 0u - (group & 1u), high = 0u - ((group >> 1u) & 1u); + const auto select = [](uint32_t a, uint32_t bb, uint32_t mask) { + uint32_t value; + asm("v_cndmask_b32_e64 %0, %1, %2, %3" : "=v"(value) : "v"(a), "v"(bb), "s"(mask)); + return value; + }; + const uint4 &c0 = code_cache[0], &c1 = code_cache[1], &c2 = code_cache[2], &c3 = code_cache[3]; + f_codes = make_uint4(select(select(c0.x, c1.x, low), select(c2.x, c3.x, low), high), + select(select(c0.y, c1.y, low), select(c2.y, c3.y, low), high), + select(select(c0.z, c1.z, low), select(c2.z, c3.z, low), high), + select(select(c0.w, c1.w, low), select(c2.w, c3.w, low), high)); } + f_sb32 = sb32; + if constexpr (Q5K) { + 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}; + uint32_t hb = 0; +#pragma unroll + for (int i = 0; i < 8; ++i) hb |= gather_bit(qh[i], sb32) << (4 * i); + f_high = hb; + } + as.fetch(s); + }; + + const auto commit_stage = [&]() { + const int row = tid >> 1; + s_codes[swizzle(row, f_c)] = f_codes; + if constexpr (Q5K) s_high[f_c * ROWS + row] = f_high; + const int sb32 = f_sb32; + uint32_t sc, mn; + if (sb32 < 4) { + sc = header_byte(f_header, 4 + sb32) & 0x3FU; + mn = header_byte(f_header, 8 + sb32) & 0x3FU; + } else { + sc = (header_byte(f_header, 8 + sb32) & 0x0FU) | ((header_byte(f_header, sb32) >> 6U) << 4U); + mn = (header_byte(f_header, 8 + sb32) >> 4U) | ((header_byte(f_header, 4 + sb32) >> 6U) << 4U); + } + const __half2 dm = __builtin_bit_cast(__half2, f_header.x); + const float scale = __low2float(dm) * (float) sc, offset = __high2float(dm) * (float) mn; + s_scale[f_c * ROWS + row] = __builtin_bit_cast(uint32_t, __floats2half2_rn(scale, -offset)); + as.commit(s_act); + }; + + v8f acc[BN / 16]; +#pragma unroll + 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}; + + const auto compute_stage = [&]() { + const int row = wave * 16 + sub_lane; // waves 0-3: gate rows, 4-7: the matching up rows + const uint4 raw0 = s_codes[swizzle(row, 0)], raw1 = s_codes[swizzle(row, 1)]; +#pragma unroll + for (int kb = 0; kb < 2; ++kb) { + const __half2 sb = __builtin_bit_cast(__half2, s_scale[kb * ROWS + row]); + const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb); + // 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 + const unsigned shift = 4U * (unsigned) kb; + const uint32_t words[8] = {raw0.x, raw0.y, raw0.z, raw0.w, raw1.x, raw1.y, raw1.z, raw1.w}; + const uint32_t hb = Q5K ? s_high[kb * ROWS + row] : 0U; + __half2 h[16]; +#pragma unroll + for (int i = 0; i < 8; ++i) { + uint32_t nib = (words[i] >> shift) & 0x0F0F0F0FU; + if constexpr (Q5K) nib |= spread_high_bits((hb >> (4 * i)) & 0xFU); + codes_to_halves(nib, magic, scale2, bias2, h[2 * i], h[2 * i + 1]); + } + v16h a_lo, a_hi; + __builtin_memcpy(&a_lo, &h[0], 32); + __builtin_memcpy(&a_hi, &h[8], 32); + mma_tiles(acc, a_lo, a_hi, s_act, kb, sub_lane, live_tiles); + } + }; + + fetch_stage(0); + for (int s = 0; s < GU_NS; ++s) { + commit_stage(); + __syncthreads(); + if (s + 1 < GU_NS) fetch_stage(s + 1); + compute_stage(); + __syncthreads(); } + gu_epilogue(acc, lds, tid, live_tiles, nrows, row0, fb, out); #else (void) b; (void) geo; (void) ts; (void) tiles; (void) off; (void) act; (void) src; (void) out; __builtin_trap(); #endif } -// Q5_1 down: 128 of the 2560 output rows (DNFB items per tile) against a tile's (or pair's) H rows, K = 640 in 10 -// stages; the products are the routed rows' FP32 outputs in `dm` (native_w11_kernel's). gufo's -// RoutedF16GEMMKernel: a K block's 16 code bytes and its high-bit word in LDS, w = q d + m per wave. -constexpr int D_ROWS = 128, DNFB = 2560 / D_ROWS, D_NS = 640 / 64, H_LD = D_NS * AB; +// Q5_1 down: 128 of the 2560 output rows against a tile's (or pair's) H rows, K = 640 in 10 stages; the routed rows' +// FP32 outputs in `dm` (native_w11_kernel's). template __global__ void __launch_bounds__(THREADS) down_kernel(const Batch b, const NativeGeom geo, const int32_t* __restrict__ ts, const int2* __restrict__ tiles, const int32_t* __restrict__ off, const uint8_t* __restrict__ h, float* __restrict__ dm) { -#if STRATA_F16KQ_DEVICE - static_assert(BN == kTileRows || BN == 2 * kTileRows, "one tile or a pair"); - constexpr int CODE_BYTES = D_ROWS * 2 * 16, HIGH_BYTES = 2 * D_ROWS * 4, SCALE_BYTES = 2 * D_ROWS * 4; +#if STRATA_F16_DEVICE + constexpr int CODE_BYTES = ROWS * 2 * 16, HIGH_BYTES = 2 * ROWS * 4, SCALE_BYTES = 2 * ROWS * 4; constexpr int STAGE_BYTES = CODE_BYTES + HIGH_BYTES + SCALE_BYTES + ActStage::BYTES; - static_assert(8 * 256 * 4 <= STAGE_BYTES, "the epilogue's 16 x 16 tile per wave fits the stage"); + static_assert(D_EPI_BYTES <= STAGE_BYTES, "the epilogue fits the stage"); __shared__ __attribute__((aligned(16))) uint8_t lds[STAGE_BYTES]; __shared__ int srow[BN]; auto* s_codes = reinterpret_cast(lds); @@ -391,23 +230,18 @@ __global__ void __launch_bounds__(THREADS) down_kernel(const Batch b, const Nati auto* s_scale = reinterpret_cast(lds + CODE_BYTES + HIGH_BYTES); auto* s_act = reinterpret_cast(lds + CODE_BYTES + HIGH_BYTES + SCALE_BYTES); - const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31, sub_lane = lane & 15, half_id = lane >> 4; + const int tid = threadIdx.x, wave = tid >> 5, sub_lane = tid & 15; const int f_c = tid & 1; // this thread's K block of its weight row const auto swizzle = [](int row, int c) { return row * 2 + (c ^ ((row >> 2) & 1)); }; const __half2 magic = __floats2half2_rn(-1024.0f, -1024.0f); - const int t0 = ts[b.e0], w = blockIdx.x; - if (w >= (ts[b.e1] - t0) * DNFB) return; - const int2 tl = tiles[t0 + w / DNFB]; - const int fb = w % DNFB, e = tl.x, row0 = tl.y; - if (BN > kTileRows && ((t0 + w / DNFB - ts[e]) & 1)) return; // the second tile of a pair: its first takes it - const int nrows = min(BN, off[e + 1] - row0); + int fb, e, row0, nrows; + if (!work_item(b, ts, tiles, off, blockIdx.x, fb, e, row0, nrows)) return; const int live_tiles = (nrows + 15) / 16; if (tid < BN) srow[tid] = tid < nrows ? row0 + tid : -1; // H is indexed by the routed row __syncthreads(); - const uint2* f_ptr = reinterpret_cast(b.blob[e - b.e0] + geo.down_off + - (size_t) (fb * D_ROWS + (tid >> 1)) * geo.d_row); + const uint2* f_ptr = reinterpret_cast(b.blob[e - b.e0] + geo.down_off + (size_t) (fb * ROWS + (tid >> 1)) * geo.d_row); uint4 f_codes; uint32_t f_high = 0, f_dm = 0; ActStage as; @@ -423,8 +257,8 @@ __global__ void __launch_bounds__(THREADS) down_kernel(const Batch b, const Nati const auto commit_stage = [&]() { const int row = tid >> 1; s_codes[swizzle(row, f_c)] = f_codes; - s_high[f_c * D_ROWS + row] = f_high; - s_scale[f_c * D_ROWS + row] = f_dm; // the half2 (d, m): w = q d + m + s_high[f_c * ROWS + row] = f_high; + s_scale[f_c * ROWS + row] = f_dm; // the half2 (d, m): w = q d + m as.commit(s_act); }; v8f acc[BN / 16]; @@ -435,11 +269,11 @@ __global__ void __launch_bounds__(THREADS) down_kernel(const Batch b, const Nati const uint4 raw[2] = {s_codes[swizzle(row, 0)], s_codes[swizzle(row, 1)]}; #pragma unroll for (int kb = 0; kb < 2; ++kb) { - const __half2 sb = __builtin_bit_cast(__half2, s_scale[kb * D_ROWS + row]); + const __half2 sb = __builtin_bit_cast(__half2, s_scale[kb * ROWS + row]); const __half2 scale2 = __low2half2(sb), bias2 = __high2half2(sb); // elements 0-15 are the low nibbles of the 16 code bytes, 16-31 the high, plus bit j of the high-bit word const uint32_t words[4] = {raw[kb].x, raw[kb].y, raw[kb].z, raw[kb].w}; - const uint32_t hb = s_high[kb * D_ROWS + row]; + const uint32_t hb = s_high[kb * ROWS + row]; __half2 hh[16]; #pragma unroll for (int i = 0; i < 4; ++i) { @@ -462,75 +296,39 @@ __global__ void __launch_bounds__(THREADS) down_kernel(const Batch b, const Nati compute_stage(); __syncthreads(); } - // Each wave's 16 x 16 tile through LDS ([token][row]), then 16 consecutive FP32 rows per routed row. - float* tile = reinterpret_cast(lds) + wave * 256; - const int r0 = fb * D_ROWS + wave * 16; -#pragma unroll - for (int j = 0; j < BN / 16; ++j) { - if (j >= live_tiles) break; // uniform -#pragma unroll - for (int l = 0; l < 8; ++l) tile[sub_lane * 16 + 2 * l + half_id] = acc[j][l]; - __builtin_amdgcn_wave_barrier(); -#pragma unroll - for (int q = 0; q < 8; ++q) { - const int flat = q * 32 + lane, t = j * 16 + (flat >> 4); - if (t < nrows) dm[(size_t) (row0 + t) * 2560 + r0 + (flat & 15)] = tile[flat]; - } - __builtin_amdgcn_wave_barrier(); - } + down_epilogue(acc, lds, tid, live_tiles, nrows, row0, fb, dm); #else (void) b; (void) geo; (void) ts; (void) tiles; (void) off; (void) h; (void) dm; __builtin_trap(); #endif } -// Two tiles a work item when an expert has a tile's rows or more on average. gfx1151, Q4_K, top 10 over 512 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 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. STRATA_PF_F16_KQ_BN=64|128 forces -// one. -int pick_bn(int64_t n, int n_expert) { - static const int forced = [] { - const char* v = std::getenv("STRATA_PF_F16_KQ_BN"); - const int t = v ? std::atoi(v) : 0; - return t == 64 || t == 128 ? t : 0; - }(); - if (forced) return forced; - return (double) n / std::max(n_expert, 1) >= kTileRows ? 2 * kTileRows : kTileRows; -} - -template -void launch(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t work_bound, - const uint8_t* act, const int32_t* src, uint8_t* out, cudaStream_t s) { - const unsigned grid = (unsigned) std::max(1, work_bound * NFB); - if (g.gu_type == T_Q5_K) gate_up_kernel<<>>(b, g, ts, tiles, off, act, src, out); - else gate_up_kernel<<>>(b, g, ts, tiles, off, act, src, out); -} - } // namespace -bool requested() { - static const bool on = [] { - const char* v = std::getenv("STRATA_PF_F16_KQ"); - return v != nullptr && v[0] == '1'; - }(); - return on; -} - bool covers(int gu_type) { return gu_type == T_Q4_K || gu_type == T_Q5_K; } bool covers_down(int d_type) { return d_type == GGML_TYPE_Q5_1; } +void gate_up(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t n, + int n_expert, int64_t work_bound, const uint8_t* act, const int32_t* src, uint8_t* out, cudaStream_t s) { + // one block per work item, the grid the batch's bound (gufo's launch: the hardware balances the blocks; the items + // of a tile are consecutive, so they meet its activations in L2) + const unsigned grid = (unsigned) std::max(1, work_bound * GU_NFB); + const bool q5k = g.gu_type == T_Q5_K; + if (pick_bn(n, n_expert) == 2 * kTileRows) { + if (q5k) gate_up_kernel<<>>(b, g, ts, tiles, off, act, src, out); + else gate_up_kernel<<>>(b, g, ts, tiles, off, act, src, out); + } else { + if (q5k) gate_up_kernel<<>>(b, g, ts, tiles, off, act, src, out); + else gate_up_kernel<<>>(b, g, ts, tiles, off, act, src, out); + } +} + void down(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t n, int n_expert, int64_t work_bound, const uint8_t* h, float* dm, cudaStream_t s) { - const unsigned grid = (unsigned) std::max(1, work_bound * DNFB); + const unsigned grid = (unsigned) std::max(1, work_bound * D_NFB); if (pick_bn(n, n_expert) == 2 * kTileRows) down_kernel<2 * kTileRows><<>>(b, g, ts, tiles, off, h, dm); else down_kernel<<>>(b, g, ts, tiles, off, h, dm); } -void gate_up(const Batch& b, const NativeGeom& g, const int32_t* ts, const int2* tiles, const int32_t* off, int64_t n, - int n_expert, int64_t work_bound, const uint8_t* act, const int32_t* src, uint8_t* out, cudaStream_t s) { - if (pick_bn(n, n_expert) == 2 * kTileRows) launch<2 * kTileRows>(b, g, ts, tiles, off, work_bound, act, src, out, s); - else launch(b, g, ts, tiles, off, work_bound, act, src, out, s); -} - } // namespace strata::prefill::fused::f16kq diff --git a/src/prefill/moe_f16_kq.hpp b/src/prefill/moe_f16_kq.hpp index 28260d8e..c7f80eb1 100644 --- a/src/prefill/moe_f16_kq.hpp +++ b/src/prefill/moe_f16_kq.hpp @@ -1,4 +1,5 @@ -// src/prefill/moe_f16_kq.hpp - gfx11: the K-quant prompt experts on the F16 matrix cores (moe_f16_kq.cu). +// src/prefill/moe_f16_kq.hpp - gfx11: the K-quant prompt experts on the F16 matrix cores (moe_f16_kq.cu; the switch, +// STRATA_PF_F16=1 with STRATA_PF_FUSED_KQ=1, is moe_f16_common.cuh's). // Internal to moe_fused_iq.cu, which owns the native experts' tables and launches. #pragma once @@ -11,9 +12,6 @@ namespace strata::prefill::fused::f16kq { -/// STRATA_PF_F16_KQ=1 (on top of STRATA_PF_FUSED=1 and STRATA_PF_FUSED_KQ=1): Q4_K / Q5_K gate/up and Q5_1 down -/// take these kernels. -bool requested(); /// The gate/up type has a kernel here (and this build has gfx11 device code). bool covers(int gu_type); diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu index 46f8a9a9..f37de7de 100644 --- a/src/prefill/moe_fused_iq.cu +++ b/src/prefill/moe_fused_iq.cu @@ -23,6 +23,7 @@ #include "strata/kernels/gfx_arch.hpp" #if defined(__HIPCC__) +#include "moe_f16_common.cuh" #include "moe_f16_kq.hpp" #endif @@ -978,6 +979,133 @@ native_w11_kernel(const Batch b, const NativeGeom geo, const Tables tb, const ui __builtin_trap(); #endif } + +// STRATA_PF_F16=1 (gfx11): the other native formats on the F16 matrix cores - moe_f16_common.cuh's work item, +// staged activations and epilogues. load_unit / convert decode each sub-block once into the weight tile in LDS (int8 +// codes, the scales as half2), and each wave turns its own 16 rows into F16 before its products. Gate/up rows 0..63 +// are the item's gate rows, 64..127 its up rows; down rows are output rows. The output differs from +// native_w11_kernel's (F16 products instead of int8 dots with float scales). +// gfx1151, IQ3_S / IQ4_NL, 16384 tokens x top 10 over 512 experts, one 128-expert launch (ms, native_w11_kernel -> +// this): gate/up 11.65 -> 9.87, down 6.11 -> 4.71; weights decoded to F16 in LDS (18 KB a block) were 9.83 and 5.71. +template +__global__ void __launch_bounds__(f16::THREADS) +native_f16_kernel(const Batch b, const NativeGeom geo, const Tables tb, const uint8_t* __restrict__ act, + const int32_t* __restrict__ src, uint8_t* __restrict__ out, float* __restrict__ dm) { +#if STRATA_F16_DEVICE + // (moe_fused_iq.cu has its own THREADS and AB: the f16 names are qualified where they collide) + using namespace f16; + constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K + constexpr int NFB = GU ? GU_NFB : D_NFB; + constexpr int RW = raw_words(WT); + constexpr int BS = block_bytes(WT); + constexpr bool K16 = per16(WT); + constexpr int GB = grid_bytes(WT) > 0 ? grid_bytes(WT) : 16; + constexpr int SGN = (WT == T_IQ2_XXS || WT == T_IQ2_XS || WT == T_IQ2_S || WT == T_IQ3_XXS || WT == T_IQ3_S) + ? sign_entries(WT) : 1; + constexpr int WLD8 = 80; // bytes per weight row: 64 int8 codes + 16 (rows 80 bytes apart spread a fragment read) + constexpr int W_BYTES = ROWS * WLD8 + 2 * ROWS * 4; // the codes, then the (s0, s1) half2 per row and sub-block + constexpr int STAGE_BYTES = W_BYTES + ActStage::BYTES; + static_assert(GU_EPI_BYTES <= STAGE_BYTES && D_EPI_BYTES <= STAGE_BYTES, "the epilogues fit the stage"); + __shared__ __align__(16) uint8_t lds[STAGE_BYTES]; + __shared__ __align__(16) uint8_t sgrid[GB]; + __shared__ __align__(16) uint4 ssign[SGN]; + __shared__ int srow[BN]; + uint8_t* s_w = lds; + auto* s_sc = reinterpret_cast(lds + ROWS * WLD8); + auto* s_act = reinterpret_cast(lds + W_BYTES); + const int tid = threadIdx.x, wave = tid >> 5, sub_lane = tid & 15; + + int fb, e, row0, nrows; + if (!work_item(b, tb.ts, tb.tiles, tb.off, blockIdx.x, fb, e, row0, nrows)) return; + if constexpr (grid_bytes(WT) > 0) { + const uint32_t* gs = (const uint32_t*) grid_src(); + for (int i = tid; i < grid_bytes(WT) / 4; i += f16::THREADS) ((uint32_t*) sgrid)[i] = gs[i]; + } + if constexpr (SGN > 1) { + for (int i = tid; i < SGN; i += f16::THREADS) ssign[i] = sign_entry(i, SGN == 128); + } + uint32_t kv[4] = {0, 0, 0, 0}; + if constexpr (WT == T_IQ4_XS || WT == T_IQ4_NL) { +#pragma unroll + for (int k = 0; k < 16; ++k) kv[k >> 2] |= (uint32_t) (uint8_t) kvalues_iq4nl[k] << (8 * (k & 3)); + } + const int live_tiles = (nrows + 15) / 16; + const uint8_t* blob = b.blob[e - b.e0]; + if (tid < BN) srow[tid] = tid < nrows ? (GU ? src[row0 + tid] : row0 + tid) : -1; // tokens; H by routed row + __syncthreads(); + + const int ur = tid >> 1, uj = tid & 1; // this thread's decode unit: weight-tile row ur, sub-block uj of a stage + const uint8_t* wrow = GU ? blob + (ur >= 64 ? geo.up_off : 0) + (size_t) (fb * 64 + (ur & 63)) * geo.gu_row + : blob + geo.down_off + (size_t) (fb * ROWS + ur) * geo.d_row; + const auto unit = [&](int s) -> const uint8_t* { + if (GU) return wrow + (s >> 2) * BS; + return (WT == T_IQ4_NL || WT == T_Q8_0) ? wrow + (2 * s + uj) * BS : wrow + s * BS; + }; + const auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; }; + uint32_t raw[RW]; + ActStage as; + as.init(act, GU ? GU_ACT_LD : H_LD, srow, tid); + const auto fetch_stage = [&](int s) { + load_unit(unit(s), sub(s), raw); + as.fetch(s); + }; + // the sub-block as int8 codes and its scales into the weight tile + const auto commit_stage = [&]() { + uint32_t q[8]; + float s0, s1; + convert(raw, sgrid, kv, q, s0, s1, ssign); + uint4* d = reinterpret_cast(s_w + ur * WLD8 + 32 * uj); + d[0] = make_uint4(q[0], q[1], q[2], q[3]); + d[1] = make_uint4(q[4], q[5], q[6], q[7]); + s_sc[uj * ROWS + ur] = __builtin_bit_cast(uint32_t, __floats2half2_rn(s0, K16 ? s1 : s0)); + as.commit(s_act); + }; + v8f acc[BN / 16]; +#pragma unroll + 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}; + // int8 codes to F16 per wave (gufo's Q8_0 decode): the sign bit flipped carries q + 128, a byte permute makes it + // the mantissa of 1024 (exact), minus 1152 is q, then one packed multiply by the sub-block's scale + const __half2 magic = __floats2half2_rn(-1152.0f, -1152.0f), zero2 = __floats2half2_rn(0.0f, 0.0f); + const auto compute_stage = [&]() { + const int row = wave * 16 + sub_lane; + const uint4* wp = reinterpret_cast(s_w + row * WLD8); +#pragma unroll + for (int kb = 0; kb < 2; ++kb) { + const uint4 c0 = wp[2 * kb], c1 = wp[2 * kb + 1]; + const __half2 sc = __builtin_bit_cast(__half2, s_sc[kb * ROWS + row]); + const __half2 sc0 = __low2half2(sc), sc1 = __high2half2(sc); + const uint32_t words[8] = {c0.x, c0.y, c0.z, c0.w, c1.x, c1.y, c1.z, c1.w}; + uint32_t hw[16]; +#pragma unroll + for (int i = 0; i < 8; ++i) { // values 4i .. 4i + 3 (s0: values 0-15, s1: 16-31) + const uint32_t c = words[i] ^ 0x80808080u; + const uint32_t p0 = __builtin_amdgcn_perm(c, 0x64646464u, 0x01050004u); + const uint32_t p1 = __builtin_amdgcn_perm(c, 0x64646464u, 0x03070206u); + const __half2 s2 = i < 4 ? sc0 : sc1; + hw[2 * i] = __builtin_bit_cast(uint32_t, __hfma2(__hadd2(__builtin_bit_cast(__half2, p0), magic), s2, zero2)); + hw[2 * i + 1] = __builtin_bit_cast(uint32_t, __hfma2(__hadd2(__builtin_bit_cast(__half2, p1), magic), s2, zero2)); + } + v16h a_lo, a_hi; + __builtin_memcpy(&a_lo, &hw[0], 32); + __builtin_memcpy(&a_hi, &hw[8], 32); + mma_tiles(acc, a_lo, a_hi, s_act, kb, sub_lane, live_tiles); + } + }; + fetch_stage(0); + for (int s = 0; s < NS; ++s) { + commit_stage(); + __syncthreads(); + if (s + 1 < NS) fetch_stage(s + 1); + compute_stage(); + __syncthreads(); + } + if constexpr (GU) gu_epilogue(acc, lds, tid, live_tiles, nrows, row0, fb, out); + else down_epilogue(acc, lds, tid, live_tiles, nrows, row0, fb, dm); +#else + (void) b; (void) geo; (void) tb; (void) act; (void) src; (void) out; (void) dm; + __builtin_trap(); +#endif +} #endif // __HIPCC__ unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } @@ -1096,6 +1224,11 @@ bool kq_on() { }(); return on; } +// STRATA_PF_F16=1 (gfx11): the formats native_f16_kernel takes (the K-quants are moe_f16_kq.cu's) +bool f16_gu(int t) { + return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS; +} +bool f16_d(int t) { return t == T_Q2_0 || t == T_IQ4_NL || t == T_Q8_0; } bool gu_covered(int t) { return t == T_IQ2_XXS || t == T_IQ2_XS || t == T_IQ2_S || t == T_IQ3_XXS || t == T_IQ3_S || t == T_IQ4_XS #if defined(__HIPCC__) @@ -1204,9 +1337,28 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n const uint8_t* xa8 = (const uint8_t*) xa; uint8_t* ha8 = (uint8_t*) ha; #define STRATA_NW_GU(T) do { if (occ_gu) native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr); else native_w11_kernel<<>>(b, g, tb, xa8, src, ha8, nullptr); } while (0) - // STRATA_PF_F16_KQ=1: the K-quant gate/up and Q5_1 down on gfx11's F16 matrix cores (moe_f16_kq.cu; gfx12's - // WMMA layout differs, so it keeps the int8 kernels) - if (!d.w12 && f16kq::requested() && f16kq::covers(g.gu_type)) f16kq::gate_up(b, g, tb.ts, tb.tiles, tb.off, n, n_expert, tiles, xa8, src, ha8, s); + // STRATA_PF_F16=1: gfx11's F16 matrix cores - the K-quants' kernels (moe_f16_kq.cu) and native_f16_kernel for + // f16_gu / f16_d (gfx12's WMMA layout differs, so it keeps the int8 kernels) + const bool f16 = !d.w12 && f16::requested(); + const bool f16_wide = f16::pick_bn(n, n_expert) == 2 * kTileRows; +#define STRATA_F16_LAUNCH(T, GU, NFB, ACT, OUT, DM) do { \ + const unsigned grid_f = (unsigned) std::max(1, tiles * (NFB)); \ + if (f16_wide) native_f16_kernel<<>>(b, g, tb, ACT, src, OUT, DM); \ + else native_f16_kernel<<>>(b, g, tb, ACT, src, OUT, DM); \ +} while (0) + if (f16 && f16kq::covers(g.gu_type)) f16kq::gate_up(b, g, tb.ts, tb.tiles, tb.off, n, n_expert, tiles, xa8, src, ha8, s); + else if (f16 && f16_gu(g.gu_type)) { +#define STRATA_F16_GU(T) STRATA_F16_LAUNCH(T, true, f16::GU_NFB, xa8, ha8, nullptr) + switch (g.gu_type) { + case T_IQ2_XXS: STRATA_F16_GU(T_IQ2_XXS); break; + case T_IQ2_XS: STRATA_F16_GU(T_IQ2_XS); break; + case T_IQ2_S: STRATA_F16_GU(T_IQ2_S); break; + case T_IQ3_XXS: STRATA_F16_GU(T_IQ3_XXS); break; + case T_IQ3_S: STRATA_F16_GU(T_IQ3_S); break; + default: STRATA_F16_GU(T_IQ4_XS); break; + } +#undef STRATA_F16_GU + } else switch (g.gu_type) { case T_IQ2_XXS: STRATA_NW_GU(T_IQ2_XXS); break; case T_IQ2_XS: STRATA_NW_GU(T_IQ2_XS); break; @@ -1219,12 +1371,18 @@ void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n } #undef STRATA_NW_GU #define STRATA_NW_D(T) do { if (occ_d) native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); else native_w11_kernel<<>>(b, g, tb, ha8, src, nullptr, dm); } while (0) - if (!d.w12 && f16kq::requested() && f16kq::covers_down(g.d_type)) f16kq::down(b, g, tb.ts, tb.tiles, tb.off, n, n_expert, tiles, ha8, dm, s); + if (f16 && f16kq::covers_down(g.d_type)) f16kq::down(b, g, tb.ts, tb.tiles, tb.off, n, n_expert, tiles, ha8, dm, s); + else if (f16 && f16_d(g.d_type)) { + if (g.d_type == T_Q2_0) STRATA_F16_LAUNCH(T_Q2_0, false, f16::D_NFB, ha8, nullptr, dm); + else if (g.d_type == T_Q8_0) STRATA_F16_LAUNCH(T_Q8_0, false, f16::D_NFB, ha8, nullptr, dm); + else STRATA_F16_LAUNCH(T_IQ4_NL, false, f16::D_NFB, ha8, nullptr, dm); + } else if (g.d_type == T_Q2_0) STRATA_NW_D(T_Q2_0); else if (g.d_type == T_Q5_1) STRATA_NW_D(T_Q5_1); else if (g.d_type == T_Q8_0) STRATA_NW_D(T_Q8_0); else STRATA_NW_D(T_IQ4_NL); #undef STRATA_NW_D +#undef STRATA_F16_LAUNCH ck(cudaGetLastError(), "experts_native"); return; } diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp index 6af2ae97..af6099c1 100644 --- a/tests/cuda/prefill_fused_iq_test.cpp +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -78,6 +78,12 @@ struct Geo { }; // random blocks with a sane fp16 scale `d` at each block's start (every format here begins with it): scales chosen so +// STRATA_PF_F16=1: the covered formats run on F16 weights (moe_f16_kq.cu, native_f16_kernel), not the int8 kernels +bool f16_on() { + const char* v = std::getenv("STRATA_PF_F16"); + return v != nullptr && v[0] == '1'; +} + // that the weights' typical size is that of a 2-3 bit expert (a few hundredths) void fill_matrix(uint8_t* m, ggml_type t, int64_t rows, int64_t cols, std::mt19937& rng) { const size_t bs = ggml_type_size(t), nb = (size_t) rows * (size_t) (cols / ggml_blck_size(t)); @@ -397,11 +403,9 @@ void reference_part(const Pair& p, cudaStream_t s) { const Err e2 = compare(y_f, frow, ref2, pair, (size_t) rows); std::printf(" fused vs the int8-rounded model (same activation / H rounding, double sums): rel RMS %.3e worst %.3e\n", e2.rms, e2.worst); - // STRATA_PF_F16_KQ=1: the K-quant gate/up runs on F16 weights (moe_f16_kq.cu), so H's int8 rounding meets values - // a few F16 ulps from the int8 model's; the FP32 reference checks below stay as they are - const char* f16e = std::getenv("STRATA_PF_F16_KQ"); - const bool f16 = f16e != nullptr && f16e[0] == '1' && (p.gu == GGML_TYPE_Q4_K || p.gu == GGML_TYPE_Q5_K); - if (e2.rms > (f16 ? 5e-3 : 2e-3) || e2.worst > 3e-2) + // STRATA_PF_F16=1: H's int8 rounding meets values a few F16 ulps from the int8 model's (f16_on); the FP32 reference + // checks below stay as they are + if (e2.rms > (f16_on() ? 5e-3 : 2e-3) || e2.worst > 3e-2) throw std::runtime_error(std::string(p.name) + ": the fused path differs from its own arithmetic's model"); if (mq) std::printf(" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", em.rms, em.worst); std::printf(" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n", ef.rms, ef.worst); @@ -631,7 +635,8 @@ void timing_part(const Pair& p, int T, cudaStream_t s) { cudaEventDestroy(b); delete mbp; // the two int8 paths at the real shape, every tile of the layer: R9700 rel RMS 1.3-1.9e-4, worst row 2.9e-3-8.3e-3 - if (mq && !no_mmq && (efm.rms > 1e-3 || efm.worst > 2e-2)) + // (STRATA_PF_F16=1: F16 products against MMQ's int8, gfx1151 rel RMS 2.5-2.7e-3, worst row 6.4e-3-8.8e-3) + if (mq && !no_mmq && (efm.rms > (f16_on() ? 5e-3 : 1e-3) || efm.worst > 2e-2)) throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape"); } } // namespace