From b18700c8f7d1b9d036da53977b548270406a0c83 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 13:27:00 +0200 Subject: [PATCH 1/2] Adaptive tier: the engine chooses the asynchronous tier by measurement (arena, one CUDA GPU) Without --adapt-async on the command line, the expert arena on one CUDA GPU (--serve, adaptive tier on, no --batch, no layer split, no pipelined windows, no peer or remote tier) starts on the blocking tier, ignores 64 steady decode windows, measures 64, and when the tier's wait is at least 5% of a window runs 64 windows on the asynchronous tier, going back (for the session) only if that was more than 2% slower per token. One log line at each switch. --adapt-async 0|1 and STRATA_ADAPT_ASYNC=0 keep their meaning; the identity gates run with --adapt-every 100000 and never reach it. Decision logic and its unit test are header-only (adapt_async_default.hpp, adapt_async_default_test). --- CMakeLists.txt | 3 + include/strata/core/adapt_async_default.hpp | 121 ++++++++++++++++++ src/core/adapt_async_default_test.cpp | 135 ++++++++++++++++++++ src/program/generate.cpp | 85 ++++++++++-- 4 files changed, 333 insertions(+), 11 deletions(-) create mode 100644 include/strata/core/adapt_async_default.hpp create mode 100644 src/core/adapt_async_default_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index acc76446..7dd95dfd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1538,6 +1538,9 @@ if(STRATA_BUILD_TESTS) add_executable(arch_defaults_test src/core/arch_defaults_test.cpp src/core/arch_defaults.cpp) target_include_directories(arch_defaults_test PRIVATE include) add_test(NAME arch_defaults_test COMMAND arch_defaults_test) + add_executable(adapt_async_default_test src/core/adapt_async_default_test.cpp) + target_include_directories(adapt_async_default_test PRIVATE include) + add_test(NAME adapt_async_default_test COMMAND adapt_async_default_test) add_executable(uma_cache_test src/core/uma_cache_test.cpp) target_include_directories(uma_cache_test PRIVATE include) add_test(NAME uma_cache_test COMMAND uma_cache_test) diff --git a/include/strata/core/adapt_async_default.hpp b/include/strata/core/adapt_async_default.hpp new file mode 100644 index 00000000..7e0987d5 --- /dev/null +++ b/include/strata/core/adapt_async_default.hpp @@ -0,0 +1,121 @@ +// include/strata/core/adapt_async_default.hpp - the asynchronous adaptive tier (--adapt-async 1) as a measured, per-session choice. +// +// Measured: on an RTX PRO 5000 box (64 cores) with every expert in the RAM arena, `--adapt-async 1` gave decode story +5.6%, +// code +5.1%, doc8k +10.9% (5/5 pairs faster in every class; the tier's wait per verify window fell from 1.4 ms to 0.14 ms). +// On a CPU-bound box (RTX A4000, Xeon E5-2643 v3, 12 threads, CPU experts 35 of 55 ms per window) the same switch gave +// story 0.99, code 1.00, doc8k 1.04 and a 4K-prompt decode 0.945: the helper thread competes with the expert pool. So it +// is neither always on nor always off: where the engine could run it (CUDA, `--serve`, one GPU, the expert arena, no batch +// slots, no layer split) it starts on the blocking tier, measures ~64 windows, and only when the tier's wait is a large part +// of a window does it try the asynchronous tier for ~64 windows and go back to the blocking tier if the decode got slower by more than 2%. +// Off switches: `--adapt-async 0`, `STRATA_ADAPT_ASYNC=0`. `--adapt-async 1` keeps its old meaning (always on). +// Not bit-exact from run to run, like the adaptive tier itself. The identity gates run with `--adapt-every 100000` (no +// adaptive tier), so they never reach this. +#pragma once + +#include + +namespace strata::core { + +struct AdaptAsyncAuto { + int flag = -1; ///< --adapt-async on the command line: -1 not given, else 0 / 1 + int env = -1; ///< STRATA_ADAPT_ASYNC: -1 unset, else its value (0 = off) + bool cuda = false; ///< a CUDA build (the HIP builds keep it opt-in) + bool serve = false; + bool adaptive = false; ///< --adapt-every and --adapt-swaps both above 0 + bool arena = false; ///< the experts come from the RAM arena (every expert in RAM) + bool multi_gpu = false; ///< a layer split + bool pipeline_windows = false; + bool batch = false; ///< --batch slots + bool peer = false; ///< --peer-device + bool remote_opt = false; ///< --remote-expert-opt + bool adapt_overlap = false; ///< the opt-in STRATA_ADAPT_OVERLAP tier, which excludes the asynchronous one +}; + +/// STRATA_ADAPT_ASYNC as the process sees it (-1 unset). +inline int adapt_async_env() { + const char* v = std::getenv("STRATA_ADAPT_ASYNC"); + return v == nullptr || v[0] == '\0' ? -1 : std::atoi(v); +} + +/// true: the engine may choose the asynchronous tier by measurement. `why_not` (may be null) gets a short reason otherwise. +inline bool adapt_async_self_decides(const AdaptAsyncAuto& a, const char** why_not = nullptr) { + auto no = [&](const char* why) { if (why_not != nullptr) *why_not = why; return false; }; + if (a.flag >= 0) return no("--adapt-async was given"); // the user's choice, 0 or 1, is applied as before + if (a.env == 0) return no("STRATA_ADAPT_ASYNC=0"); + if (!a.cuda) return no("not a CUDA build"); + if (!a.serve) return no("it needs --serve"); + if (!a.adaptive) return no("the adaptive tier is off"); + if (!a.arena) return no("not the expert arena"); + if (a.multi_gpu) return no("a layer split"); + if (a.pipeline_windows) return no("--pipeline-windows"); + if (a.batch) return no("--batch slots"); + if (a.peer) return no("--peer-device"); + if (a.remote_opt) return no("--remote-expert-opt"); + if (a.adapt_overlap) return no("STRATA_ADAPT_OVERLAP"); + return true; +} + +/// The measure -> trial -> keep or go back decision. Feed it one finished decode window at a time (wall ms of the window, +/// ms of it the adaptive tier held it up, tokens it produced); it answers what to do before the next window. +class AdaptAsyncSelf { +public: + enum class Phase { Off, Measure, Trial, Done }; + enum class Action { None, ToAsync, ToBlocking }; + struct Config { + int warmup_windows = 64; ///< steady windows ignored first: the swap tier, the cache and the drafter are still settling after a start + int measure_windows = 64; ///< windows measured on the blocking tier + int trial_windows = 64; ///< windows measured on the asynchronous tier (after trial_skip warm-up windows) + int trial_skip = 4; + double wait_frac_min = 0.05; ///< try the asynchronous tier when the wait is at least this part of a window + double gain_min = 0.98; ///< keep it unless ms per token got worse by more than 1/gain_min (a guard against harm: 64 windows of text cannot resolve a 3-5% gain) + }; + AdaptAsyncSelf() = default; + explicit AdaptAsyncSelf(const Config& c) : c_(c) {} + + void arm() { phase_ = Phase::Measure; reset_sums(); } + Phase phase() const { return phase_; } + bool trialing() const { return phase_ == Phase::Trial; } + bool kept() const { return phase_ == Phase::Done && kept_; } + + /// One decode window. Windows with no token (or a non-positive time) are ignored. + Action window(double window_ms, double wait_ms, int tokens) { + if (tokens <= 0 || !(window_ms > 0.0)) return Action::None; + if (phase_ == Phase::Measure) { + if (warmed_ < c_.warmup_windows) { ++warmed_; return Action::None; } + ms_ += window_ms; wait_ += wait_ms; tok_ += tokens; ++n_; + if (n_ < c_.measure_windows) return Action::None; + measure_ms_per_token_ = ms_ / (double) tok_; + wait_frac_ = ms_ > 0.0 ? wait_ / ms_ : 0.0; + reset_sums(); + if (wait_frac_ >= c_.wait_frac_min) { phase_ = Phase::Trial; skipped_ = 0; return Action::ToAsync; } + phase_ = Phase::Done; kept_ = false; // the wait is small: nothing to win + return Action::None; + } + if (phase_ == Phase::Trial) { + if (skipped_ < c_.trial_skip) { ++skipped_; return Action::None; } + ms_ += window_ms; tok_ += tokens; ++n_; + if (n_ < c_.trial_windows) return Action::None; + trial_ms_per_token_ = ms_ / (double) tok_; + phase_ = Phase::Done; + kept_ = trial_ms_per_token_ * c_.gain_min <= measure_ms_per_token_; + return kept_ ? Action::None : Action::ToBlocking; + } + return Action::None; + } + + double wait_fraction() const { return wait_frac_; } + double measure_ms_per_token() const { return measure_ms_per_token_; } + double trial_ms_per_token() const { return trial_ms_per_token_; } + +private: + void reset_sums() { ms_ = wait_ = 0.0; tok_ = 0; n_ = 0; } + Config c_{}; + Phase phase_ = Phase::Off; + double ms_ = 0.0, wait_ = 0.0; + long long tok_ = 0; + int n_ = 0, skipped_ = 0, warmed_ = 0; + double wait_frac_ = 0.0, measure_ms_per_token_ = 0.0, trial_ms_per_token_ = 0.0; + bool kept_ = false; +}; + +} // namespace strata::core diff --git a/src/core/adapt_async_default_test.cpp b/src/core/adapt_async_default_test.cpp new file mode 100644 index 00000000..96a748a0 --- /dev/null +++ b/src/core/adapt_async_default_test.cpp @@ -0,0 +1,135 @@ +// adapt_async_default_test: the asynchronous adaptive tier as a measured choice (include/strata/core/adapt_async_default.hpp). +#include "strata/core/adapt_async_default.hpp" + +#include +#include + +static int g_fail = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { std::fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++g_fail; } \ + } while (0) + +using strata::core::AdaptAsyncAuto; +using strata::core::AdaptAsyncSelf; +using Action = AdaptAsyncSelf::Action; +using Phase = AdaptAsyncSelf::Phase; + +static AdaptAsyncAuto good() { + AdaptAsyncAuto a; + a.cuda = a.serve = a.adaptive = a.arena = true; + return a; +} + +static AdaptAsyncSelf::Config cfg0() { // no warm-up: the cases below count their windows from the first + AdaptAsyncSelf::Config c; + c.warmup_windows = 0; + return c; +} + +// feed `n` windows of `ms` / `wait` / `tok`; returns the last non-None action +static Action feed(AdaptAsyncSelf& s, int n, double ms, double wait, int tok) { + Action last = Action::None; + for (int i = 0; i < n; ++i) { + const Action a = s.window(ms, wait, tok); + if (a != Action::None) last = a; + } + return last; +} + +int main() { + const char* why = nullptr; + // ---- where the engine may choose by measurement + CHECK(strata::core::adapt_async_self_decides(good(), &why)); + { AdaptAsyncAuto a = good(); a.flag = 0; CHECK(!strata::core::adapt_async_self_decides(a, &why)); CHECK(why && std::strstr(why, "given")); } + { AdaptAsyncAuto a = good(); a.flag = 1; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.env = 0; CHECK(!strata::core::adapt_async_self_decides(a, &why)); CHECK(why && std::strstr(why, "STRATA_ADAPT_ASYNC")); } + { AdaptAsyncAuto a = good(); a.env = 1; CHECK(strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.env = -1; CHECK(strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.cuda = false; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.serve = false; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.adaptive = false; CHECK(!strata::core::adapt_async_self_decides(a)); } // --adapt-every 100000 gates + { AdaptAsyncAuto a = good(); a.arena = false; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.multi_gpu = true; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.pipeline_windows = true; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.batch = true; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.peer = true; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.remote_opt = true; CHECK(!strata::core::adapt_async_self_decides(a)); } + { AdaptAsyncAuto a = good(); a.adapt_overlap = true; CHECK(!strata::core::adapt_async_self_decides(a)); } + CHECK(!strata::core::adapt_async_self_decides(AdaptAsyncAuto{})); + + // ---- the state machine + { // not armed: nothing happens + AdaptAsyncSelf s; + CHECK(s.phase() == Phase::Off); + CHECK(feed(s, 500, 20.0, 5.0, 3) == Action::None); + } + { // the wait is small (3% of a window): measure 64 windows, stay blocking, never switch + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 63, 20.0, 0.6, 3) == Action::None); + CHECK(s.phase() == Phase::Measure); + CHECK(feed(s, 1, 20.0, 0.6, 3) == Action::None); + CHECK(s.phase() == Phase::Done && !s.kept()); + CHECK(feed(s, 500, 20.0, 0.6, 3) == Action::None); + } + { // the wait is 7%: switch to async after the 64th window; the async windows are 10% faster per token: kept + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 63, 20.0, 1.4, 3) == Action::None); + CHECK(s.window(20.0, 1.4, 3) == Action::ToAsync); + CHECK(s.phase() == Phase::Trial && s.trialing()); + CHECK(s.wait_fraction() > 0.069 && s.wait_fraction() < 0.071); + CHECK(feed(s, 4 + 63, 18.0, 0.1, 3) == Action::None); // 4 warm-up windows are not counted + CHECK(s.window(18.0, 0.1, 3) == Action::None); // kept: no action + CHECK(s.phase() == Phase::Done && s.kept()); + CHECK(s.trial_ms_per_token() < s.measure_ms_per_token()); + } + { // the wait is 7% and async is 3% SLOWER per token (> 2%): back to blocking, and it stays there + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 64, 20.0, 1.4, 3) == Action::ToAsync); + CHECK(feed(s, 4 + 63, 20.6, 0.1, 3) == Action::None); + CHECK(s.window(20.6, 0.1, 3) == Action::ToBlocking); + CHECK(s.phase() == Phase::Done && !s.kept()); + CHECK(feed(s, 1000, 19.6, 0.1, 3) == Action::None); + } + { // async slower (the CPU-bound box): back + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 64, 55.0, 4.0, 3) == Action::ToAsync); + CHECK(feed(s, 4 + 63, 58.0, 0.2, 3) == Action::None); + CHECK(s.window(58.0, 0.2, 3) == Action::ToBlocking); + } + { // async 1% slower or equal: kept (the trial guards against harm, it does not demand a gain) + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 64, 20.0, 1.4, 3) == Action::ToAsync); + CHECK(feed(s, 4 + 64, 20.2, 0.1, 3) == Action::None); + CHECK(s.kept()); + } + { // 5% wait switches; a 3% gain is kept + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 64, 100.0, 5.0, 4) == Action::ToAsync); + const double t = 100.0 / 1.0301; + CHECK(feed(s, 4 + 64, t, 0.0, 4) == Action::None); + CHECK(s.kept()); + } + { // windows with no token or no time are ignored (they neither count nor move the phase) + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 200, 20.0, 5.0, 0) == Action::None); + CHECK(feed(s, 200, 0.0, 0.0, 3) == Action::None); + CHECK(s.phase() == Phase::Measure); + } + { // tokens per window matter: more tokens per window at the same time is faster per token + AdaptAsyncSelf s(cfg0()); s.arm(); + CHECK(feed(s, 64, 20.0, 2.0, 2) == Action::ToAsync); // 10 ms per token + CHECK(feed(s, 4 + 64, 20.0, 0.1, 3) == Action::None); // 6.7 ms per token: kept + CHECK(s.kept()); + } + { // the default has a warm-up: the first 64 steady windows are not measured (a fresh engine's cache is still settling) + AdaptAsyncSelf s; s.arm(); + CHECK(feed(s, 64, 20.0, 5.0, 3) == Action::None); // warm-up + CHECK(s.phase() == Phase::Measure); + CHECK(feed(s, 63, 20.0, 1.4, 3) == Action::None); + CHECK(s.window(20.0, 1.4, 3) == Action::ToAsync); // 128th window: the measurement is the last 64 only + CHECK(s.wait_fraction() > 0.069 && s.wait_fraction() < 0.071); + } + if (g_fail == 0) std::printf("adapt_async_default_test: OK\n"); + return g_fail == 0 ? 0 : 1; +} diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 7bafd685..d381227d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -16,6 +16,7 @@ // (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump. #include "strata/platform/memory.hpp" +#include "strata/core/adapt_async_default.hpp" #include "strata/core/arch_defaults.hpp" #include "strata/core/nv_defaults.hpp" #include "strata/kernels/gfx_arch.hpp" @@ -700,6 +701,8 @@ struct Options { /// windows on a helper thread instead of one window waiting for a whole round (see the tier in the --serve block). /// Not bit-exact run to run. 0 = the blocking tier. int adapt_async = 0; + int adapt_async_given = -1; ///< --adapt-async on the command line (-1: not given; then the engine may decide, adapt_async_default.hpp) + bool adapt_async_self = false; ///< the engine measures and chooses the asynchronous tier during the session (adapt_async_default.hpp) /// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least /// this probability under the draft layer; 0 = always --spec-1 drafts. double spec_min_p = 0.0; @@ -1071,10 +1074,12 @@ void usage() { " does not fit. Same answers as --mmap-experts for the same placement.\n" " --adapt-min-gain F the adaptive tier swaps an expert in only when its decayed routing count beats\n" " the one it replaces by more than F (default 1.5; higher = fewer, surer swaps)\n" - " --adapt-async 1 --serve with the resident RAM mode or the arena (one GPU; opt-in): the adaptive\n" + " --adapt-async 0|1 --serve with the resident RAM mode or the arena (one GPU): the adaptive\n" " tier's swaps advance between verify windows instead of a window waiting for a\n" - " whole round (the arena: copy-in only). Not bit-exact run to run. 0 (default)\n" - " = the blocking tier.\n"); + " whole round (the arena: copy-in only). Not bit-exact run to run. Without the flag,\n" + " the expert arena on one CUDA GPU (no --batch) starts blocking and tries it for a\n" + " while when the swaps hold the windows up, keeping it only if it is faster; 0 = the\n" + " blocking tier always (also STRATA_ADAPT_ASYNC=0); 1 = always on.\n"); } // --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last @@ -2626,7 +2631,7 @@ int main(int argc, char** argv) { else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_every_given = true; } else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay")); else if (a == "--adapt-min-gain") o.adapt_min_gain = (float) std::atof(next("--adapt-min-gain")); - else if (a == "--adapt-async") o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0; + else if (a == "--adapt-async") { o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0; o.adapt_async_given = o.adapt_async; } else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p")); else if (a == "--stop-eos") o.stop_eos = true; else if (a == "--spec-split") o.spec_split = true; @@ -8074,6 +8079,27 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n", why); o.adapt_async = 0; }; + // Where the asynchronous tier could run on its own (CUDA, one GPU, the expert arena, no batch slots), the engine measures + // and chooses during the session: see include/strata/core/adapt_async_default.hpp. --adapt-async 0 or + // STRATA_ADAPT_ASYNC=0 keep the blocking tier; --adapt-async 1 keeps its old meaning. + if (o.adapt_async_given < 0) { + strata::core::AdaptAsyncAuto aa; + aa.flag = o.adapt_async_given; + aa.env = strata::core::adapt_async_env(); +#if !defined(STRATA_USE_HIP) + aa.cuda = true; +#endif + aa.serve = o.serve; + aa.adaptive = o.adapt_every > 0 && o.adapt_swaps > 0; + aa.arena = srcp == &arena_src; + aa.multi_gpu = multi_gpu; + aa.pipeline_windows = o.pipeline_windows >= 2; + aa.batch = o.batch > 0; + aa.peer = peer.valid(); + aa.remote_opt = remote_opt != nullptr; + aa.adapt_overlap = adapt_overlap(); + o.adapt_async_self = strata::core::adapt_async_self_decides(aa); + } if (o.adapt_async) { static const bool pl_async = [] { const char* v = std::getenv("STRATA_PIPELINE_ADAPT_ASYNC"); @@ -10541,15 +10567,25 @@ int main(int argc, char** argv) { const bool a_inline = a_arena && a_env("STRATA_ADAPT_PICK_INLINE", 1) != 0; const bool a_wait = a_arena && a_env("STRATA_ADAPT_ASYNC_WAIT", 1) != 0; const size_t a_batch = a_arena ? (size_t) std::max(0, a_env("STRATA_ADAPT_ASYNC_BATCH", 0)) : 0; - if (o.adapt_async && !drive.d.usage.empty() && + // o.adapt_async_self (arena, one GPU, nothing explicit): the homes are set up, the job thread is created only when the + // session's measurement turns the asynchronous tier on (asw_*, in the decode loop) + const bool a_self = o.adapt_async_self && !o.adapt_async && a_arena && !drive.d.usage.empty(); + if ((o.adapt_async || a_self) && !drive.d.usage.empty() && ((src.complement_ready() && src.exchange_capacity() >= 2 * a_cap) || a_arena)) { ahomes.push_back({&xcache, adapt_stream, adapt_ev, 0, false}); for (auto& st : stages) ahomes.push_back({&st->cache, st->adapt_stream, st->adapt_ev, st->dev, false}); - ajob = std::make_unique(); - std::fprintf(stderr, "strata serve: adaptive tier asynchronous (--adapt-async 1): up to %lld swaps per round, " - "a round every %d windows%s\n", (long long) a_cap, o.adapt_every, - a_arena ? " (arena: copy-in only)" : ""); + if (o.adapt_async) { + ajob = std::make_unique(); + std::fprintf(stderr, "strata serve: adaptive tier asynchronous (--adapt-async 1): up to %lld swaps per round, " + "a round every %d windows%s\n", (long long) a_cap, o.adapt_every, + a_arena ? " (arena: copy-in only)" : ""); + } else { + std::fprintf(stderr, "strata serve: adaptive tier: blocking, and the asynchronous tier is tried once the session " + "shows the swaps hold the windows up (--adapt-async 0 or STRATA_ADAPT_ASYNC=0: never)\n"); + } } + strata::core::AdaptAsyncSelf asw; // the session's choice between the two tiers (adapt_async_default.hpp) + if (a_self && !ahomes.empty()) asw.arm(); // the pipelined loop's side (see above): whether stage `st` has no window in flight; per home, the copies back // and in to queue at its next gap, the RAM fence still to pass and the gaps seen std::function a_pl_idle; @@ -14934,6 +14970,8 @@ int main(int argc, char** argv) { // expert ran on the GPU or the CPU (they round differently) depended on the copy's timing // (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) const Clock::time_point taw0 = Clock::now(); + const bool asw_skip = first_window || merged; // the session's tier choice counts steady decode windows only + double asw_wait_ms = 0; if (adapt_nowait()) apply_pending(false); else if (aov && !pending.empty() && !aflipped) { // 0.1.43 STRATA_ADAPT_OVERLAP: the tables take the swaps now, exactly where the wait would have ended; @@ -15062,7 +15100,8 @@ int main(int argc, char** argv) { std::printf("ERR an adaptive refill failed\n"); return 1; } - dt_adapt_wait += std::chrono::duration(Clock::now() - taw0).count(); + asw_wait_ms = std::chrono::duration(Clock::now() - taw0).count(); + dt_adapt_wait += asw_wait_ms; if (hist_n > 0) { // the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the // fed-back head `x` (it joins `consumed` only after this window commits), then the drafts @@ -15177,12 +15216,36 @@ int main(int argc, char** argv) { if (adapt_thr.joinable()) { const Clock::time_point taj0 = Clock::now(); adapt_thr.join(); - dt_adapt_join += std::chrono::duration(Clock::now() - taj0).count(); + const double asw_join = std::chrono::duration(Clock::now() - taj0).count(); + dt_adapt_join += asw_join; + asw_wait_ms += asw_join; } if (!adapt_ok) { std::printf("ERR an adaptive refill failed\n"); return 1; } + // the session's choice of the adaptive tier (adapt_async_default.hpp): ~64 windows on the blocking tier, then + // ~64 on the asynchronous one if the swaps held the windows up, kept only if the decode got faster + if (!asw_skip && (asw.phase() == strata::core::AdaptAsyncSelf::Phase::Measure || asw.trialing())) { + const bool was_trial = asw.trialing(); + const double asw_ms = std::chrono::duration(Clock::now() - taw0).count(); + const auto act = asw.window(asw_ms, asw_wait_ms, a + 1); + if (act == strata::core::AdaptAsyncSelf::Action::ToAsync) { + ajob = std::make_unique(); + std::fprintf(stderr, "strata serve: adaptive tier: the swaps held the windows up by %.1f%% (%.2f ms per " + "token): trying the asynchronous tier for a while\n", + 100.0 * asw.wait_fraction(), asw.measure_ms_per_token()); + } else if (act == strata::core::AdaptAsyncSelf::Action::ToBlocking) { + adapt_quiesce(); + ajob.reset(); + std::fprintf(stderr, "strata serve: adaptive tier: the asynchronous tier was slower (%.2f against " + "%.2f ms per token): back to the blocking tier for this session\n", + asw.trial_ms_per_token(), asw.measure_ms_per_token()); + } else if (was_trial && asw.kept()) { + std::fprintf(stderr, "strata serve: adaptive tier: the asynchronous tier stays on (%.2f against %.2f ms " + "per token)\n", asw.trial_ms_per_token(), asw.measure_ms_per_token()); + } + } if (!drafted) { std::printf("ERR %s\n", err.c_str()); return 1; From 16c4da9443fba119dab8f25be8cef3264aa625ec Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 24 Oct 2026 14:09:08 +0200 Subject: [PATCH 2/2] CPU expert rows: 512-bit grid lookups by gather where a gather is cheap; one IQ3 token on the exact 512-bit rows The 512-bit i-quant rows (IQ2_XXS/XS/S, IQ3_XXS/S) assembled their grid words from scalar loads (~30 uops a 64-value chunk). Where cpu_gather_fast() (Intel Sapphire Rapids and later) they now load them by one gather, 32-bit for IQ3 and 64-bit for IQ2 (STRATA_IQ_GATHER=1/0 force it; Zen 4 stays scalar: its gathers are microcoded). The same words are loaded, so every output bit is unchanged. One token of an IQ3_XXS / IQ3_S expert takes the exact 512-bit rows (ggml-cpu's single-token AVX2 dot bit for bit) with the gather, after a first-use bit check against this ggml; STRATA_NO_IQ512X1=1 turns it off. Xeon 8468, native_gu_rows (gate+up of an expert), us: IQ3_XXS 1 token 295 -> 219, 2 tokens 462 -> 300, 4 tokens 558 -> 389; IQ3_S 415 -> 305, 603 -> 342, 562 -> 296; IQ2_S 2 tokens 377 -> 235, 4 tokens 437 -> 327 (one IQ2_S token stays on ggml: 239 against 234). Output checksums identical with and without. Test iq512_gather_parity (both lookup modes): exact rows == ggml vec_dot at 1-4 tokens, engine rows within float rounding. --- CMakeLists.txt | 8 +++ include/strata/kernels/cpu/iq_avx512.hpp | 3 + src/kernels/cpu/iq512_gather_parity.cpp | 76 ++++++++++++++++++++++++ src/kernels/cpu/iq_avx512.cpp | 32 ++++++++-- src/kernels/cpu/native_expert.cpp | 53 +++++++++++++++++ 5 files changed, 166 insertions(+), 6 deletions(-) create mode 100644 src/kernels/cpu/iq512_gather_parity.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 7dd95dfd..41d9fd86 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1776,6 +1776,14 @@ if(STRATA_NATIVE_EXPERTS) # against ggml-cpu's dot, on random blocks; --bench: ms per expert on one thread, the weights streamed from DRAM add_executable(iq_avx2_parity src/kernels/cpu/iq_avx2_parity.cpp) target_link_libraries(iq_avx2_parity PRIVATE strata_kernels_cpu) + # the 512-bit i-quant rows against ggml-cpu's dot: the exact rows bit for bit at 1-4 tokens, the engine's multi-token rows to float + # rounding, with the grid lookups as scalar loads and as gathers (SKIP without AVX-512) + add_executable(iq512_gather_parity src/kernels/cpu/iq512_gather_parity.cpp) + target_link_libraries(iq512_gather_parity PRIVATE strata_kernels_cpu) + if(STRATA_BUILD_TESTS) + add_test(NAME iq512_gather_parity_scalar COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=0 $) + add_test(NAME iq512_gather_parity_gather COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ_GATHER=1 $) + endif() # MODEL-UPDATE: the pool's expert rows per format on T threads against the RAM bandwidth (a benchmark, no test) add_executable(kq_cpu_bench src/kernels/cpu/kq_cpu_bench.cpp) target_link_libraries(kq_cpu_bench PRIVATE strata_kernels_cpu) diff --git a/include/strata/kernels/cpu/iq_avx512.hpp b/include/strata/kernels/cpu/iq_avx512.hpp index ae21dfd4..3f51b9de 100644 --- a/include/strata/kernels/cpu/iq_avx512.hpp +++ b/include/strata/kernels/cpu/iq_avx512.hpp @@ -8,6 +8,9 @@ namespace strata::kernels::cpu { bool iq512_supported(int ggml_type) noexcept; +/// Whether the grid lookups of these rows are gathers (the default where cpu_gather_fast(), STRATA_IQ_GATHER=1 / 0 force it): the +/// same words, so the same bits as the scalar lookups, and 1.3-2x faster where a gather is cheap (Sapphire Rapids). +bool iq512_gather_on() noexcept; /// ff[t][r] = silu(gate_r . a[t]) * (up_r . a[t]), rows [r0, r1); gate rows at blob, up rows at blob + up_off. void iq512_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt, float* const* ff, int r0, int r1); diff --git a/src/kernels/cpu/iq512_gather_parity.cpp b/src/kernels/cpu/iq512_gather_parity.cpp new file mode 100644 index 00000000..502880ea --- /dev/null +++ b/src/kernels/cpu/iq512_gather_parity.cpp @@ -0,0 +1,76 @@ +// iq512_gather_parity: the 512-bit i-quant rows (iq_avx512.cpp) against ggml-cpu's own dot. +// (a) iq512x_rows, for 1..4 tokens, is ggml-cpu's single-token vec_dot bit for bit (IQ3_XXS, IQ3_S, IQ2_S), whatever the +// grid lookup is (scalar loads or gathers: STRATA_IQ_GATHER=0 / 1, ctest runs both); +// (b) iq512_rows (the engine's multi-token rows) agrees with it to float rounding (another summation order). +// Synthetic blocks (random bytes, a fixed f16 scale), so no quantizer and no imatrix are needed. SKIP without AVX-512. +#include "strata/kernels/cpu/expert_layout.hpp" +#include "strata/kernels/cpu/iq_avx512.hpp" + +#include "ggml.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include + +namespace cpu = strata::kernels::cpu; + +static int g_fail = 0; +#define CHECK(c) \ + do { \ + if (!(c)) { std::fprintf(stderr, "FAIL %s:%d %s\n", __FILE__, __LINE__, #c); ++g_fail; } \ + } while (0) + +int main() { + ggml_cpu_init(); + if (!cpu::cpu_avx512_ok()) { + std::printf("iq512_gather_parity: SKIP (no AVX-512)\n"); + return 0; + } + std::printf("iq512_gather_parity: gather %d\n", (int) cpu::iq512_gather_on()); + constexpr int n = 2560, rows = 96, ntmax = 4; + const ggml_type_traits_cpu* t8 = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K); + uint32_t seed = 987654321u; + auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; }; + const size_t ab = ggml_row_size(GGML_TYPE_Q8_K, n); + std::vector> act(ntmax, std::vector(ab)); + const void* ap[ntmax]; + for (int t = 0; t < ntmax; ++t) { + std::vector x(n); + for (auto& v : x) v = ((float) (rnd() % 2001) - 1000.f) * 0.001f * (1.f + (float) t); + t8->from_float(x.data(), act[t].data(), n); + ap[t] = act[t].data(); + } + for (int type : {18, 21, 22}) { + const ggml_type_traits_cpu* tr = ggml_get_type_traits_cpu((ggml_type) type); + CHECK(tr != nullptr && tr->vec_dot != nullptr); + CHECK(cpu::iq512x_supported(type) && cpu::iq512_supported(type)); + const size_t rb = ggml_row_size((ggml_type) type, n), nb = (size_t) n / 256, bb = rb / nb; + std::vector w((size_t) rows * rb); + for (auto& b : w) b = (uint8_t) rnd(); + for (int r = 0; r < rows; ++r) + for (size_t k = 0; k < nb; ++k) { uint8_t* d = &w[(size_t) r * rb + k * bb]; d[0] = 0x66; d[1] = 0x2e; } // f16 ~0.1 + std::vector want((size_t) ntmax * rows), gx((size_t) ntmax * rows), ge((size_t) ntmax * rows); + for (int t = 0; t < ntmax; ++t) + for (int r = 0; r < rows; ++r) + tr->vec_dot(n, &want[(size_t) t * rows + r], 0, w.data() + (size_t) r * rb, 0, act[t].data(), 0, 1); + for (int nt = 1; nt <= ntmax; ++nt) { + float* ox[ntmax]; + float* oe[ntmax]; + for (int t = 0; t < ntmax; ++t) { ox[t] = &gx[(size_t) t * rows]; oe[t] = &ge[(size_t) t * rows]; } + cpu::iq512x_rows(type, w.data(), rb, n, ap, nt, ox, 0, rows); + cpu::iq512_rows(type, w.data(), rb, n, ap, nt, oe, 0, rows); + for (int t = 0; t < nt; ++t) + for (int r = 0; r < rows; ++r) { + const float want_v = want[(size_t) t * rows + r]; + CHECK(std::memcmp(&gx[(size_t) t * rows + r], &want_v, 4) == 0); // (a) bit for bit + const float e = ge[(size_t) t * rows + r]; + CHECK(std::fabs(e - want_v) <= 1e-3f * std::fabs(want_v) + 1e-3f); // (b) float-rounding agreement + } + } + std::printf(" type %d: ok\n", type); + } + if (g_fail == 0) std::printf("iq512_gather_parity: OK\n"); + return g_fail == 0 ? 0 : 1; +} diff --git a/src/kernels/cpu/iq_avx512.cpp b/src/kernels/cpu/iq_avx512.cpp index 14330f6e..aaa0adaa 100644 --- a/src/kernels/cpu/iq_avx512.cpp +++ b/src/kernels/cpu/iq_avx512.cpp @@ -9,6 +9,7 @@ // Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22). IQ1_M stays on ggml-cpu (no shipped // model has IQ1_M expert rows: the 'Coder IQ1_M' pack's gate/up are IQ2_S / IQ3_XXS / IQ3_S). #include "strata/kernels/cpu/iq_avx512.hpp" +#include "strata/kernels/cpu/expert_layout.hpp" #define GGML_COMMON_DECL_CPP #define GGML_COMMON_IMPL_CPP @@ -36,7 +37,14 @@ inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); retur // E-2: the IQ3 grids by one AVX-512 gather (the same words, the same results) - measured 3-5% SLOWER than the scalar // lookups on a Ryzen 5 7600 (Zen 4 gathers are microcoded), so opt-in: STRATA_IQ_GATHER=1 -const bool gather = std::getenv("STRATA_IQ_GATHER") != nullptr; +// 0.2.5: DEFAULT on where gathers are fast (Intel server and HEDT cores with AVX-512: cpu_gather_fast), off on Zen 4 (microcoded); +// STRATA_IQ_GATHER=1 / 0 force it either way. The same words are loaded, so the results are bit for bit the scalar decode's. +const bool gather = [] { + const char* v = std::getenv("STRATA_IQ_GATHER"); + return v != nullptr && v[0] != '\0' ? std::atoi(v) != 0 : cpu_gather_fast(); +}(); +// the grid lookups by one 64-bit gather of eight entries (IQ2_XXS / IQ2_XS / IQ2_S): `idx` = eight 32-bit indices +inline __m512i gather64(__m256i idx, const void* grid) { return _mm512_i32gather_epi64(idx, grid, 8); } // E-2: software prefetch distance in bytes (STRATA_IQ_PREFETCH; 0 = off): -2-3% gate/up time on IQ3_S decode // (the rows are read at ~30 GB/s by 6 cores, near what DDR5 with 4 KB pages gives: the pool is memory-bound) const int prefetch_ahead = [] { @@ -62,7 +70,8 @@ template <> struct Fmt<16> { // IQ2_XXS: d, qs[32] u16 static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { const uint8_t* q = b + 2 + 16 * j; const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12); - g = _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255], + g = gather ? gather64(_mm256_cvtepu8_epi32(_mm_cvtsi64_si128((long long) ((uint64_t) a0 | ((uint64_t) b0 << 32)))), iq2xxs_grid) + : _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255], (long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255], (long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255], (long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]); @@ -83,7 +92,8 @@ template <> struct Fmt<17> { // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bi const uint8_t* q = b + 2 + 16 * j; uint16_t v[8]; std::memcpy(v, q, 16); - g = _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511], + g = gather ? gather64(_mm256_and_si256(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) q)), _mm256_set1_epi32(511)), iq2xs_grid) + : _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511], (long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511], (long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511], (long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]); @@ -101,6 +111,11 @@ template <> struct Fmt<22> { // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { const uint8_t* qs = b + 2 + 8 * j; const uint8_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1]; + if (gather) { // the 10-bit indices: the byte plus two high bits from qh (h0 for lanes 0-3, h1 for 4-7), one 64-bit gather + const __m256i hi = _mm256_and_si256(_mm256_sllv_epi32(_mm256_setr_epi32(h0, h0, h0, h0, h1, h1, h1, h1), + _mm256_setr_epi32(8, 6, 4, 2, 8, 6, 4, 2)), _mm256_set1_epi32(0x300)); + g = gather64(_mm256_or_si256(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) qs)), hi), iq2s_grid); + } else g = _mm512_set_epi64((long long) iq2s_grid[qs[7] | ((h1 << 2) & 0x300)], (long long) iq2s_grid[qs[6] | ((h1 << 4) & 0x300)], (long long) iq2s_grid[qs[5] | ((h1 << 6) & 0x300)], (long long) iq2s_grid[qs[4] | ((h1 << 8) & 0x300)], (long long) iq2s_grid[qs[3] | ((h0 << 2) & 0x300)], (long long) iq2s_grid[qs[2] | ((h0 << 4) & 0x300)], @@ -265,7 +280,8 @@ template <> struct FmtX<16> : Fmt<16> { static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { const uint8_t* q = b + 2 + 16 * j; const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12); - g = _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255], + g = gather ? gather64(_mm256_cvtepu8_epi32(_mm_cvtsi64_si128((long long) ((uint64_t) a0 | ((uint64_t) b0 << 32)))), iq2xxs_grid) + : _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255], (long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255], (long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255], (long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]); @@ -279,7 +295,8 @@ template <> struct FmtX<17> : Fmt<17> { const uint8_t* q = b + 2 + 16 * j; uint16_t v[8]; std::memcpy(v, q, 16); - g = _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511], + g = gather ? gather64(_mm256_and_si256(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) q)), _mm256_set1_epi32(511)), iq2xs_grid) + : _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511], (long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511], (long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511], (long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]); @@ -291,7 +308,8 @@ template <> struct FmtX<17> : Fmt<17> { template <> struct FmtX<18> : Fmt<18> { static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) { const uint8_t* q = b + 2 + 16 * j; - g = _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]], + g = gather ? _mm512_i32gather_epi32(_mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)), iq3xxs_grid, 4) + : _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]], (int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]], (int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]], (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]); @@ -578,6 +596,8 @@ static bool has_vpopcnt() { return ok; } +bool iq512_gather_on() noexcept { return gather; } + bool iq512x_supported(int type) noexcept { return has_vpopcnt() && (type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 29); } diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index 7c491832..ec1a6870 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -39,6 +39,40 @@ bool tq_rows_own(int type) { return type >= (int) GGML_TYPE_COUNT || traits(type) == nullptr || traits(type)->vec_dot == nullptr; } +// 0.2.5: the 512-bit exact rows (iq512x_rows) take one token of an IQ3_XXS / IQ3_S expert only if this build's ggml-cpu dot gives +// the same bits on synthetic blocks of that type (a ggml built for AVX-512 may carry another summation order): checked once a type. +bool x512_one_ok(int type) { + static std::mutex mu; + static std::map memo; + std::lock_guard lk(mu); + if (const auto it = memo.find(type); it != memo.end()) return it->second; + bool ok = false; + const ggml_type_traits_cpu* tr = traits(type); + const ggml_type_traits_cpu* t8 = traits(GGML_TYPE_Q8_K); + if (tr != nullptr && tr->vec_dot != nullptr && t8 != nullptr && t8->from_float != nullptr && iq512x_supported(type)) { + constexpr int n = 2560, rows = 24; + const size_t rb = ggml_row_size((ggml_type) type, n), nb = (size_t) n / 256, bb = rb / nb; + std::vector w((size_t) rows * rb), act(ggml_row_size(GGML_TYPE_Q8_K, n)); + uint32_t seed = 12345u; + auto rnd = [&seed] { seed = seed * 1664525u + 1013904223u; return seed >> 8; }; + for (auto& b : w) b = (uint8_t) rnd(); + for (int r = 0; r < rows; ++r) + for (size_t k = 0; k < nb; ++k) { uint8_t* d = &w[(size_t) r * rb + k * bb]; d[0] = 0x66; d[1] = 0x2e; } // d = ~0.1 (f16) + std::vector x(n); + for (auto& v : x) v = ((float) (rnd() % 2001) - 1000.f) * 0.001f; + t8->from_float(x.data(), act.data(), n); + std::vector got((size_t) rows), want((size_t) rows); + const void* ap[1] = {act.data()}; + float* op[1] = {got.data()}; + iq512x_rows(type, w.data(), rb, n, ap, 1, op, 0, rows); + for (int r = 0; r < rows; ++r) tr->vec_dot(n, &want[(size_t) r], 0, w.data() + (size_t) r * rb, 0, act.data(), 0, 1); + ok = std::memcmp(got.data(), want.data(), got.size() * sizeof(float)) == 0; + if (!ok) std::fprintf(stderr, "strata: the 512-bit exact one-token rows of type %d differ from this ggml-cpu's dot: not used\n", type); + } + memo[type] = ok; + return ok; +} + void init_once() { static std::once_flag once; std::call_once(once, [] { ggml_cpu_init(); }); @@ -299,6 +333,25 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* iq256_gu_rows_exact_one(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act[0], ff[0], r0, r1); return; } + // 0.2.5 (AVX-512 CPUs where a gather is cheap: Intel Sapphire Rapids and later): ONE token of an IQ3_XXS / IQ3_S expert on the + // 512-bit exact rows, ggml-cpu's single-token AVX2 dot bit for bit with the grid words gathered: 1.3x ggml's dot on a Xeon 8468 + // (x512_bench), the same output. Where the multi-token rule (#152) already sends one token to the multi-token kernel + // (STRATA_IQ_MT_MIN=1) that stays; STRATA_NO_IQ512X1=1 turns this off; the first use checks the bits against this ggml. + static const bool x512_one = avx512 && iq512_gather_on() && std::getenv("STRATA_NO_IQ512X1") == nullptr; + if (x512_one && nt == 1 && nt < native_gu_mt_min(f.gu_type) && f.tail_off == 0 && (f.gu_type == 18 || f.gu_type == 21) && + x512_one_ok(f.gu_type)) { + const int n1 = (int) f.n_embd; + float g[64], u[64]; + float* gp[1] = {g}; + float* up[1] = {u}; + for (int c0 = r0; c0 < r1; c0 += 64) { + const int c1 = std::min(r1, c0 + 64); + iq512x_rows(f.gu_type, blob + (size_t) c0 * f.gu_row, f.gu_row, n1, act, 1, gp, 0, c1 - c0); + iq512x_rows(f.gu_type, blob + f.up_off + (size_t) c0 * f.gu_row, f.gu_row, n1, act, 1, up, 0, c1 - c0); + for (int r = c0; r < c1; ++r) ff[0][r] = (g[r - c0] / (1.f + std::exp(-g[r - c0]))) * u[r - c0]; + } + return; + } const int mt_min = native_gu_mt_min(f.gu_type); // #152 // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot (any group // size, no #152 rule). Opt-in, STRATA_KQ256=1: measured no faster in the engine (a window's expert groups hold