From 1fe9bec4cdca47b8bda2c645ef9b6a30ba672577 Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Thu, 5 Nov 2026 16:37:45 -0800 Subject: [PATCH 1/2] [1/2] 35b-a3b perf -- auto CPU/GPU split on expert cache misses (#27) * strata-poly: hybrid expert streaming while an answer is written (--stage-rows, --stage-overlap) An answer's decode windows can take the prompt path's hybrid handling of the experts outside VRAM (--stage-rows 1): the misses go through the pinned staging buffer to the card and run there by MMQ, an adaptive --cpu-share of them computed on the CPU meanwhile, instead of every miss on the CPU. --stage-overlap (default on) copies a single staging round on the upload stream, under the cached experts' kernels. STRATA_WORKER_SPINS=N shortens the workers' spin before they sleep; STRATA_BLOCKING_SYNC=1 has the waiting thread sleep on the card (set before the single-card path). On a GTX 1060 6 GB laptop (Qwen3.6-35B-A3B UD-IQ3_XXS, 128K q8_0 KV, 4K prompt, 512-token decode, nvprof): 20.6 -> 26.5-29.3 tok/s, CPU 6.2 -> 2.5-3.6 cores, CPU throttle events 2389 -> 484, PCIe 0.3-0.7 GB/s at decode, GPU 82-85% busy. Fixes the streamed path needed: a streamed window never takes the halves pipelining (it corrupted output); it feeds recent_ so the cache keeps trading for the answer's experts; the pinned copies go to a few stager threads so the expert workers sleep. Co-Authored-By: Claude Fable 5.1 * strata-poly: a streamed window applies --tail-skip as moe() did With --stage-rows under 32 an answer's windows take moe_rows(), which computed every routed expert: the tail-rank skip lived only in moe(), so lowering --stage-rows silently turned --tail-skip off while the startup line still claimed it. moe_rows() now leaves out an expert outside VRAM that every token of the window ranks at tail_skip or later, counts it in tail_experts, and zeroes its rows' places. Co-Authored-By: Claude Fable 5.1 * strata-poly: an answer's streamed misses count as misses in the stats A window through moe_rows() counted its cached rows as gpu_experts and nothing for the rows staged to the card, and the front end's DONE line and the run summary take hits over gpu_experts + cpu_experts: a window of two hits and six streamed misses reported 100% from VRAM. Stats::staged_experts holds them and both totals include it. Co-Authored-By: Claude Fable 5.1 * strata-poly: the MMQ path is set up from --stage-rows rows, not 32 alloc() gave a layer its MMQ tiles only when a call could hold kStageRows rows, so --prompt-batch 16 --stage-rows 1 (or a context that small) accepted both flags and streamed nothing: mmq_ was never made and batched() was always false. The buffers are sized from rows_ either way. Co-Authored-By: Claude Fable 5.1 * strata-poly: STRATA_BLOCKING_SYNC leaves the caller's device selected The flag loop ended on the last card it visited, so an unsplit engine opened from device 1 with the variable set loaded on device 0. The device that was current is restored after the loop. Co-Authored-By: Claude Fable 5.1 * strata-poly: make staging overlap opt-in --------- Co-authored-by: Claude Fable 5.1 --- src/poly/cpu_experts.cpp | 8 +++- src/poly/engine.cpp | 79 ++++++++++++++++++++++++++++++++++++---- src/poly/engine.hpp | 8 ++++ src/poly/main.cpp | 11 +++++- 4 files changed, 95 insertions(+), 11 deletions(-) diff --git a/src/poly/cpu_experts.cpp b/src/poly/cpu_experts.cpp index 0c4dcb6..8442713 100644 --- a/src/poly/cpu_experts.cpp +++ b/src/poly/cpu_experts.cpp @@ -4,6 +4,7 @@ #include "ggml.h" #include "ggml-cpu.h" +#include #include #include #include @@ -18,7 +19,12 @@ namespace { // idle at the end of every layer: 64 rows gave Tiel's 512-row experts 8 tasks each, and its down products 32 tasks. constexpr int kRowsPerTask = 32; constexpr int kRowsPerDownTask = 16; -constexpr int kSpinsBeforeSleep = 20000; // about a millisecond of pause instructions +// About a millisecond of pause instructions before a worker sleeps; STRATA_WORKER_SPINS=N for another count (a +// laptop whose CPU is not the lane that matters cools down with a few hundred). +const int kSpinsBeforeSleep = [] { + const char* v = std::getenv("STRATA_WORKER_SPINS"); + return v && std::atoi(v) >= 0 ? std::atoi(v) : 20000; +}(); const ggml_type_traits_cpu* traits(int type) { return ggml_get_type_traits_cpu((ggml_type) type); } diff --git a/src/poly/engine.cpp b/src/poly/engine.cpp index 1bdeae7..be1784d 100644 --- a/src/poly/engine.cpp +++ b/src/poly/engine.cpp @@ -1011,6 +1011,20 @@ std::unique_ptr Engine::open(const Options& o) { starts = layer_starts(o.layer_split, file, (int) blocks->u - (nextn ? (int) nextn->u : 0), cards); ck(cudaSetDevice(was), "cudaSetDevice"); } + // STRATA_BLOCKING_SYNC=1: the thread that waits for the card sleeps on it instead of spinning (a laptop whose + // CPU shares the card's heat); a wake costs some microseconds a wait. + if (const char* v = std::getenv("STRATA_BLOCKING_SYNC"); v && std::atoi(v) != 0) { + int was = 0; // an unsplit engine loads on the caller's card: leave it selected + ck(cudaGetDevice(&was), "cudaGetDevice"); + for (int d = 0; d < std::max(1, devices); ++d) { + ck(cudaSetDevice(d), "cudaSetDevice"); + if (cudaSetDeviceFlags(cudaDeviceScheduleBlockingSync) != cudaSuccess) { + cudaGetLastError(); + std::fprintf(stderr, "strata-poly: card %d: could not set blocking sync\n", d); + } + } + ck(cudaSetDevice(was), "cudaSetDevice"); + } if (starts.empty()) { std::unique_ptr engine = make(); engine->load(o); @@ -1587,6 +1601,8 @@ void Engine::load(const Options& o) { throw std::runtime_error("a prompt batch is 1 to 4096 tokens"); if (opt_.stage_mib < 1) throw std::runtime_error("the staging buffer must be at least 1 MiB"); if (opt_.stage_ahead < 0) throw std::runtime_error("the batch size to stage ahead from cannot be negative"); + if (opt_.stage_rows < 1 || opt_.stage_rows > kStageRows) + throw std::runtime_error("--stage-rows takes 1 to " + std::to_string(kStageRows)); if (opt_.expert_swaps < 0 || opt_.expert_swaps > 64) throw std::runtime_error("0 to 64 experts can be on their way into the cache at a time"); if (opt_.window < 0 || opt_.window > 8) @@ -1838,7 +1854,7 @@ void Engine::alloc() { for (int il = 0; il < n_layer_; ++il) { Layer& L = layers_[(size_t) il]; if (!L.moe) continue; - L.mmq = opt_.gpu_experts && rows_ >= kStageRows && Mmq::fits((int) L.gu_type, 2 * n_ff_exp_, n_embd_) && + 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; one_expert = std::max(one_expert, 2 * L.gu_bytes + L.d_bytes); @@ -2008,6 +2024,7 @@ const Stats& Engine::stats() const { const Stats& s = e->stats_; all_stats_.gpu_experts += s.gpu_experts; all_stats_.cpu_experts += s.cpu_experts; + all_stats_.staged_experts += s.staged_experts; all_stats_.batch_cached += s.batch_cached; all_stats_.batch_staged += s.batch_staged; all_stats_.swapped_experts += s.swapped_experts; @@ -2105,7 +2122,7 @@ void Engine::lin(const Dev& w, const float* x, float* y, int n, const void* xq, void Engine::router_scores(const Layer& L, int n) { lin(L.gate_inp, xn_, rl_, n, xq_); } -bool Engine::batched(const Layer& L, int n) const { return mmq_ && L.mmq && n >= kStageRows; } +bool Engine::batched(const Layer& L, int n) const { return mmq_ && L.mmq && n >= opt_.stage_rows; } // The router's scores, and the copies of them and of the experts' input to the host. void Engine::moe_router(const Layer& L, int n) { @@ -2406,9 +2423,29 @@ void Engine::moe_rows(Layer& L, int il, int n) { w + (size_t) t * n_used_, tmp); }); count_.assign((size_t) n_expert_, 0); + const bool answer = n < kStageRows; // an answer's window through this path (--stage-rows), not a prompt batch for (int i = 0; i < rr; ++i) { ++count_[(size_t) ids_[(size_t) i]]; ++use_[(size_t) il * n_expert_ + (size_t) ids_[(size_t) i]]; + // what moe() counts for follow(): the cache keeps trading for the experts the answer uses + if (answer && n_swap_ > 0) recent_[(size_t) il * n_expert_ + (size_t) ids_[(size_t) i]] += 1.f; + } + // Options::tail_skip, as moe() applies it to the calls that went through it before --stage-rows was lowered: an + // expert outside VRAM that every token of the window ranks at tail_skip or later is left out. Its rows keep no + // weight and take no place among the card's or the CPU's. + int n_tail = 0; + left_out_.assign((size_t) n_expert_, 0); + if (answer && opt_.tail_skip > 0) { + for (int i = 0; i < rr; ++i) + if (i % n_used_ < opt_.tail_skip) left_out_[(size_t) ids_[(size_t) i]] = 2; // ranked high by a token: kept + for (int e = 0; e < n_expert_; ++e) { + const bool out = count_[(size_t) e] > 0 && !L.slot[(size_t) e] && left_out_[(size_t) e] != 2; + left_out_[(size_t) e] = out; + if (!out) continue; + stats_.tail_experts += count_[(size_t) e]; + n_tail += count_[(size_t) e]; + count_[(size_t) e] = 0; + } } // The CPU computes some of the routed experts outside VRAM while the others are copied: the ones the fewest // tokens chose, whose copy costs as much as any other's and which cost the CPU about as much as their tokens. @@ -2459,6 +2496,10 @@ void Engine::moe_rows(Layer& L, int il, int n) { host_.clear(); for (int i = 0; i < rr; ++i) { const size_t e = (size_t) ids_[(size_t) i]; + if (left_out_[e]) { // left out (tail_skip): no row, and nothing of it in the sum + w[i] = 0.f; + continue; + } if (on_cpu_[e]) { // by token, as cpu_experts() takes them, and nothing of it in the card's sum host_.push_back({L.exp_gate + e * L.gu_stride, L.exp_up + e * L.gu_stride, L.exp_down + e * L.d_bytes, w[i], i / n_used_}); @@ -2496,16 +2537,22 @@ void Engine::moe_rows(Layer& L, int il, int n) { "expert rows"); const int rc = bounds[n_cached]; // the rows of the cached experts - stats_.batch_cached += rc; - stats_.batch_staged += rg - rc; + if (answer) { // an answer's window: counted as decoding, the staged rows as misses + stats_.gpu_experts += rc; + stats_.staged_experts += rg - rc; + } else { + stats_.batch_cached += rc; + stats_.batch_staged += rg - rc; + } const float limit = clamp_exp_[(size_t) il]; const int gt = (int) L.gu_type, dt = (int) L.d_type; const int64_t ff = n_ff_exp_, ff2 = 2 * ff; int holds = -1; // the round in the buffer when this call is done - // The card's part. With the CPU's beside it, the rows of its experts' places are left at nothing. + // The card's part. With the CPU's beside it, or experts left out, the rows of those places are left at nothing. const auto card = [&] { - if (n_cpu > 0) ck(cudaMemsetAsync(dx_, 0, (size_t) rr * n_embd_ * sizeof(float), cs(st_)), "expert rows"); + if (n_cpu > 0 || n_tail > 0) + ck(cudaMemsetAsync(dx_, 0, (size_t) rr * n_embd_ * sizeof(float), cs(st_)), "expert rows"); if (rg > 0) Mmq::quantize(xn_, d_tok, mq_, gt, n_embd_, n_embd_, rg, st_); // The cached experts whose slots lie one behind the other are the matrices of one launch, as the experts of @@ -2556,7 +2603,19 @@ void Engine::moe_rows(Layer& L, int il, int n) { } else if (r == 0 && early) { ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_ahead_, 0), "expert staging"); } else if (rows > 0) { - stage(L, group_.data() + g0, m, st_, n_cpu > 0); + // an answer's window: the four stagers copy, so the expert workers sleep instead of spinning + if (answer && !stagers_) stagers_ = std::make_unique(4); + if (n_round == 1 && opt_.stage_overlap) { + // One round: its copy goes on the upload stream, under the cached experts' kernels queued + // above, and the compute stream takes it up when it lands. More rounds reuse the buffer, so + // a round's copy has to follow the round before it on the compute stream. + ck(cudaStreamWaitEvent(cs(up_), (cudaEvent_t) ev_free_, 0), "expert staging"); + stage(L, group_.data() + g0, m, up_, n_cpu > 0 || answer); + ck(cudaEventRecord((cudaEvent_t) ev_ahead_, cs(up_)), "expert staging"); + ck(cudaStreamWaitEvent(cs(st_), (cudaEvent_t) ev_ahead_, 0), "expert staging"); + } else { + stage(L, group_.data() + g0, m, st_, n_cpu > 0 || answer); + } holds = r; } if (rows == 0) continue; // nothing routed to the experts that go ahead @@ -2732,7 +2791,11 @@ void Engine::run(const int32_t* tokens, int n) { // // A half's launches are the ones its tokens have in a call of their own, at their rows of the buffers // (shift_rows()), so each token comes out as it would alone. - if (n > 1 && windowed_ && !all_cached() && halves_) { + // With --stage-rows under kStageRows a window's experts take the batch path (moe_rows(), below), whose call + // does the shared expert and the routing itself: up() leaves them out, and moe() would then miss them, so + // the halves (which call moe() directly) are not for such a window. + const bool streamed = mmq_ && n >= opt_.stage_rows && opt_.stage_rows < kStageRows; + if (n > 1 && windowed_ && !all_cached() && halves_ && !streamed) { const int first[3] = {0, (n + 1) / 2, n}; // half k is the tokens [first[k], first[k + 1]) const unsigned bits = snap_bits_; // the window's tokens that leave the recurrent state int at = 0; diff --git a/src/poly/engine.hpp b/src/poly/engine.hpp index 255f5fa..676c357 100644 --- a/src/poly/engine.hpp +++ b/src/poly/engine.hpp @@ -61,6 +61,11 @@ struct Options { float cpu_share = -1; ///< of the experts outside VRAM that such a call routes to, the share the CPU ///< computes while the others are copied: the ones the fewest tokens chose; ///< below 0: as the two took the time between them; 0: none + int stage_rows = 32; ///< from this many tokens (kStageRows) a call takes its routed experts as a prompt batch + ///< (moe_rows(): the cached ones by MMQ, the others through the staging buffer + ///< 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 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 @@ -134,6 +139,8 @@ struct Layer { /// (gpu_experts, cpu_experts), and in a prompt batch from the cache or the staging buffer (batch_*). struct Stats { int64_t tokens = 0, gpu_experts = 0, cpu_experts = 0, batch_cached = 0, batch_staged = 0; + int64_t staged_experts = 0; ///< an answer's experts outside VRAM copied to the card and computed there + ///< (--stage-rows): misses, like cpu_experts int64_t swapped_experts = 0; ///< experts that took a cached one's slot (follow()) int64_t tail_experts = 0; ///< a token's experts left out by Options::tail_skip double cpu_ms = 0, route_wait_ms = 0; @@ -697,6 +704,7 @@ protected: std::vector sent_; // A call that copies only the experts it routes to leaves some of those outside VRAM to the CPU (moe_rows()). std::vector on_cpu_; ///< per expert of the layer: the CPU's + std::vector left_out_; ///< per expert of the layer: left out by Options::tail_skip std::vector spare_; ///< the layer's routed experts outside VRAM, the fewest tokens' first std::vector host_; ///< their uses, by token double share_[5] = {0.25, 0.25, 0.25, 0.25, 0.25}; ///< the CPU's share of spare_, by the call's tokens: diff --git a/src/poly/main.cpp b/src/poly/main.cpp index 92935e9..a8b846b 100644 --- a/src/poly/main.cpp +++ b/src/poly/main.cpp @@ -877,7 +877,7 @@ int serve(Session& ss) { const strata::poly::Stats& now = engine.stats(); // the cache's share of the experts looked up while answering: a prompt batch's go through VRAM either way const long long hits = now.gpu_experts - before.gpu_experts; - const long long misses = now.cpu_experts - before.cpu_experts; + const long long misses = (now.cpu_experts - before.cpu_experts) + (now.staged_experts - before.staged_experts); std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld 0 0 0.0 %lld 0\n", (long long) r.produced, n, r.prompt_ms, r.decode_ms, r.finish, (long long) r.guessed_right, (long long) r.guessed, (long long) r.resume, hits, hits + misses, (long long) r.read); @@ -953,7 +953,7 @@ int once(Session& ss, const std::vector& ids, const Pictures& pictures, [](int64_t, int64_t, double, bool) {}); std::printf("%s\n", out.c_str()); const strata::poly::Stats& st = ss.engine.stats(); - const double experts = (double) std::max(st.gpu_experts + st.cpu_experts, 1); + const double experts = (double) std::max(st.gpu_experts + st.cpu_experts + st.staged_experts, 1); std::fprintf(stderr, "prompt %lld tokens %.1f tok/s, generated %lld tokens %.2f tok/s (%s); experts from VRAM %.1f%%, " "CPU experts %.1f ms/token, router wait %.1f ms/token, %lld experts swapped into VRAM, " @@ -1063,6 +1063,11 @@ void usage() { " of them are copied after the layer has routed\n" " --stage-ahead N from N tokens, a batch copies those experts before it routes (default 1024,\n" " 0 = never)\n" + " --stage-rows N from N tokens a call copies the experts outside the cache to the card\n" + " (--stage-mib) and computes them there, the CPU taking its share meanwhile;\n" + " 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" " --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" @@ -1162,6 +1167,8 @@ int main(int argc, char** argv) { else if (a == "--prompt-batch") o.prompt_batch = std::atoi(val()); else if (a == "--stage-mib") o.stage_mib = std::atoi(val()); 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 == "--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()); From ff19037a1cacbc219e35d17fbf89d78b3a3d7c2f Mon Sep 17 00:00:00 2001 From: Robert Karl Date: Thu, 5 Nov 2026 16:39:38 -0800 Subject: [PATCH 2/2] [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 (cherry picked from commit 1a3b9a42f39132f6b02e0c8f9082a39ef9b898c2) * strata-poly: make pointer-table MMQ opt-in at runtime --------- Co-authored-by: Claude Fable 5.1 --- CMakeLists.txt | 62 +++++++++++++++++++------- src/poly/engine.cpp | 62 +++++++++++++++++++++++--- src/poly/engine.hpp | 4 ++ src/poly/main.cpp | 3 ++ src/poly/mmq.cu | 106 +++++++++++++++++++++++++++++++++++--------- src/poly/mmq.hpp | 10 +++++ 6 files changed, 204 insertions(+), 43 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 912fd49..148fa90 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 $<$:--extended-lambda -use_fast_math>) if(MSVC) target_compile_options(strata_poly_mmq PRIVATE $<$:-Xcompiler=/bigobj>) diff --git a/src/poly/engine.cpp b/src/poly/engine.cpp index be1784d..205a860 100644 --- a/src/poly/engine.cpp +++ b/src/poly/engine.cpp @@ -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(); @@ -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. diff --git a/src/poly/engine.hpp b/src/poly/engine.hpp index 676c357..98f84c4 100644 --- a/src/poly/engine.hpp +++ b/src/poly/engine.hpp @@ -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 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 chan_; ///< a layer's cached experts in the order of their slots std::vector sent_; // A call that copies only the experts it routes to leaves some of those outside VRAM to the CPU (moe_rows()). diff --git a/src/poly/main.cpp b/src/poly/main.cpp index a8b846b..2ce9c2a 100644 --- a/src/poly/main.cpp +++ b/src/poly/main.cpp @@ -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()); diff --git a/src/poly/mmq.cu b/src/poly/mmq.cu index c221957..dbfd257 100644 --- a/src/poly/mmq.cu +++ b/src/poly/mmq.cu @@ -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 #include @@ -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(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 diff --git a/src/poly/mmq.hpp b/src/poly/mmq.hpp index 1a06e4e..fd9f510 100644 --- a/src/poly/mmq.hpp +++ b/src/poly/mmq.hpp @@ -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 };