diff --git a/CMakeLists.txt b/CMakeLists.txt index e28abd9b..c4b684a1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -85,6 +85,10 @@ if(STRATA_Q6K_EXPERTS) add_compile_definitions(STRATA_Q6K_EXPERTS=1) endif() option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_K_S" OFF) +# STRATA_MMQ_DIRECT (opt-in at run time): the prompt path's MMQ reads resident experts in their cache slots through a +# Strata-side copy of llama.cpp's MMQ scheduler with a per-expert pointer table (src/prefill/moe_mmq_tab.cuh). CUDA +# only; switched off at configure time when the llama.cpp tree's mmq.cuh is not one the copy was verified against. +option(STRATA_MMQ_TAB "prompt MMQ reads resident experts in place (STRATA_MMQ_DIRECT=1; CUDA)" ON) if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP) message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON") endif() @@ -1455,6 +1459,44 @@ if(STRATA_NATIVE_EXPERTS) endif() target_link_libraries(strata_mmq_w4a4 PUBLIC ggml-base ${_strata_gpu_runtime_target}) target_link_libraries(strata_mmq PRIVATE strata_mmq_w4a4) + # STRATA_MMQ_TAB: the pointer-table copy of MMQ's scheduler mirrors mmq.cuh from mul_mat_q_process_tile through + # mul_mat_q_case (struct mmq_args included). A fingerprint of that text instead of a compile probe: nothing is + # compiled at configure time, and a llama.cpp tree with another scheduler turns the feature off instead of + # failing the build. _strata_mmq_tab_known: the hashes moe_mmq_tab.cuh was verified against (3cf03257, the + # fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh). + set(_strata_mmq_tab_on OFF) + if(STRATA_MMQ_TAB) + set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0) + set(_strata_mmq_tab_hash "") + if(EXISTS ${_strata_mmq}/mmq.cuh) + file(READ ${_strata_mmq}/mmq.cuh _strata_mmq_src) + string(REPLACE "\r\n" "\n" _strata_mmq_src "${_strata_mmq_src}") + string(FIND "${_strata_mmq_src}" "static __device__ __forceinline__ void mul_mat_q_process_tile" _strata_tab_a) + string(FIND "${_strata_mmq_src}" "#define DECL_MMQ_CASE" _strata_tab_b) + if(_strata_tab_a GREATER -1 AND _strata_tab_b GREATER _strata_tab_a) + math(EXPR _strata_tab_len "${_strata_tab_b} - ${_strata_tab_a}") + string(SUBSTRING "${_strata_mmq_src}" ${_strata_tab_a} ${_strata_tab_len} _strata_tab_region) + string(SHA256 _strata_mmq_tab_hash "${_strata_tab_region}") + endif() + unset(_strata_mmq_src) + unset(_strata_tab_region) + endif() + if(_strata_mmq_tab_hash AND _strata_mmq_tab_hash IN_LIST _strata_mmq_tab_known) + set(_strata_mmq_tab_on ON) + else() + message(STATUS "STRATA_MMQ_TAB off: mmq.cuh differs from the mirrored scheduler (${_strata_mmq_tab_hash})") + endif() + endif() + if(_strata_mmq_tab_on) + set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh) + foreach(_t IN LISTS _strata_mmq_cuda_types) + string(TOUPPER ${_t} _strata_tab_T) + configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu @ONLY) + target_sources(strata_mmq PRIVATE ${CMAKE_BINARY_DIR}/mmq_tab/mmq-tab-${_t}.cu) + endforeach() + target_compile_definitions(strata_mmq PRIVATE STRATA_MMQ_TAB=1) + message(STATUS "STRATA_MMQ_TAB on: pointer-table MMQ for ${_strata_mmq_cuda_types}") + endif() target_include_directories(strata_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq} PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_compile_options(strata_mmq PRIVATE $<$:--extended-lambda -use_fast_math>) @@ -1515,6 +1557,13 @@ if(STRATA_NATIVE_EXPERTS) 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_tab_on) + # STRATA_MMQ_DIRECT: the pointer-table MMQ bit for bit against the gathered MMQ (exit 77 below sm_80) + add_executable(prefill_mmq_tab_test tests/cuda/prefill_mmq_tab_test.cu) + target_link_libraries(prefill_mmq_tab_test PRIVATE strata_mmq ggml-base ${_strata_gpu_runtime_target}) + add_test(NAME prefill_mmq_tab_test COMMAND prefill_mmq_tab_test) + set_tests_properties(prefill_mmq_tab_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) add_executable(prefill_mmq_kquant_test tests/cuda/prefill_mmq_kquant_test.cpp) diff --git a/include/strata/prefill/moe_mmq.hpp b/include/strata/prefill/moe_mmq.hpp index 7c37fb41..3492023c 100644 --- a/include/strata/prefill/moe_mmq.hpp +++ b/include/strata/prefill/moe_mmq.hpp @@ -47,6 +47,14 @@ void scale_gu_rows(float* gu, int64_t ld, int64_t n_ff, const int32_t* bounds, i /// output, not folded into up, where the hidden would sit near 1e-5 (FP16-subnormal block scales in q8 formats). void scale_down_rows(float* d, int64_t ld, const int32_t* bounds, int n, const float* tails, int64_t nrows, void* stream); +constexpr int kGatherGroupMax = 16; +/// STRATA_MMQ_DIRECT: each expert's own weight address (gate|up or down), in place of `w + z * expert_bytes` - +/// expert z < n <= kGatherGroupMax starts at p[z]. The launch (tiles, stream-k split, fixup) is the same as +/// with `w`: only the base address of each expert's matrix changes. +struct WeightTab { + const void* p[kGatherGroupMax] = {}; +}; + /// One launch over n experts whose weights lie `expert_bytes` apart from `w`: for expert e, the activation rows /// [bounds[e], bounds[e+1]) of `xq` (bounds on the device, n+1 entries) times its [w_rows, w_cols] matrix into /// dst rows of the same indices (`ld_dst` floats apart, via `ids`: dst row = ids[row], an identity table works). @@ -64,6 +72,9 @@ struct Product { float* dst = nullptr; int64_t ld_dst = 0; const float* y_scale = nullptr; ///< NVFP4 w4a4: the per-row activation scales (fp4_activations) + /// set: expert z's matrix starts at tab->p[z] (w and expert_bytes are not used for addressing). CUDA only, + /// and only where `tab_fits` said so. + const WeightTab* tab = nullptr; }; /// The launch context (llama.cpp's MMQ keeps a small scratch pool for its stream-k fixup). One per prompt path. @@ -91,7 +102,6 @@ void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const /// each. Every pointer, offset and size 16-byte aligned (false otherwise: nothing launched, gather one at a time). /// NVFP4: `tail_off` (0 = none) is each blob's 16-byte tail, copied to tail_dst + 16 q; `zero_bytes` are zeroed after /// the last expert's gu and d slots (the MMQ tail). -constexpr int kGatherGroupMax = 16; struct GatherGroup { const uint8_t* blob[kGatherGroupMax] = {}; int first = 0, n = 0; @@ -120,4 +130,29 @@ void f16_to_f32(const uint16_t* x, float* y, int64_t n, void* stream); /// dst = {0, rows} (the bounds of one matrix; dst on the device). void set_bounds(int32_t* dst, int32_t rows, void* stream); +// ---- STRATA_MMQ_DIRECT: the prompt MMQ reads resident experts in place (docs: README, "STRATA_MMQ_DIRECT") ---- +/// This build has the pointer-table MMQ (CUDA, STRATA_MMQ_TAB on: the llama.cpp tree matched the mirrored +/// scheduler's fingerprint). false under HIP, SYCL and builds without MMQ. +bool tab_built(); +/// `tab_built`, `fits`, rows a multiple of 128 (no fallback tiles) and a pointer-table instance for the type. +bool tab_fits(int ggml_type, int64_t w_rows); +/// The bytes past a [rows, cols] matrix that its last row's final K tile reads (the largest K tile of any config +/// on any visible GPU): 72 for IQ4_NL and 136 for Q8_0 at 640 columns, 0 for IQ3_S at 2560. 0 without MMQ. +size_t overread_bytes(int ggml_type, int64_t cols); +/// The room kept after each sized expert slot's blob for that over-read (the guard). +constexpr size_t kSlotGuard = 256; +/// STRATA_MMQ_DIRECT, read once: 0 (default) today's gather; 1 the guard layout and resident experts read in +/// place; 2 the guard layout with today's gather (the bitwise A/B reference). 0 whenever !tab_built(). +int direct_mode(); +/// kSlotGuard when direct_mode() != 0, else 0 (no CUDA call). +size_t direct_slot_guard(); +/// The guards a group's direct experts' down over-reads land in (each `guard_bytes` long). +struct GuardTab { + uint8_t* p[kGatherGroupMax] = {}; + int n = 0; +}; +/// One launch: zeroes `guard_bytes` at each g.p[i] and `tail_bytes` at tail_gu and tail_d (null: skipped). It +/// replaces the two tail memsets of a group in direct mode. Nothing is launched when there is nothing to zero. +void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream); + } // namespace strata::prefill::mmq diff --git a/src/prefill/mmq_tab_instance.cu.in b/src/prefill/mmq_tab_instance.cu.in new file mode 100644 index 00000000..10da98b6 --- /dev/null +++ b/src/prefill/mmq_tab_instance.cu.in @@ -0,0 +1,8 @@ +// Generated by CMake from src/prefill/mmq_tab_instance.cu.in (STRATA_MMQ_TAB): the pointer-table MMQ for one type, +// in its own TU so nvcc builds the types in parallel and each object stays small. +#include "@_strata_tab_cuh@" + +namespace strata::prefill::mmq { +template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, + cudaStream_t); +} // namespace strata::prefill::mmq diff --git a/src/prefill/moe_mmq.cu b/src/prefill/moe_mmq.cu index 9861b607..6b2b019c 100644 --- a/src/prefill/moe_mmq.cu +++ b/src/prefill/moe_mmq.cu @@ -6,9 +6,13 @@ #include "common.cuh" #include "mmq.cuh" #include "quantize.cuh" +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) +#include "moe_mmq_tab.hpp" // declarations only: the tab kernels live in the per-type mmq-tab-*.cu TUs +#endif #include "strata/prefill/mmq_kq_abi.hpp" +#include #include #include #include @@ -173,6 +177,68 @@ __global__ void set_bounds_kernel(int32_t* d, int32_t rows) { unsigned blocks(int64_t n) { return (unsigned) ((n + 255) / 256); } +// STRATA_MMQ_DIRECT: a group's guards (y < g.n, byte stores) and its two zero tails (y == g.n: gate/up, y == g.n + 1: +// down; uint4 stores when `tail16`, which the host checked: both pointers and the size 16-byte aligned) +__global__ void prep_group_kernel(GuardTab g, int64_t guard, uint8_t* tail_gu, uint8_t* tail_d, int64_t tail, bool tail16) { + const int y = (int) blockIdx.y; + const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; + if (y < g.n) { + if (i < guard) g.p[y][i] = 0; + return; + } + uint8_t* t = y == g.n ? tail_gu : tail_d; + if (t == nullptr) return; + if (tail16) { + if (i < tail / 16) ((uint4*) t)[i] = make_uint4(0, 0, 0, 0); + } else if (i < tail) { + t[i] = 0; + } +} + +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) +// the pointer-table MMQ per type: the same types and #ifdefs as Context::run's switch. false: no instance +bool run_tab(ggml_backend_cuda_context* ctx, const mmq_args* a, const mmq_x_tab* tab, cudaStream_t s) { + const ggml_type t = a ? a->type_x : GGML_TYPE_COUNT; +#define STRATA_TAB_CASE(T) case T: return ctx == nullptr || mul_mat_q_tab_case(*ctx, *a, *tab, s) + switch (t) { +#ifdef STRATA_ORCA_Q4KS_MMQ + STRATA_TAB_CASE(GGML_TYPE_Q5_0); +#endif + STRATA_TAB_CASE(GGML_TYPE_Q2_0); + STRATA_TAB_CASE(GGML_TYPE_IQ2_XXS); + STRATA_TAB_CASE(GGML_TYPE_IQ2_XS); + STRATA_TAB_CASE(GGML_TYPE_IQ2_S); + STRATA_TAB_CASE(GGML_TYPE_IQ3_XXS); + STRATA_TAB_CASE(GGML_TYPE_IQ3_S); + STRATA_TAB_CASE(GGML_TYPE_IQ4_NL); + STRATA_TAB_CASE(GGML_TYPE_IQ4_XS); + STRATA_TAB_CASE(GGML_TYPE_Q8_0); +#ifdef STRATA_MMQ_KQUANTS + STRATA_TAB_CASE(GGML_TYPE_Q4_K); + STRATA_TAB_CASE(GGML_TYPE_Q5_K); +#if defined(STRATA_Q6K_EXPERTS) + STRATA_TAB_CASE(GGML_TYPE_Q6_K); +#endif + STRATA_TAB_CASE(GGML_TYPE_Q5_1); +#endif + default: return false; + } +#undef STRATA_TAB_CASE +} +// whether run_tab has an instance for type t (no launch) +bool tab_has_type(int t) { + mmq_args a{}; + a.type_x = (ggml_type) t; + return run_tab(nullptr, &a, nullptr, nullptr); +} +#else +bool run_tab(ggml_backend_cuda_context*, const mmq_args*, const void*, cudaStream_t) { + std::fprintf(stderr, "prefill mmq: this build has no pointer-table MMQ (STRATA_MMQ_TAB)\n"); + std::exit(1); +} +bool tab_has_type(int) { return false; } +#endif + } // namespace // mmq_nvfp4_w4a8.cu: mmq.cuh's int8 NVFP4 path, compiled for this GPU with Blackwell's FP4 MMA hidden @@ -337,11 +403,30 @@ void Context::run(const Product& p, void* stream) { const int64_t qk = ggml_blck_size(t), bpr = p.w_cols / qk; const mmq_args a = {(const char*) p.w, t, (const int*) p.xq, p.ids, p.bounds, p.dst, p.y_scale, p.w_cols, p.w_rows, p.total_rows, bpr, p.total_rows, p.ld_dst, - p.n, p.n, (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0, + p.n, p.n, p.tab ? 0 : (int64_t) (p.expert_bytes / ggml_type_size(t)), 0, 0, 1, 1, 0, 0, 0, p.max_rows, p.max_rows}; auto& ctx = *(ggml_backend_cuda_context*) ctx_; const cudaStream_t s = (cudaStream_t) stream; + if (p.tab) { + if (p.n > kGatherGroupMax) { + std::fprintf(stderr, "prefill mmq: a pointer table holds at most %d experts (got %d)\n", kGatherGroupMax, p.n); + std::exit(1); + } +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) + mmq_x_tab tab{}; + for (int z = 0; z < p.n; ++z) tab.p[z] = (const char*) p.tab->p[z]; + if (!run_tab(&ctx, &a, &tab, s)) { + std::fprintf(stderr, "prefill mmq: no pointer-table MMQ for %s with %lld rows\n", ggml_type_name(t), + (long long) p.w_rows); + std::exit(1); + } +#else + run_tab(&ctx, &a, nullptr, s); +#endif + ck(cudaGetLastError(), "mul_mat_q (pointer table)"); + return; + } switch (t) { #ifdef STRATA_ORCA_Q4KS_MMQ case GGML_TYPE_Q5_0: mul_mat_q_case(ctx, a, s); break; @@ -383,6 +468,65 @@ void Context::run(const Product& p, void* stream) { ck(cudaGetLastError(), "mul_mat_q"); } +// ---- STRATA_MMQ_DIRECT ---- +bool tab_built() { +#if defined(STRATA_MMQ_TAB) && !defined(__HIPCC__) + return true; +#else + return false; +#endif +} + +bool tab_fits(int t, int64_t w_rows) { + return tab_built() && w_rows % 128 == 0 && tab_has_type(t) && fits(t, w_rows); +} + +size_t overread_bytes(int t, int64_t cols) { + if (!supported(t)) return 0; + // the longest K tile any (fallback=false) config reads on any visible GPU; MMQ_ITER_K when none is known + int64_t k_vram = MMQ_ITER_K; + const ggml_cuda_device_info& info = ggml_cuda_info(); + for (int id = 0; id < info.device_count; ++id) + for (int J = 8; J <= 128; J += 8) { + const ggml_cuda_mmq_config c = ggml_cuda_mmq_get_config((ggml_type) t, J, false, info.devices[id].cc); + if (c.type != GGML_TYPE_COUNT) k_vram = std::max(k_vram, c.K_vram); + } + const int64_t qk = ggml_blck_size((ggml_type) t), bpi = k_vram / qk, bpn = cols / qk; + if (bpi <= 0) return 0; + return (size_t) ((bpi - bpn % bpi) % bpi) * ggml_type_size((ggml_type) t); +} + +int direct_mode() { + static const int mode = [] { + const char* v = std::getenv("STRATA_MMQ_DIRECT"); + const int m = v ? std::atoi(v) : 0; + if (m != 1 && m != 2) return 0; + if (!tab_built()) { + std::fprintf(stderr, "strata: STRATA_MMQ_DIRECT=%d is ignored: this build has no pointer-table MMQ " + "(CUDA with STRATA_MMQ_TAB only)\n", m); + return 0; + } + return m; + }(); + return mode; +} + +size_t direct_slot_guard() { return direct_mode() != 0 ? kSlotGuard : 0; } + +void prep_group(const GuardTab& g, size_t guard_bytes, void* tail_gu, void* tail_d, size_t tail_bytes, void* stream) { + const int n = g.n > 0 ? std::min(g.n, kGatherGroupMax) : 0; + const size_t guard = n > 0 ? guard_bytes : 0; + const size_t tail = tail_gu || tail_d ? tail_bytes : 0; + if (guard == 0 && tail == 0) return; + GuardTab gt = g; + gt.n = guard > 0 ? n : 0; + const bool tail16 = ((uintptr_t) tail_gu | (uintptr_t) tail_d | tail_bytes) % 16 == 0; + const size_t span = std::max(guard, tail); + prep_group_kernel<<>>( + gt, (int64_t) guard, (uint8_t*) tail_gu, (uint8_t*) tail_d, (int64_t) tail, tail16); + ck(cudaGetLastError(), "prep_group"); +} + void gather_native(const void* gate, const void* up, size_t gu_half_bytes, const void* down, size_t d_bytes, void* gu_dst, void* d_dst, void* stream, const void* tail, void* tail_dst, size_t zero_bytes) { const cudaStream_t s = (cudaStream_t) stream; diff --git a/src/prefill/moe_mmq_tab.cuh b/src/prefill/moe_mmq_tab.cuh new file mode 100644 index 00000000..89099761 --- /dev/null +++ b/src/prefill/moe_mmq_tab.cuh @@ -0,0 +1,510 @@ +// src/prefill/moe_mmq_tab.cuh - STRATA_MMQ_DIRECT: llama.cpp's MMQ outer scheduler (ggml-cuda mmq.cuh, MIT) with a +// per-expert pointer table, so the prompt path's MMQ reads resident experts in their expert-cache slots instead of +// a gathered copy. Included only by the per-type instance TUs (CMake: mmq_tab_instance.cu.in); moe_mmq.cu sees +// the declarations in moe_mmq_tab.hpp. +// +// Mirrored from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d (the fetched pin; the vendored third_party tree's +// mmq.cuh is byte-identical to it), ggml/src/ggml-cuda/mmq.cuh: +// mul_mat_q lines 953-1238 -> mul_mat_q_tab +// launch_mul_mat_q lines 1395-1475 -> launch_mul_mat_q_tab +// mul_mat_q_switch_J lines 1477-1558 -> mul_mat_q_tab_switch_J +// fallback = false only (mul_mat_q_tab_case refuses rows % 128 != 0). Everything else is the upstream text, and +// mul_mat_q_process_tile, the tile loaders, vec_dot, write_back and mul_mat_q_stream_k_fixup are upstream's own +// templates from the same mmq.cuh, compiled in the same target with the same flags. Deliberate deviations: +// 1. at the three offset_x sites the expert's base is `tab.p[fastdiv(zt, channel_ratio)]` and the +// fastdiv(zt, channel_ratio)*stride_channel_x term leaves offset_x (stride_channel_x is still passed, unused); +// 2. the launcher raises the shared-memory limit of mul_mat_q_tab only - upstream's line for +// mul_mat_q is dropped, so no fallback=true kernel is instantiated. +// The launch geometry (J, tiles, the stream-k grid and k split, the fixup) is computed from the same mmq_args as +// upstream's, so every output tile is summed in the same order: the results are bitwise the same as gathering the +// experts `stride_channel_x` apart (tests/cuda/prefill_mmq_tab_test.cu checks it per type and J). +// CMake turns STRATA_MMQ_TAB off unless the SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through +// mul_mat_q_case, which includes struct mmq_args) is one this copy was verified against; when the llama.cpp pin +// moves, re-sync this file, re-run the test and record the new hash in CMakeLists.txt (_strata_mmq_tab_known). +#pragma once + +#include "mmq.cuh" +#include "moe_mmq_tab.hpp" + +#include + +namespace strata::prefill::mmq { + +// A second net behind the configure fingerprint: the upstream templates this copy calls keep their signatures. +static_assert(std::is_same), + void (*)(const char*, int, const int*, const int*, float*, float*, const float*, int, int, int, + int, int, int, int)>::value, + "mmq.cuh: mul_mat_q_process_tile changed - re-sync src/prefill/moe_mmq_tab.cuh"); +static_assert(std::is_same), + void (*)(const int32_t*, const int32_t*, float*, float*, uint3, int, int, int, uint3, int, + uint3, int, uint3)>::value, + "mmq.cuh: mul_mat_q_stream_k_fixup changed - re-sync src/prefill/moe_mmq_tab.cuh"); + +// ---- mirrored: mul_mat_q (fallback = false, per-expert base from `tab`) ---- +template +__launch_bounds__(ggml_cuda_mmq_get_nthreads(type, J, false), ggml_cuda_mmq_get_occupancy(type, J, false)) +static __global__ void mul_mat_q_tab( + const mmq_x_tab tab, const int * __restrict__ y, const int32_t * __restrict__ ids_dst, + const int32_t * __restrict__ expert_bounds, float * __restrict__ dst, float * __restrict__ tmp_fixup, + const float * __restrict__ y_scale, + const uint3 blocks_per_ne00, const int nrows_x, const int ncols_dst, const int stride_row_x, const int ncols_y, const int stride_col_dst, + const uint3 channel_ratio, const uint3 nchannels_y, const int stride_channel_x, const int stride_channel_y, const int stride_channel_dst, + const uint3 sample_ratio, const uint3 nsamples_y, const int stride_sample_x, const int stride_sample_y, const int stride_sample_dst, + const uint3 ntx) { + constexpr bool fallback = false; // STRATA: the tab copy has no fallback (rows % 128 == 0) instantiation + + // Skip unused template specializations for faster compilation: + if (ggml_cuda_mmq_get_config(type, J, fallback).type == GGML_TYPE_COUNT) { + NO_DEVICE_CODE; + return; + } + + constexpr int warp_size = ggml_cuda_get_physical_warp_size(); + constexpr int nwarps = ggml_cuda_mmq_get_nthreads(type, J, fallback) / warp_size; + constexpr int qk = ggml_cuda_type_traits::qk; + constexpr int I = ggml_cuda_mmq_get_I(type, J, fallback); + + const uint32_t nty = (nrows_x + I - 1) / I; // Number of tiles y + + // Initialize the ids for writing back data with just the index. + // For regular matrix multiplications this is never changed. + // For MoE the correct indices are loaded from ids_dst. + extern __shared__ int ids_dst_shared[]; // Stored at beginning of shared memory. +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = j; + } + __syncthreads(); + + if constexpr (!ggml_cuda_mmq_get_stream_k(type, J, fallback)) { + const uint2 tmp2 = fast_div_modulo(blockIdx.z, nchannels_y); + const int wt = tmp2.x; + const int zt = tmp2.y; + const int jt = blockIdx.y; + const int it = blockIdx.x; + + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); + } + + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; + + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } + + if (jt*J >= col_diff) { + return; + } + + // __syncthreads(); // There is no previous tile that could cause a race condition. +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = ids_dst[col_low + jt*J + j]; + } + __syncthreads(); + } + + offset_y += (col_low + jt*J)*(sizeof(block_q8_1_mmq)/sizeof(int)); + offset_dst += it*I; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt*J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } + + const int tile_x_max_i = nrows_x - it*I - 1; + const int tile_y_max_j = col_diff - jt*J - 1; + + const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; + + constexpr bool fixup = false; + mul_mat_q_process_tile + (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, 0, blocks_per_ne00.z); + return; + } + + constexpr int ITER_K = ggml_cuda_mmq_get_K_vram(type, J, fallback); + constexpr int blocks_per_iter = ITER_K / qk; + + // kbc == k block continuous, current index in continuous ijk space. + int kbc = int64_t(blockIdx.x) *(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x; + int kbc_stop = int64_t(blockIdx.x + 1)*(nsamples_y.z*nchannels_y.z*ntx.z*nty*blocks_per_ne00.z) / gridDim.x; + + kbc -= fastmodulo(kbc, blocks_per_ne00) % blocks_per_iter; + kbc_stop -= fastmodulo(kbc_stop, blocks_per_ne00) % blocks_per_iter; + + // kb0 == k index when doing the matrix multiplication for an output tile. + int kb0_start = fastmodulo(kbc, blocks_per_ne00); + int kb0_stop = min(blocks_per_ne00.z, uint32_t(kb0_start + kbc_stop - kbc)); + while (kbc < kbc_stop && kb0_stop == int(blocks_per_ne00.z)) { + int tmp = fastdiv(kbc, blocks_per_ne00); + uint2 tmp2 = fast_div_modulo(tmp, ntx); + const int jt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nchannels_y); + const int zt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nsamples_y); + const int wt = tmp2.y; + const int it = tmp2.x; + + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); + } + + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; + + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } + + if (jt*J >= col_diff) { + kbc += blocks_per_ne00.z; + kbc -= fastmodulo(kbc, blocks_per_ne00); + + kb0_start = 0; + kb0_stop = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc)); + + continue; + } + + __syncthreads(); +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = ids_dst[col_low + jt*J + j]; + } + __syncthreads(); + } + + offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int)); + offset_dst += it*I; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt * J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } + + const int tile_x_max_i = nrows_x - it*I - 1; + const int tile_y_max_j = col_diff - jt*J - 1; + + const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; + + constexpr bool fixup = false; // All but (potentially) the last iterations write their data to dst rather than the fixup buffer. + mul_mat_q_process_tile + (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop); + + kbc += blocks_per_ne00.z; + kbc -= fastmodulo(kbc, blocks_per_ne00); + + kb0_start = 0; + kb0_stop = min(blocks_per_ne00.z, uint32_t(kbc_stop - kbc)); + } + + if (kbc >= kbc_stop) { + return; + } + + int tmp = fastdiv(kbc, blocks_per_ne00); + uint2 tmp2 = fast_div_modulo(tmp, ntx); + const int jt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nchannels_y); + const int zt = tmp2.y; + tmp = tmp2.x; + tmp2 = fast_div_modulo(tmp, nsamples_y); + const int wt = tmp2.y; + const int it = tmp2.x; + + // Defaults for regular matrix multiplication: + int col_low = 0; + int col_high = ncols_dst; + int col_diff = ncols_dst; + int offset_y = wt*stride_sample_y + zt*stride_channel_y; + int offset_dst = wt*stride_sample_dst + zt*stride_channel_dst + jt*J*stride_col_dst; + int offset_y_scale; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = wt*nchannels_y.z*ncols_y + zt*ncols_y; + } else { + GGML_UNUSED(offset_y_scale); + } + + if (ids_dst) { + col_low = expert_bounds[zt + 0]; + col_high = expert_bounds[zt + 1]; + col_diff = col_high - col_low; + + offset_y = 0; + offset_dst = 0; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale = 0; + } + + if (jt*J >= col_diff) { + return; + } + + // The memory layout for the fixup buffer is always contiguous, therefore reset ids: + __syncthreads(); +#pragma unroll + for (int j0 = 0; j0 < J; j0 += nwarps*warp_size) { + const int j = j0 + threadIdx.y*warp_size + threadIdx.x; + + if (j0 + nwarps*warp_size > J && j >= J) { + break; + } + + ids_dst_shared[j] = j; + } + __syncthreads(); + } + + offset_y += (col_low + jt * J) * (sizeof(block_q8_1_mmq) / sizeof(int)); + offset_dst += it*I; + const float * y_scale_tile = nullptr; + if constexpr (type == GGML_TYPE_NVFP4) { + offset_y_scale += col_low + jt * J; + y_scale_tile = y_scale ? y_scale + offset_y_scale : nullptr; + } + + const int tile_x_max_i = nrows_x - it*I - 1; + const int tile_y_max_j = col_diff - jt*J - 1; + + const char * xz = tab.p[fastdiv(zt, channel_ratio)]; // STRATA: per-expert base + const int offset_x = fastdiv(wt, sample_ratio)*stride_sample_x + it*I*stride_row_x; + + constexpr bool fixup = true; // Last index writes its data to fixup buffer to avoid data races with other blocks. + mul_mat_q_process_tile + (xz, offset_x, y + offset_y, ids_dst_shared, dst + offset_dst, tmp_fixup, y_scale_tile, + stride_row_x, ncols_y, stride_col_dst, + tile_x_max_i, tile_y_max_j, kb0_start, kb0_stop); +} + +// ---- mirrored: launch_mul_mat_q (fallback = false) ---- +template +static void launch_mul_mat_q_tab(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) { + constexpr bool fallback = false; + const int id = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[id].cc; + const int nsm = ggml_cuda_info().devices[id].nsm; + const int warp_size = ggml_cuda_info().devices[id].warp_size; + + const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc); + GGML_ASSERT(config.nthreads % warp_size == 0); + const int nwarps = config.nthreads / warp_size; + const int nbytes_shared = mmq_get_nbytes_shared(config, cc); + + const dim3 block_dims(warp_size, nwarps, 1); + + CUDA_SET_SHARED_MEMORY_LIMIT((mul_mat_q_tab), nbytes_shared); // STRATA: no fallback=true line + + const int nty = (args.nrows_x + config.I - 1) / config.I; + const int ntx = (args.ncols_max + config.J - 1) / config.J; + const int ntzw = args.nchannels_y * args.nsamples_y; + const dim3 block_nums_xy_tiling(nty, ntx, ntzw); + + GGML_ASSERT(args.nchannels_y % args.nchannels_x == 0); + GGML_ASSERT(args.nsamples_y % args.nsamples_x == 0); + const int channel_ratio = args.nchannels_y / args.nchannels_x; + const int sample_ratio = args.nsamples_y / args.nsamples_x; + + const uint3 blocks_per_ne00_fd = init_fastdiv_values(args.ncols_x / ggml_cuda_type_traits::qk); + const uint3 ntx_fd = init_fastdiv_values(ntx); + const uint3 nchannels_y_fd = init_fastdiv_values(args.nchannels_y); + const uint3 nsamples_y_fd = init_fastdiv_values(args.nsamples_y); + const uint3 channel_ratio_fd = init_fastdiv_values(channel_ratio); + const uint3 sample_ratio_fd = init_fastdiv_values(sample_ratio); + + if (!ggml_cuda_mmq_get_stream_k(type, J, fallback, cc)) { + mul_mat_q_tab<<>> + (tab, args.y, args.ids_dst, args.expert_bounds, args.dst, nullptr, args.y_scale, + blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, + channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, + sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, + ntx_fd); + return; + } + + // For the stream-k kernel it is possible to run it with tiling by setting the number of CUDA blocks equal to the number of tiles. + // This is worthwhile if the efficiency of tiling is high and skipping the fixup kernel is more important. + const int ntiles_dst = ntx * nty * ntzw; + const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm; + const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves); + const dim3 block_nums_stream_k(GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : nsm, 1, 1); + + GGML_ASSERT(ntiles_dst * blocks_per_ne00_fd.z < (1 << 30)); // Assert that variable kbc will not overflow. + + const bool fixup_needed = ntiles_dst % block_nums_stream_k.x != 0; + + ggml_cuda_pool & pool = ctx.pool(id); + ggml_cuda_pool_alloc tmp_fixup(pool); + if (fixup_needed) { + tmp_fixup.alloc(block_nums_stream_k.x * config.J*config.I); + } + + const dim3 block_nums_fixup(block_nums_stream_k.x, config.I/warp_size, 1); + const dim3 block_dims_fixup(block_dims.x, block_dims.y/2, block_dims.z); + + mul_mat_q_tab<<>> + (tab, args.y, args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, args.y_scale, + blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, args.stride_row_x, args.ncols_y, args.nrows_dst, + channel_ratio_fd, nchannels_y_fd, args.stride_channel_x, args.stride_channel_y, args.stride_channel_dst, + sample_ratio_fd, nsamples_y_fd, args.stride_sample_x, args.stride_sample_y, args.stride_sample_dst, + ntx_fd); + + if (!fixup_needed) { + return; + } + + CUDA_CHECK(cudaGetLastError()); + mul_mat_q_stream_k_fixup<<>> + (args.ids_dst, args.expert_bounds, args.dst, tmp_fixup.ptr, blocks_per_ne00_fd, args.nrows_x, args.ncols_dst, + args.nrows_dst, nchannels_y_fd, args.stride_channel_dst, nsamples_y_fd, args.stride_sample_dst, + ntx_fd); +} + +// ---- mirrored: mul_mat_q_switch_J (fallback = false) ---- +template +static void mul_mat_q_tab_switch_J(ggml_backend_cuda_context & ctx, const mmq_args & args, const mmq_x_tab & tab, cudaStream_t stream) { + constexpr bool fallback = false; + const int id = ggml_cuda_get_device(); + const int cc = ggml_cuda_info().devices[id].cc; + const size_t smpbo = ggml_cuda_info().devices[id].smpbo; + + int J_best = 0; + int ntiles_J_best = INT_MAX; + + for (int J = 8; J <= 128 && ntiles_J_best > 1; J += 8) { + const ggml_cuda_mmq_config config = ggml_cuda_mmq_get_config(type, J, fallback, cc); + if (config.type == GGML_TYPE_COUNT) { + continue; + } + + if (mmq_get_nbytes_shared(config, cc) > smpbo) { + continue; + } + + const int ntiles_x = (args.ncols_opt + config.J - 1) / config.J; + + if (ntiles_x < ntiles_J_best) { + J_best = J; + ntiles_J_best = ntiles_x; + } + } + + switch (J_best) { + case 8: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 16: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 24: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 32: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 40: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 48: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 56: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 64: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 72: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 80: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 88: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 96: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 104: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 112: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 120: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + case 128: + launch_mul_mat_q_tab(ctx, args, tab, stream); + break; + default: + fprintf(stderr, "J_best=%d\n", J_best); + GGML_ABORT("fatal error"); + break; + } +} + +template +bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s) { + if (a.nrows_x % 128 != 0) return false; // upstream would take the fallback configs: not mirrored + mul_mat_q_tab_switch_J(ctx, a, tab, s); + return true; +} + +} // namespace strata::prefill::mmq diff --git a/src/prefill/moe_mmq_tab.hpp b/src/prefill/moe_mmq_tab.hpp new file mode 100644 index 00000000..c0c2a8b5 --- /dev/null +++ b/src/prefill/moe_mmq_tab.hpp @@ -0,0 +1,41 @@ +// src/prefill/moe_mmq_tab.hpp - STRATA_MMQ_DIRECT: declarations of the pointer-table MMQ (moe_mmq_tab.cuh). +// moe_mmq.cu includes only this header, so the tab kernels are instantiated once, in the per-type TUs that CMake +// generates from mmq_tab_instance.cu.in (STRATA_MMQ_TAB on), never implicitly in moe_mmq.cu. +#pragma once + +#include "mmq.cuh" + +namespace strata::prefill::mmq { + +/// Expert z's weight matrix starts at p[z] (z < the launch's nchannels <= 16). +struct mmq_x_tab { + const char* p[16]; +}; + +/// llama.cpp's mul_mat_q_case for fallback=false, with the per-expert base address from `tab` instead of +/// x + z * stride_channel_x. false (nothing launched) when the rows are not a multiple of 128. +template +bool mul_mat_q_tab_case(ggml_backend_cuda_context& ctx, const mmq_args& a, const mmq_x_tab& tab, cudaStream_t s); + +#ifdef STRATA_ORCA_Q4KS_MMQ +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#endif +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#ifdef STRATA_MMQ_KQUANTS +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#if defined(STRATA_Q6K_EXPERTS) +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#endif +extern template bool mul_mat_q_tab_case(ggml_backend_cuda_context&, const mmq_args&, const mmq_x_tab&, cudaStream_t); +#endif + +} // namespace strata::prefill::mmq diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 2fa71c7c..e68855b7 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -79,6 +79,12 @@ void swiglu(const float*, float*, int64_t, int64_t, bool, void*) {} void swiglu_scaled(const float*, float*, int64_t, int64_t, const int32_t*, int, const float*, int64_t, void*) {} void down_row_scales(float*, const int32_t*, int, const float*, int64_t, void*) {} void iota(int32_t*, int64_t, void*) {} +bool tab_built() { return false; } +bool tab_fits(int, int64_t) { return false; } +size_t overread_bytes(int, int64_t) { return 0; } +int direct_mode() { return 0; } +size_t direct_slot_guard() { return 0; } +void prep_group(const GuardTab&, size_t, void*, void*, size_t, void*) {} } // namespace strata::prefill::mmq #endif #ifndef STRATA_PREFILL_FUSED diff --git a/tests/cuda/prefill_mmq_tab_test.cu b/tests/cuda/prefill_mmq_tab_test.cu new file mode 100644 index 00000000..d005de04 --- /dev/null +++ b/tests/cuda/prefill_mmq_tab_test.cu @@ -0,0 +1,469 @@ +// prefill_mmq_tab_test - STRATA_MMQ_DIRECT: the pointer-table MMQ (src/prefill/moe_mmq_tab.cuh, Product::tab) bit for +// bit against the gathered MMQ the prompt path runs today (experts copied `expert_bytes` apart, a zeroed 4096-byte +// tail after the last one). +// +// Part 1, per product type (IQ3_S gate/up [1280, 2560], IQ4_NL and Q8_0 down [2560, 640], and every other type with a +// pointer-table instance, at its pack shape): random valid expert matrices at scattered 256-aligned addresses, each +// followed by a guard filled with an fp16 NaN pattern (0xFF 0x7C); prep_group zeroes the over-read bytes, then the +// table launch; memcmp of the whole output (pre-filled with a NaN pattern in both runs) against the gathered launch. +// Sweep: 1..16 experts with mixed row counts {0,1,7,8,9,31,64,100,512,1000}; max_rows from 1 to 1000 so that every +// tile width J from 8 to 128 is taken (and max_rows above the largest count); few-tile launches (stream-k grid of +// nsm blocks with the fixup kernel) and many-tile ones (one block per tile). +// Part 2, negative control: the same table launch with the guards NOT zeroed must give non-finite values in a down +// product (proves the guard handling is load-bearing; skipped for types that read nothing past a matrix). +// Part 3, mixed groups as prefill.cpp's walk builds them: native expert blobs (gate|up|down) for IQ3_S + IQ4_NL and +// IQ3_S + Q8_0, some read in place (direct), the others gathered at compact positions c != q - one at a time +// (gather_native) or by gather_native_group with a mid-group flush (first > 0) - including groups whose last entry is +// direct and groups with no gathered entry; both products bitwise equal to all-gathered. +// Exit 77 without a CUDA device of sm_80 or newer or without the pointer-table build. +#include "strata/prefill/moe_mmq.hpp" + +#include "ggml.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +namespace mmq = strata::prefill::mmq; + +constexpr int G = mmq::kGatherGroupMax; +constexpr size_t TAIL = 4096; + +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; + size_t n = 0; + explicit Dev(size_t bytes) : n(bytes) { ck(cudaMalloc(&p, bytes), "cudaMalloc"); } + ~Dev() { cudaFree(p); } + Dev(const Dev&) = delete; + Dev& operator=(const Dev&) = delete; + uint8_t* b() const { return (uint8_t*) p; } +}; + +// random blocks with a sane fp16 scale at each block's start (every format here begins with it) +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_Q8_0 ? 0.0001f : 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); + if (t == GGML_TYPE_Q4_K || t == GGML_TYPE_Q5_K || t == GGML_TYPE_Q5_1) { + const ggml_fp16_t h2 = ggml_fp32_to_fp16(sc(rng) * ((rng() & 1) ? 1.0f : -1.0f)); + std::memcpy(m + b * bs + 2, &h2, 2); + } + } +} + +// host -> device, finished before any work on the (non-blocking) test stream starts: a pageable cudaMemcpy returns +// before its DMA lands, and the legacy stream does not order it against a cudaStreamNonBlocking stream +void upload(void* dst, const void* src, size_t n, const char* what) { + ck(cudaMemcpy(dst, src, n, cudaMemcpyHostToDevice), what); + ck(cudaDeviceSynchronize(), what); +} + +// the fp16 NaN pattern a guard holds before prep_group (0x7CFF little-endian at every even offset) +void fill_nan(uint8_t* dev, size_t n) { + std::vector h(n); + for (size_t i = 0; i < n; ++i) h[i] = (i & 1) ? 0x7C : 0xFF; + upload(dev, h.data(), n, "fill_nan"); +} + +struct Shape { + ggml_type t; + int64_t rows, cols; // the weight matrix [rows, cols] + const char* role; +}; + +// activations for `total` rows of `cols`, quantized for type t (q8_1), plus an identity map and the bounds +struct Acts { + Dev x, xq, ids, bounds; + int64_t total; + Acts(ggml_type t, int64_t cols, const std::vector& cnt, std::mt19937& rng, cudaStream_t s) + : x((size_t) std::max(1, sum(cnt)) * cols * 4), xq(mmq::q8_bytes(std::max(1, sum(cnt)), cols)), + ids((size_t) std::max(1, sum(cnt)) * 4), bounds((cnt.size() + 1) * 4), total(sum(cnt)) { + std::vector hx((size_t) std::max(1, total) * cols); + std::normal_distribution nd(0.0f, 1.0f); + for (auto& v : hx) v = nd(rng); + upload(x.p, hx.data(), hx.size() * 4, "x"); + std::vector hb(cnt.size() + 1, 0); + for (size_t i = 0; i < cnt.size(); ++i) hb[i + 1] = hb[i] + cnt[i]; + upload(bounds.p, hb.data(), hb.size() * 4, "bounds"); + mmq::iota((int32_t*) ids.p, std::max(1, total), s); + if (total > 0) mmq::quantize((const float*) x.p, nullptr, xq.p, (int) t, cols, cols, total, s); + ck(cudaStreamSynchronize(s), "acts"); + } + static int64_t sum(const std::vector& c) { + int64_t n = 0; + for (int v : c) n += v; + return n; + } +}; + +mmq::Product product(const Shape& sh, const Acts& a, int n, int64_t max_rows, float* dst) { + mmq::Product p; + p.type = (int) sh.t; p.w_rows = sh.rows; p.w_cols = sh.cols; + p.n = n; p.xq = a.xq.p; p.bounds = (const int32_t*) a.bounds.p; p.ids = (const int32_t*) a.ids.p; + p.total_rows = a.total; p.max_rows = max_rows; p.dst = dst; p.ld_dst = sh.rows; + return p; +} + +int g_cases = 0, g_fail = 0; + +bool same_bits(const Dev& a, const Dev& b, size_t n, const char* what) { + std::vector ha(n), hb(n); + ck(cudaMemcpy(ha.data(), a.p, n, cudaMemcpyDeviceToHost), "dtoh a"); + ck(cudaMemcpy(hb.data(), b.p, n, cudaMemcpyDeviceToHost), "dtoh b"); + ++g_cases; + if (std::memcmp(ha.data(), hb.data(), n) == 0) return true; + size_t i = 0; + while (i < n && ha[i] == hb[i]) ++i; + std::printf(" FAIL %s: first differing byte %zu of %zu\n", what, i, n); + if (std::getenv("TAB_TEST_DEBUG")) { + const float* fa = (const float*) ha.data(); + const float* fb = (const float*) hb.data(); + size_t nd = 0; + for (size_t k = 0; k < n / 4; ++k) + if (std::memcmp(fa + k, fb + k, 4) != 0) { + if (nd < 6) std::printf(" float %zu: %.9g vs %.9g\n", k, fa[k], fb[k]); + ++nd; + } + std::printf(" %zu floats differ\n", nd); + } + ++g_fail; + return false; +} + +bool any_nonfinite(const Dev& d, size_t floats) { + std::vector h(floats); + ck(cudaMemcpy(h.data(), d.p, floats * 4, cudaMemcpyDeviceToHost), "dtoh"); + for (float v : h) + if (!std::isfinite(v)) return true; + return false; +} + +// Part 1 + 2: one product, `cnt` rows per expert +void product_case(mmq::Context& ctx, const Shape& sh, const std::vector& cnt, int64_t max_rows, std::mt19937& rng, + cudaStream_t s, bool negative, const char* label) { + const int n = (int) cnt.size(); + const size_t eb = mmq::matrix_bytes((int) sh.t, sh.rows, sh.cols); + const size_t over = mmq::overread_bytes((int) sh.t, sh.cols); + Acts a(sh.t, sh.cols, cnt, rng, s); + // the experts' matrices on the host + std::vector> w((size_t) n, std::vector(eb)); + for (auto& m : w) fill_matrix(m.data(), sh.t, sh.rows, sh.cols, rng); + // gathered: back to back, a zeroed tail, the space after it NaN-patterned + Dev grp((size_t) n * eb + TAIL + 4096); + fill_nan(grp.b(), grp.n); + for (int z = 0; z < n; ++z) upload(grp.b() + (size_t) z * eb, w[(size_t) z].data(), eb, "grp"); + ck(cudaMemset(grp.b() + (size_t) n * eb, 0, TAIL), "tail"); + ck(cudaDeviceSynchronize(), "tail"); + // in place: scattered 256-aligned slots in one arena (shuffled order, random gaps), each with a NaN guard + const size_t stride = (eb + mmq::kSlotGuard + 255) / 256 * 256; + std::vector pos((size_t) n); + for (int z = 0; z < n; ++z) pos[(size_t) z] = (size_t) z; + std::shuffle(pos.begin(), pos.end(), rng); + std::uniform_int_distribution gap(0, 8); + Dev arena((size_t) n * (stride + 8 * 256) + 4096); + fill_nan(arena.b(), arena.n); + mmq::WeightTab tab; + mmq::GuardTab guards; + size_t at = 0; + std::vector where((size_t) n); + for (int k = 0; k < n; ++k) { + at += (size_t) gap(rng) * 256; + where[pos[(size_t) k]] = at; + at += stride; + } + for (int z = 0; z < n; ++z) { + uint8_t* p = arena.b() + where[(size_t) z]; + upload(p, w[(size_t) z].data(), eb, "arena"); + tab.p[z] = p; + guards.p[guards.n++] = p + eb; + } + const size_t out = (size_t) std::max(1, a.total) * (size_t) sh.rows * 4; + Dev ref(out), got(out); + fill_nan(ref.b(), out); + fill_nan(got.b(), out); + mmq::Product pr = product(sh, a, n, max_rows, (float*) ref.p); + pr.w = grp.p; pr.expert_bytes = eb; + ctx.run(pr, s); + if (!negative) mmq::prep_group(guards, over, nullptr, nullptr, 0, s); + mmq::Product pt = product(sh, a, n, max_rows, (float*) got.p); + pt.w = nullptr; pt.expert_bytes = 0; pt.tab = &tab; + ctx.run(pt, s); + ck(cudaStreamSynchronize(s), "run"); + char what[256]; + std::snprintf(what, sizeof what, "%s %s n=%d rows=%lld max_rows=%lld (%s)", ggml_type_name(sh.t), sh.role, n, + (long long) a.total, (long long) max_rows, label); + if (!negative) { + same_bits(ref, got, out, what); + return; + } + ++g_cases; + if (!any_nonfinite(got, out / 4)) { + std::printf(" FAIL negative control %s: no non-finite value with the guards left as NaN\n", what); + ++g_fail; + } else if (any_nonfinite(ref, (size_t) a.total * (size_t) sh.rows)) { + std::printf(" FAIL negative control %s: the gathered reference is not finite\n", what); + ++g_fail; + } +} + +std::vector random_counts(int n, std::mt19937& rng) { + static const int kRows[] = {0, 1, 7, 8, 9, 31, 64, 100, 512, 1000}; + std::uniform_int_distribution pick(0, 9); + std::vector c((size_t) n); + for (auto& v : c) v = kRows[pick(rng)]; + return c; +} +int64_t max_of(const std::vector& c) { + int64_t m = 0; + for (int v : c) m = std::max(m, v); + return m; +} + +void sweep(mmq::Context& ctx, const Shape& sh, bool full, std::mt19937& rng, cudaStream_t s) { + const int f0 = g_fail, c0 = g_cases; + // 1..16 experts, mixed counts (max_rows = the largest count, as prefill.cpp passes it) + for (int n = 1; n <= G; ++n) { + if (!full && n != 1 && n != 3 && n != 8 && n != G) continue; + for (int rep = 0; rep < (full ? 3 : 1); ++rep) { + std::vector c = random_counts(n, rng); + if (max_of(c) == 0) c[0] = 1; + product_case(ctx, sh, c, max_of(c), rng, s, false, "mixed"); + } + } + // every J: one expert with m rows, the others fewer; and max_rows above the largest count + static const int kMax[] = {1, 7, 8, 9, 16, 17, 24, 25, 32, 33, 40, 41, 48, 56, 64, 65, 72, 80, 88, 96, 100, 104, + 112, 120, 127, 128, 129, 300, 1000}; + for (int m : kMax) { + if (!full && m % 8 != 0 && m != 1 && m != 129) continue; + for (int n : {1, 5, 16}) { + if (!full && n == 5) continue; + std::uniform_int_distribution fewer(0, m); + std::vector c((size_t) n); + for (auto& v : c) v = fewer(rng); + c[(size_t) (rng() % (unsigned) n)] = m; + product_case(ctx, sh, c, m, rng, s, false, "J sweep"); + } + } + for (int n : {1, 4, 16}) { + std::vector c = random_counts(n, rng); + if (max_of(c) == 0) c[0] = 9; + product_case(ctx, sh, c, max_of(c) + 37, rng, s, false, "max_rows above the largest count"); + } + // experts with 0 rows at the ends and in the middle + product_case(ctx, sh, {0, 0, 5, 0, 1000, 0, 0}, 1000, rng, s, false, "empty experts"); + product_case(ctx, sh, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 1, rng, s, false, "only the last expert"); + std::printf("%-8s %-7s %4d cases, %s\n", ggml_type_name(sh.t), sh.role, g_cases - c0, + g_fail == f0 ? "all bitwise identical" : "FAILURES"); + // negative control: a down product that reads past its matrix, guards not zeroed + if (mmq::overread_bytes((int) sh.t, sh.cols) > 0) { + const int f1 = g_fail; + product_case(ctx, sh, {3, 64, 0, 17}, 64, rng, s, true, "negative"); + product_case(ctx, sh, {200}, 200, rng, s, true, "negative"); + std::printf("%-8s %-7s negative control (guards not zeroed): %s\n", ggml_type_name(sh.t), sh.role, + g_fail == f1 ? "non-finite output, as required" : "FAILED"); + } +} + +// Part 3: groups as prefill.cpp's walk builds them, both products +struct Pair { + ggml_type gu, d; +}; +void group_case(mmq::Context& ctx, const Pair& pr, const std::vector& cnt, const std::vector& direct, + bool group_gather, int flush_at, std::mt19937& rng, cudaStream_t s, const char* label) { + const int n = (int) cnt.size(); + const Shape gs{pr.gu, 1280, 2560, "gate/up"}, ds{pr.d, 2560, 640, "down"}; + const size_t gub = mmq::matrix_bytes((int) pr.gu, 1280, 2560), db = mmq::matrix_bytes((int) pr.d, 2560, 640); + const size_t up_off = gub / 2, down_off = gub, bytes = gub + db; + const size_t over = mmq::overread_bytes((int) pr.d, 640); + // native blobs, each in its own place: direct ones in "cache slots" with a guard, gathered ones elsewhere + std::vector> blob((size_t) n, std::vector(bytes)); + for (auto& b : blob) { + fill_matrix(b.data(), pr.gu, 1280, 2560, rng); + fill_matrix(b.data() + down_off, pr.d, 2560, 640, rng); + } + const size_t stride = (bytes + mmq::kSlotGuard + 255) / 256 * 256; + Dev arena((size_t) n * (stride + 4 * 256) + 4096); + fill_nan(arena.b(), arena.n); + std::vector at((size_t) n); + size_t o = 0; + for (int z = 0; z < n; ++z) { + o += (size_t) (rng() % 4) * 256; + at[(size_t) z] = arena.b() + o; + o += stride; + upload(at[(size_t) z], blob[(size_t) z].data(), bytes, "blob"); + } + Acts ag(pr.gu, 2560, cnt, rng, s), ad(pr.d, 640, cnt, rng, s); + const int64_t mr = std::max(1, max_of(cnt)); + const size_t out_g = (size_t) std::max(1, ag.total) * 1280 * 4, out_d = (size_t) std::max(1, ad.total) * 2560 * 4; + // reference: today's walk (gather at q, two tail memsets) + Dev rgu((size_t) G * gub + TAIL), rd((size_t) G * db + TAIL), ref_g(out_g), ref_d(out_d); + fill_nan(rgu.b(), rgu.n); + fill_nan(rd.b(), rd.n); + fill_nan(ref_g.b(), out_g); + fill_nan(ref_d.b(), out_d); + for (int q = 0; q < n; ++q) { + const uint8_t* b = at[(size_t) q]; + mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, rgu.b() + (size_t) q * gub, rd.b() + (size_t) q * db, s); + } + ck(cudaMemsetAsync(rgu.b() + (size_t) n * gub, 0, TAIL, s), "memset"); + ck(cudaMemsetAsync(rd.b() + (size_t) n * db, 0, TAIL, s), "memset"); + mmq::Product p = product(gs, ag, n, mr, (float*) ref_g.p); + p.w = rgu.p; p.expert_bytes = gub; + ctx.run(p, s); + p = product(ds, ad, n, mr, (float*) ref_d.p); + p.w = rd.p; p.expert_bytes = db; + ctx.run(p, s); + // direct: prefill.cpp's compute() in direct mode + Dev tgu_buf((size_t) G * gub + TAIL), td_buf((size_t) G * db + TAIL), got_g(out_g), got_d(out_d); + fill_nan(tgu_buf.b(), tgu_buf.n); + fill_nan(td_buf.b(), td_buf.n); + fill_nan(got_g.b(), out_g); + fill_nan(got_d.b(), out_d); + mmq::WeightTab tgu, td; + mmq::GuardTab gd; + mmq::GatherGroup gg; + int ns = 0; + auto flush = [&]() { + if (gg.n <= gg.first) return; + if (!mmq::gather_native_group(gg, up_off, gub / 2, down_off, db, tgu_buf.p, gub, td_buf.p, db, s)) + throw std::runtime_error("gather_native_group refused an aligned group"); + gg.first = gg.n; + }; + for (int q = 0; q < n; ++q) { + uint8_t* b = at[(size_t) q]; + if (direct[(size_t) q]) { + tgu.p[q] = b; + td.p[q] = b + down_off; + gd.p[gd.n++] = b + bytes; + } else { + const int c = ns++; + tgu.p[q] = tgu_buf.b() + (size_t) c * gub; + td.p[q] = td_buf.b() + (size_t) c * db; + if (group_gather) { + gg.blob[c] = b; + gg.n = c + 1; + } else { + mmq::gather_native(b, b + up_off, gub / 2, b + down_off, db, tgu_buf.b() + (size_t) c * gub, + td_buf.b() + (size_t) c * db, s); + } + } + if (group_gather && q == flush_at) flush(); // release_to's mid-group flush + } + if (group_gather) flush(); + mmq::prep_group(gd, over, ns ? tgu_buf.b() + (size_t) ns * gub : nullptr, ns ? td_buf.b() + (size_t) ns * db : nullptr, + TAIL, s); + p = product(gs, ag, n, mr, (float*) got_g.p); + p.tab = &tgu; + ctx.run(p, s); + p = product(ds, ad, n, mr, (float*) got_d.p); + p.tab = &td; + ctx.run(p, s); + ck(cudaStreamSynchronize(s), "group"); + char what[256]; + std::snprintf(what, sizeof what, "%s+%s group n=%d direct=%d %s (%s)", ggml_type_name(pr.gu), ggml_type_name(pr.d), n, + gd.n, group_gather ? "gather_native_group" : "gather_native", label); + std::string w1 = std::string(what) + " gate/up", w2 = std::string(what) + " down"; + same_bits(ref_g, got_g, out_g, w1.c_str()); + same_bits(ref_d, got_d, out_d, w2.c_str()); +} + +} // namespace + +int main() { + try { + int dev = 0; + cudaDeviceProp prop{}; + if (cudaGetDevice(&dev) != cudaSuccess || cudaGetDeviceProperties(&prop, dev) != cudaSuccess || prop.major < 8) { + std::printf("needs a CUDA device of sm_80 or newer: skipped\n"); + return 77; + } + if (!mmq::built() || !mmq::tab_built()) { + std::printf("no pointer-table MMQ in this build: skipped\n"); + return 77; + } + std::printf("%s (sm_%d%d, %d SMs)\n", prop.name, prop.major, prop.minor, prop.multiProcessorCount); + cudaStream_t s; + ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream"); + mmq::Context ctx; + std::mt19937 rng(20261011); + // the pack's three formats, fully; every other type with an instance, a shorter sweep + const Shape main_shapes[] = {{GGML_TYPE_IQ3_S, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_NL, 2560, 640, "down"}, + {GGML_TYPE_Q8_0, 2560, 640, "down"}}; + for (const Shape& sh : main_shapes) { + if (!mmq::tab_fits((int) sh.t, sh.rows)) { + std::printf("FAIL: no pointer-table MMQ for %s\n", ggml_type_name(sh.t)); + return 1; + } + std::printf("%-8s %-7s over-read past the matrix: %zu B\n", ggml_type_name(sh.t), sh.role, + mmq::overread_bytes((int) sh.t, sh.cols)); + sweep(ctx, sh, true, rng, s); + } + const Shape other[] = {{GGML_TYPE_IQ2_XXS, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ2_XS, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ2_S, 1280, 2560, "gate/up"}, {GGML_TYPE_IQ3_XXS, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_XS, 1280, 2560, "gate/up"}, {GGML_TYPE_Q8_0, 1280, 2560, "gate/up"}, + {GGML_TYPE_IQ4_NL, 1280, 2560, "gate/up"}, {GGML_TYPE_Q2_0, 2560, 640, "down"}}; + for (const Shape& sh : other) { + if (!mmq::tab_fits((int) sh.t, sh.rows)) { + std::printf("%-8s %-7s no pointer-table instance here: skipped\n", ggml_type_name(sh.t), sh.role); + continue; + } + sweep(ctx, sh, false, rng, s); + } + // Part 3 + const int f0 = g_fail, c0 = g_cases; + for (const Pair pr : {Pair{GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL}, Pair{GGML_TYPE_IQ3_S, GGML_TYPE_Q8_0}}) { + for (int gg = 0; gg < 2; ++gg) { + const bool group_gather = gg == 1; + // alternating direct / gathered, last entry direct + group_case(ctx, pr, {5, 0, 31, 64, 1, 100, 8, 9}, {0, 1, 0, 1, 1, 0, 0, 1}, group_gather, 3, rng, s, + "interleaved, last direct"); + // a full group, the first entries gathered, then mostly direct; flush after entry 5 + group_case(ctx, pr, {7, 8, 9, 31, 64, 100, 1, 0, 512, 3, 17, 33, 2, 64, 90, 128}, + {0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0}, group_gather, 5, rng, s, + "full group, last gathered"); + // every entry direct (ns == 0: no tails), and every entry gathered + group_case(ctx, pr, {12, 40, 0, 7}, {1, 1, 1, 1}, group_gather, -1, rng, s, "all direct"); + group_case(ctx, pr, {12, 40, 0, 7}, {0, 0, 0, 0}, group_gather, 1, rng, s, "all gathered"); + // one entry + group_case(ctx, pr, {1000}, {1}, group_gather, -1, rng, s, "one direct entry"); + // random mixes + for (int r = 0; r < 4; ++r) { + const int n = 1 + (int) (rng() % G); + std::vector c = random_counts(n, rng); + if (max_of(c) == 0) c[0] = 1; + std::vector d((size_t) n); + for (auto& v : d) v = (char) (rng() & 1); + group_case(ctx, pr, c, d, group_gather, (int) (rng() % (unsigned) n), rng, s, "random mix"); + } + } + } + std::printf("mixed groups: %d comparisons, %s\n", g_cases - c0, g_fail == f0 ? "all bitwise identical" : "FAILURES"); + cudaStreamDestroy(s); + std::printf("%d comparisons, %d failed\n", g_cases, g_fail); + return g_fail == 0 ? 0 : 1; + } catch (const std::exception& e) { + std::printf("error: %s\n", e.what()); + return 1; + } +}