diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 485733b2..84339efc 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -136,6 +137,49 @@ public: /// The `n` experts of `layer` the CPU is about to ask `blob` for, all at once: a source that reads a file may /// fetch them in parallel. The bytes `blob` then returns are the same. Default: nothing. virtual void prefetch(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } + /// CS-T: the experts of `layer` a predictor expects next - a source that reads a file may start reading their + /// pages now, in the background. Only warms: what `blob` returns is unchanged. Default: nothing. + virtual void warm(int64_t layer, const int64_t* experts, int64_t n) { (void) layer; (void) experts; (void) n; } + /// Whether `warm` does anything (the predictor is not run otherwise). + virtual bool warms() const { return false; } +}; + +/// CS-T, routing-aware prefetch of the file tier: when the CPU pool starts layer `l`, a worker thread applies layer +/// l+1's router (BF16, host copy) to layer l's MoE input - the residual stream changes little from one layer to the +/// next - takes each token's top `k` experts, drops the ones the GPU cache or the RAM copy holds, and asks the +/// source to `warm` the rest, so their pages are on the way while layer l computes. A prediction only warms pages: +/// it never changes which experts are computed or how. +class RouterLookahead { +public: + RouterLookahead() = default; + ~RouterLookahead(); + RouterLookahead(const RouterLookahead&) = delete; + RouterLookahead& operator=(const RouterLookahead&) = delete; + /// `routers[l]`: layer l's ffn_gate_inp as BF16 bits, n_expert rows of n_embd. + bool start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, ExpertSource* src, + std::string& err); + /// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a + /// prediction still running for an earlier layer makes this one skip. + void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res); + int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); } + int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); } + double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; } + +private: + void run(); + std::vector> routers_; + int64_t n_embd_ = 0, n_expert_ = 0; + int k_ = 10; + ExpertSource* src_ = nullptr; + std::thread thread_; + std::mutex mu_; + std::condition_variable cv_; + bool quit_ = false, pending_ = false, busy_ = false; + int64_t layer_ = -1, n_tok_ = 0; + const int32_t* host_res_ = nullptr; + std::vector x_; + std::atomic predicted_{0}, skipped_{0}; + std::atomic busy_us_{0}; }; /// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right @@ -169,6 +213,7 @@ struct GpuPlanSink { struct ExpertDispatch { strata::kernels::cpu::ExpertPool* pool = nullptr; ExpertSource* src = nullptr; + RouterLookahead* lookahead = nullptr; ///< CS-T: warms the next layer's predicted file-tier experts RemoteExperts* remote[3] = {}; ///< optional CUDA1..3 tiers for otherwise CPU-served rows int remote_count = 0; int64_t n_expert = strata::kernels::cpu::NE; @@ -433,6 +478,13 @@ public: void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override; /// CS-T: the GGUF in place assembles the missed experts on `fetch_threads_` threads. void prefetch(int64_t layer, const int64_t* experts, int64_t n) override; + /// CS-T: the GGUF in place asks the OS for the predicted experts' pages (PrefetchVirtualMemory on Windows, + /// madvise(WILLNEED) elsewhere), skipping the RAM copy's. + void warm(int64_t layer, const int64_t* experts, int64_t n) override; + bool warms() const override { return !role_ptr_.empty(); } + /// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand. + int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); } + int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); } /// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only /// interesting once Phase 3 makes it not so. @@ -474,6 +526,8 @@ private: std::condition_variable stage_cv_; int fetch_threads_ = 8; std::atomic file_blob_bytes_{0}, file_us_{0}; + std::unique_ptr[]> warm_stamp_; ///< per (layer, expert): epoch_ + 1 when warmed + std::atomic warm_hits_{0}, warm_count_{0}; std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; @@ -496,6 +550,7 @@ private: bool complement_pinned_ = false; bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered uint64_t complement_pin_limit_ = 0; + uint64_t complement_lock_off_ = 0; ///< the working-set lock covers [lock_off, lock_off + locked) bool complement_ready_ = false; uint64_t complement_locked_ = 0; ///< bytes held in the working set (pin refused) int64_t complement_lent_slots_ = 0; diff --git a/include/strata/kernels/cpu/kq_avx2.hpp b/include/strata/kernels/cpu/kq_avx2.hpp index 0b307404..01b7a63c 100644 --- a/include/strata/kernels/cpu/kq_avx2.hpp +++ b/include/strata/kernels/cpu/kq_avx2.hpp @@ -17,4 +17,9 @@ void kq256_gu_rows(int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_ void kq256_rows(int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out, int r0, int r1); +/// out[r] = w_r . x for BF16 rows (bits), fp32 x: the routing-aware prefetch's router (an estimate only). +void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out); +/// The same for `nt` <= 8 tokens (x: nt rows of cols, cols % 8 == 0), out[t * rows + r]. +void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out); + } // namespace strata::kernels::cpu diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 6463c344..c426d3ac 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -9,6 +9,7 @@ #include "strata/kernels/elementwise.hpp" #include "strata/kernels/quantize_act.hpp" #include "strata/kernels/s2_expert_grouped.hpp" +#include "strata/kernels/cpu/kq_avx2.hpp" #include @@ -460,7 +461,8 @@ void FileExpertSource::close() { if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_); else { if (complement_partial_) (void) cudaHostUnregister(complement_arena_); - if (complement_locked_ > 0) strata::platform::unlock_resident(complement_arena_, complement_locked_); + if (complement_locked_ > 0) + strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_); std::free(complement_arena_); } } @@ -484,6 +486,7 @@ void FileExpertSource::close() { complement_pinned_ = false; complement_partial_ = false; complement_pin_limit_ = 0; + complement_lock_off_ = 0; complement_ready_ = false; complement_locked_ = 0; complement_lent_slots_ = 0; @@ -518,6 +521,9 @@ void FileExpertSource::close() { stage_grew_ = false; } ram_reads_.store(0); + warm_stamp_.reset(); + warm_hits_.store(0); + warm_count_.store(0); file_read_bytes_.store(0); file_blob_bytes_.store(0); file_us_.store(0); @@ -627,6 +633,7 @@ bool FileExpertSource::open_gguf(std::string& err) { } } base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode + warm_stamp_.reset(new std::atomic[(size_t) (n_layers_ * n_expert_)]()); for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b); return true; } @@ -756,10 +763,40 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n if (!override_.empty() && override_[index] != nullptr) continue; size_t v = 0; bool fill = false; - if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) todo.push_back({v, e, stage_buf_[v].get()}); + if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) { + todo.push_back({v, e, stage_buf_[v].get()}); + if (warm_stamp_) { + const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed); + if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed); + } + } } } if (todo.empty()) return; +#if defined(_WIN32) + // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large + // requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below + // then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm. + { + using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); + static const Pvm pvm = [] { + const char* v = std::getenv("STRATA_FETCH_PVM"); + if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr; + return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); + }(); + if (pvm != nullptr) { + std::vector ranges; + ranges.reserve(todo.size() * 3); + for (const Fill& f : todo) + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])), + (SIZE_T) role_bytes_[i]}); + } + (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); + } + } +#endif // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full std::atomic next{0}; auto work = [&] { @@ -773,6 +810,125 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n for (auto& t : th) t.join(); } + +void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { + if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return; + uint32_t stamp; + { + std::lock_guard lk(stage_mu_); + stamp = (uint32_t) epoch_ + 1; + } +#if defined(_WIN32) + using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG); + static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory"); + std::vector ranges; +#endif + for (int64_t j = 0; j < n; ++j) { + const int64_t e = experts[j]; + if (e < 0 || e >= n_expert_) continue; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; + if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + continue; // in the RAM copy + if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed); + warm_count_.fetch_add(1, std::memory_order_relaxed); + for (int r = 0; r < 3; ++r) { + const size_t i = (size_t) (3 * layer + r); + const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]); +#if defined(_WIN32) + ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]}); +#else + const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1); + (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED); +#endif + } + } +#if defined(_WIN32) + if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0); +#endif +} + +RouterLookahead::~RouterLookahead() { + { + std::lock_guard lk(mu_); + quit_ = true; + } + cv_.notify_all(); + if (thread_.joinable()) thread_.join(); +} + +bool RouterLookahead::start(std::vector> routers, int64_t n_embd, int64_t n_expert, int k, + ExpertSource* src, std::string& err) { + if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; } + if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; } + for (const auto& r : routers) + if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; } + routers_ = std::move(routers); + n_embd_ = n_embd; + n_expert_ = n_expert; + k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k; + src_ = src; + x_.assign((size_t) (8 * n_embd), 0.f); + thread_ = std::thread([this] { run(); }); + return true; +} + +void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) { + if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return; + { + std::lock_guard lk(mu_); + if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; } + n_tok_ = std::min(n_tok, 8); + std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float)); + layer_ = layer + 1; + host_res_ = host_res; + pending_ = true; + } + cv_.notify_one(); +} + +void RouterLookahead::run() { + std::vector logits((size_t) (8 * n_expert_)); + std::vector order((size_t) n_expert_); + std::vector want; + for (;;) { + int64_t layer, nt; + const int32_t* host_res; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [&] { return quit_ || pending_; }); + if (quit_) return; + pending_ = false; + busy_ = true; + layer = layer_; + nt = n_tok_; + host_res = host_res_; + } + const auto t0 = std::chrono::steady_clock::now(); + want.clear(); + strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_, + x_.data(), (int) nt, logits.data()); + for (int64_t t = 0; t < nt; ++t) { + const float* lt = logits.data() + (size_t) (t * n_expert_); + for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e; + std::partial_sort(order.begin(), order.begin() + k_, order.end(), + [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; }); + for (int j = 0; j < k_; ++j) { + const int64_t e = order[(size_t) j]; + if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; // on the GPU + if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e); + } + } + src_->warm(layer, want.data(), (int64_t) want.size()); + predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed); + busy_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + { + std::lock_guard lk(mu_); + busy_ = false; + } + } +} + void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) { (void) ids; (void) k; @@ -949,13 +1105,14 @@ bool FileExpertSource::pin_cache_complement( bool pinned_ok = false; uint64_t locked = 0; uint64_t partial_pin = 0; ///< CS-T: a registered prefix of a locked arena + uint64_t lock_off = 0; ///< where the working-set lock starts (after the registered prefix) std::string note; auto release = [&]() { if (arena == nullptr) return; if (pinned_ok) (void) cudaFreeHost(arena); else { if (partial_pin > 0) (void) cudaHostUnregister(arena); - if (locked > 0) strata::platform::unlock_resident(arena, locked); + if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked); std::free(arena); } arena = nullptr; @@ -995,20 +1152,36 @@ bool FileExpertSource::pin_cache_complement( return false; } if (pin) { - const strata::platform::LockResult lr = strata::platform::lock_resident(arena, bytes); - locked = lr.locked_bytes; - note += (note.empty() ? "" : "; ") + lr.note; // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to - // register the largest prefix it takes (from the whole, down in 2 GiB steps). Those experts can be - // read by the GPU over PCIe (--pcie-frac) and copied by DMA; the rest stay locked-only. + // register the largest prefix it takes (from the cap down in 2 GiB steps). Those experts can be + // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working + // set (the registered prefix is page-locked by the driver already - locking it twice made the next + // device allocation fail). + // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no + // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74 + // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure static const bool partial_on = [] { - const char* v = std::getenv("STRATA_PARTIAL_PIN"); // 0: the A/B arm without it - return v == nullptr || std::atoi(v) != 0; + const char* v = std::getenv("STRATA_PARTIAL_PIN"); + return v != nullptr && std::atoi(v) != 0; + }(); + // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver + // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM) + static const uint64_t pin_cap = [] { + const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB"); + return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0); }(); if (budget_bytes > 0 && partial_on) { const uint64_t step = 2ull << 30; - for (uint64_t want = bytes; want >= step; want = want > step ? want - step : 0) { - const uint64_t w = want - want % (64ull << 10); + for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) { + // cut at an expert boundary: a blob that started inside the registered range and ran past it + // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed") + uint64_t w = want; + for (size_t i = 0; i < offsets.size(); ++i) { + if (offsets[i] == kNoComplement) continue; + const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_]; + if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; } + } + if (w == 0) break; if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) == cudaSuccess) { void* alias = nullptr; @@ -1029,6 +1202,11 @@ bool FileExpertSource::pin_cache_complement( (double) partial_pin / 1073741824.0); note += std::string("; ") + msg; } + lock_off = partial_pin; + const strata::platform::LockResult lr = + strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off); + locked = lr.locked_bytes; + note += (note.empty() ? "" : "; ") + lr.note; } } host = (const uint8_t*) arena; @@ -1125,6 +1303,7 @@ bool FileExpertSource::pin_cache_complement( complement_pin_limit_ = pinned_ok ? bytes : partial_pin; complement_partial_ = !pinned_ok && partial_pin > 0; complement_locked_ = locked; + complement_lock_off_ = lock_off; complement_lent_slots_ = lend ? n_slots - keep_from : 0; complement_ready_ = true; std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB%s%s\n", @@ -1407,6 +1586,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 d.fail_layer = d.layers; return; } + if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1 if (k < 1 || n_tok * k > kMaxWindowEntries) { d.failed = true; d.fail = "a verify window routes more entries than the expert pool's window tables hold"; diff --git a/src/kernels/cpu/kq_avx2.cpp b/src/kernels/cpu/kq_avx2.cpp index 8f08a2a8..a3473119 100644 --- a/src/kernels/cpu/kq_avx2.cpp +++ b/src/kernels/cpu/kq_avx2.cpp @@ -201,6 +201,41 @@ void dot_rows(int type, const uint8_t* row, int n, const void* const* act, int n bool kq256_supported(int type) noexcept { return type == 12 || type == 7 || type == 8; } +void bf16_rows_dot_multi(const uint16_t* w, int rows, int cols, const float* x, int nt, float* out) { + // each row is read once for all `nt` (<= 8) tokens: the router (2.6 MB per layer) streams once per prediction + for (int r = 0; r < rows; ++r) { + const uint16_t* wr = w + (size_t) r * (size_t) cols; + __m256 acc[8]; + for (int t = 0; t < nt; ++t) acc[t] = _mm256_setzero_ps(); + for (int c = 0; c + 8 <= cols; c += 8) { + const __m256 wf = _mm256_castsi256_ps( + _mm256_slli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))), 16)); + for (int t = 0; t < nt; ++t) acc[t] = _mm256_fmadd_ps(wf, _mm256_loadu_ps(x + (size_t) t * cols + c), acc[t]); + } + for (int t = 0; t < nt; ++t) out[(size_t) t * rows + r] = hsum_float_8(acc[t]); // cols % 8 == 0 (2560) + } +} + +void bf16_rows_dot(const uint16_t* w, int rows, int cols, const float* x, float* out) { + for (int r = 0; r < rows; ++r) { + const uint16_t* wr = w + (size_t) r * (size_t) cols; + __m256 acc = _mm256_setzero_ps(); + int c = 0; + for (; c + 8 <= cols; c += 8) { + const __m256i h = _mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) (wr + c))); + acc = _mm256_fmadd_ps(_mm256_castsi256_ps(_mm256_slli_epi32(h, 16)), _mm256_loadu_ps(x + c), acc); + } + float s = hsum_float_8(acc); + for (; c < cols; ++c) { + const uint32_t b = (uint32_t) wr[c] << 16; + float f; + std::memcpy(&f, &b, 4); + s += f * x[c]; + } + out[r] = s; + } +} + void kq256_gu_rows(int 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) { for (int t0 = 0; t0 < nt; t0 += MAXT) { diff --git a/src/kernels/cpu/native_expert.cpp b/src/kernels/cpu/native_expert.cpp index 673d4ec9..2e8d8adb 100644 --- a/src/kernels/cpu/native_expert.cpp +++ b/src/kernels/cpu/native_expert.cpp @@ -90,10 +90,11 @@ void native_gu_rows(const NativeFmt& f, const uint8_t* blob, const void* const* // can depend on how many drafts a verify window held. STRATA_IQ_MT_MIN=1 (opt-in, 0.1.30) uses the multi-token // kernels for every group: output independent of the drafting, at a measured -1..-3% decode on IQ3_S (AVX-512). static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); - // Unsloth UD-Q4_K_XL's Q4_K gate/up: the multi-token kernel is bit-exact against ggml's per-token dot, so it - // runs for every group size (no #152 rule). STRATA_NO_KQ256 falls back to ggml's vec_dot. - static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; - if (kq && f.gu_type == 12) { + // 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 + // ~1.4 tokens and the weights stay in L1 across ggml's per-token calls; 1.01-1.13x in native_expert_parity). + static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); + if (kq && f.gu_type == 12 && nt >= 2) { // one token: ggml's own dot below (the same bits, less overhead) kq256_gu_rows(f.gu_type, blob, f.gu_row, f.up_off, (int) f.n_embd, act, nt, ff, r0, r1); return; } @@ -127,8 +128,8 @@ void native_down_rows(const NativeFmt& f, const uint8_t* blob, const void* const // block instead of once per token; ggml-cpu's dot is single-token. STRATA_NO_IQ4NL falls back to it. static const bool iq4nl_mt = std::getenv("STRATA_NO_IQ4NL") == nullptr; static const int mt_min = [] { const char* e = std::getenv("STRATA_IQ_MT_MIN"); return e ? std::atoi(e) : 2; }(); - static const bool kq = std::getenv("STRATA_NO_KQ256") == nullptr; - if (kq && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, every group size + static const bool kq = [] { const char* v = std::getenv("STRATA_KQ256"); return v != nullptr && std::atoi(v) != 0; }(); + if (kq && nt >= 2 && (f.d_type == 7 || f.d_type == 8)) { // Q5_1 / Q8_0 down: bit-exact, any group size kq256_rows(f.d_type, blob + f.down_off, f.d_row, (int) f.n_ff, hq, nt, out, r0, r1); return; } diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp index 2a968d99..117cae95 100644 --- a/src/prefill/prefill.cpp +++ b/src/prefill/prefill.cpp @@ -504,8 +504,8 @@ bool Prefill::init(const core::WeightTable& wt, const core::ModelGeometry& g, co return false; } if (m.tok_dev == nullptr) { - if (cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)) != cudaSuccess) { - err = "prefill: the token id buffer"; + if (const cudaError_t e = cudaMalloc((void**) &m.tok_dev, (size_t) chunk * sizeof(int32_t)); e != cudaSuccess) { + err = std::string("prefill: the token id buffer (") + cudaGetErrorString(e) + ")"; return false; } m.owned.push_back(m.tok_dev); diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2a5eadef..caf47d6b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -2831,6 +2831,32 @@ int main(int argc, char** argv) { drive.d.src = srcp; drive.d.n_expert = g.n_expert; drive.d.jobs.resize((size_t) K); + // CS-T: routing-aware prefetch of the file tier (the GGUF in place): the next layer's router on this layer's MoE + // input predicts its experts and their pages are warmed meanwhile. It only warms pages; STRATA_LOOKAHEAD=0 is + // the A/B arm, STRATA_LOOKAHEAD_K the experts per token (default 10). + strata::core::RouterLookahead lookahead; + if (srcp == &src && src.warms() && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { + std::vector> routers((size_t) g.n_layers); + bool ok = true; + for (int64_t l = 0; l < g.n_layers && ok; ++l) { + const strata::core::WeightRef* w = wt.find("blk." + std::to_string(l) + ".ffn_gate_inp.weight"); + ok = w != nullptr && w->kind == strata::core::WeightKind::Bf16InF32 && + w->bytes == (uint64_t) (g.n_expert * g.n_embd) * 2; + if (!ok) break; + routers[(size_t) l].resize((size_t) (g.n_expert * g.n_embd)); + ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; + } + const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); + if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) { + drive.d.lookahead = &lookahead; + std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n"); + } else { + (void) cudaGetLastError(); + std::fprintf(stderr, "strata generate: routing-aware prefetch off (%s)\n", + ok ? err.c_str() : "the routers are not BF16 in the arena"); + err.clear(); + } + } // ---- R4.2c: THE HIT PATH. Every one of these is required for `hits_ready()`, which is all-or-nothing on // purpose: a half-configured hit path would compute some experts twice and others not at all, and a token // built on that is wrong rather than refused. @@ -5899,6 +5925,13 @@ int main(int argc, char** argv) { fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0, fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "", (double) (fall0 - fbytes0) / 1e6); + if (drive.d.lookahead != nullptr) + std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); " + "predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch", + (long long) src.warmed(), (long long) src.warmed_hits(), + (long long) (src.file_reads() - files0), + src.file_reads() > files0 ? 100.0 * (double) src.warmed_hits() / (double) (src.file_reads() - files0) : 0.0, + rounds > 0 ? drive.d.lookahead->busy_ms() / rounds : 0.0, (long long) drive.d.lookahead->skipped()); } if (rounds > 0 && drive.d.pcie_num > 0) std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n",