[2/2] 35b-a3b perf -- consolidate mmq launches (#29)

* strata-poly: --mmq-tab, a layer's cached experts in pointer-table launches of 16 wherever their slots lie

Once follow() has traded slots, a layer's cached experts lie in many short runs and a decode window's
experts with rows went one MMQ launch each (205K launches in a 512-token decode on the 1060).  The
pointer-table MMQ the prompt path already has (src/prefill/moe_mmq_tab.cuh) takes up to 16 matrices by
address; Mmq::mul_tab wraps it for strata-poly and moe_rows() takes it for a class when that is fewer
launches than its runs.  Built under STRATA_POLY_MMQ_TAB (off by default, like STRATA_MMQ_TAB; same
fingerprint of mmq.cuh, now a CMake function both options use).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit 1a3b9a42f39132f6b02e0c8f9082a39ef9b898c2)

* strata-poly: make pointer-table MMQ opt-in at runtime

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Robert KarlandClaude Fable 5.1 authored and GitHub committed 2026-11-05 16:39:38 -08:00
1 parent 1fe9bec4cd
commit ff19037a1c
6 files changed
+204 -43

No files matched your search

+46 -16
View File
@@ -94,6 +94,30 @@ option(STRATA_ORCA_Q4KS_MMQ "Build the GGML Q5_0 MMQ instance for OrcaRouter Q4_
# only (not HIP, not gfx906); 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 "Build the pointer-table prompt MMQ for STRATA_MMQ_DIRECT=1 (CUDA; ~37 MiB VRAM per GPU)" OFF)
# strata-poly: the same pointer-table kernels (src/poly/mmq.cu's Mmq::mul_tab) for the cached experts of a routed
# layer, so that a layer's cached experts go in one launch per 16 wherever follow() has traded their slots to, instead
# of one per run of adjacent slots (Engine::moe_rows()). Off by default for the same reasons: VRAM for the eagerly
# loaded instances (~2 MiB a type) and nvcc time. CUDA only, gated by the same fingerprint of mmq.cuh.
option(STRATA_POLY_MMQ_TAB "Build the pointer-table MMQ for strata-poly's cached experts (CUDA; VRAM per type)" OFF)
# The SHA-256 of mmq.cuh's mirrored region (mul_mat_q_process_tile through mul_mat_q_case, struct mmq_args included)
# into `out`, or "" when the region is not found: src/prefill/moe_mmq_tab.cuh is a copy of that text and is used only
# with a tree it was verified against (_strata_mmq_tab_known, below).
function(strata_mmq_tab_fingerprint mmq_cuh out)
set(_hash "")
if(EXISTS ${mmq_cuh})
file(READ ${mmq_cuh} _src)
string(REPLACE "\r\n" "\n" _src "${_src}")
string(FIND "${_src}" "static __device__ __forceinline__ void mul_mat_q_process_tile" _a)
string(FIND "${_src}" "#define DECL_MMQ_CASE" _b)
if(_a GREATER -1 AND _b GREATER _a)
math(EXPR _len "${_b} - ${_a}")
string(SUBSTRING "${_src}" ${_a} ${_len} _region)
string(SHA256 _hash "${_region}")
endif()
endif()
set(${out} "${_hash}" PARENT_SCOPE)
endfunction()
set(_strata_mmq_tab_known 36e4dc716c504470ec09cc0852d29a6ac5eace257f6e5e72db3805ca4f043eb0)
if(STRATA_PREFILL_MMQ AND NOT STRATA_ENABLE_HIP)
message(FATAL_ERROR "STRATA_PREFILL_MMQ requires STRATA_ENABLE_HIP=ON")
endif()
@@ -1617,21 +1641,7 @@ if(STRATA_NATIVE_EXPERTS)
# fetched pin; the vendored third_party/llama.cpp tree has the same mmq.cuh).
set(_strata_mmq_tab_on OFF)
if(STRATA_MMQ_TAB AND NOT STRATA_HIP_GFX906) # gfx906 compiles no .cu from here (its HIP glob): no tab at all
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()
strata_mmq_tab_fingerprint(${_strata_mmq}/mmq.cuh _strata_mmq_tab_hash)
if(_strata_mmq_tab_hash AND _strata_mmq_tab_hash IN_LIST _strata_mmq_tab_known)
set(_strata_mmq_tab_on ON)
else()
@@ -2037,7 +2047,27 @@ if(STRATA_NATIVE_EXPERTS AND (STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) AND NOT S
add_library(strata_poly_mmq STATIC src/poly/mmq.cu src/prefill/ggml_cuda_host.cu ${_strata_mmq}/quantize.cu
${_strata_poly_mmq_instances})
target_include_directories(strata_poly_mmq PRIVATE ${_strata_gg}/include ${_strata_gg}/src ${_strata_mmq}
${CMAKE_CURRENT_SOURCE_DIR}/include)
${CMAKE_CURRENT_SOURCE_DIR}/include
${CMAKE_CURRENT_SOURCE_DIR}/src/prefill)
# STRATA_POLY_MMQ_TAB: the pointer-table kernels (src/prefill/moe_mmq_tab.cuh) for the types above but MXFP4, one
# TU each as for strata_mmq, under the same fingerprint of mmq.cuh
if(STRATA_POLY_MMQ_TAB AND STRATA_ENABLE_CUDA)
strata_mmq_tab_fingerprint(${_strata_mmq}/mmq.cuh _strata_poly_tab_hash)
if(_strata_poly_tab_hash AND _strata_poly_tab_hash IN_LIST _strata_mmq_tab_known)
set(_strata_tab_cuh ${CMAKE_CURRENT_SOURCE_DIR}/src/prefill/moe_mmq_tab.cuh)
set(_strata_poly_tab_types q4_0 q4_1 q5_0 q5_1 q8_0 q2_k q3_k q4_k q5_k q6_k iq1_s iq2_xxs iq2_xs iq2_s
iq3_xxs iq3_s iq4_nl iq4_xs)
foreach(_t IN LISTS _strata_poly_tab_types)
string(TOUPPER ${_t} _strata_tab_T)
configure_file(src/prefill/mmq_tab_instance.cu.in ${CMAKE_BINARY_DIR}/poly_mmq_tab/mmq-tab-${_t}.cu @ONLY)
target_sources(strata_poly_mmq PRIVATE ${CMAKE_BINARY_DIR}/poly_mmq_tab/mmq-tab-${_t}.cu)
endforeach()
target_compile_definitions(strata_poly_mmq PRIVATE STRATA_POLY_MMQ_TAB=1)
message(STATUS "STRATA_POLY_MMQ_TAB on: pointer-table MMQ for strata-poly's cached experts")
else()
message(STATUS "STRATA_POLY_MMQ_TAB off: mmq.cuh differs from the mirrored scheduler (${_strata_poly_tab_hash})")
endif()
endif()
target_compile_options(strata_poly_mmq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:--extended-lambda -use_fast_math>)
if(MSVC)
target_compile_options(strata_poly_mmq PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-Xcompiler=/bigobj>)
+56 -6
View File
@@ -1857,6 +1857,16 @@ void Engine::alloc() {
L.mmq = opt_.gpu_experts && rows_ >= opt_.stage_rows && Mmq::fits((int) L.gu_type, 2 * n_ff_exp_, n_embd_) &&
Mmq::fits((int) L.d_type, n_embd_, n_ff_exp_);
tiles = tiles || L.mmq;
// the pointer-table kernels have no tile for rows that are not a multiple of 128 (Mmq::mul_tab)
L.tab = L.mmq && opt_.mmq_tab && Mmq::tab((int) L.gu_type) && Mmq::tab((int) L.d_type) &&
(2 * n_ff_exp_) % 128 == 0 && n_embd_ % 128 == 0;
if (L.mmq && opt_.mmq_tab && !L.tab && !tab_warned_) {
tab_warned_ = true;
std::fprintf(stderr, "strata-poly: layer %d's cached experts go one launch per run of slots: %s\n", il,
Mmq::tab((int) L.gu_type) && Mmq::tab((int) L.d_type)
? "the expert width is not a multiple of 128"
: "this build has no pointer-table MMQ for their types (STRATA_POLY_MMQ_TAB)");
}
one_expert = std::max(one_expert, 2 * L.gu_bytes + L.d_bytes);
}
if (tiles) mmq_ = std::make_unique<Mmq>();
@@ -2559,6 +2569,11 @@ void Engine::moe_rows(Layer& L, int il, int n) {
// a staging round are; a launch for each class that has rows among them. The cache is filled a layer's
// experts side by side, so that is the whole layer until experts trade slots (follow()). A launch for each
// expert was a sixth of a long prompt's time in a model with 256 experts a layer.
//
// Once follow() has traded slots away, a layer's cached experts lie in many short runs, and a window's few
// experts with rows would go one launch each. The pointer-table kernel (Mmq::mul_tab) takes up to kTab of
// them wherever their slots lie: a class goes by the table when that is fewer launches than its runs. The
// table's launch runs over exactly the class's experts with rows, which group_ has class after class.
auto slot_of = [&](int j) { return L.slot[(size_t) chan_[(size_t) j]]; };
runs_.clear();
for (int j = 0; j < n_chan;) {
@@ -2572,17 +2587,52 @@ void Engine::moe_rows(Layer& L, int il, int n) {
if (most[c] > 0) runs_.push_back({c, j, m, most[c]});
j += m;
}
for (const Run& r : runs_)
mmq_->mul(slot_of(r.j), gt, ff2, n_embd_, L.slot_bytes, r.m, mq_, d_cb + (size_t) r.c * cb_row + r.j, iota_,
rg, r.most, gu_, ff2, st_);
int n_run[kClasses] = {}, c0[kClasses + 1] = {}; // a class's runs; where its experts start in group_
for (const Run& r : runs_) ++n_run[r.c];
for (int c = 0, g = 0; c < kClasses; ++c) {
c0[c] = g;
while (g < n_cached && tile_class(rows_of(g)) == c) ++g;
}
c0[kClasses] = n_cached;
bool by_tab[kClasses];
for (int c = 0; c < kClasses; ++c)
by_tab[c] = L.tab && c0[c + 1] > c0[c] && (c0[c + 1] - c0[c] + Mmq::kTab - 1) / Mmq::kTab < n_run[c];
const auto cached = [&](bool down) {
for (const Run& r : runs_) {
if (by_tab[r.c]) continue;
const int32_t* b = d_cb + (size_t) r.c * cb_row + r.j;
if (down)
mmq_->mul(slot_of(r.j) + gu2, dt, n_embd_, ff, L.slot_bytes, r.m, mq2_, b, d_place, rc, r.most, dx_,
n_embd_, st_);
else
mmq_->mul(slot_of(r.j), gt, ff2, n_embd_, L.slot_bytes, r.m, mq_, b, iota_, rg, r.most, gu_, ff2, st_);
}
for (int c = 0; c < kClasses; ++c) {
if (!by_tab[c]) continue;
for (int g0 = c0[c]; g0 < c0[c + 1]; g0 += Mmq::kTab) {
const int m = std::min(Mmq::kTab, c0[c + 1] - g0);
const void* tab[Mmq::kTab];
int most = 0;
for (int k = 0; k < m; ++k) {
tab[k] = L.slot[(size_t) group_[(size_t) (g0 + k)]] + (down ? gu2 : 0);
most = std::max(most, rows_of(g0 + k));
}
const bool launched =
down ? mmq_->mul_tab(tab, dt, n_embd_, ff, m, mq2_, d_bounds + g0, d_place, rc, most, dx_,
n_embd_, st_)
: mmq_->mul_tab(tab, gt, ff2, n_embd_, m, mq_, d_bounds + g0, iota_, rg, most, gu_, ff2,
st_);
if (!launched) throw std::runtime_error("mmq: no pointer-table launch for the cached experts");
}
}
};
cached(false);
if (rc > 0) {
if (gelu_) geglu_rows(gu_, hx_, n_ff_exp_, rc, st_);
else swiglu_clamp_rows(gu_, hx_, n_ff_exp_, rc, limit, st_);
Mmq::quantize(hx_, nullptr, mq2_, dt, ff, ff, rc, st_);
}
for (const Run& r : runs_)
mmq_->mul(slot_of(r.j) + gu2, dt, n_embd_, ff, L.slot_bytes, r.m, mq2_, d_cb + (size_t) r.c * cb_row + r.j,
d_place, rc, r.most, dx_, n_embd_, st_);
cached(true);
// The round the buffer holds goes first and is not copied. If it holds none of this call's, the experts
// that go ahead are copied last, so the next call finds them. The order does not change a round's launches.
+4
View File
@@ -66,6 +66,8 @@ struct Options {
///< with the CPU's share computed meanwhile); under it the CPU computes every
///< expert outside VRAM (moe()). 1: an answer's windows stream their misses too
bool stage_overlap = false; ///< opt-in: copy a single staging round under the cached experts' kernels
bool mmq_tab = false; ///< opt-in: a layer's cached experts in launches of up to Mmq::kTab wherever their slots lie,
///< when that is fewer launches than one per run of adjacent slots
int expert_swaps = 64; ///< experts on their way into the cache at a time while an answer is written, each
///< to the slot of one the answer uses less; 0: the cache stays as it was loaded
bool stay_near = true; ///< with several NUMA nodes, keep the CPU threads on the one that holds the experts
@@ -107,6 +109,7 @@ struct Dev {
struct Layer {
bool moe = false;
bool mmq = false; ///< the card has MMQ tiles for its routed experts' types (Engine::batched())
bool tab = false; ///< and pointer-table kernels for them (Mmq::mul_tab)
bool fixed = false; ///< one token's launches can be recorded and replayed for the next ones (eval()): they
///< are the same for every token, or read the position on the card (Engine::at_)
Dev attn_norm, ffn_norm; ///< the norms ahead of the attention and of the FFN
@@ -700,6 +703,7 @@ protected:
int c, j, m, most; ///< the rows' class, its first cached expert and how many, the most rows one has
};
std::vector<Run> runs_; ///< a layer's launches over cached experts whose slots lie one behind the other
bool tab_warned_ = false; ///< said once why a layer's cached experts go by runs (--mmq-tab)
std::vector<int32_t> chan_; ///< a layer's cached experts in the order of their slots
std::vector<uint8_t> sent_;
// A call that copies only the experts it routes to leaves some of those outside VRAM to the CPU (moe_rows()).
+3
View File
@@ -1068,6 +1068,8 @@ void usage() {
" under N the CPU computes all of them (default 32; 1 = also while an\n"
" answer is written, which keeps the card and the bus busy instead of the CPU)\n"
" --stage-overlap 0|1 copy a single staging round under the cached experts' kernels (default 0)\n"
" --mmq-tab 0|1 a layer's cached experts in launches of up to 16 wherever their slots lie,\n"
" when that is fewer launches than one per run of adjacent slots (default 0)\n"
" --cpu-share F under that, the share of those experts the CPU computes meanwhile, the\n"
" ones the fewest tokens chose (default: as the times say; 0 = none)\n"
" --prompt-cache N checkpoints kept of a conversation, about 150 MB of RAM each (default 6;\n"
@@ -1169,6 +1171,7 @@ int main(int argc, char** argv) {
else if (a == "--stage-ahead") o.stage_ahead = std::atoi(val());
else if (a == "--stage-rows") o.stage_rows = std::atoi(val());
else if (a == "--stage-overlap") o.stage_overlap = std::atoi(val()) != 0;
else if (a == "--mmq-tab") o.mmq_tab = std::atoi(val()) != 0;
else if (a == "--cpu-share") o.cpu_share = (float) std::atof(val());
else if (a == "--prompt-cache") cache.o.checkpoints = std::atoi(val());
else if (a == "--prompt-cache-every") cache.o.every = std::atoll(val());
+85 -21
View File
@@ -6,6 +6,10 @@
#include "mmq.cuh"
#include "quantize.cuh"
#ifdef STRATA_POLY_MMQ_TAB
#include "moe_mmq_tab.hpp" // declarations: the instances are the per-type TUs CMake generates (poly_mmq_tab/)
#endif
#include <stdexcept>
#include <string>
@@ -17,8 +21,41 @@ namespace {
X(Q4_0) X(Q4_1) X(Q5_0) X(Q5_1) X(Q8_0) X(Q2_K) X(Q3_K) X(Q4_K) X(Q5_K) X(Q6_K) \
X(IQ1_S) X(IQ2_XXS) X(IQ2_XS) X(IQ2_S) X(IQ3_XXS) X(IQ3_S) X(IQ4_NL) X(IQ4_XS) X(MXFP4)
// the types with pointer-table instances (CMakeLists.txt, _strata_poly_tab_types): the list above but MXFP4
#define STRATA_POLY_TAB_TYPES(X) \
X(Q4_0) X(Q4_1) X(Q5_0) X(Q5_1) X(Q8_0) X(Q2_K) X(Q3_K) X(Q4_K) X(Q5_K) X(Q6_K) \
X(IQ1_S) X(IQ2_XXS) X(IQ2_XS) X(IQ2_S) X(IQ3_XXS) X(IQ3_S) X(IQ4_NL) X(IQ4_XS)
int64_t pad512(int64_t n) { return (n + 511) / 512 * 512; }
// mul()'s and mul_tab()'s arguments to llama.cpp's launcher: the matrices are the channels of x; the tokens' rows
// are the columns of y and of dst
mmq_args args_of(const void* w, ggml_type t, int64_t w_rows, int64_t w_cols, size_t stride, int n, const void* xq,
const int32_t* bounds, const int32_t* ids, int64_t total_rows, int64_t max_rows, float* dst,
int64_t ld_dst) {
mmq_args a = {};
a.x = (const char*) w;
a.type_x = t;
a.y = (const int*) xq;
a.ids_dst = ids;
a.expert_bounds = bounds;
a.dst = dst;
a.ncols_x = w_cols;
a.nrows_x = w_rows;
a.stride_row_x = w_cols / ggml_blck_size(t);
a.ncols_y = total_rows;
a.ncols_dst = total_rows;
a.nrows_dst = ld_dst;
a.nchannels_x = n;
a.nchannels_y = n;
a.stride_channel_x = (int64_t) (stride / ggml_type_size(t));
a.nsamples_x = 1;
a.nsamples_y = 1;
a.ncols_max = max_rows;
a.ncols_opt = max_rows;
return a;
}
void ck(const char* what) {
const cudaError_t e = cudaGetLastError();
if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
@@ -85,27 +122,7 @@ void Mmq::mul(const void* w, int type, int64_t w_rows, int64_t w_cols, size_t st
int64_t ld_dst, void* stream) {
if (n <= 0 || max_rows <= 0) return;
const ggml_type t = (ggml_type) type;
// the matrices are the channels of x; the tokens' rows are the columns of y and of dst
mmq_args a = {};
a.x = (const char*) w;
a.type_x = t;
a.y = (const int*) xq;
a.ids_dst = ids;
a.expert_bounds = bounds;
a.dst = dst;
a.ncols_x = w_cols;
a.nrows_x = w_rows;
a.stride_row_x = w_cols / ggml_blck_size(t);
a.ncols_y = total_rows;
a.ncols_dst = total_rows;
a.nrows_dst = ld_dst;
a.nchannels_x = n;
a.nchannels_y = n;
a.stride_channel_x = (int64_t) (stride / ggml_type_size(t));
a.nsamples_x = 1;
a.nsamples_y = 1;
a.ncols_max = max_rows;
a.ncols_opt = max_rows;
const mmq_args a = args_of(w, t, w_rows, w_cols, stride, n, xq, bounds, ids, total_rows, max_rows, dst, ld_dst);
auto& ctx = *(ggml_backend_cuda_context*) ctx_;
const cudaStream_t s = (cudaStream_t) stream;
@@ -118,4 +135,51 @@ void Mmq::mul(const void* w, int type, int64_t w_rows, int64_t w_cols, size_t st
ck("mmq product");
}
bool Mmq::tab(int type) {
#ifdef STRATA_POLY_MMQ_TAB
switch ((ggml_type) type) {
#define X(T) case GGML_TYPE_##T:
STRATA_POLY_TAB_TYPES(X)
#undef X
return true;
default: return false;
}
#else
(void) type;
return false;
#endif
}
bool Mmq::mul_tab(const void* const* w, int type, int64_t w_rows, int64_t w_cols, int n, const void* xq,
const int32_t* bounds, const int32_t* ids, int64_t total_rows, int64_t max_rows, float* dst,
int64_t ld_dst, void* stream) {
if (n <= 0 || max_rows <= 0) return true;
if (n > kTab) throw std::invalid_argument("mmq: " + std::to_string(n) + " matrices in one pointer-table launch");
#ifdef STRATA_POLY_MMQ_TAB
const ggml_type t = (ggml_type) type;
// the stride is not read: each channel's matrix starts where the table says
const mmq_args a = args_of(w[0], t, w_rows, w_cols, 0, n, xq, bounds, ids, total_rows, max_rows, dst, ld_dst);
strata::prefill::mmq::mmq_x_tab tab = {};
for (int i = 0; i < n; ++i) tab.p[i] = (const char*) w[i];
auto& ctx = *(ggml_backend_cuda_context*) ctx_;
const cudaStream_t s = (cudaStream_t) stream;
bool launched = false;
switch (t) {
#define X(T) \
case GGML_TYPE_##T: \
launched = strata::prefill::mmq::mul_mat_q_tab_case<GGML_TYPE_##T>(ctx, a, tab, s); \
break;
STRATA_POLY_TAB_TYPES(X)
#undef X
default: return false;
}
ck("mmq product");
return launched;
#else
(void) w; (void) type; (void) w_rows; (void) w_cols; (void) xq; (void) bounds; (void) ids; (void) total_rows;
(void) dst; (void) ld_dst; (void) stream;
return false;
#endif
}
} // namespace strata::poly
+10
View File
@@ -37,6 +37,16 @@ public:
const int32_t* bounds, const int32_t* ids, int64_t total_rows, int64_t max_rows, float* dst,
int64_t ld_dst, void* stream);
/// Up to this many matrices in one mul_tab() launch.
static constexpr int kTab = 16;
/// This build has the pointer-table kernels (STRATA_POLY_MMQ_TAB) for ggml_type.
static bool tab(int ggml_type);
/// mul() over n matrices that lie where w[0..n) say instead of `stride` apart (n <= kTab). false, and nothing
/// launched, when this build has no pointer-table kernel for the type or w_rows is not a multiple of 128.
bool mul_tab(const void* const* w, int ggml_type, int64_t w_rows, int64_t w_cols, int n, const void* xq,
const int32_t* bounds, const int32_t* ids, int64_t total_rows, int64_t max_rows, float* dst,
int64_t ld_dst, void* stream);
private:
void* ctx_ = nullptr; ///< llama.cpp's launch context: a small scratch pool
};