okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanadsv41: opt-in DS4_STAGE_MB staging that lets prompt reads run ahead, DS4_READ_RUN_MB merged preadv of adjacent expert reads, reader occupancy in the prompt-stream line00c004617

main
15.5 KiB350 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// 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
4// returns when every job is done.  The design is glmfast::Workers' (src/core/glm_fast_state.hpp): one 64-bit ticket
5// (generation << 32 | next index) claimed by CAS, so a worker that wakes late for an older batch can never take a job
6// of the current one; idle workers spin for a while, then sleep on a condition variable.
7#pragma once
8
9#include <atomic>
10#include <chrono>
11#include <condition_variable>
12#include <cstdint>
13#include <cstring>
14#include <deque>
15#include <functional>
16#include <mutex>
17#include <thread>
18#include <vector>
19
20#include "ds4_os.hpp"
21#if defined(_MSC_VER)
22#include <intrin.h>
23#endif
24
25namespace strata::ds4 {
26
27inline void cpu_relax() {
28#if defined(_MSC_VER)
29    _mm_pause();
30#elif defined(__x86_64__) || defined(_M_X64)
31    __builtin_ia32_pause();
32#endif
33}
34
35class Pool {
36public:
37    explicit Pool(int n, const std::vector<int>& cpus = {}, int spin_us = 200) : spin_us_(spin_us) {
38        for (int i = 0; i < n; ++i) {
39            th_.emplace_back([this] { loop(); });
40            if (!cpus.empty()) os::pin_thread(th_.back(), cpus[(size_t) i % cpus.size()]);
41        }
42    }
43    ~Pool() {
44        quit_.store(true);
45        {
46            std::lock_guard<std::mutex> lk(mu_);
47        }
48        cv_.notify_all();
49        for (auto& t : th_) t.join();
50    }
51    int size() const { return (int) th_.size() + 1; }
52
53    void run(int n, const std::function<void(int)>& fn) {
54        start(n, fn);
55        help();
56        wait();
57    }
58    /// The batch goes to the workers; the caller may help() and must wait() before fn goes out of scope.  (Two pools
59    /// - one a NUMA node - run at once this way: start both, help one, wait for both.)
60    void start(int n, const std::function<void(int)>& fn) {
61        n_ = n;
62        if (n <= 0) return;
63        const uint64_t g = (gen_.load(std::memory_order_relaxed) + 1) & 0xffffffffu;
64        ticket_.store((g << 32) | 0x7fffffffu, std::memory_order_seq_cst);
65        fn_ = &fn;
66        total_.store(n, std::memory_order_release);
67        done_.store(0, std::memory_order_relaxed);
68        ticket_.store(g << 32, std::memory_order_release);
69        gen_.store(g, std::memory_order_release);
70        if (sleeping_.load(std::memory_order_acquire) > 0) {
71            std::lock_guard<std::mutex> lk(mu_);
72            cv_.notify_all();
73        }
74    }
75    void help() {
76        if (n_ > 0) work(gen_.load(std::memory_order_acquire));
77    }
78    void wait() {
79        if (n_ <= 0) return;
80        while (done_.load(std::memory_order_acquire) < n_) cpu_relax();
81        n_ = 0;
82    }
83
84private:
85    void work(uint64_t g) {
86        for (;;) {
87            uint64_t t = ticket_.load(std::memory_order_acquire);
88            if ((t >> 32) != g) return;
89            const int n = total_.load(std::memory_order_acquire);
90            if ((int) (t & 0xffffffffu) >= n) return;
91            if (!ticket_.compare_exchange_weak(t, t + 1, std::memory_order_acq_rel)) continue;
92            (*fn_)((int) (t & 0xffffffffu));
93            done_.fetch_add(1, std::memory_order_acq_rel);
94        }
95    }
96    void loop() {
97        uint64_t seen = gen_.load();
98        for (;;) {
99            const auto t0 = std::chrono::steady_clock::now();
100            uint64_t g;
101            for (;;) {
102                g = gen_.load(std::memory_order_acquire);
103                if (g != seen || quit_.load(std::memory_order_relaxed)) break;
104                cpu_relax();
105                if (std::chrono::steady_clock::now() - t0 > std::chrono::microseconds(spin_us_)) {
106                    std::unique_lock<std::mutex> lk(mu_);
107                    sleeping_.fetch_add(1);
108                    cv_.wait(lk, [&] { return gen_.load() != seen || quit_.load(); });
109                    sleeping_.fetch_sub(1);
110                }
111            }
112            if (quit_.load()) return;
113            seen = g;
114            work(g);
115        }
116    }
117
118    std::vector<std::thread> th_;
119    int spin_us_;
120    int n_ = 0;   // the current batch's size (the caller's side)
121    const std::function<void(int)>* fn_ = nullptr;
122    alignas(64) std::atomic<uint64_t> ticket_{0};
123    alignas(64) std::atomic<uint64_t> gen_{0};
124    alignas(64) std::atomic<int> total_{0};
125    alignas(64) std::atomic<int> done_{0};
126    std::atomic<int> sleeping_{0};
127    std::atomic<bool> quit_{false};
128    std::mutex mu_;
129    std::condition_variable cv_;
130};
131
132/// File reads on threads of their own, in the order they were pushed, the pusher never waiting: the prompt path's
133/// streamed experts (each part of an expert a job), unbuffered where the job has a direct descriptor and its range is
134/// not all in the page cache already (the disk straight into dst, the cache neither used nor disturbed), buffered
135/// otherwise or when the unbuffered read fails - the bytes land at dst + off % os::kDirectAlign either way.  A job's `left` is
136/// counted down when it is done (`bad` set if it failed); wait_any() sleeps until some job finished or the timeout.
137class IoQueue {
138public:
139    struct Job {
140        os::fd_t fd = os::kBadFd, dfd = os::kBadFd;
141        uint64_t off = 0, len = 0;
142        uint8_t* dst = nullptr;
143        std::atomic<int>* left = nullptr;
144        std::atomic<bool>* bad = nullptr;
145        const uint8_t* mem = nullptr;   // non-null: a copy of len bytes from memory to dst instead of a read
146        const void* map = nullptr;      // the range in the file's mapping: all in the page cache, it is read buffered
147        uint8_t* keep = nullptr;        // non-null (a read): the len bytes read copied here as well
148        std::atomic<bool>* cancel = nullptr;   // set before the job starts: it is dropped unread (bad is set, left counted down)
149        std::atomic<uint64_t>* mask = nullptr;   // non-null: `bit` set here once the read landed whole (before left counts down)
150        uint64_t bit = 0;
151    };
152    explicit IoQueue(int n) {
153        for (int i = 0; i < n; ++i) th_.emplace_back([this] { loop(); });
154    }
155    ~IoQueue() {
156        {
157            std::lock_guard<std::mutex> lk(mu_);
158            quit_ = true;
159        }
160        cv_.notify_all();
161        for (auto& t : th_) t.join();
162    }
163    /// low: a read that can wait (a guess) - the jobs of the first queue are all taken before any of this one's
164    void push(const Job* jobs, int n, bool low = false) {
165        {
166            std::lock_guard<std::mutex> lk(mu_);
167            for (int i = 0; i < n; ++i) (low ? ql_ : q_).push_back(jobs[i]);
168        }
169        if (n == 1) cv_.notify_one();
170        else cv_.notify_all();
171    }
172    // Recheck the request under done_mu_: it may have completed before this wait began.
173    void wait_any(int us, const std::atomic<int>* left = nullptr) {
174        std::unique_lock<std::mutex> lk(done_mu_);
175        const uint64_t seen = done_;
176        done_cv_.wait_for(lk, std::chrono::microseconds(us), [&] {
177            return done_ != seen || (left != nullptr && left->load(std::memory_order_acquire) <= 0);
178        });
179    }
180    double busy_ms() const { return busy_us_.load(std::memory_order_relaxed) / 1000.0; }
181    /// the time at least one read was running (busy_ms() / any_ms(): the reads' mean depth then)
182    double any_ms() const {
183        std::lock_guard<std::mutex> lk(run_mu_);
184        double us = (double) any_us_;
185        if (running_ > 0) us += (double) std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - any_t0_).count();
186        return us / 1000.0;
187    }
188    uint64_t direct_bytes() const { return direct_.load(std::memory_order_relaxed); }
189    uint64_t buffered_bytes() const { return buffered_.load(std::memory_order_relaxed); }
190    /// the reads done as part of a merged run (DS4_READ_RUN_MB), and the runs
191    uint64_t run_jobs() const { return run_jobs_.load(std::memory_order_relaxed); }
192    uint64_t runs() const { return runs_.load(std::memory_order_relaxed); }
193
194private:
195    // DS4_READ_RUN_MB (0: off): a reader taking an unbuffered read also takes the queued ones that continue it in the
196    // file (the next expert's same matrix), up to this many MiB, and reads them all with one request scattered into
197    // their buffers - the disk sees a few large reads in place of many small ones
198    static uint64_t run_cap() {
199        static const uint64_t cap = [] {
200            const char* v = std::getenv("DS4_READ_RUN_MB");
201            return v != nullptr ? (uint64_t) (std::atof(v) * 1048576.0) : 0;
202        }();
203        return cap;
204    }
205    static bool joins(const Job& j) {
206        return j.mem == nullptr && j.dfd != os::kBadFd && j.cancel == nullptr && j.mask == nullptr && j.len > 0;   // (the flow's)
207    }
208    /// j read into j.dst (+ off % kDirectAlign) and copied to j.keep: unbuffered unless its range is in the page cache
209    bool read_one(const Job& j) {
210        const uint64_t lead = j.off % os::kDirectAlign;
211        bool ok = false;
212        if (j.mem != nullptr) {
213            std::memcpy(j.dst, j.mem, (size_t) j.len);
214            ok = true;
215        } else if (j.dfd != os::kBadFd && !(j.map != nullptr && os::resident(j.map, (size_t) j.len)) &&
216                   os::pread_direct(j.dfd, j.dst, j.len, j.off)) {   // (the page cache's ones: buffered, below)
217            ok = true;
218            direct_.fetch_add(j.len, std::memory_order_relaxed);
219        } else if (os::pread_par(j.fd, j.dst + lead, j.len, j.off)) {
220            ok = true;
221            buffered_.fetch_add(j.len, std::memory_order_relaxed);
222        }
223        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)
224        return ok;
225    }
226    /// adjacent ranges (each the next's start) with one unbuffered read: part i's sectors land in its own buffer as
227    /// read_one's would, from its start rounded down to 512 bytes; the < 512 bytes of each part before the next one's
228    /// first sector land in the next one's buffer and are copied back after.  False: nothing usable (read each alone)
229    bool read_run(const std::vector<Job>& r) {
230        const size_t n = r.size();
231        const uint64_t A = os::kDirectAlign, a0 = r[0].off & ~(A - 1);
232        const uint64_t end = r[n - 1].off + r[n - 1].len, a1 = (end + A - 1) & ~(A - 1);
233        std::vector<uint8_t*> bufs(n);
234        std::vector<uint64_t> lens(n);
235        uint64_t pos = a0;
236        for (size_t i = 0; i < n; ++i) {
237            if (r[i].map != nullptr && os::resident(r[i].map, (size_t) r[i].len)) return false;
238            const uint64_t cut = i + 1 < n ? r[i + 1].off & ~(uint64_t) 511 : a1;
239            bufs[i] = r[i].dst + (pos - (r[i].off & ~(A - 1)));
240            lens[i] = cut - pos;
241            pos = cut;
242        }
243        if (!os::preadv_direct(r[0].dfd, bufs.data(), lens.data(), (int) n, a0, end - a0)) return false;
244        for (size_t i = 0; i + 1 < n; ++i) {
245            const uint64_t cut = r[i + 1].off & ~(uint64_t) 511;
246            if (cut < r[i + 1].off)
247                std::memcpy(r[i].dst + (cut - (r[i].off & ~(A - 1))), r[i + 1].dst + (cut - (r[i + 1].off & ~(A - 1))),
248                            (size_t) (r[i + 1].off - cut));
249        }
250        for (const Job& j : r) {
251            if (j.keep != nullptr) std::memmove(j.keep, j.dst + j.off % A, (size_t) j.len);
252            direct_.fetch_add(j.len, std::memory_order_relaxed);
253        }
254        return true;
255    }
256    static void finish(const Job& j, bool ok) {
257        if (!ok && j.bad != nullptr) j.bad->store(true, std::memory_order_release);
258        if (ok && j.mask != nullptr) j.mask->fetch_or(j.bit, std::memory_order_acq_rel);
259        if (j.left != nullptr) j.left->fetch_sub(1, std::memory_order_acq_rel);
260    }
261    void loop() {
262        std::vector<Job> run;
263        for (;;) {
264            Job j;
265            run.clear();
266            {
267                std::unique_lock<std::mutex> lk(mu_);
268                cv_.wait(lk, [&] { return quit_ || !q_.empty() || !ql_.empty(); });
269                if (quit_ && q_.empty() && ql_.empty()) return;
270                std::deque<Job>& qq = q_.empty() ? ql_ : q_;
271                j = qq.front();
272                qq.pop_front();
273                if (run_cap() > 0 && joins(j)) {   // (the queued reads that continue it, in queue order)
274                    uint64_t at = j.off + j.len, bytes = j.len;
275                    run.push_back(j);
276                    for (bool more = true; more && bytes < run_cap();) {
277                        more = false;
278                        const size_t scan = std::min<size_t>(qq.size(), 64);
279                        for (size_t i = 0; i < scan; ++i) {
280                            const Job& x = qq[i];
281                            if (x.off != at || x.dfd != j.dfd || !joins(x) || bytes + x.len > run_cap()) continue;
282                            run.push_back(x);
283                            at += x.len;
284                            bytes += x.len;
285                            qq.erase(qq.begin() + (std::ptrdiff_t) i);
286                            more = true;
287                            break;
288                        }
289                    }
290                    if (run.size() == 1) run.clear();
291                }
292            }
293            if (j.cancel != nullptr && j.cancel->load(std::memory_order_acquire)) {   // (dropped unread)
294                if (j.bad != nullptr) j.bad->store(true, std::memory_order_release);
295                if (j.left != nullptr) j.left->fetch_sub(1, std::memory_order_acq_rel);
296                {
297                    std::lock_guard<std::mutex> lk(done_mu_);
298                    ++done_;
299                }
300                done_cv_.notify_all();
301                continue;
302            }
303            const auto t0 = std::chrono::steady_clock::now();
304            {
305                std::lock_guard<std::mutex> lk(run_mu_);
306                if (running_++ == 0) any_t0_ = t0;
307            }
308            std::vector<char> oks;
309            if (!run.empty()) {
310                if (read_run(run)) {
311                    oks.assign(run.size(), 1);
312                    run_jobs_.fetch_add(run.size(), std::memory_order_relaxed);
313                    runs_.fetch_add(1, std::memory_order_relaxed);
314                }
315                else
316                    for (const Job& x : run) oks.push_back(read_one(x) ? 1 : 0);
317            } else
318                oks.push_back(read_one(j) ? 1 : 0);
319            const auto t1 = std::chrono::steady_clock::now();
320            busy_us_.fetch_add((uint64_t) std::chrono::duration_cast<std::chrono::microseconds>(t1 - t0).count(),
321                               std::memory_order_relaxed);
322            {
323                std::lock_guard<std::mutex> lk(run_mu_);
324                if (--running_ == 0) any_us_ += (uint64_t) std::chrono::duration_cast<std::chrono::microseconds>(t1 - any_t0_).count();
325            }
326            if (!run.empty())
327                for (size_t i = 0; i < run.size(); ++i) finish(run[i], oks[i] != 0);
328            else
329                finish(j, oks[0] != 0);
330            {
331                std::lock_guard<std::mutex> lk(done_mu_);
332                done_ += run.empty() ? 1 : run.size();
333            }
334            done_cv_.notify_all();
335        }
336    }
337    std::vector<std::thread> th_;
338    std::mutex mu_, done_mu_;
339    std::condition_variable cv_, done_cv_;
340    std::deque<Job> q_, ql_;
341    uint64_t done_ = 0;
342    bool quit_ = false;
343    std::atomic<uint64_t> busy_us_{0}, direct_{0}, buffered_{0}, run_jobs_{0}, runs_{0};
344    mutable std::mutex run_mu_;   // (running_, any_us_, any_t0_)
345    int running_ = 0;
346    uint64_t any_us_ = 0;
347    std::chrono::steady_clock::time_point any_t0_;
348};
349
350}  // namespace strata::ds4