// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). // Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. // src/ds4/ds4_pool.hpp - the DeepSeek engine's CPU workers: run(n, fn) runs fn(0..n-1) on the workers and the caller and // returns when every job is done. The design is glmfast::Workers' (src/core/glm_fast_state.hpp): one 64-bit ticket // (generation << 32 | next index) claimed by CAS, so a worker that wakes late for an older batch can never take a job // of the current one; idle workers spin for a while, then sleep on a condition variable. #pragma once #include #include #include #include #include #include #include #include #include #include #include "ds4_os.hpp" #if defined(_MSC_VER) #include #endif namespace strata::ds4 { inline void cpu_relax() { #if defined(_MSC_VER) _mm_pause(); #elif defined(__x86_64__) || defined(_M_X64) __builtin_ia32_pause(); #endif } class Pool { public: explicit Pool(int n, const std::vector& cpus = {}, int spin_us = 200) : spin_us_(spin_us) { for (int i = 0; i < n; ++i) { th_.emplace_back([this] { loop(); }); if (!cpus.empty()) os::pin_thread(th_.back(), cpus[(size_t) i % cpus.size()]); } } ~Pool() { quit_.store(true); { std::lock_guard lk(mu_); } cv_.notify_all(); for (auto& t : th_) t.join(); } int size() const { return (int) th_.size() + 1; } void run(int n, const std::function& fn) { start(n, fn); help(); wait(); } /// The batch goes to the workers; the caller may help() and must wait() before fn goes out of scope. (Two pools /// - one a NUMA node - run at once this way: start both, help one, wait for both.) void start(int n, const std::function& fn) { n_ = n; if (n <= 0) return; const uint64_t g = (gen_.load(std::memory_order_relaxed) + 1) & 0xffffffffu; ticket_.store((g << 32) | 0x7fffffffu, std::memory_order_seq_cst); fn_ = &fn; total_.store(n, std::memory_order_release); done_.store(0, std::memory_order_relaxed); ticket_.store(g << 32, std::memory_order_release); gen_.store(g, std::memory_order_release); if (sleeping_.load(std::memory_order_acquire) > 0) { std::lock_guard lk(mu_); cv_.notify_all(); } } void help() { if (n_ > 0) work(gen_.load(std::memory_order_acquire)); } void wait() { if (n_ <= 0) return; while (done_.load(std::memory_order_acquire) < n_) cpu_relax(); n_ = 0; } private: void work(uint64_t g) { for (;;) { uint64_t t = ticket_.load(std::memory_order_acquire); if ((t >> 32) != g) return; const int n = total_.load(std::memory_order_acquire); if ((int) (t & 0xffffffffu) >= n) return; if (!ticket_.compare_exchange_weak(t, t + 1, std::memory_order_acq_rel)) continue; (*fn_)((int) (t & 0xffffffffu)); done_.fetch_add(1, std::memory_order_acq_rel); } } void loop() { uint64_t seen = gen_.load(); for (;;) { const auto t0 = std::chrono::steady_clock::now(); uint64_t g; for (;;) { g = gen_.load(std::memory_order_acquire); if (g != seen || quit_.load(std::memory_order_relaxed)) break; cpu_relax(); if (std::chrono::steady_clock::now() - t0 > std::chrono::microseconds(spin_us_)) { std::unique_lock lk(mu_); sleeping_.fetch_add(1); cv_.wait(lk, [&] { return gen_.load() != seen || quit_.load(); }); sleeping_.fetch_sub(1); } } if (quit_.load()) return; seen = g; work(g); } } std::vector th_; int spin_us_; int n_ = 0; // the current batch's size (the caller's side) const std::function* fn_ = nullptr; alignas(64) std::atomic ticket_{0}; alignas(64) std::atomic gen_{0}; alignas(64) std::atomic total_{0}; alignas(64) std::atomic done_{0}; std::atomic sleeping_{0}; std::atomic quit_{false}; std::mutex mu_; std::condition_variable cv_; }; /// File reads on threads of their own, in the order they were pushed, the pusher never waiting: the prompt path's /// streamed experts (each part of an expert a job), unbuffered where the job has a direct descriptor and its range is /// not all in the page cache already (the disk straight into dst, the cache neither used nor disturbed), buffered /// otherwise or when the unbuffered read fails - the bytes land at dst + off % os::kDirectAlign either way. A job's `left` is /// counted down when it is done (`bad` set if it failed); wait_any() sleeps until some job finished or the timeout. class IoQueue { public: struct Job { os::fd_t fd = os::kBadFd, dfd = os::kBadFd; uint64_t off = 0, len = 0; uint8_t* dst = nullptr; std::atomic* left = nullptr; std::atomic* bad = nullptr; const uint8_t* mem = nullptr; // non-null: a copy of len bytes from memory to dst instead of a read const void* map = nullptr; // the range in the file's mapping: all in the page cache, it is read buffered uint8_t* keep = nullptr; // non-null (a read): the len bytes read copied here as well std::atomic* cancel = nullptr; // set before the job starts: it is dropped unread (bad is set, left counted down) std::atomic* mask = nullptr; // non-null: `bit` set here once the read landed whole (before left counts down) uint64_t bit = 0; }; explicit IoQueue(int n) { for (int i = 0; i < n; ++i) th_.emplace_back([this] { loop(); }); } ~IoQueue() { { std::lock_guard lk(mu_); quit_ = true; } cv_.notify_all(); for (auto& t : th_) t.join(); } /// low: a read that can wait (a guess) - the jobs of the first queue are all taken before any of this one's void push(const Job* jobs, int n, bool low = false) { { std::lock_guard lk(mu_); for (int i = 0; i < n; ++i) (low ? ql_ : q_).push_back(jobs[i]); } if (n == 1) cv_.notify_one(); else cv_.notify_all(); } // Recheck the request under done_mu_: it may have completed before this wait began. void wait_any(int us, const std::atomic* left = nullptr) { std::unique_lock lk(done_mu_); const uint64_t seen = done_; done_cv_.wait_for(lk, std::chrono::microseconds(us), [&] { return done_ != seen || (left != nullptr && left->load(std::memory_order_acquire) <= 0); }); } double busy_ms() const { return busy_us_.load(std::memory_order_relaxed) / 1000.0; } /// the time at least one read was running (busy_ms() / any_ms(): the reads' mean depth then) double any_ms() const { std::lock_guard lk(run_mu_); double us = (double) any_us_; if (running_ > 0) us += (double) std::chrono::duration_cast(std::chrono::steady_clock::now() - any_t0_).count(); return us / 1000.0; } uint64_t direct_bytes() const { return direct_.load(std::memory_order_relaxed); } uint64_t buffered_bytes() const { return buffered_.load(std::memory_order_relaxed); } /// the reads done as part of a merged run (DS4_READ_RUN_MB), and the runs uint64_t run_jobs() const { return run_jobs_.load(std::memory_order_relaxed); } uint64_t runs() const { return runs_.load(std::memory_order_relaxed); } private: // DS4_READ_RUN_MB (0: off): a reader taking an unbuffered read also takes the queued ones that continue it in the // file (the next expert's same matrix), up to this many MiB, and reads them all with one request scattered into // their buffers - the disk sees a few large reads in place of many small ones static uint64_t run_cap() { static const uint64_t cap = [] { const char* v = std::getenv("DS4_READ_RUN_MB"); return v != nullptr ? (uint64_t) (std::atof(v) * 1048576.0) : 0; }(); return cap; } static bool joins(const Job& j) { return j.mem == nullptr && j.dfd != os::kBadFd && j.cancel == nullptr && j.mask == nullptr && j.len > 0; // (the flow's) } /// j read into j.dst (+ off % kDirectAlign) and copied to j.keep: unbuffered unless its range is in the page cache bool read_one(const Job& j) { const uint64_t lead = j.off % os::kDirectAlign; bool ok = false; if (j.mem != nullptr) { std::memcpy(j.dst, j.mem, (size_t) j.len); ok = true; } else if (j.dfd != os::kBadFd && !(j.map != nullptr && os::resident(j.map, (size_t) j.len)) && os::pread_direct(j.dfd, j.dst, j.len, j.off)) { // (the page cache's ones: buffered, below) ok = true; direct_.fetch_add(j.len, std::memory_order_relaxed); } else if (os::pread_par(j.fd, j.dst + lead, j.len, j.off)) { ok = true; buffered_.fetch_add(j.len, std::memory_order_relaxed); } if (ok && j.keep != nullptr && j.mem == nullptr) std::memmove(j.keep, j.dst + lead, (size_t) j.len); // (keep may overlap dst: the store reads in place and moves up) return ok; } /// adjacent ranges (each the next's start) with one unbuffered read: part i's sectors land in its own buffer as /// read_one's would, from its start rounded down to 512 bytes; the < 512 bytes of each part before the next one's /// first sector land in the next one's buffer and are copied back after. False: nothing usable (read each alone) bool read_run(const std::vector& r) { const size_t n = r.size(); const uint64_t A = os::kDirectAlign, a0 = r[0].off & ~(A - 1); const uint64_t end = r[n - 1].off + r[n - 1].len, a1 = (end + A - 1) & ~(A - 1); std::vector bufs(n); std::vector lens(n); uint64_t pos = a0; for (size_t i = 0; i < n; ++i) { if (r[i].map != nullptr && os::resident(r[i].map, (size_t) r[i].len)) return false; const uint64_t cut = i + 1 < n ? r[i + 1].off & ~(uint64_t) 511 : a1; bufs[i] = r[i].dst + (pos - (r[i].off & ~(A - 1))); lens[i] = cut - pos; pos = cut; } if (!os::preadv_direct(r[0].dfd, bufs.data(), lens.data(), (int) n, a0, end - a0)) return false; for (size_t i = 0; i + 1 < n; ++i) { const uint64_t cut = r[i + 1].off & ~(uint64_t) 511; if (cut < r[i + 1].off) std::memcpy(r[i].dst + (cut - (r[i].off & ~(A - 1))), r[i + 1].dst + (cut - (r[i + 1].off & ~(A - 1))), (size_t) (r[i + 1].off - cut)); } for (const Job& j : r) { if (j.keep != nullptr) std::memmove(j.keep, j.dst + j.off % A, (size_t) j.len); direct_.fetch_add(j.len, std::memory_order_relaxed); } return true; } static void finish(const Job& j, bool ok) { if (!ok && j.bad != nullptr) j.bad->store(true, std::memory_order_release); if (ok && j.mask != nullptr) j.mask->fetch_or(j.bit, std::memory_order_acq_rel); if (j.left != nullptr) j.left->fetch_sub(1, std::memory_order_acq_rel); } void loop() { std::vector run; for (;;) { Job j; run.clear(); { std::unique_lock lk(mu_); cv_.wait(lk, [&] { return quit_ || !q_.empty() || !ql_.empty(); }); if (quit_ && q_.empty() && ql_.empty()) return; std::deque& qq = q_.empty() ? ql_ : q_; j = qq.front(); qq.pop_front(); if (run_cap() > 0 && joins(j)) { // (the queued reads that continue it, in queue order) uint64_t at = j.off + j.len, bytes = j.len; run.push_back(j); for (bool more = true; more && bytes < run_cap();) { more = false; const size_t scan = std::min(qq.size(), 64); for (size_t i = 0; i < scan; ++i) { const Job& x = qq[i]; if (x.off != at || x.dfd != j.dfd || !joins(x) || bytes + x.len > run_cap()) continue; run.push_back(x); at += x.len; bytes += x.len; qq.erase(qq.begin() + (std::ptrdiff_t) i); more = true; break; } } if (run.size() == 1) run.clear(); } } if (j.cancel != nullptr && j.cancel->load(std::memory_order_acquire)) { // (dropped unread) if (j.bad != nullptr) j.bad->store(true, std::memory_order_release); if (j.left != nullptr) j.left->fetch_sub(1, std::memory_order_acq_rel); { std::lock_guard lk(done_mu_); ++done_; } done_cv_.notify_all(); continue; } const auto t0 = std::chrono::steady_clock::now(); { std::lock_guard lk(run_mu_); if (running_++ == 0) any_t0_ = t0; } std::vector oks; if (!run.empty()) { if (read_run(run)) { oks.assign(run.size(), 1); run_jobs_.fetch_add(run.size(), std::memory_order_relaxed); runs_.fetch_add(1, std::memory_order_relaxed); } else for (const Job& x : run) oks.push_back(read_one(x) ? 1 : 0); } else oks.push_back(read_one(j) ? 1 : 0); const auto t1 = std::chrono::steady_clock::now(); busy_us_.fetch_add((uint64_t) std::chrono::duration_cast(t1 - t0).count(), std::memory_order_relaxed); { std::lock_guard lk(run_mu_); if (--running_ == 0) any_us_ += (uint64_t) std::chrono::duration_cast(t1 - any_t0_).count(); } if (!run.empty()) for (size_t i = 0; i < run.size(); ++i) finish(run[i], oks[i] != 0); else finish(j, oks[0] != 0); { std::lock_guard lk(done_mu_); done_ += run.empty() ? 1 : run.size(); } done_cv_.notify_all(); } } std::vector th_; std::mutex mu_, done_mu_; std::condition_variable cv_, done_cv_; std::deque q_, ql_; uint64_t done_ = 0; bool quit_ = false; std::atomic busy_us_{0}, direct_{0}, buffered_{0}, run_jobs_{0}, runs_{0}; mutable std::mutex run_mu_; // (running_, any_us_, any_t0_) int running_ = 0; uint64_t any_us_ = 0; std::chrono::steady_clock::time_point any_t0_; }; } // namespace strata::ds4