From 60445b58c0d3ffe730d78422acff3b502701b294 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Fri, 2 Oct 2026 16:25:57 +0200 Subject: [PATCH] #136: the fused int8 prompt experts for the native IQ packs (gate/up IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL; opt-in STRATA_PF_FUSED=1) src/prefill/moe_fused_iq.cu: the Q2_0 path's design (moe_fused.cu: the grouping on the GPU, a pointer per expert - cache slot or ring slot, no gather -, SwiGLU and H's int8 rounding in the gate/up epilogue) for the raw GGUF blobs of the native packs. The load stage decodes the i-quant blocks to int8 in shared memory (llama.cpp's codebooks and sign tables, held in shared memory; a 32-value sub-block per thread per 64 values of K, read one stage ahead with 16-bit loads and two 256-value blocks ahead into L2), with each sub-block's scale (per 16 values for IQ2_XS / IQ2_S, which multiply at m16n8k16). The activations are int8 per 32 values in natural order (quantize_act_native); fragments by ldmatrix; the magic bias 1.5 * 2^23 enters as the mma's C, so a dot becomes a float with one add. A work item is 256 weight rows x 64 routed rows, or 128 x 128 when the experts have 56-112 rows each (STRATA_PF_FUSED_TILE=64|128). Wiring (prefill.cpp): a native layer takes these kernels when both its formats are covered, else MMQ (IQ1_M keeps the FP16 path); the 512-slot ring of the fused path now also for a native pack with such layers. sm_75, HIP and the default (no variable) are unchanged: on IQ2_XS, IQ3_XXS and IQ3_S the default output is 0.1.35's (256/256 greedy tokens, 4K and 32K). tests/cuda/prefill_fused_iq_test (exit 77 below sm_80), RTX 5070, 256 tokens x 64 experts against a double-precision reference from ggml's to_float, rel RMS / worst row - MMQ and fused equal to four digits: IQ2_S/Q2_0 1.489e-2 / 2.93e-2 (fused vs MMQ 2.6e-4), IQ2_XXS/Q2_0 1.464e-2 / 2.96e-2 (1.9e-4), IQ2_XS/IQ4_NL 1.465e-2 / 2.41e-2 (3.5e-5), IQ3_XXS/IQ4_NL 1.458e-2 / 2.73e-2 (1.6e-4), IQ3_S/IQ4_NL 1.470e-2 / 2.65e-2 (6.5e-5), IQ4_XS/Q2_0 1.446e-2 / 2.72e-2 (4.4e-5); both tile shapes. One layer (512 experts, top 10), ms, MMQ path -> fused at 2048 / 3584 / 8192 tokens: IQ2_S 10.5 -> 5.2, 12.5 -> 9.3, 21.4 -> 17.5; IQ2_XXS 8.8 -> 4.2, 10.7 -> 7.6, 17.9 -> 13.6; IQ3_S 10.6 -> 5.6, 12.3 -> 8.8, 19.8 -> 18.4; IQ3_XXS 10.2 -> 5.1, 11.9 -> 8.3, 19.1 -> 16.5. MMQ's products alone (no gathers) at 3584 / 8192: IQ2_S 8.9 / 17.9, IQ3_S 8.1 / 15.6: the kernels are about even with MMQ's, the gain is the path around them. (The test syncs the device after its uploads: a cudaMemcpy from pageable memory on the legacy stream can still be queued on Windows while a non-blocking stream runs - the grouping then read zeroed ids, every pair on expert 0. prefill_fused_moe_test's timing part has the same pattern.) End to end, RTX 5070, speed_135.py's settings, greedy, A (MMQ) / B (STRATA_PF_FUSED=1) alternating, 2 pairs, prompt tok/s: IQ2_XS 4K 1,228 -> 1,378 (+12%; a cold first A run of 590 left out), 32K 2,107 -> 2,170 (+3.0%); IQ3_XXS 4K 1,001 -> 1,020 (+1.8%), 32K 1,745 -> 1,739 (-0.4%); IQ3_S 4K 927 -> 925 (-0.2%), 32K 1,382 -> 1,362 (-1.4%). The IQ3 packs' prompts here wait on the host copies of their unpinned experts (IQ3_XXS 4K: 5,062 of 22,573 streamed, ~3.0 s of 3.4 s), so faster kernels change little. Each arm repeats itself (256/256; IQ3_XXS 32K B and IQ3_S 32K A split at 162 / 223, the decode's timing); A vs B greedy agreement, identical prefix of 256: IQ2_XS 204 / 88, IQ3_XXS 182 / 89, IQ3_S 31 / 256. --- CMakeLists.txt | 9 +- include/strata/prefill/moe_fused_iq.hpp | 41 ++ src/prefill/moe_fused_iq.cu | 630 +++++++++++++++++++++++ src/prefill/prefill.cpp | 41 +- tests/cuda/prefill_fused_iq_test.cpp | 633 ++++++++++++++++++++++++ 5 files changed, 1345 insertions(+), 9 deletions(-) create mode 100644 include/strata/prefill/moe_fused_iq.hpp create mode 100644 src/prefill/moe_fused_iq.cu create mode 100644 tests/cuda/prefill_fused_iq_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index cf98e508..df5f9354 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -870,8 +870,8 @@ if(STRATA_NATIVE_EXPERTS) set(_strata_mmq ${_strata_gg}/src/ggml-cuda) # #136: the Q2_0 pack's prompt experts on Strata's own int8 kernels (moe_fused.cu, opt-in STRATA_PF_FUSED=1; CUDA # only: the HIP branch below keeps MMQ, and an sm_75 device or an sm_75-only build reports them unavailable) - add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/ggml_cuda_host.cu - ${_strata_mmq}/quantize.cu) + add_library(strata_mmq STATIC src/prefill/moe_mmq.cu src/prefill/moe_fused.cu src/prefill/moe_fused_iq.cu + src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu) # q8_0: the drafter's matrices (E-9); STRATA_ORCA_Q4KS_MMQ adds q5_0 (#296, in _strata_mmq_types), and # STRATA_MMQ_KQUANTS q4_k q5_k q5_1, the experts of Unsloth's UD-Q4_K_XL (docs/UNSLOTH_Q4.md; the dispatch # follows eddoursul/Strata 7706c1b) @@ -903,6 +903,11 @@ if(STRATA_NATIVE_EXPERTS) target_link_libraries(prefill_fused_moe_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) add_test(NAME prefill_fused_moe_test COMMAND prefill_fused_moe_test) set_tests_properties(prefill_fused_moe_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 300) + # #136: the same for the native packs' formats (IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL) + add_executable(prefill_fused_iq_test tests/cuda/prefill_fused_iq_test.cpp) + target_link_libraries(prefill_fused_iq_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_fused_iq_test COMMAND prefill_fused_iq_test) + set_tests_properties(prefill_fused_iq_test PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 600) endif() if(STRATA_BUILD_TESTS AND STRATA_MMQ_KQUANTS) # the UD-Q4_K_XL expert formats through MMQ against ggml's dequantized weights (synthetic, a few seconds) diff --git a/include/strata/prefill/moe_fused_iq.hpp b/include/strata/prefill/moe_fused_iq.hpp new file mode 100644 index 00000000..7c9e3282 --- /dev/null +++ b/include/strata/prefill/moe_fused_iq.hpp @@ -0,0 +1,41 @@ +// include/strata/prefill/moe_fused_iq.hpp - #136: the fused int8 prompt experts (moe_fused.hpp) for the native GGUF +// packs (tools/iq_pack.py: an expert is its raw GGUF slices [gate rows | up rows | down rows], formats per layer in +// expert_layout().fmt), opt-in with the same STRATA_PF_FUSED=1 (NVIDIA sm_80 and newer; sm_75 and HIP: MMQ). +// +// The grouping on the GPU (fused::group), the per-expert pointers (fused::Batch: a cache slot or a ring slot, no +// gather) and the launch shape are the Q2_0 path's. What differs is the load stage: the i-quant blocks are decoded to +// int8 in shared memory before the mma (codebook and sign lookups, as llama.cpp's MMQ load_tiles does), with the +// block's scale per 32 (or per 16: IQ2_XS, IQ2_S, multiplied at m16n8k16) beside them. The activations and H are +// int8 per 32 values in their natural order here (quantize_act_native), not the Q2_0 path's permuted one. +// +// Covered: gate/up IQ2_XXS, IQ2_XS, IQ2_S, IQ3_XXS, IQ3_S, IQ4_XS; down Q2_0, IQ4_NL - every layer of the IQ2_XS, +// IQ3_XXS and IQ3_S packs but the IQ1_M ones (which MMQ does not cover either). Other layers keep MMQ. +#pragma once + +#include "strata/prefill/moe_fused.hpp" + +#include +#include + +namespace strata::prefill::fused { + +/// One layer's native expert geometry (cpu::NativeFmt's fields the kernels read; n_embd 2560, n_ff 640). +struct NativeGeom { + int gu_type = -1, d_type = -1; ///< ggml types + size_t gu_row = 0, d_row = 0; ///< bytes per gate/up row and per down row + size_t up_off = 0, down_off = 0; ///< inside the blob +}; + +/// enabled() (STRATA_PF_FUSED=1 on sm_80+), and the kernels cover this gate/up and down pair on this device. +bool native_supported(int gu_type, int d_type); + +/// x [rows][cols] FP32 -> `xa` (act_bytes(rows, cols)): int8 per 32 values in natural order, the native kernels' form. +void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, void* stream); + +/// experts() for native blobs: b.blob[e - e0] is the native blob of expert e (gate at 0, up at g.up_off, down at +/// g.down_off; 2-byte aligned). `xa` from quantize_act_native; H in `ha` (act_bytes(n, 640)); down into `dm` at the +/// rows of `group`. +void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, + const int32_t* src, void* ha, float* dm, void* stream); + +} // namespace strata::prefill::fused diff --git a/src/prefill/moe_fused_iq.cu b/src/prefill/moe_fused_iq.cu new file mode 100644 index 00000000..6a77feb0 --- /dev/null +++ b/src/prefill/moe_fused_iq.cu @@ -0,0 +1,630 @@ +// src/prefill/moe_fused_iq.cu - see include/strata/prefill/moe_fused_iq.hpp (#136: the native packs' prompt experts on +// the fused int8 kernels of moe_fused.cu). +// +// The arithmetic. An activation block of 32 values is x = d_x * a, a = round(x / d_x) in -127..127, stored in natural +// order (per 64 values: 64 codes, then {d_0, d_1} and 8 unused bytes - 80 bytes, the Q2_0 path's size). A weight +// block of 32 (or 16) values is w = d_w * q with q an int8: the i-quants' codebook entries with their signs applied +// (IQ2_XXS / IQ2_XS / IQ2_S: 0..43, IQ3_XXS: 0..62, IQ3_S: 0..15, IQ4_XS / IQ4_NL: -127..113), Q2_0's code - 1. So +// sum w x = d_w * d_x * sum q a, |sum q a| <= 32 * 127 * 127 < 2^22, +// and the int32 dot becomes a float exactly with one float add: the mma starts from C = 0x4B400000 (the bits of +// 1.5 * 2^23), so as_float(D) - 1.5 * 2^23 is the dot. Per output and 32 values: that add, d_w * d_x, one fma (the +// formats with a scale per 16 values: two dots, each times its d_w, then d_x). d_w is llama.cpp's own: IQ2_XXS +// d (2s + 1) / 8, IQ2_XS / IQ2_S d (2s + 1) / 8 per 16, IQ3_XXS d (2s + 1) / 4, IQ3_S d (2s + 1), IQ4_XS d (s - 32), +// IQ4_NL and Q2_0 d (dequantize_row_* in ggml-quants.c, mmq-load-tiles.cuh). +// +// The load stage. Per 64 values of K (a stage), a thread decodes one 32-value sub-block of one of the work item's +// weight rows: its block bytes are read from the blob with 16-bit loads (the GGUF blocks are 2-byte aligned: 66 / 74 / +// 82 / 98 / 110 / 136 / 18 bytes) one stage ahead into registers (and two 256-value blocks ahead into L2), then turned +// into 32 int8 and the sub-block's scales in shared memory, double-buffered. The codebooks live in shared memory (up +// to 8 KB, IQ2_S). The activations arrive by cp.async, four stages deep, as in moe_fused.cu; the fragments come by +// ldmatrix. The products are mma.sync m16n8k32 (m16n8k16 for the formats with a scale per 16 values); the epilogues +// (SwiGLU, H to int8 per 32 features; down into the per-slot rows) are moe_fused.cu's. +#include "strata/prefill/moe_fused_iq.hpp" + +#include +#include + +#include "ggml.h" + +#define GGML_COMMON_DECL_CUDA +#define GGML_COMMON_IMPL_CUDA +#include "ggml-common.h" + +#include +#include +#include +#include + +namespace strata::prefill::fused { +namespace { + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) { + std::fprintf(stderr, "prefill fused experts (native): %s: %s\n", what, cudaGetErrorString(e)); + std::exit(1); + } +} + +constexpr int AB = 80; // activation bytes per 64 values: 64 codes, {d0, d1}, 8 unused +constexpr int MAGIC = 0x4B400000; // the bits of 1.5 * 2^23 +constexpr float MAGICF = 12582912.0f; +// 16 warps, each 64 weight rows x 16 routed rows; WW of them along the weight rows and 16 / WW along the routed rows: a +// work item is (WR = 64 WW weight rows) x (TR = 256 / WW routed rows of one expert) - 256 x 64 or 128 x 128, chosen +// per launch by the rows per expert (pick_ww) +constexpr int THREADS = 512; +constexpr int WLD = 80; // bytes per decoded weight row of a stage: 64 int8 + 16 (no bank conflicts) +__host__ __device__ constexpr int tile_rows(int ww) { return 256 / ww; } +__host__ __device__ constexpr int weight_rows(int ww) { return 64 * ww; } +constexpr int ASTAGES = 4; // cp.async depth of the activations (64 values of K a stage) +constexpr int GU_ROWS_K = 2560, D_ROWS_K = 640; // K of gate/up (n_embd) and of down (n_ff) + +// the formats (ggml type ids) +constexpr int T_IQ2_XXS = GGML_TYPE_IQ2_XXS, T_IQ2_XS = GGML_TYPE_IQ2_XS, T_IQ2_S = GGML_TYPE_IQ2_S, + T_IQ3_XXS = GGML_TYPE_IQ3_XXS, T_IQ3_S = GGML_TYPE_IQ3_S, T_IQ4_XS = GGML_TYPE_IQ4_XS, + T_IQ4_NL = GGML_TYPE_IQ4_NL, T_Q2_0 = GGML_TYPE_Q2_0; +static_assert(sizeof(block_iq2_xxs) == 66 && sizeof(block_iq2_xs) == 74 && sizeof(block_iq2_s) == 82 && + sizeof(block_iq3_xxs) == 98 && sizeof(block_iq3_s) == 110 && sizeof(block_iq4_xs) == 136 && + sizeof(block_iq4_nl) == 18 && sizeof(block_q2_0) == 18, "the block layouts this file decodes"); + +// block bytes, scale per 16 values, codebook bytes in shared memory +__host__ __device__ constexpr int block_bytes(int t) { + return t == T_IQ2_XXS ? 66 : t == T_IQ2_XS ? 74 : t == T_IQ2_S ? 82 : t == T_IQ3_XXS ? 98 : t == T_IQ3_S ? 110 + : t == T_IQ4_XS ? 136 : 18; +} +__host__ __device__ constexpr bool per16(int t) { return t == T_IQ2_XS || t == T_IQ2_S; } +__host__ __device__ constexpr int grid_bytes(int t) { + return t == T_IQ2_XXS ? 256 * 8 : t == T_IQ2_XS ? 512 * 8 : t == T_IQ2_S ? 1024 * 8 : t == T_IQ3_XXS ? 256 * 4 + : t == T_IQ3_S ? 512 * 4 : 0; +} +__host__ __device__ constexpr size_t smem_bytes(int t, int ww) { + return (size_t) 2 * weight_rows(ww) * (WLD + 16) + (size_t) ASTAGES * tile_rows(ww) * AB + + (size_t) tile_rows(ww) * 4 + grid_bytes(t); +} + +// moe_fused.cu's grouping tables (the same layout: fused::group writes them) +struct Tables { + int32_t *cnt, *off, *fill, *ts; + int2* tiles; +}; +size_t tiles_at(int n_expert) { return ((size_t) (4 * n_expert + 2) * 4 + 15) / 16 * 16; } +Tables tables(void* scratch, int n_expert) { + int32_t* p = (int32_t*) scratch; + return {p, p + n_expert, p + 2 * n_expert + 1, p + 3 * n_expert + 1, + (int2*) ((uint8_t*) scratch + tiles_at(n_expert))}; +} + +// ---- activations in natural order: one warp per 64 values +__global__ void quant_act_nat_kernel(const float* __restrict__ x, int64_t nblk, uint8_t* __restrict__ xa) { + const int64_t w = (int64_t) blockIdx.x * (blockDim.x / 32) + threadIdx.x / 32; + const int lane = threadIdx.x & 31; + if (w >= nblk) return; + const float v0 = x[w * 64 + lane], v1 = x[w * 64 + 32 + lane]; + float a0 = fabsf(v0), a1 = fabsf(v1); +#pragma unroll + for (int o = 16; o > 0; o >>= 1) { + a0 = fmaxf(a0, __shfl_xor_sync(0xffffffffu, a0, o)); + a1 = fmaxf(a1, __shfl_xor_sync(0xffffffffu, a1, o)); + } + uint8_t* out = xa + w * AB; + out[lane] = (uint8_t) (int8_t) (a0 > 0.0f ? __float2int_rn(v0 * (127.0f / a0)) : 0); + out[32 + lane] = (uint8_t) (int8_t) (a1 > 0.0f ? __float2int_rn(v1 * (127.0f / a1)) : 0); + if (lane == 0) *(float4*) (out + 64) = make_float4(a0 / 127.0f, a1 / 127.0f, 0.0f, 0.0f); +} + +#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 +__device__ __forceinline__ void cp16(void* dst, const void* src) { + asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(dst)), + "l"(src)); +} +__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;\n" ::); } +__device__ __forceinline__ void pf_l2(const void* p) { asm volatile("prefetch.global.L2 [%0];\n" ::"l"(p)); } +template __device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;\n" ::"n"(N)); } +// d = MAGIC + A (16 x 32 s8, row) * B (32 x 8 s8, col): the int32 dot with the magic bias already added (the C +// operand), so as_float(d) - 1.5 * 2^23 is the dot as a float +__device__ __forceinline__ void mma32(int (&d)[4], const uint32_t (&a)[4], uint32_t b0, uint32_t b1) { + asm("mma.sync.aligned.m16n8k32.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%10,%10,%10,%10};\n" + : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3]) + : "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b0), "r"(b1), "r"(MAGIC)); +} +// the same at m16n8k16 (A 16 x 16, B 16 x 8) +__device__ __forceinline__ void mma16(int (&d)[4], uint32_t a0, uint32_t a1, uint32_t b0) { + asm("mma.sync.aligned.m16n8k16.row.col.s32.s8.s8.s32 {%0,%1,%2,%3}, {%4,%5}, {%6}, {%7,%7,%7,%7};\n" + : "=r"(d[0]), "=r"(d[1]), "=r"(d[2]), "=r"(d[3]) + : "r"(a0), "r"(a1), "r"(b0), "r"(MAGIC)); +} +__device__ __forceinline__ float dotf(int d) { return __int_as_float(d) - MAGICF; } +// four 8 x 16-byte matrices, row addresses from lanes 0-7, 8-15, 16-23, 24-31: lane (g, t) gets bytes 4t..4t+3 of row g +// of each - an mma fragment +__device__ __forceinline__ void ldsm4(uint32_t (&r)[4], const void* p) { + asm volatile("ldmatrix.sync.aligned.m8n8.x4.shared.b16 {%0,%1,%2,%3}, [%4];\n" + : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]) + : "r"((unsigned) __cvta_generic_to_shared(p)) + : "memory"); +} + +// ---- the load stage: a 32-value sub-block's bytes into registers, then int8 and scales +__device__ __forceinline__ uint32_t ld16(const uint8_t* p) { return *(const uint16_t*) p; } +__device__ __forceinline__ uint32_t ld32(const uint8_t* p) { return ld16(p) | (ld16(p + 2) << 16); } +__device__ __forceinline__ float half_at(uint32_t w) { return __half2float(__ushort_as_half((unsigned short) w)); } +// llama.cpp's sign unpacking: 7 bits of signs, the 8th their parity (bit 7 of v may be anything) +__device__ __forceinline__ uint32_t unpack_ksigns(uint32_t v) { + v &= 0xFF; + const uint32_t p = __popc(v) & 1; + return (v ^ p << 7) * 0x01010101u; +} +// 8 bytes of a codebook entry with the sign byte `s` (broadcast) applied: bits 0-3 to .x, 4-7 to .y +__device__ __forceinline__ void signed8(uint32_t gx, uint32_t gy, uint32_t s, uint32_t& qx, uint32_t& qy) { + const uint32_t m0 = __vcmpne4(s & 0x08040201u, 0), m1 = __vcmpne4(s & 0x80402010u, 0); + qx = __vsub4(gx ^ m0, m0); + qy = __vsub4(gy ^ m1, m1); +} +// 8 nibbles of q4 through a 16-entry int8 table (4 words): the low nibbles' values in .x, the high ones' in .y +__device__ __forceinline__ void table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) { + uint32_t tmp[2]; + const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1); +#pragma unroll + for (int i = 0; i < 2; ++i) { + const uint32_t sh = 16 * i; + const uint32_t l = __byte_perm(t[0], t[1], q4 >> sh), h = __byte_perm(t[2], t[3], q4 >> sh); + tmp[i] = __byte_perm(l, h, sel >> sh); + } + lo = __byte_perm(tmp[0], tmp[1], 0x6420); + hi = __byte_perm(tmp[0], tmp[1], 0x7531); +} + +// Raw bytes of sub-block `ib` of the block at `bp` (IQ: the 256-value super-block, ib 0..7; Q2_0: the 64-value block, +// ib 0..1; IQ4_NL: the 32-value block). +template __device__ __forceinline__ void load_unit(const uint8_t* bp, int ib, uint32_t (&w)[5]) { + if constexpr (T == T_IQ2_XXS) { + w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); + } else if constexpr (T == T_IQ2_XS) { + w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16); + } else if constexpr (T == T_IQ2_S) { + w[0] = ld32(bp + 2 + 4 * ib); w[1] = ld32(bp + 34 + 4 * ib); + w[2] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) bp[74 + ib] << 24); + } else if constexpr (T == T_IQ3_XXS) { + w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 66 + 4 * ib); w[3] = ld16(bp); + } else if constexpr (T == T_IQ3_S) { + w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld32(bp + 74 + 4 * ib); + w[3] = ld16(bp) | ((uint32_t) bp[66 + ib] << 16) | ((uint32_t) ((bp[106 + ib / 2] >> (4 * (ib & 1))) & 15) << 24); + } else if constexpr (T == T_IQ4_XS) { +#pragma unroll + for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 8 + 16 * ib + 4 * k); + const uint32_t ls = ((bp[4 + ib / 2] >> (4 * (ib & 1))) & 15) | (((ld16(bp + 2) >> (2 * ib)) & 3) << 4); + w[4] = ld16(bp) | (ls << 16); + } else if constexpr (T == T_IQ4_NL) { +#pragma unroll + for (int k = 0; k < 4; ++k) w[k] = ld32(bp + 2 + 4 * k); + w[4] = ld16(bp); + } else { // Q2_0 + w[0] = ld32(bp + 2 + 8 * ib); w[1] = ld32(bp + 6 + 8 * ib); w[2] = ld16(bp); + } +} + +// The sub-block as 32 int8 (q[0..7], natural order) and its scales (s0: values 0-15, s1: 16-31). +template +__device__ __forceinline__ void convert(const uint32_t (&w)[5], const uint8_t* grid, const uint32_t (&kv)[4], + uint32_t (&q)[8], float& s0, float& s1) { + if constexpr (T == T_IQ2_XXS) { + const uint2* g = (const uint2*) grid; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint2 e = g[(w[0] >> (8 * l)) & 255]; + signed8(e.x, e.y, unpack_ksigns(w[1] >> (7 * l)), q[2 * l], q[2 * l + 1]); + } + s0 = s1 = half_at(w[2]) * (float) ((w[1] >> 27) | 1) * 0.125f; + } else if constexpr (T == T_IQ2_XS) { + const uint2* g = (const uint2*) grid; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF; + const uint2 e = g[c & 511]; + signed8(e.x, e.y, unpack_ksigns(c >> 9), q[2 * l], q[2 * l + 1]); + } + const float d = half_at(w[2]); + const uint32_t sc = w[2] >> 16; + s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f; + s1 = d * (float) (2 * ((sc >> 4) & 15) + 1) * 0.125f; + } else if constexpr (T == T_IQ2_S) { + const uint2* g = (const uint2*) grid; + const uint32_t qh = (w[2] >> 16) & 255; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint2 e = g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)]; + signed8(e.x, e.y, ((w[1] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); + } + const float d = half_at(w[2]); + const uint32_t sc = w[2] >> 24; + s0 = d * (float) (2 * (sc & 15) + 1) * 0.125f; + s1 = d * (float) (2 * (sc >> 4) + 1) * 0.125f; + } else if constexpr (T == T_IQ3_XXS) { + const uint32_t* g = (const uint32_t*) grid; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; + signed8(g[i0], g[i1], unpack_ksigns(w[2] >> (7 * l)), q[2 * l], q[2 * l + 1]); + } + s0 = s1 = half_at(w[3]) * (float) (2 * (w[2] >> 28) + 1) * 0.25f; + } else if constexpr (T == T_IQ3_S) { + const uint32_t* g = (const uint32_t*) grid; + const uint32_t qh = (w[3] >> 16) & 255; +#pragma unroll + for (int l = 0; l < 4; ++l) { + const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255; + signed8(g[i0 | ((qh << (8 - 2 * l)) & 256)], g[i1 | ((qh << (7 - 2 * l)) & 256)], + ((w[2] >> (8 * l)) & 255) * 0x01010101u, q[2 * l], q[2 * l + 1]); + } + s0 = s1 = half_at(w[3]) * (float) (1 + 2 * (w[3] >> 24)); + } else if constexpr (T == T_IQ4_XS || T == T_IQ4_NL) { +#pragma unroll + for (int k = 0; k < 4; ++k) table16(w[k], kv, q[k], q[4 + k]); + s0 = s1 = T == T_IQ4_XS ? half_at(w[4]) * (float) ((int) (w[4] >> 16) - 32) : half_at(w[4]); + } else { // Q2_0: code - 1 via a byte table {-1, 0, 1, 2} +#pragma unroll + for (int h = 0; h < 4; ++h) { + const uint32_t c = (w[h >> 1] >> (16 * (h & 1))) & 0xFFFF; + const uint32_t qe = __byte_perm(0x020100FFu, 0x020100FFu, c & 0x7777); + const uint32_t qo = __byte_perm(0x020100FFu, 0x020100FFu, (c >> 2) & 0x7777); + q[2 * h] = __byte_perm(qe, qo, 0x5140); + q[2 * h + 1] = __byte_perm(qe, qo, 0x7362); + } + s0 = s1 = half_at(w[2]); + } +} + +template __device__ __forceinline__ const void* grid_src() { + if constexpr (T == T_IQ2_XXS) return iq2xxs_grid; + else if constexpr (T == T_IQ2_XS) return iq2xs_grid; + else if constexpr (T == T_IQ2_S) return iq2s_grid; + else if constexpr (T == T_IQ3_XXS) return iq3xxs_grid; + else if constexpr (T == T_IQ3_S) return iq3s_grid; + else return nullptr; +} +#endif + +// One work item = (TR routed rows of expert e - one or two of group()'s 64-row tiles -, a block of WR weight rows); +// a persistent grid walks the batch's items. GU: gate/up rows of WR / 2 features (format WT) against the rows' +// tokens' activations, SwiGLU, H to int8 per 32 features into `out`. !GU: down rows (format WT) against H, FP32 into +// `dm`. Warp (wf, wt): weight rows 64 wf.. as four m16 tiles (GU: a tile = 8 features, gate rows as mma rows 0-7 and +// up rows as 8-15, so a lane holds gate and up of one feature), routed rows 16 wt.. as two n8. +template +__global__ void __launch_bounds__(THREADS, 1) +native_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 defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 + constexpr int TR = tile_rows(WW), WR = weight_rows(WW); + constexpr int WT_BYTES = WR * WLD, WS_FLOATS = WR * 4, ACT_STAGE = TR * AB; + constexpr int NS = (GU ? GU_ROWS_K : D_ROWS_K) / 64; // 64-value stages along K + constexpr int NFB = (GU ? 1280 : 2560) / WR; // weight-row blocks per tile + constexpr int ACT_LD = NS * AB; // bytes per activation row: 3200 (a token), 800 (a row's H) + constexpr int BS = block_bytes(WT); + constexpr bool K16 = per16(WT); + extern __shared__ __align__(16) uint8_t smem[]; + uint8_t* wt = smem; // [2][WR][WLD] decoded int8 weights + float* ws = (float*) (smem + 2 * WT_BYTES); // [2][WR][4] their scales per 16 values + uint8_t* stages = (uint8_t*) (ws + 2 * WS_FLOATS); // [ASTAGES][TR][AB] activations + int* srow = (int*) (stages + ASTAGES * ACT_STAGE); // [TR] the activation row of each tile row + uint8_t* sgrid = (uint8_t*) (srow + TR); // the codebook + + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5, g = lane >> 2, tig = lane & 3; + const int wf = warp % WW, nb0 = 16 * (warp / WW); + 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 += THREADS) ((uint32_t*) sgrid)[i] = gs[i]; + } + 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)); + } + // Local weight rows: m tile i of warp wf is rows 64 wf + 16 i.. (mma rows g and g + 8: rows +g and +8+g). For + // gate/up a tile is 8 features, its gate rows then its up rows, so a lane holds gate and up of one feature. The + // fragments come by ldmatrix: lane l gives the address of row (l & 7) of matrix l >> 3 - A: {rows 0-7, rows 8-15} + // x {bytes 0-15, 16-31} of a 32-value chunk; B: {tokens nb0 + 0-7, + 8-15} x {bytes 0-15, 16-31}. + const int lm = lane >> 3, l8 = lane & 7; + const int a_off = (64 * wf + 8 * (lm & 1) + l8) * WLD + 16 * (lm >> 1); + const int b_off = (nb0 + 8 * (lm >> 1) + l8) * AB + 16 * (lm & 1); + // this thread's decode unit (the first 2 WR threads): local weight row ur, sub-block uj of each stage + const bool dec = tid < 2 * WR; + const int ur = dec ? tid >> 1 : 0, uj = tid & 1; + const int t0 = tb.ts[b.e0], nwork = (tb.ts[b.e1] - t0) * NFB; + for (int w = blockIdx.x; w < nwork; w += gridDim.x) { + const int2 tl = tb.tiles[t0 + w / NFB]; + const int fb = w % NFB, e = tl.x, row0 = tl.y; + if ((row0 - tb.off[e]) % TR != 0) continue; // a 64-row tile inside an earlier item's TR rows + const int nrows = min(TR, tb.off[e + 1] - row0); + const uint8_t* blob = b.blob[e - b.e0]; + const int rbase = fb * WR; + // local row ur: gate/up - feature (WR / 2) fb + 8 (ur >> 4) + (ur & 7), its up row when bit 3 is set + const uint8_t* wrow = GU ? blob + ((ur & 8) ? geo.up_off : 0) + + (size_t) (fb * (WR / 2) + 8 * (ur >> 4) + (ur & 7)) * geo.gu_row + : blob + geo.down_off + (size_t) (rbase + ur) * geo.d_row; + auto unit = [&](int s) -> const uint8_t* { // the block of stage s's sub-block + if (GU) return wrow + (s >> 2) * BS; + return WT == T_IQ4_NL ? wrow + (2 * s + uj) * BS : wrow + s * BS; + }; + auto sub = [&](int s) { return GU ? 2 * (s & 3) + uj : uj; }; + // the weight bytes into L2 ahead of the register loads (one stage ahead only - less than a DRAM round trip): + // gate/up PF super-blocks ahead (the row's two threads take a block's first and last line), down the whole row + // slice at once (180 or 360 bytes a row) + constexpr int PF = 2; + auto prefetch_sb = [&](int sb) { + if (dec && sb < GU_ROWS_K / 256) pf_l2(wrow + sb * BS + (uj ? BS - 1 : 0)); + }; + if (GU) { +#pragma unroll + for (int sb = 0; sb < PF; ++sb) prefetch_sb(sb); + } else if (dec) { + for (size_t o = 128 * (size_t) uj; o < geo.d_row + 127; o += 256) pf_l2(wrow + min(o, geo.d_row - 1)); + } + __syncthreads(); // the previous item is done with the buffers + if (tid < TR) srow[tid] = tid < nrows ? (GU ? src[row0 + tid] : row0 + tid) : -1; + __syncthreads(); // srow + // the rows past the item's end are not loaded: a warp entirely past it skips the products, and the columns + // of a partial one are never written (no reduction mixes columns) + auto load_act = [&](int s) { + uint8_t* st = stages + (s % ASTAGES) * ACT_STAGE; + for (int c = tid; c < TR * 5; c += THREADS) { + const int r = c / 5, q = c % 5; + if (r < nrows) cp16(st + r * AB + q * 16, act + (size_t) srow[r] * ACT_LD + s * AB + q * 16); + } + }; + auto put = [&](const uint32_t (&raw)[5], int buf) { + if (!dec) return; + uint32_t q[8]; + float s0, s1; + convert(raw, sgrid, kv, q, s0, s1); + uint4* d = (uint4*) (wt + buf * WT_BYTES + ur * WLD + 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]); + *(float2*) (ws + buf * WS_FLOATS + ur * 4 + 2 * uj) = make_float2(s0, s1); + }; +#pragma unroll + for (int s = 0; s < ASTAGES - 1; ++s) { + if (s < NS) load_act(s); + cp_commit(); + } + uint32_t raw[5] = {0, 0, 0, 0, 0}; + if (dec) load_unit(unit(0), sub(0), raw); + put(raw, 0); + if (dec) load_unit(unit(1), sub(1), raw); + // a warp whose rows are all past the tile's end only takes part in the loads + const bool on0 = nb0 < nrows, on1 = nb0 + 8 < nrows; + float acc[4][2][4]; +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int n = 0; n < 2; ++n) +#pragma unroll + for (int q = 0; q < 4; ++q) acc[i][n][q] = 0.0f; + for (int s = 0; s < NS; ++s) { + cp_wait(); + __syncthreads(); + if (s + ASTAGES - 1 < NS) load_act(s + ASTAGES - 1); + cp_commit(); + if (GU && (s & 3) == 0) prefetch_sb((s >> 2) + PF); + if (on0) { + const uint8_t* W = wt + (s & 1) * WT_BYTES; + const float* S = ws + (s & 1) * WS_FLOATS; + const uint8_t* sa = stages + (s % ASTAGES) * ACT_STAGE; + // the stage's scales: per weight row 4 (per 16 values), per routed row 2 (per 32) + float2 dx[2][2]; // [n8 tile][column 2 tig + cc] +#pragma unroll + for (int n = 0; n < 2; ++n) +#pragma unroll + for (int cc = 0; cc < 2; ++cc) dx[n][cc] = *(const float2*) (sa + (nb0 + 8 * n + 2 * tig + cc) * AB + 64); +#pragma unroll + for (int h = 0; h < 2; ++h) { // the stage's two 32-value halves + uint32_t bq[4]; // {n0 bytes 0-15, n0 16-31, n1 0-15, n1 16-31} + ldsm4(bq, sa + b_off + 32 * h); +#pragma unroll + for (int i = 0; i < 4; ++i) { + uint32_t a[4]; // {rows g, g + 8} x {bytes 0-15, 16-31} + ldsm4(a, W + a_off + 16 * i * WLD + 32 * h); + const float2 swa = *(const float2*) (S + (64 * wf + 16 * i + g) * 4 + 2 * h); + const float2 swb = *(const float2*) (S + (64 * wf + 16 * i + 8 + g) * 4 + 2 * h); + const float wa0 = swa.x, wa1 = swa.y, wb0 = swb.x, wb1 = swb.y; +#pragma unroll + for (int n = 0; n < 2; ++n) { + if (n == 1 && !on1) break; + if constexpr (K16) { + // a scale per 16 weights: the two halves' dots, each times its scale, then d_x + int d0[4], d1[4]; + mma16(d0, a[0], a[1], bq[2 * n]); + mma16(d1, a[2], a[3], bq[2 * n + 1]); +#pragma unroll + for (int q = 0; q < 4; ++q) { + const float v = fmaf(q < 2 ? wa1 : wb1, dotf(d1[q]), (q < 2 ? wa0 : wb0) * dotf(d0[q])); + acc[i][n][q] = fmaf(h ? dx[n][q & 1].y : dx[n][q & 1].x, v, acc[i][n][q]); + } + } else { + int d[4]; + mma32(d, a, bq[2 * n], bq[2 * n + 1]); +#pragma unroll + for (int q = 0; q < 4; ++q) { + const float p = (q < 2 ? wa0 : wb0) * (h ? dx[n][q & 1].y : dx[n][q & 1].x); + acc[i][n][q] = fmaf(p, dotf(d[q]), acc[i][n][q]); + } + } + } + } + } + } + // the next stage's weights (into the other buffer, read after the next barrier). (Decoding them before + // this stage's products instead was slower on the RTX 5070: a layer of 2048 / 3584 / 8192 tokens, IQ2_S + // 5.2 / 9.5 / 17.5 ms -> 6.0 / 10.2 / 18.3.) + if (s + 1 < NS) { + put(raw, (s + 1) & 1); + if (dec && s + 2 < NS) load_unit(unit(s + 2), sub(s + 2), raw); + } + } + if (!on0) continue; + if (GU) { + // SwiGLU of feature (WR / 2) fb + 32 wf + 8 i + g (lane g of m tile i: rows 64 wf + 16 i + g and + 8), tile + // rows nb0 + 8 n + 2 tig + c; H to int8 per row over the warp's 32 features (one 32-value half-block of the + // down product's K) + const int blk = WW * fb + wf; +#pragma unroll + for (int n = 0; n < 2; ++n) { + if (n == 1 && !on1) break; +#pragma unroll + for (int c = 0; c < 2; ++c) { + float h[4], am = 0.0f; +#pragma unroll + for (int i = 0; i < 4; ++i) { + const float gt = acc[i][n][c], up = acc[i][n][2 + c]; + h[i] = gt / (1.0f + __expf(-gt)) * up; + am = fmaxf(am, fabsf(h[i])); + } +#pragma unroll + for (int o = 4; o < 32; o <<= 1) am = fmaxf(am, __shfl_xor_sync(0xffffffffu, am, o)); + const float inv = am > 0.0f ? 127.0f / am : 0.0f; + const int r = nb0 + 8 * n + 2 * tig + c; + if (r < nrows) { + uint8_t* o = out + (size_t) (row0 + r) * (10 * AB) + (blk >> 1) * AB; + const int hh = blk & 1; +#pragma unroll + for (int i = 0; i < 4; ++i) o[32 * hh + 8 * i + g] = (uint8_t) (int8_t) __float2int_rn(h[i] * inv); + if (g == 0) *(float*) (o + 64 + 4 * hh) = am / 127.0f; + } + } + } + } else { +#pragma unroll + for (int i = 0; i < 4; ++i) +#pragma unroll + for (int n = 0; n < 2; ++n) { + if (n == 1 && !on1) break; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const int r = nb0 + 8 * n + 2 * tig + (q & 1); + if (r < nrows) dm[(size_t) (row0 + r) * 2560 + rbase + 64 * wf + 16 * i + 8 * (q >> 1) + g] = acc[i][n][q]; + } + } + } + } +#endif +} + +unsigned blocks(int64_t n, int per) { return (unsigned) ((n + per - 1) / per); } + +// per device: whether every kernel here runs (sm_80+, device code in this build, fits), and their occupancy +struct DevInfo { + bool done = false, ok = false; + int sms = 0, occ = 1; +}; +std::mutex g_mu; +DevInfo g_dev[32]; + +template bool setup_ww(int& occ) { + cudaFuncAttributes fa{}; + if (cudaFuncGetAttributes(&fa, native_kernel) != cudaSuccess || fa.ptxVersion < 80) return false; + if (cudaFuncSetAttribute(native_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, + (int) smem_bytes(T, WW)) != cudaSuccess) + return false; + int o = 0; + if (cudaOccupancyMaxActiveBlocksPerMultiprocessor(&o, native_kernel, THREADS, smem_bytes(T, WW)) != + cudaSuccess || o < 1) + return false; + occ = std::min(occ, o); + return true; +} +template bool setup_one(int& occ) { return setup_ww(occ) && setup_ww(occ); } + +const DevInfo& dev_info() { + int dev = 0; + cudaGetDevice(&dev); + std::lock_guard lk(g_mu); + DevInfo& d = g_dev[dev & 31]; + if (d.done) return d; + d.done = true; + int major = 0; + cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev); + cudaDeviceGetAttribute(&d.sms, cudaDevAttrMultiProcessorCount, dev); + if (major < 8) return d; + int occ = 1 << 20; + d.ok = setup_one(occ) && setup_one(occ) && setup_one(occ) && + setup_one(occ) && setup_one(occ) && setup_one(occ) && + setup_one(occ) && setup_one(occ); + d.occ = d.ok ? occ : 1; + cudaGetLastError(); + return d; +} + +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; +} +bool d_covered(int t) { return t == T_Q2_0 || t == T_IQ4_NL; } + +template +void launch(int ww, unsigned grid, const Batch& b, const NativeGeom& g, const Tables& tb, const void* act, + const int32_t* src, void* out, float* dm, cudaStream_t s) { + const uint8_t* a = (const uint8_t*) act; + uint8_t* o = (uint8_t*) out; + if (ww == 4) native_kernel<<>>(b, g, tb, a, src, o, dm); + else native_kernel<<>>(b, g, tb, a, src, o, dm); +} + +// The work item's shape for a layer of `n` routed rows over `n_expert` experts: 128 routed rows when an expert has +// about one such tile (56 to 112 rows on average), else 64. Measured on the RTX 5070 (tests/cuda/prefill_fused_iq_test, +// a layer of 2048 / 3584 / 8192 tokens, ms, 64 -> 128): IQ2_S 5.2 -> 6.7, 9.5 -> 9.3, 17.5 -> 19.5; IQ2_XXS 4.2 -> +// 5.8, 7.4 -> 7.6, 13.6 -> 16.5; IQ3_S 5.6 -> 6.6, 10.2 -> 8.8, 18.4 -> 19.0; IQ3_XXS 5.1 -> 6.3, 9.1 -> 8.3, 16.5 -> +// 17.5 (256 rows was slower still). STRATA_PF_FUSED_TILE=64|128 forces one. +int pick_ww(int64_t n, int n_expert) { + static const int forced = [] { + const char* v = std::getenv("STRATA_PF_FUSED_TILE"); + const int t = v ? std::atoi(v) : 0; + return t == 64 ? 4 : t == 128 ? 2 : 0; + }(); + if (forced) return forced; + const double avg = (double) n / std::max(n_expert, 1); + return avg > 56.0 && avg <= 112.0 ? 2 : 4; +} + +} // namespace + +bool native_supported(int gu_type, int d_type) { + static const bool off = [] { // STRATA_PF_FUSED_NATIVE=0: the native packs keep MMQ under STRATA_PF_FUSED=1 (A/B) + const char* v = std::getenv("STRATA_PF_FUSED_NATIVE"); + return v != nullptr && v[0] == '0'; + }(); + return !off && enabled() && gu_covered(gu_type) && d_covered(d_type) && dev_info().ok; +} + +void quantize_act_native(const float* x, int64_t rows, int64_t cols, void* xa, void* stream) { + if (rows <= 0) return; + const int64_t nblk = rows * (cols / 64); + quant_act_nat_kernel<<>>(x, nblk, (uint8_t*) xa); + ck(cudaGetLastError(), "quantize_act_native"); +} + +void experts_native(const Batch& b, const NativeGeom& g, int n_expert, int64_t n, const void* scratch, const void* xa, + const int32_t* src, void* ha, float* dm, void* stream) { + if (b.e1 <= b.e0 || n <= 0) return; + const DevInfo& d = dev_info(); + if (!d.ok || !gu_covered(g.gu_type) || !d_covered(g.d_type)) { + std::fprintf(stderr, "prefill fused experts (native): types %d / %d are not covered here\n", g.gu_type, g.d_type); + std::exit(1); + } + const cudaStream_t s = (cudaStream_t) stream; + const Tables tb = tables(const_cast(scratch), n_expert); + const int ww = pick_ww(n, n_expert); + // the most 64-row tiles the batch can have (every row in it, plus a partial tile per expert) - the items of the + // ones inside a larger item end at once + const int64_t tiles = (n + kTileRows - 1) / kTileRows + (b.e1 - b.e0); + const unsigned g_gu = (unsigned) std::min(tiles * (1280 / weight_rows(ww)), (int64_t) d.sms * d.occ); + const unsigned g_d = (unsigned) std::min(tiles * (2560 / weight_rows(ww)), (int64_t) d.sms * d.occ); + switch (g.gu_type) { + case T_IQ2_XXS: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_XS: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ2_S: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ3_XXS: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + case T_IQ3_S: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + default: launch(ww, g_gu, b, g, tb, xa, src, ha, nullptr, s); break; + } + if (g.d_type == T_Q2_0) launch(ww, g_d, b, g, tb, ha, src, nullptr, dm, s); + else launch(ww, g_d, b, g, tb, ha, src, nullptr, dm, s); + ck(cudaGetLastError(), "experts_native"); +} + +} // namespace strata::prefill::fused diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index a4859cea..5ae37646 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -24,6 +24,7 @@ #include "strata/kernels/qsa_select.hpp" #include "strata/prefill/gemm.hpp" #include "strata/prefill/moe_fused.hpp" +#include "strata/prefill/moe_fused_iq.hpp" #include "strata/prefill/moe_mmq.hpp" #include "strata/prefill/kernels.hpp" @@ -71,6 +72,10 @@ size_t group_bytes(int64_t, int) { return 0; } void quantize_act(const float*, int64_t, int64_t, void*, void*) {} void group(const int32_t*, int64_t, int, int, void*, int32_t*, int32_t*, void*) {} void experts(const Batch&, int, int64_t, const void*, const void*, const int32_t*, void*, float*, void*) {} +bool native_supported(int, int) { return false; } +void quantize_act_native(const float*, int64_t, int64_t, void*, void*) {} +void experts_native(const Batch&, const NativeGeom&, int, int64_t, const void*, const void*, const int32_t*, void*, + float*, void*) {} } // namespace strata::prefill::fused #endif @@ -106,8 +111,20 @@ int g_ring_override = 0; // #340: set by a layer split (Prefill::set_ring_over // should hold a whole layer's (~460 of 512 on Q2_0): with 384 slots a layer's last batch waits for slots its own // first batch frees. Measured on the 5070, Q2_0, the 4K / 32K code-agent prompts (one run each): fused at 384 slots // +5% / +3% over MMQ, at 512 +19-22% / +11-12% (MMQ itself at 512: -2% / -1%). 1024 slots (RING_MAX 1024): 4K -// +24-27%, but 32K -> +6%: its chunk falls from 8192 to 6144. -inline bool fused_ring() { return fused::enabled() && !strata::kernels::cpu::expert_layout().native; } +// +24-27%, but 32K -> +6%: its chunk falls from 8192 to 6144. A native pack likewise when the native kernels +// (moe_fused_iq.hpp) take any of its layers: IQ2_XS, 4K / 32K, their first version at 384 slots -3% / -6% against MMQ, +// at 512 +8% / 0%. +inline bool fused_ring() { + if (!fused::enabled()) return false; + const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); + if (!lay.native) return true; + static const bool any = [&lay] { + for (const auto& f : lay.fmt) + if (fused::native_supported(f.gu_type, f.d_type)) return true; + return false; + }(); + return any; +} inline int ring_slots(size_t T) { const char* v = std::getenv("STRATA_PREFILL_RING"); #if defined(STRATA_USE_HIP) @@ -1604,13 +1621,15 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e // grouped on the GPU: no host sync. Only where every expert's place is known before the routing - // the streamed walk, in which every non-resident expert of the layer comes through the ring in id // order - and where the MMQ buffers exist: they hold the fused path's own (the per-token int8 - // activations in Xq, the int8 H in H, the grouping tables in GU). Native packs and chunks below - // stream_all_min() keep MMQ; without the variable nothing here runs. + // activations in Xq, the int8 H in H, the grouping tables in GU). Chunks below stream_all_min() + // keep MMQ; without the variable nothing here runs. A native pack's layer takes the native kernels + // (moe_fused_iq.hpp) where they cover its two formats, else MMQ (or the FP16 path: IQ1_M). const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout(); const bool use_mmq = mmq_plan().any && mmq_plan().layer[(size_t) l]; const int mmq_gt = lay.native ? lay.fmt[(size_t) l].gu_type : 42; const int mmq_dt = lay.native ? lay.fmt[(size_t) l].d_type : 42; - const bool fused_l = use_mmq && stream_all && !lay.native && fused::enabled(); + const bool fused_nat = use_mmq && stream_all && lay.native && fused::native_supported(mmq_gt, mmq_dt); + const bool fused_l = (use_mmq && stream_all && !lay.native && fused::enabled()) || fused_nat; size_t n_order = 0; // the routed experts (the debug report; unknown when fused) if (fused_l) { if (static bool said = false; !said) { @@ -1620,7 +1639,8 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e } pt.mark(kPfGather, cs); // the layer's input to int8 once per token; the rows of each expert from the router's ids - fused::quantize_act(m.mixed, T, N, m.Xq, m.cs); + if (fused_nat) fused::quantize_act_native(m.mixed, T, N, m.Xq, m.cs); + else fused::quantize_act(m.mixed, T, N, m.Xq, m.cs); fused::group(m.ids, T * K, (int) K, (int) m.g->n_expert, m.GU, m.slot_dev, m.src_dev, m.cs); // launches over the experts in id order, each at most kMaxBatch experts of which at most a // third of the ring streamed: the next batch's blobs arrive while one computes. An expert @@ -1649,7 +1669,14 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& e cudaStreamWaitEvent(m.cs, m.copied[(k - 1) % (size_t) m.ring], 0); } pt.mark(kPfGemmGU, cs); - fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs); + if (fused_nat) { + const auto& f = lay.fmt[(size_t) l]; + const fused::NativeGeom ng{f.gu_type, f.d_type, f.gu_row, f.d_row, f.up_off, f.down_off}; + fused::experts_native(b, ng, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, + m.Dm, m.cs); + } else { + fused::experts(b, (int) m.g->n_expert, T * K, m.GU, m.Xq, m.src_dev, m.H, m.Dm, m.cs); + } for (size_t kk = k0; kk < k; ++kk) cudaEventRecord(m.used[kk % (size_t) m.ring], m.cs); if (k > k0) { consumed = k; diff --git a/tests/cuda/prefill_fused_iq_test.cpp b/tests/cuda/prefill_fused_iq_test.cpp new file mode 100644 index 00000000..d436a605 --- /dev/null +++ b/tests/cuda/prefill_fused_iq_test.cpp @@ -0,0 +1,633 @@ +// prefill_fused_iq_test - #136: the fused int8 expert kernels for the native packs (moe_fused_iq.hpp, STRATA_PF_FUSED=1) +// on random native expert blobs ([gate rows | up rows | down rows], GGUF blocks) and random routing, per format pair, +// against +// - a double-precision reference: the weights dequantized by ggml's own to_float, times the FP32 activations +// (gate/up, SwiGLU, down), and +// - the MMQ path in prefill.cpp's sequence (gather_native into 16-expert groups, q8_1 of the slots' activations, +// gate/up, SwiGLU, q8_1 of H, down). +// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused +// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row). +// The pairs cover every format the kernels take: gate/up IQ2_XXS IQ2_XS IQ2_S IQ3_XXS IQ3_S IQ4_XS, down Q2_0 IQ4_NL. +// Part 1 (reference), per pair: 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with +// several 64-row tiles - an all-zero token, per-expert blobs at unrelated (2-byte aligned) addresses, three launches of +// different expert ranges. Part 2 (timing): one layer at the engine's chunks (2048, 3584, 8192 tokens; 512 experts, +// top 10) on both paths and on MMQ's products alone (no gathers), for the IQ2_XS, IQ3_XXS and IQ3_S packs' most +// common layers, with the grouping checked and a sample of rows against the reference. --no-ref, --no-timing, +// --only=NAME, --chunks=A,B. Exit 77 without a CUDA device of sm_80 or newer. +#include "strata/prefill/moe_fused_iq.hpp" +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; +namespace fused = strata::prefill::fused; + +constexpr int N = 2560, FF = 640, K = 10, GROUP = 16; + +void ck(cudaError_t e, const char* what) { + if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e)); +} + +struct Dev { + void* p = nullptr; + explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + template T* as() const { return (T*) p; } +}; + +struct Pair { + ggml_type gu, d; + const char* name; +}; + +struct Geo { + size_t gu_row, d_row, up_off, down_off, bytes; + explicit Geo(const Pair& p) { + gu_row = ggml_row_size(p.gu, N); + d_row = ggml_row_size(p.d, FF); + up_off = gu_row * FF; + down_off = 2 * up_off; + bytes = down_off + d_row * N; + } + fused::NativeGeom native(const Pair& p) const { + fused::NativeGeom g; + g.gu_type = (int) p.gu; g.d_type = (int) p.d; g.gu_row = gu_row; g.d_row = d_row; g.up_off = up_off; + g.down_off = down_off; + return g; + } +}; + +// random blocks with a sane fp16 scale `d` at each block's start (every format here begins with it): scales chosen so +// 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)); + std::uniform_int_distribution byte(0, 255); + const float lo = t == GGML_TYPE_IQ3_S ? 0.0004f : t == GGML_TYPE_IQ4_XS ? 0.00005f + : t == GGML_TYPE_IQ4_NL ? 0.0002f : t == GGML_TYPE_Q2_0 ? 0.004f : 0.0008f; + std::uniform_real_distribution sc(lo, 6.0f * lo); + for (size_t i = 0; i < nb * bs; ++i) m[i] = (uint8_t) byte(rng); + for (size_t b = 0; b < nb; ++b) { + const ggml_fp16_t h = ggml_fp32_to_fp16(sc(rng)); + std::memcpy(m + b * bs, &h, 2); + } +} +std::vector make_blob(const Pair& p, const Geo& g, std::mt19937& rng) { + std::vector b(g.bytes); + fill_matrix(b.data(), p.gu, 2 * FF, N, rng); + fill_matrix(b.data() + g.down_off, p.d, N, FF, rng); + return b; +} + +// ggml's dequantized weights: gate [640][2560], up [640][2560], down [2560][640] +void dequant(const Pair& p, const Geo& g, const std::vector& b, std::vector& gu, std::vector& dn) { + const auto* tg = ggml_get_type_traits(p.gu); + const auto* td = ggml_get_type_traits(p.d); + gu.resize((size_t) 2 * FF * N); + dn.resize((size_t) N * FF); + for (int r = 0; r < 2 * FF; ++r) tg->to_float(b.data() + (size_t) r * g.gu_row, gu.data() + (size_t) r * N, N); + for (int r = 0; r < N; ++r) td->to_float(b.data() + g.down_off + (size_t) r * g.d_row, dn.data() + (size_t) r * FF, FF); +} + +// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero +std::vector make_x(int T, std::mt19937& rng, int zero) { + std::vector x((size_t) T * N); + std::normal_distribution nd(0.0f, 1.0f); + std::uniform_int_distribution pick(0, 199); + for (float& v : x) v = nd(rng) * (pick(rng) == 0 ? 12.0f : 1.0f); + if (zero >= 0) std::fill(x.begin() + (size_t) zero * N, x.begin() + (size_t) (zero + 1) * N, 0.0f); + return x; +} + +// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids +std::vector make_ids(int T, int E, std::mt19937& rng, int hot, int unused) { + std::vector ids((size_t) T * K); + std::uniform_int_distribution any(0, E - 1 - unused); + for (int t = 0; t < T; ++t) + for (int k = 0; k < K; ++k) { + int e; + bool dup; + do { + e = (hot > 0 && k < 3 && (int) (rng() % 4) != 0) ? (int) (rng() % (unsigned) hot) : any(rng); + dup = false; + for (int j = 0; j < k; ++j) dup |= ids[(size_t) t * K + j] == e; + } while (dup); + ids[(size_t) t * K + k] = e; + } + return ids; +} + +struct Routing { + std::vector cnt, off, src; // per expert; sorted row -> token (rows in pair order within an expert) + std::vector row_of; // pair -> sorted row +}; +Routing sort_rows(const std::vector& ids, int E) { + Routing r; + r.cnt.assign((size_t) E, 0); + for (int32_t e : ids) ++r.cnt[(size_t) e]; + r.off.assign((size_t) E + 1, 0); + for (int e = 0; e < E; ++e) r.off[(size_t) e + 1] = r.off[(size_t) e] + r.cnt[(size_t) e]; + std::vector fill(r.off.begin(), r.off.end() - 1); + r.src.resize(ids.size()); + r.row_of.resize(ids.size()); + for (size_t i = 0; i < ids.size(); ++i) { + const int32_t p = fill[(size_t) ids[i]]++; + r.row_of[i] = p; + r.src[(size_t) p] = (int32_t) (i / K); + } + return r; +} + +// MMQ, as prefill.cpp runs a native layer: per group of 16 routed experts a gather, gate/up, SwiGLU (gate rows, then +// up rows), q8_1 of H, down. Returns Dm [rows][N] in sorted-row order. +struct MmqBufs { + Dev xq, gu, h, hq, dm, ident, bounds, grp_gu, grp_d; + MmqBufs(const Pair& p, int64_t rows, int E) + : xq(mmq::q8_bytes(rows, N)), gu((size_t) rows * 1280 * 4), h((size_t) rows * FF * 4), + hq(mmq::q8_bytes(rows, FF)), dm((size_t) rows * N * 4), ident((size_t) rows * 4), + bounds((size_t) (2 * (E + E / GROUP + 2)) * 4), grp_gu(GROUP * mmq::matrix_bytes(p.gu, 1280, N) + 4096), + grp_d(GROUP * mmq::matrix_bytes(p.d, N, FF) + 4096) {} +}; +// `direct`: no gathers - the products read the blobs where they are (they must lie at a fixed stride, every expert +// with rows: the timing part's layout), the cost of MMQ's own kernels alone +void run_mmq(const Pair& p, const Geo& geo, mmq::Context& ctx, MmqBufs& b, const Routing& r, const float* x_dev, + const int32_t* src_dev, const std::vector& blob, int64_t rows, cudaStream_t s, + bool direct = false, size_t stride = 0) { + const size_t gub = mmq::matrix_bytes(p.gu, 1280, N), db = mmq::matrix_bytes(p.d, N, FF); + const int E = (int) r.cnt.size(); + std::vector order; + for (int e = 0; e < E; ++e) if (r.cnt[(size_t) e] > 0) order.push_back(e); + const size_t n = order.size(), ng = (n + GROUP - 1) / GROUP; + std::vector bh(n + 1 + ng * (GROUP + 1)); + for (size_t j = 0; j < n; ++j) bh[j] = r.off[(size_t) order[j]]; + bh[n] = (int32_t) rows; + for (size_t g = 0; g < ng; ++g) + for (size_t i = 0; i <= GROUP; ++i) + bh[n + 1 + g * (GROUP + 1) + i] = bh[std::min(n, g * GROUP + i)] - bh[g * GROUP]; + ck(cudaMemcpyAsync(b.bounds.p, bh.data(), bh.size() * 4, cudaMemcpyHostToDevice, s), "bounds"); + mmq::iota(b.ident.as(), rows, s); + mmq::quantize(x_dev, src_dev, b.xq.p, (int) p.gu, N, N, rows, s); + for (size_t j = 0; j < n; ++j) { + const size_t q = j % GROUP; + const uint8_t* bl = blob[(size_t) order[j]]; + if (!direct) + mmq::gather_native(bl, bl + geo.up_off, gub / 2, bl + geo.down_off, db, b.grp_gu.as() + q * gub, + b.grp_d.as() + q * db, s); + if (q + 1 < GROUP && j + 1 < n) continue; + const size_t j0 = j - q, g = j0 / GROUP; + const int ngx = (int) (q + 1); + const int64_t r0 = bh[j0], nr = bh[j + 1] - r0; + int64_t maxr = 0; + for (size_t i = j0; i <= j; ++i) maxr = std::max(maxr, r.cnt[(size_t) order[i]]); + if (!direct) { + ck(cudaMemsetAsync(b.grp_gu.as() + (size_t) ngx * gub, 0, 4096, s), "tail"); + ck(cudaMemsetAsync(b.grp_d.as() + (size_t) ngx * db, 0, 4096, s), "tail"); + } + const uint8_t* b0 = blob[(size_t) order[j0]]; + mmq::Product gu; + gu.w = direct ? (const void*) b0 : b.grp_gu.p; gu.type = (int) p.gu; gu.w_rows = 1280; gu.w_cols = N; + gu.expert_bytes = direct ? stride : gub; + gu.n = ngx; gu.xq = b.xq.p; gu.bounds = b.bounds.as() + j0; gu.ids = b.ident.as(); + gu.total_rows = rows; gu.max_rows = maxr; gu.dst = b.gu.as(); gu.ld_dst = 1280; + ctx.run(gu, s); + mmq::swiglu(b.gu.as() + r0 * 1280, b.h.as() + r0 * FF, nr, FF, false, s); + mmq::quantize(b.h.as() + r0 * FF, nullptr, b.hq.p, (int) p.d, FF, FF, nr, s); + mmq::Product dn; + dn.w = direct ? (const void*) (b0 + geo.down_off) : b.grp_d.p; dn.type = (int) p.d; dn.w_rows = N; dn.w_cols = FF; + dn.expert_bytes = direct ? stride : db; + dn.n = ngx; dn.xq = b.hq.p; dn.bounds = b.bounds.as() + n + 1 + g * (GROUP + 1); + dn.ids = b.ident.as(); dn.total_rows = nr; dn.max_rows = maxr; dn.dst = b.dm.as() + r0 * N; + dn.ld_dst = N; + ctx.run(dn, s); + } +} + +// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64}) +struct FusedBufs { + Dev xa, ha, dm, scratch, slot, src, ids; + FusedBufs(int T, int64_t rows, int E) + : xa(fused::act_bytes(T, N)), ha(fused::act_bytes(rows, FF)), dm((size_t) rows * N * 4), + scratch(fused::group_bytes(rows, E)), slot((size_t) rows * 4), src((size_t) rows * 4), + ids((size_t) rows * 4) {} +}; +void run_fused(const Pair& p, const Geo& geo, FusedBufs& b, const float* x_dev, int T, int E, + const std::vector& cuts, const std::vector& blob, cudaStream_t s) { + const int64_t rows = (int64_t) T * K; + const fused::NativeGeom ng = geo.native(p); + fused::quantize_act_native(x_dev, T, N, b.xa.p, s); + fused::group(b.ids.as(), rows, K, E, b.scratch.p, b.slot.as(), b.src.as(), s); + for (size_t c = 0; c + 1 < cuts.size(); ++c) { + for (int e0 = cuts[c]; e0 < cuts[c + 1]; e0 += fused::kMaxBatch) { + fused::Batch bt; + bt.e0 = e0; + bt.e1 = std::min(cuts[c + 1], e0 + fused::kMaxBatch); + for (int e = bt.e0; e < bt.e1; ++e) bt.blob[e - bt.e0] = blob[(size_t) e]; + fused::experts_native(bt, ng, E, rows, b.scratch.p, b.xa.p, b.src.as(), b.ha.p, b.dm.as(), s); + } + } +} + +struct Err { + double rms = 0, worst = 0; // RMS error / RMS of the reference; the worst row's max |error| / its max |ref| +}; +// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values) +template +Err compare(const std::vector& a, RA row_a, const std::vector& b, RB row_b, size_t pairs) { + double e2 = 0, r2 = 0; + Err out; + for (size_t i = 0; i < pairs; ++i) { + const float* ya = a.data() + (size_t) row_a(i) * N; + const float* yb = b.data() + (size_t) row_b(i) * N; + double me = 0, mr = 0; + for (int o = 0; o < N; ++o) { + if (!std::isfinite(ya[o])) throw std::runtime_error("a non-finite output"); + const double d = (double) ya[o] - yb[o]; + e2 += d * d; + r2 += (double) yb[o] * yb[o]; + me = std::max(me, std::fabs(d)); + mr = std::max(mr, (double) std::fabs(yb[o])); + } + if (mr > 0) out.worst = std::max(out.worst, me / mr); + else if (me > 0) out.worst = 1e30; // a zero row must stay exactly zero + } + out.rms = r2 > 0 ? std::sqrt(e2 / r2) : 0; + return out; +} + +std::vector download(const Dev& d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); + return h; +} +std::vector download_i(const Dev& d, size_t n) { + std::vector h(n); + ck(cudaMemcpy(h.data(), d.p, n * 4, cudaMemcpyDeviceToHost), "download"); + return h; +} + +// part 1: against the double-precision reference +void reference_part(const Pair& p, cudaStream_t s) { + constexpr int T = 256, E = 64, ZERO = 77; + const Geo geo(p); + std::mt19937 rng(136 + (unsigned) p.gu * 7 + (unsigned) p.d); + std::vector> host((size_t) E); + std::vector> dev; + std::vector blob((size_t) E); + for (int e = 0; e < E; ++e) { + host[(size_t) e] = make_blob(p, geo, rng); + dev.push_back(std::make_unique(geo.bytes + 4096 * (size_t) (e % 3) + 64)); // unrelated addresses + uint8_t* q = dev.back()->as() + 256 * (size_t) (e % 3) + 2 * (size_t) (e % 2); // 2-byte aligned + ck(cudaMemcpy(q, host[(size_t) e].data(), geo.bytes, cudaMemcpyHostToDevice), "blob"); + blob[(size_t) e] = q; + } + const std::vector x = make_x(T, rng, ZERO); + const std::vector ids = make_ids(T, E, rng, 2, 4); // experts 0, 1 hot (several tiles), 60-63 unused + const int64_t rows = (int64_t) T * K; + const Routing r = sort_rows(ids, E); + std::printf("%s - reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n", p.name, + T, E, *std::max_element(r.cnt.begin(), r.cnt.end()), (int) std::count(r.cnt.begin(), r.cnt.end(), 0)); + + Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); + ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + // (the uploads above are on the legacy stream and the work below on a non-blocking one: a cudaMemcpy from pageable + // memory may return before its DMA lands - on Windows it can wait in the queue until the next synchronous call) + ck(cudaDeviceSynchronize(), "uploads"); + mmq::Context ctx; + MmqBufs mb(p, rows, E); + run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); + FusedBufs fb(T, rows, E); + ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaMemset(fb.dm.p, 0xff, (size_t) rows * N * 4), "sentinel"); // an unwritten row is NaN + ck(cudaDeviceSynchronize(), "uploads"); + run_fused(p, geo, fb, x_dev.as(), T, E, {0, 1, 20, E}, blob, s); + ck(cudaStreamSynchronize(s), "sync"); + const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector slot = download_i(fb.slot, (size_t) rows), fsrc = download_i(fb.src, (size_t) rows); + for (int64_t i = 0; i < rows; ++i) + if (fsrc[(size_t) slot[(size_t) i]] != (int32_t) (i / K)) throw std::runtime_error("group: slot/src disagree"); + + // the reference, an expert at a time on all cores + std::vector ref((size_t) rows * N); + std::vector th; + const int nth = std::max(1, std::min(16, (int) std::thread::hardware_concurrency())); + for (int w = 0; w < nth; ++w) + th.emplace_back([&, w] { + std::vector gu, dn, h(FF); + for (int e = w; e < E; e += nth) { + if (r.cnt[(size_t) e] == 0) continue; + dequant(p, geo, host[(size_t) e], gu, dn); + for (int64_t i = 0; i < rows; ++i) { + if (ids[(size_t) i] != e) continue; + const float* xr = x.data() + (size_t) (i / K) * N; + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } + h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; + ref[(size_t) i * N + o] = (float) a; + } + } + } + }); + for (auto& t : th) t.join(); + + auto pair = [](size_t i) { return (int64_t) i; }; + auto mrow = [&](size_t i) { return (int64_t) r.row_of[i]; }; + auto frow = [&](size_t i) { return (int64_t) slot[i]; }; + const Err em = compare(y_mmq, mrow, ref, pair, (size_t) rows); + const Err ef = compare(y_f, frow, ref, pair, (size_t) rows); + const Err efm = compare(y_f, frow, y_mmq, mrow, (size_t) rows); + 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); + std::printf(" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n", efm.rms, efm.worst); + double zmax = 0; + for (int k = 0; k < K; ++k) + for (int o = 0; o < N; ++o) + zmax = std::max(zmax, (double) std::fabs(y_f[(size_t) slot[(size_t) (ZERO * K + k)] * N + o])); + if (zmax != 0) throw std::runtime_error(std::string(p.name) + ": the all-zero token's outputs are not zero"); + if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's"); +} + +// part 2: one layer at a real chunk, timed +void timing_part(const Pair& p, int T, cudaStream_t s) { + constexpr int E = 512; + const Geo geo(p); + std::mt19937 rng(1360); + const int64_t rows = (int64_t) T * K; + // 512 distinct blobs - the products read each once per tile, as the engine does + // at a stride of whole blocks of both formats (MMQ's expert stride counts blocks), + MMQ's read past the end + size_t unit = ggml_type_size(p.gu); + while (unit % ggml_type_size(p.d) != 0 || unit % 16 != 0) unit += ggml_type_size(p.gu); + const size_t stride = (geo.bytes + unit - 1) / unit * unit; + Dev blobs((size_t) E * stride + 4096); + ck(cudaMemset(blobs.p, 0, (size_t) E * stride + 4096), "zero"); + { + std::vector b = make_blob(p, geo, rng); + for (int e = 0; e < E; ++e) { + b[4 + (size_t) (e % 16)] ^= (uint8_t) e; // not all equal (inside the first block, not its scale) + ck(cudaMemcpy(blobs.as() + (size_t) e * stride, b.data(), geo.bytes, cudaMemcpyHostToDevice), + "blob"); + } + } + std::vector blob((size_t) E); + for (int e = 0; e < E; ++e) blob[(size_t) e] = blobs.as() + (size_t) e * stride; + const std::vector x = make_x(T, rng, -1); + const std::vector ids = make_ids(T, E, rng, 0, 0); + const Routing r = sort_rows(ids, E); + Dev x_dev(x.size() * 4), src_dev((size_t) rows * 4); + ck(cudaMemcpy(x_dev.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x"); + ck(cudaMemcpy(src_dev.p, r.src.data(), r.src.size() * 4, cudaMemcpyHostToDevice), "src"); + mmq::Context ctx; + MmqBufs mb(p, rows, E); + FusedBufs fb(T, rows, E); + ck(cudaMemcpy(fb.ids.p, ids.data(), ids.size() * 4, cudaMemcpyHostToDevice), "ids"); + ck(cudaDeviceSynchronize(), "uploads"); // (see reference_part) + cudaEvent_t a, b; + ck(cudaEventCreate(&a), "event"); + ck(cudaEventCreate(&b), "event"); + auto once = [&](auto&& f) { + ck(cudaEventRecord(a, s), "record"); + f(); + ck(cudaEventRecord(b, s), "record"); + ck(cudaEventSynchronize(b), "sync"); + float t = 0; + ck(cudaEventElapsedTime(&t, a, b), "elapsed"); + return t; + }; + auto mmq_run = [&] { run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s); }; + auto fused_run = [&] { run_fused(p, geo, fb, x_dev.as(), T, E, {0, E}, blob, s); }; + const bool all_routed = std::count(r.cnt.begin(), r.cnt.end(), 0) == 0; + auto direct_run = [&] { + run_mmq(p, geo, ctx, mb, r, x_dev.as(), src_dev.as(), blob, rows, s, true, stride); + }; + if (std::getenv("S20_IDSDIAG")) { // which step overwrites the routing ids on the device + auto check = [&](const char* after) { + ck(cudaStreamSynchronize(s), "sync"); + const std::vector d = download_i(fb.ids, (size_t) rows); + int64_t bad = 0; + for (size_t i = 0; i < (size_t) rows; ++i) bad += d[i] != ids[i]; + std::printf(" ids on the device after %s: %lld of %lld differ (fb.ids %p, mb.dm %p..%p, fb.dm %p..%p)\n", + after, (long long) bad, (long long) rows, fb.ids.p, mb.dm.p, + (void*) (mb.dm.as() + (size_t) rows * N * 4), fb.dm.p, + (void*) (fb.dm.as() + (size_t) rows * N * 4)); + }; + check("the upload"); + mmq_run(); + check("an MMQ run"); + fused_run(); + check("a fused run"); + if (all_routed) { + direct_run(); + check("an MMQ run without gathers"); + } + } + // ~1 s of both first (the clocks ramp up), then alternating rounds; the medians + const bool no_mmq = std::getenv("S20_NOMMQ") != nullptr; // (debug: the fused runs alone) + for (float spent = 0; spent < 1000.0f;) spent += (no_mmq ? 0.0f : once(mmq_run)) + once(fused_run); + std::vector tm, tf, td; + for (int rep = 0; rep < 8; ++rep) { + tm.push_back(no_mmq ? 1.0f : once(mmq_run)); + tf.push_back(once(fused_run)); + if (all_routed && !no_mmq) td.push_back(once(direct_run)); + } + if (td.empty()) td.push_back(0.0f); + std::sort(tm.begin(), tm.end()); + std::sort(tf.begin(), tf.end()); + std::sort(td.begin(), td.end()); + const float t_mmq = tm[tm.size() / 2], t_f = tf[tf.size() / 2]; + if (all_routed) + std::printf(" (MMQ's products alone, no gathers: %.3f ms - fused %.2fx)\n", td[td.size() / 2], + td[td.size() / 2] / t_f); + std::vector tf2; // back to back + for (int rep = 0; rep < 8; ++rep) tf2.push_back(once(fused_run)); + std::sort(tf2.begin(), tf2.end()); + std::printf(" (fused back to back: median %.3f ms, min %.3f; alternating min %.3f; MMQ min %.3f)\n", tf2[4], + tf2[0], tf[0], tm[0]); + const std::vector y_mmq = download(mb.dm, (size_t) rows * N), y_f = download(fb.dm, (size_t) rows * N); + const std::vector slot = download_i(fb.slot, (size_t) rows); + const Err efm = compare(y_f, [&](size_t i) { return (int64_t) slot[i]; }, y_mmq, + [&](size_t i) { return (int64_t) r.row_of[i]; }, (size_t) rows); + std::printf("%s - timing part: %d tokens x top %d over %d experts, one layer: MMQ path %.3f ms, fused %.3f ms " + "(%.2fx); fused vs MMQ rel RMS %.3e worst row %.3e\n", + p.name, T, K, E, t_mmq, t_f, t_mmq / t_f, efm.rms, efm.worst); + { // the grouping: every pair in its expert's rows (the near-identical blobs here would hide a wrong expert) + const std::vector fsrc = download_i(fb.src, (size_t) rows); + int64_t bad = 0, bad_src = 0; + for (size_t i = 0; i < (size_t) rows; ++i) { + const int e = ids[i]; + bad += slot[i] < r.off[(size_t) e] || slot[i] >= r.off[(size_t) e + 1]; + bad_src += fsrc[(size_t) slot[i]] != (int32_t) (i / K); + } + if (bad || bad_src) { + std::vector tbl((size_t) 4 * E + 2); + ck(cudaMemcpy(tbl.data(), fb.scratch.p, tbl.size() * 4, cudaMemcpyDeviceToHost), "tables"); + int64_t bad_cnt = 0, bad_off = 0, bad_ids = 0; + const std::vector d_ids = download_i(fb.ids, (size_t) rows); + for (size_t i = 0; i < (size_t) rows; ++i) bad_ids += d_ids[i] != ids[i]; + std::printf(" the routing ids on the device: %lld of %lld differ (first %d %d %d)\n", (long long) bad_ids, + (long long) rows, d_ids[0], d_ids[1], d_ids[2]); + const int32_t smin = *std::min_element(slot.begin(), slot.end()), smax = *std::max_element(slot.begin(), slot.end()); + std::printf(" slots %d..%d; off[0..3] %d %d %d %d off[E] %d; fill[0..3] %d %d %d %d; ts[0..3] %d %d %d %d " + "ts[E] %d\n", smin, smax, tbl[E], tbl[E + 1], tbl[E + 2], tbl[E + 3], tbl[2 * E], tbl[2 * E + 1], + tbl[2 * E + 2], tbl[2 * E + 3], tbl[2 * E + 4], tbl[3 * E + 1], tbl[3 * E + 2], tbl[3 * E + 3], + tbl[3 * E + 4], tbl[4 * E + 1]); + // the group again on these ids, synchronously + fused::group(fb.ids.as(), rows, K, E, fb.scratch.p, fb.slot.as(), fb.src.as(), s); + ck(cudaStreamSynchronize(s), "sync"); + std::vector t2((size_t) 4 * E + 2); + ck(cudaMemcpy(t2.data(), fb.scratch.p, t2.size() * 4, cudaMemcpyDeviceToHost), "tables"); + std::printf(" group() again, synchronized: cnt[0..3] %d %d %d %d off[E] %d\n", t2[0], t2[1], t2[2], t2[3], + t2[(size_t) 2 * E]); + for (int e = 0; e < E; ++e) { + bad_cnt += tbl[(size_t) e] != r.cnt[(size_t) e]; + bad_off += tbl[(size_t) E + e] != r.off[(size_t) e]; + } + std::printf(" GROUPING WRONG: %lld pairs outside their expert's rows, %lld src mismatches; tables: %lld counts " + "and %lld offsets differ from the host's (cnt[0..3] %d %d %d %d vs %d %d %d %d)\n", + (long long) bad, (long long) bad_src, (long long) bad_cnt, (long long) bad_off, tbl[0], tbl[1], + tbl[2], tbl[3], r.cnt[0], r.cnt[1], r.cnt[2], r.cnt[3]); + throw std::runtime_error(std::string(p.name) + ": the grouping is wrong"); + } + } + if (std::getenv("S20_ROWDIAG")) { // the pairs whose rows differ most: expert, its rows, the row's place + const std::vector fsrc = download_i(fb.src, (size_t) rows); + std::vector> worst; + for (size_t i = 0; i < (size_t) rows; ++i) { + const float* a = y_f.data() + (size_t) slot[i] * N; + const float* m = y_mmq.data() + (size_t) r.row_of[i] * N; + double me = 0, mr = 0; + for (int o = 0; o < N; ++o) { me = std::max(me, (double) std::fabs(a[o] - m[o])); mr = std::max(mr, (double) std::fabs(m[o])); } + worst.push_back({mr > 0 ? me / mr : me, i}); + } + std::sort(worst.rbegin(), worst.rend()); + for (int k = 0; k < 12; ++k) { + const size_t i = worst[(size_t) k].second; + const int e = ids[i]; + // the expert's rows start at its first fused row: the smallest slot of its pairs + int32_t first = INT32_MAX; + for (size_t j = 0; j < (size_t) rows; ++j) if (ids[j] == e) first = std::min(first, slot[j]); + std::printf(" pair %zu token %zu expert %d (%d rows) fused row %d (+%d in the expert) max rel %.3e\n", i, + i / K, e, r.cnt[(size_t) e], slot[i], slot[i] - first, worst[(size_t) k].first); + } + (void) fsrc; + } + // both against the double-precision reference on a sample of 96 pairs + { + std::vector pick; + for (size_t i = 0; i < 96; ++i) pick.push_back((i * 2654435761u) % (size_t) rows); + std::vector ref(pick.size() * N), ym(pick.size() * N), yf(pick.size() * N); + std::vector hb(geo.bytes); + std::vector gu, dn, h(FF); + for (size_t j = 0; j < pick.size(); ++j) { + const size_t i = pick[j]; + const int e = ids[i]; + ck(cudaMemcpy(hb.data(), blob[(size_t) e], geo.bytes, cudaMemcpyDeviceToHost), "blob back"); + dequant(p, geo, hb, gu, dn); + const float* xr = x.data() + (i / K) * N; + for (int f = 0; f < FF; ++f) { + double gt = 0, up = 0; + const float *wg = gu.data() + (size_t) f * N, *wu = gu.data() + (size_t) (FF + f) * N; + for (int k = 0; k < N; ++k) { gt += (double) wg[k] * xr[k]; up += (double) wu[k] * xr[k]; } + h[(size_t) f] = (float) (gt / (1.0 + std::exp(-gt)) * up); + } + for (int o = 0; o < N; ++o) { + double a = 0; + const float* wd = dn.data() + (size_t) o * FF; + for (int f = 0; f < FF; ++f) a += (double) wd[f] * h[(size_t) f]; + ref[j * N + o] = (float) a; + } + std::copy_n(y_mmq.begin() + (ptrdiff_t) ((size_t) r.row_of[i] * N), N, ym.begin() + (ptrdiff_t) (j * N)); + std::copy_n(y_f.begin() + (ptrdiff_t) ((size_t) slot[i] * N), N, yf.begin() + (ptrdiff_t) (j * N)); + } + auto id = [](size_t j) { return (int64_t) j; }; + const Err em = compare(ym, id, ref, id, pick.size()), ef = compare(yf, id, ref, id, pick.size()); + std::printf(" sample of %zu pairs vs FP32 reference: MMQ rel RMS %.3e worst %.3e, fused rel RMS %.3e worst " + "%.3e\n", pick.size(), em.rms, em.worst, ef.rms, ef.worst); + if (ef.rms > 1.5 * em.rms || ef.worst > 2.0 * em.worst) + throw std::runtime_error(std::string(p.name) + ": the fused path's error is not comparable to MMQ's (timing)"); + } + cudaEventDestroy(a); + cudaEventDestroy(b); + if (efm.rms > 0.05) throw std::runtime_error(std::string(p.name) + ": the paths disagree at the real shape"); +} +} // namespace + +int main(int argc, char** argv) { + try { +#ifdef _WIN32 + _putenv_s("STRATA_PF_FUSED", "1"); +#else + setenv("STRATA_PF_FUSED", "1", 1); +#endif + int n = 0; + if (cudaGetDeviceCount(&n) != cudaSuccess || n == 0) { std::printf("no CUDA device: skipped\n"); return 77; } + if (!fused::available()) { std::printf("the fused kernels need sm_80 or newer: skipped\n"); return 77; } + if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; } + const std::vector pairs = { + {GGML_TYPE_IQ2_S, GGML_TYPE_Q2_0, "IQ2_S / Q2_0"}, {GGML_TYPE_IQ2_XXS, GGML_TYPE_Q2_0, "IQ2_XXS / Q2_0"}, + {GGML_TYPE_IQ2_XS, GGML_TYPE_IQ4_NL, "IQ2_XS / IQ4_NL"}, {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ4_NL, "IQ3_XXS / IQ4_NL"}, + {GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, "IQ3_S / IQ4_NL"}, {GGML_TYPE_IQ4_XS, GGML_TYPE_Q2_0, "IQ4_XS / Q2_0"}}; + const char* only = nullptr; // --only=NAME: the pairs whose name contains NAME + for (int i = 1; i < argc; ++i) + if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7; + bool timing = true, ref = true; // --no-timing, --no-ref: skip a part + std::vector chunks = {2048, 3584, 8192}; // --chunks=A,B: the timing part's chunk sizes + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--no-timing") == 0) timing = false; + if (std::strcmp(argv[i], "--no-ref") == 0) ref = false; + if (std::strncmp(argv[i], "--chunks=", 9) == 0) { + chunks.clear(); + for (const char* c = argv[i] + 9; *c;) { + chunks.push_back(std::atoi(c)); + while (*c && *c != ',') ++c; + if (*c == ',') ++c; + } + } + } + cudaStream_t s = nullptr; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + for (const Pair& p : pairs) { + if (only && std::string(p.name).find(only) == std::string::npos) continue; + if (!fused::native_supported((int) p.gu, (int) p.d)) + throw std::runtime_error(std::string(p.name) + ": not covered by the native kernels"); + if (ref) reference_part(p, s); + } + if (timing) { + // the IQ2_XS pack's layers (34 of 48 IQ2_S / Q2_0, 11 IQ2_XXS / Q2_0), the IQ3_S pack's most common, IQ3_XXS's + for (const Pair& p : {pairs[0], pairs[1], pairs[4], pairs[3]}) { + if (only && std::string(p.name).find(only) == std::string::npos) continue; + for (int T : chunks) timing_part(p, T, s); + } + } + ck(cudaStreamDestroy(s), "destroy"); + std::printf("prefill fused MoE (native formats) parity passed\n"); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "prefill fused MoE (native formats) parity failed: %s\n", e.what()); + return 1; + } +}