okami.mom/strata

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

waveringanadsv41: DS4_AUX_CACHE=N makes the 4060's experts a cache of the decode's hottest CPU-lane picks (N swaps a window from spare slots, DS4_AUX_ASYNC=1 commits what landed; 63K decode 9.02 -> 9.96 tok/s, 16K 10.85 -> 12.25, KL vs exact 0.036 -> 0.039), decode picks by tier and DS4_TIERDUMP376c0e158

main
32.4 KiB649 linesraw
1// Strata. src/dsv41/ds4_store.hpp - the RAM tier of the DeepSeek-V4.1 routed experts as a cache of its own: whole experts read
2// from the model's files by unbuffered requests (the OS page cache neither used nor disturbed), kept in a fixed arena of slots
3// that a replacement policy owns, filled on demand (the CPU lane's picks) and ahead of time (the lookahead's guesses).
4//
5// A slot holds an expert in the engine's blob layout (gate | up | down at the layer's offsets tr[r], the same as a VRAM slot), so
6// the CPU lane's rows read it in place and - when the arena is registered with the GPU - the device kernels read it over PCIe
7// (zero-copy, 24 GB/s on a 5070) through the same plan pointers as a VRAM expert.  An expert is three matrices at three file
8// offsets (the GGUF's one tensor a role and layer): each is read aligned (4096) into the slot and moved into place (the read's
9// lead of up to 4095 bytes), the blob layout leaving 8192 bytes between matrices (and around the blob) for the aligned spans.
10// CPU-only read_in_place slots leave matrices at the read addresses returned by mat(); mapped slots keep the canonical layout.
11//
12// Memory: slots are allocated in chunks as they are first needed (private memory), never past the budget nor past the RAM this
13// process can still get less `floor_bytes` (the owner's session and the system keep theirs).
14//
15// Policy (the slot to give up, among the unpinned, not GPU-visible ones): lru (oldest touch), lfu (lowest decayed hit count).
16// A slot whose expert a window is computing is pinned from ensure() to release(); a slot the GPU may read is `visible` until
17// sync() takes it back at a window boundary (the GPU idle), which also publishes the newly ready ones.
18#pragma once
19
20#include "ds4_os.hpp"
21#include "ds4_pool.hpp"
22
23#include <algorithm>
24#include <atomic>
25#include <chrono>
26#include <cmath>
27#include <cstdint>
28#include <cstdio>
29#include <cstdlib>
30#include <cstring>
31#include <functional>
32#include <memory>
33#include <mutex>
34#include <string>
35#include <vector>
36
37namespace strata::ds4 {
38
39class ExpertStore {
40public:
41    struct LayerGeo {
42        int n_exp = 0;
43        int file[3] = {-1, -1, -1};
44        uint64_t off[3] = {0, 0, 0}, stride[3] = {0, 0, 0};   // matrix r of expert e: file[r], off[r] + e stride[r]
45        uint64_t bytes[3] = {0, 0, 0};
46        uint64_t tr[3] = {0, 0, 0};                            // matrix r's place in the blob
47        uint64_t blob = 0;                                     // the blob's bytes (gaps of 8192 between matrices)
48    };
49    enum Policy { kLru = 0, kLfu = 1 };
50    struct Stats {
51        std::atomic<int64_t> hits{0}, misses{0}, prefetched{0}, prefetch_used{0}, prefetch_wasted{0}, evictions{0}, fails{0};
52        std::atomic<int64_t> bytes_read{0}, wait_ns{0}, no_slot{0}, cancelled{0};
53    };
54    struct Vis {                 // a slot the GPU may read from now on (dev != 0), or no longer (dev == 0)
55        int layer = 0, e = 0;
56        unsigned long long dev = 0;
57    };
58
59    struct Cfg {
60        int threads = 8;
61        bool read_in_place = false;   // CPU-only slots: keep matrices where aligned reads land them
62        size_t piece_bytes = 0;       // read_in_place: each matrix read in pieces of this (multiple of 4096; 0: one read)
63        size_t budget_bytes = 0;           // the arena at most (grown in chunks as slots are first needed)
64        size_t floor_bytes = 8ull << 30;   // RAM left alone
65        Policy policy = kLru;
66        float decay = 0.97f;               // lfu: heat x decay every `decay_every` accesses of its layer
67        int decay_every = 240;
68        std::function<uint64_t()> ram_avail;   // the RAM this process can still get (~0: unknown)
69        // a new chunk of the arena for the GPU to read in place: returns the device address of `host` (null: not visible)
70        std::function<void*(void* host, size_t bytes)> map_chunk;
71        std::function<void(void* host)> unmap_chunk;
72        size_t reserve = 192;              // slots kept evictable (not visible) for the window's demand and guesses
73        int vis_percent = 100;             // the share of experts the GPU may take (by a fixed hash): the rest stay the CPU lane's, so both lanes work
74    };
75
76    bool init(const Cfg& c, const std::vector<LayerGeo>& layers, const std::vector<os::fd_t>& dfds, const std::vector<os::fd_t>& pfds) {
77        cfg_ = c;
78        if (cfg_.map_chunk) cfg_.read_in_place = false;
79        geo_ = layers;
80        dfds_ = dfds;
81        pfds_ = pfds;
82        size_t blob = 0;
83        for (const LayerGeo& g : geo_) blob = std::max<size_t>(blob, g.blob);
84        slot_bytes_ = (blob + 2 * kSlack + os::kDirectAlign - 1) & ~(size_t) (os::kDirectAlign - 1);
85        if (blob == 0 || c.budget_bytes < slot_bytes_) return false;
86        nmax_ = c.budget_bytes / slot_bytes_;
87        // one reserved range for the whole arena (chunks committed as they are needed), 64 KB aligned chunks
88        arena_bytes_ = ((nmax_ + kChunk - 1) / kChunk) * kChunk * slot_bytes_;
89        arena_ = (uint8_t*) os::range_reserve(arena_bytes_);
90        if (arena_ == nullptr) return false;
91        slots_.reset(new Slot[nmax_]);
92        where_.resize(geo_.size());
93        heat_.resize(geo_.size());
94        hits_in_layer_.assign(geo_.size(), 0);
95        for (size_t l = 0; l < geo_.size(); ++l) {
96            where_[l].assign((size_t) geo_[l].n_exp, -1);
97            heat_[l].assign((size_t) geo_[l].n_exp, 0.0f);
98        }
99        io_.reset(new IoQueue(std::max(1, c.threads)));
100        grow();   // (the first chunk now: whether the GPU can map it is known from the start)
101        // DS4_STORE_PREGROW=1 (default on Linux with the GPU mapping, =0 off): the whole arena now.  cuMemHostRegister (the GPU mapping of a chunk) taken while a kernel of
102        // the decode is running waited on it for good on Linux (H100, driver 580): registering all chunks before the first
103        // kernel avoids it
104#if defined(__linux__)
105        const bool pregrow = cfg_.map_chunk && !(std::getenv("DS4_STORE_PREGROW") != nullptr && std::atoi(std::getenv("DS4_STORE_PREGROW")) == 0);   // (Linux: on with the GPU mapping)
106#else
107        const bool pregrow = std::getenv("DS4_STORE_PREGROW") != nullptr && std::atoi(std::getenv("DS4_STORE_PREGROW")) != 0;
108#endif
109        if (pregrow)
110            while (grow()) {
111            }
112        return true;
113    }
114    ~ExpertStore() {
115        io_.reset();
116        for (size_t i = 0; i < chunks_.size(); ++i)
117            if (cfg_.unmap_chunk && chunk_dev_[i] != nullptr) cfg_.unmap_chunk(chunks_[i].first);
118        os::range_release(arena_, arena_bytes_);
119    }
120
121    size_t slot_bytes() const { return slot_bytes_; }
122    size_t slots_allocated() const { return nalloc_; }
123    size_t slots_max() const { return nmax_; }
124    const Stats& stats() const { return st_; }
125    double busy_ms() const { return io_ ? io_->busy_ms() : 0.0; }
126    static constexpr size_t kSlack = 8192;
127
128    /// The slot holding (layer, e) ready to read, or -1.  (Any thread; a slot found stays valid while it is pinned or visible.)
129    int find(int layer, int e) const {
130        if (layer < 0 || layer >= (int) where_.size()) return -1;   // (a layer the store does not cover: the DSpark drafter's)
131        const int s = where_[(size_t) layer][(size_t) e];
132        if (s < 0) return -1;
133        Slot& sp = slots_[(size_t) s];
134        try_ready(sp);
135        return sp.state.load(std::memory_order_acquire) == kReady && sp.layer == layer && sp.expert == e ? s : -1;
136    }
137    /// (layer, e) in the store: 2 ready, 1 its read in flight, 0 not here
138    int state_of(int layer, int e) const {
139        if (layer < 0 || layer >= (int) where_.size()) return 0;
140        const int s = where_[(size_t) layer][(size_t) e];
141        if (s < 0) return 0;
142        Slot& sp = slots_[(size_t) s];
143        try_ready(sp);
144        const int st = sp.state.load(std::memory_order_acquire);
145        return st == kReady ? 2 : st == kLoading ? 1 : 0;
146    }
147    const uint8_t* mat(int slot, int r) const {
148        const Slot& sp = slots_[(size_t) slot];
149        const LayerGeo& g = geo_[(size_t) sp.layer];
150        uint8_t* fin = sp.base + g.tr[r];
151        if (!cfg_.read_in_place) return fin;
152        const uint64_t lead = (g.off[r] + (uint64_t) sp.expert * g.stride[r]) % os::kDirectAlign;
153        return read_base(fin, lead) + lead;
154    }
155    /// The device address of the slot's blob (0: the arena is not mapped for the GPU)
156    unsigned long long dev_blob(int slot) const {
157        const size_t c = (size_t) slot / kChunk;
158        if (c >= chunk_dev_.size() || chunk_dev_[c] == nullptr) return 0;
159        return (unsigned long long) ((uint8_t*) chunk_dev_[c] + (slots_[(size_t) slot].base - (uint8_t*) chunks_[c].first));
160    }
161
162    /// Makes the experts es[0..n) of `layer` ready and pinned (reading what is not here), waiting for the reads; the
163    /// caller releases them.  False if a read failed or no slot could be had for one (ok[i] says which are fine; the caller
164    /// reads the others another way).
165    bool ensure(int layer, const int* es, int n, std::vector<char>& ok) {
166        std::vector<int> sl;
167        begin(layer, es, n, ok, sl);
168        return wait_slots(sl, ok, 0, n);
169    }
170    /// The first half of ensure(): the experts' slots found or their reads started (pinned), no waiting.  sl[i] is the slot or -1.
171    void begin(int layer, const int* es, int n, std::vector<char>& ok, std::vector<int>& sl) {
172        ok.assign((size_t) n, 0);
173        sl.assign((size_t) n, -1);
174        if (layer < 0 || layer >= (int) geo_.size()) return;
175        std::lock_guard<std::mutex> lk(mu_);
176        for (int i = 0; i < n; ++i) {
177            const int e = es[i];
178            touch_heat(layer, e);
179            int s = where_[(size_t) layer][(size_t) e];
180            if (s >= 0) {
181                Slot& sp = slots_[(size_t) s];
182                try_ready(sp);
183                if (sp.state.load() == kReady && !sp.prefetch) st_.hits.fetch_add(1, std::memory_order_relaxed);
184                if (sp.prefetch) st_.prefetch_used.fetch_add(1, std::memory_order_relaxed);
185                sp.prefetch = false;
186                sp.pin++;
187                sp.tick = ++clock_;
188                sl[(size_t) i] = s;
189                continue;
190            }
191            st_.misses.fetch_add(1, std::memory_order_relaxed);
192            s = start_fill(layer, e, true);
193            sl[(size_t) i] = s;
194        }
195    }
196    /// Whether bytes [lo, hi) of slot s's matrix r (a slot from begin, pinned) have landed: 1 yes, -1 a read of the slot
197    /// failed and these did not land (read them elsewhere), 0 not yet.
198    int bytes_ready(int s, int r, uint64_t lo, uint64_t hi) const {
199        const Slot& sp = slots_[(size_t) s];
200        const uint64_t pb = sp.pbytes[r];
201        const uint64_t lead = (geo_[(size_t) sp.layer].off[r] + (uint64_t) sp.expert * geo_[(size_t) sp.layer].stride[r]) % os::kDirectAlign;
202        const uint64_t k0 = (lead + lo) / pb, k1 = (lead + hi - 1) / pb;
203        const uint64_t need = (k1 >= 63 ? ~0ull : ((1ull << (k1 + 1)) - 1)) & ~((1ull << k0) - 1);
204        if ((sp.mask[r].load(std::memory_order_acquire) & need) == need) return 1;
205        return sp.bad.load(std::memory_order_acquire) ? -1 : 0;
206    }
207    /// True when the reads of slot sl (from begin) are all done.
208    bool loaded(int s) const { return s >= 0 && slots_[(size_t) s].left.load(std::memory_order_acquire) <= 0; }
209    /// The second half: waits for the slots sl[a..b) and marks ok[i] for the good ones.  False if any failed or had no slot.
210    bool wait_slots(std::vector<int>& sl, std::vector<char>& ok, int a, int b) {
211        const auto t0 = std::chrono::steady_clock::now();
212        bool all = true;
213        for (int i = a; i < b; ++i) {
214            const int s = sl[(size_t) i];
215            if (s < 0) {
216                all = false;
217                continue;
218            }
219            Slot& sp = slots_[(size_t) s];
220            while (sp.left.load(std::memory_order_acquire) > 0) io_->wait_any(2000, &sp.left);
221            std::lock_guard<std::mutex> lk(mu_);
222            finish(sp, sp.pin <= 1);
223            if (sp.state.load() == kReady) ok[(size_t) i] = 1;
224            else {
225                sp.pin--;
226                sl[(size_t) i] = -1;
227                all = false;
228            }
229        }
230        st_.wait_ns.fetch_add(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count(),
231                              std::memory_order_relaxed);
232        return all;
233    }
234    void release(int layer, const int* es, int n, const std::vector<char>& ok) {
235        if (layer < 0 || layer >= (int) geo_.size()) return;
236        std::lock_guard<std::mutex> lk(mu_);
237        for (int i = 0; i < n; ++i)
238            if (ok[(size_t) i]) {
239                const int s = where_[(size_t) layer][(size_t) es[i]];
240                if (s >= 0 && slots_[(size_t) s].pin > 0) slots_[(size_t) s].pin--;
241            }
242    }
243    /// Starts reading (layer, e) if it is neither here nor on its way (a guess: unpinned, may be given up before it is used).
244    void prefetch(int layer, int e) {
245        if (layer < 0 || layer >= (int) geo_.size() || e < 0 || e >= geo_[(size_t) layer].n_exp) return;
246        if (where_[(size_t) layer][(size_t) e] >= 0) return;
247        std::lock_guard<std::mutex> lk(mu_);
248        if (where_[(size_t) layer][(size_t) e] >= 0) return;
249        if (start_fill(layer, e, false) >= 0) st_.prefetched.fetch_add(1, std::memory_order_relaxed);
250    }
251    /// Reads the experts of `list` (layer, expert; hottest first) into free slots and returns when they are in (a start that
252    /// is already warm: the profile's hottest, so the first tokens find them).  The first `list.size()` fit the arena less
253    /// `leave` slots; returns how many were read.
254    size_t preload(const std::vector<std::pair<int, int>>& list, size_t leave) {
255        size_t n = 0;
256        {
257            std::lock_guard<std::mutex> lk(mu_);
258            const size_t room = nmax_ > leave ? nmax_ - leave : 0;
259            const size_t take = std::min(list.size(), room);
260            for (size_t k = take; k-- > 0;) {   // (coldest first: the hottest get the newest ticks)
261                const int layer = list[k].first, e = list[k].second;
262                if (layer < 0 || layer >= (int) geo_.size() || e < 0 || e >= geo_[(size_t) layer].n_exp) continue;
263                if (where_[(size_t) layer][(size_t) e] >= 0) continue;
264                const int s = start_fill(layer, e, false);
265                if (s < 0) break;
266                slots_[(size_t) s].prefetch = false;   // (warm, not a guess)
267                ++n;
268            }
269        }
270        for (size_t i = 0;; ++i) {   // until every read is done
271            bool busy = false;
272            {
273                std::lock_guard<std::mutex> lk(mu_);
274                for (size_t j = 0; j < nalloc_; ++j) {
275                    Slot& sp = slots_[j];
276                    if (sp.state.load(std::memory_order_acquire) != kLoading) continue;
277                    if (sp.left.load(std::memory_order_acquire) > 0) busy = true;
278                    else {
279                        try_ready(sp);
280                        if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
281                    }
282                }
283            }
284            if (!busy) break;
285            io_->wait_any(5000);
286        }
287        return n;
288    }
289    /// Guesses still waiting in the queue for a layer the token is past: dropped unread (their slots free once the queue has gone by)
290    void cancel_stale(int layer_now) {
291        std::lock_guard<std::mutex> lk(mu_);
292        for (size_t i = 0; i < nalloc_; ++i) {
293            Slot& sp = slots_[i];
294            if (sp.prefetch && sp.pin == 0 && sp.layer >= 0 && sp.layer <= layer_now && sp.state.load(std::memory_order_acquire) == kLoading)
295                sp.cancel.store(true, std::memory_order_release);
296        }
297    }
298    /// An access the host saw for an expert the GPU computed (keeps it warm in the policy's eyes).
299    void touch(int layer, int e) {
300        if (layer < 0 || layer >= (int) where_.size()) return;
301        std::lock_guard<std::mutex> lk(mu_);
302        touch_heat(layer, e);
303        const int s = where_[(size_t) layer][(size_t) e];
304        if (s >= 0) slots_[(size_t) s].tick = ++clock_;
305    }
306    bool gpu_mapped() const { return !chunk_dev_.empty() && chunk_dev_[0] != nullptr; }
307    /// The arena's address range (the device sees its host pointers as they are when the mapping is the identity)
308    unsigned long long arena_lo() const { return (unsigned long long) (uintptr_t) arena_; }
309    unsigned long long arena_hi() const { return (unsigned long long) (uintptr_t) (arena_ + arena_bytes_); }
310    bool identity_mapped() const {
311        for (size_t i = 0; i < chunks_.size(); ++i)
312            if (chunk_dev_[i] != nullptr && chunk_dev_[i] != chunks_[i].first) return false;
313        return true;
314    }
315    size_t max_blob() const { return slot_bytes_ - 2 * kSlack; }
316
317    /// Waits until no read is in flight (each finished read's slot made ready): DS4_STORE_ZC_DET's window boundary, so which
318    /// slots the GPU may read depends on the routing alone, not on how far the drives had got.
319    void drain() {
320        for (;;) {
321            bool busy = false;
322            {
323                std::lock_guard<std::mutex> lk(mu_);
324                for (size_t j = 0; j < nalloc_; ++j) {
325                    Slot& sp = slots_[j];
326                    if (sp.state.load(std::memory_order_acquire) != kLoading) continue;
327                    if (sp.left.load(std::memory_order_acquire) > 0) busy = true;
328                    else {
329                        try_ready(sp);
330                        if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
331                    }
332                }
333            }
334            if (!busy) return;
335            io_->wait_any(5000);
336        }
337    }
338    /// At a window boundary (nothing reading the slots; the caller applies `ev` to the device's table before the next window):
339    /// every ready slot not visible yet becomes visible (`gpu_ok(layer, e)`: false for an expert VRAM holds), and visible
340    /// slots of the lowest score are taken back until `cfg.reserve` slots can be given up.  Returns the number of events.
341    size_t sync(std::vector<Vis>& ev, const std::function<bool(int, int)>& gpu_ok) {
342        std::lock_guard<std::mutex> lk(mu_);
343        size_t nvis = 0, nfree = 0;
344        for (size_t i = 0; i < nalloc_; ++i) {
345            Slot& sp = slots_[i];
346            if (sp.state.load(std::memory_order_acquire) == kLoading && sp.left.load(std::memory_order_acquire) == 0) {
347                try_ready(sp);
348                if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
349            }
350            const int st = sp.state.load(std::memory_order_acquire);
351            if (st == kFree) {
352                ++nfree;
353                continue;
354            }
355            if (st != kReady) continue;
356            if (sp.visible) {
357                ++nvis;
358                continue;
359            }
360            if (sp.pin == 0) ++nfree;
361            if (sp.pin == 0 && dev_blob((int) i) != 0 && gpu_ok(sp.layer, sp.expert) && !sp.prefetch && vis_hash(sp.layer, sp.expert) < cfg_.vis_percent) {
362                sp.visible = true;
363                ++nvis;
364                if (sp.pin == 0) --nfree;
365                ev.push_back({sp.layer, sp.expert, dev_blob((int) i)});
366            }
367        }
368        // give slots back until the reserve is there: the visible ones with the lowest score
369        if (nfree < cfg_.reserve && nvis > 0) {
370            std::vector<std::pair<double, size_t>> cand;
371            cand.reserve(nvis);
372            for (size_t i = 0; i < nalloc_; ++i)
373                if (slots_[i].visible && slots_[i].state.load(std::memory_order_acquire) == kReady) cand.push_back({score(slots_[i]), i});
374            const size_t want = std::min(cand.size(), cfg_.reserve - nfree);
375            std::partial_sort(cand.begin(), cand.begin() + (long) want, cand.end());
376            for (size_t k = 0; k < want; ++k) {
377                Slot& sp = slots_[cand[k].second];
378                sp.visible = false;
379                ev.push_back({sp.layer, sp.expert, 0ull});
380            }
381        }
382        return ev.size();
383    }
384    /// RAM is short: gives back whole chunks from the end of the arena (their experts forgotten) - up to `want`, stopping at one
385    /// with a slot in use (pinned, loading, or GPU-visible).  Returns the chunks given back.
386    size_t shrink_chunks(size_t want) {
387        std::lock_guard<std::mutex> lk(mu_);
388        size_t done = 0;
389        while (done < want && !chunks_.empty()) {
390            const size_t c = chunks_.size() - 1, first = c * kChunk;
391            bool busy = false;
392            for (size_t i = first; i < nalloc_ && !busy; ++i) {
393                Slot& sp = slots_[i];
394                if (sp.state.load(std::memory_order_acquire) == kLoading && sp.left.load(std::memory_order_acquire) == 0) {   // (read by now)
395                    try_ready(sp);
396                    if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
397                }
398                busy = sp.pin > 0 || sp.visible || sp.state.load(std::memory_order_acquire) == kLoading;
399            }
400            if (busy) break;
401            for (size_t i = first; i < nalloc_; ++i) {
402                Slot& sp = slots_[i];
403                if (sp.layer >= 0 && sp.expert >= 0) {
404                    where_[(size_t) sp.layer][(size_t) sp.expert] = -1;
405                    st_.evictions.fetch_add(1, std::memory_order_relaxed);
406                }
407                sp.layer = sp.expert = -1;
408                sp.prefetch = false;
409                sp.state.store(kFree, std::memory_order_release);
410                sp.base = nullptr;
411            }
412            if (cfg_.unmap_chunk && chunk_dev_[c] != nullptr) cfg_.unmap_chunk(chunks_[c].first);
413            os::range_decommit(chunks_[c].first, chunks_[c].second);
414            chunks_.pop_back();
415            chunk_dev_.pop_back();
416            nalloc_ = first;
417            free_hint_ = std::min(free_hint_, first);
418            ++done;
419            ++shrunk_;
420        }
421        return done;
422    }
423    size_t shrunk() const { return shrunk_; }
424    /// An expert VRAM took over: no longer a visible slot
425    void unmark(int layer, int e) {
426        if (layer < 0 || layer >= (int) where_.size()) return;
427        std::lock_guard<std::mutex> lk(mu_);
428        const int s = where_[(size_t) layer][(size_t) e];
429        if (s >= 0) slots_[(size_t) s].visible = false;
430    }
431    size_t visible_count() const {
432        size_t n = 0;
433        for (size_t i = 0; i < nalloc_; ++i) n += slots_[i].visible ? 1 : 0;
434        return n;
435    }
436
437private:
438    static uint8_t* read_base(uint8_t* fin, uint64_t lead) {
439        return (uint8_t*) ((uintptr_t) (fin - lead) & ~(uintptr_t) (os::kDirectAlign - 1));
440    }
441    static constexpr int kFree = 0, kLoading = 1, kReady = 2, kFailed = 3;
442    // slots a chunk of the arena (the unit the GPU mapping registers; DS4_STORE_CHUNK_SLOTS: a test knob for the registration segment size)
443    static size_t chunk_slots() {
444        const char* e = std::getenv("DS4_STORE_CHUNK_SLOTS");
445        const long v = e ? std::atol(e) : 0;
446        return v >= 8 && v <= 4096 ? (size_t) v : 64;
447    }
448    const size_t kChunk = chunk_slots();
449    struct Slot {
450        uint8_t* base = nullptr;   // the blob's first byte
451        int layer = -1, expert = -1, pin = 0;
452        bool prefetch = false, visible = false;
453        std::atomic<int> state{kFree}, left{0};
454        std::atomic<bool> bad{false}, cancel{false};
455        std::atomic<uint64_t> mask[3] = {};   // the pieces of each matrix that have landed
456        uint64_t pbytes[3] = {};              // a piece's bytes (from the matrix's aligned read start)
457        uint64_t tick = 0;
458    };
459
460    static int vis_hash(int layer, int e) { return (int) (((unsigned) layer * 2654435761u + (unsigned) e * 40503u) >> 7) % 100; }
461    double score(const Slot& sp) const {
462        if (cfg_.policy == kLru) return (double) sp.tick;
463        return (double) heat_[(size_t) sp.layer][(size_t) sp.expert] + 1e-9 * (double) sp.tick;
464    }
465    void touch_heat(int layer, int e) {
466        heat_[(size_t) layer][(size_t) e] += 1.0f;
467        if (cfg_.policy != kLru && ++hits_in_layer_[(size_t) layer] % (uint64_t) cfg_.decay_every == 0)
468            for (float& h : heat_[(size_t) layer]) h *= cfg_.decay;   // (a linear pass over 384 floats every 240 accesses of that layer)
469    }
470    // a slot for (layer, e) and its reads started; -1 if there is none to be had.  mu_ held.
471    int start_fill(int layer, int e, bool demand) {
472        int s = take_slot(demand);
473        if (s < 0) {
474            st_.no_slot.fetch_add(1, std::memory_order_relaxed);
475            return -1;
476        }
477        Slot& sp = slots_[(size_t) s];
478        if (sp.layer >= 0 && sp.expert >= 0) {
479            where_[(size_t) sp.layer][(size_t) sp.expert] = -1;
480            if (sp.prefetch) st_.prefetch_wasted.fetch_add(1, std::memory_order_relaxed);
481            st_.evictions.fetch_add(1, std::memory_order_relaxed);
482        }
483        sp.layer = layer;
484        sp.expert = e;
485        sp.pin = demand ? 1 : 0;
486        sp.prefetch = !demand;
487        sp.visible = false;
488        sp.tick = ++clock_;
489        sp.state.store(kLoading, std::memory_order_release);
490        sp.bad.store(false);
491        sp.cancel.store(false);
492        where_[(size_t) layer][(size_t) e] = s;
493        const LayerGeo& g = geo_[(size_t) layer];
494        IoQueue::Job jobs[3];
495        if (cfg_.read_in_place && cfg_.piece_bytes > 0) return start_pieces(sp, s, layer, e, demand);
496        sp.left.store(3, std::memory_order_release);
497        for (int r = 0; r < 3; ++r) {
498            const uint64_t off = g.off[r] + (uint64_t) e * g.stride[r];
499            const uint64_t lead = off % os::kDirectAlign;
500            uint8_t* fin = sp.base + g.tr[r];   // where the matrix belongs
501            // the aligned read lands the file's byte `off` at dst + lead: dst is fin - lead rounded down to 4096 (its span spills
502            // under 4096 bytes either way into the blob's gaps), the matrix is then moved up to fin
503            uint8_t* dst = read_base(fin, lead);
504            IoQueue::Job& j = jobs[r];
505            j.fd = pfds_[(size_t) g.file[r]];
506            j.dfd = dfds_[(size_t) g.file[r]];
507            j.off = off;
508            j.len = g.bytes[r];
509            j.dst = dst;
510            j.keep = cfg_.read_in_place ? nullptr : fin;
511            j.left = &sp.left;
512            j.bad = &sp.bad;
513            j.cancel = demand ? nullptr : &sp.cancel;
514            sp.mask[r].store(0, std::memory_order_relaxed);
515            sp.pbytes[r] = os::direct_span(off, g.bytes[r]);
516            j.mask = &sp.mask[r];
517            j.bit = 1;
518        }
519        st_.bytes_read.fetch_add((int64_t) (g.bytes[0] + g.bytes[1] + g.bytes[2]), std::memory_order_relaxed);
520        io_->push(jobs, 3, !demand);   // (a guess waits behind every demand read)
521        return s;
522    }
523    // start_fill's reads in pieces (read_in_place): each matrix's aligned span cut into at most 64 pieces of piece_bytes or more,
524    // landing where the one read would have put them.  mu_ held.
525    int start_pieces(Slot& sp, int s, int layer, int e, bool demand) {
526        const LayerGeo& g = geo_[(size_t) layer];
527        std::vector<IoQueue::Job> per[3];
528        for (int r = 0; r < 3; ++r) {
529            const uint64_t off = g.off[r] + (uint64_t) e * g.stride[r], lead = off % os::kDirectAlign, a0 = off - lead;
530            const uint64_t span = os::direct_span(off, g.bytes[r]);
531            uint64_t pb = std::max<uint64_t>(cfg_.piece_bytes, (span + 63) / 64);
532            pb = (pb + os::kDirectAlign - 1) & ~(uint64_t) (os::kDirectAlign - 1);
533            sp.pbytes[r] = pb;
534            sp.mask[r].store(0, std::memory_order_relaxed);
535            uint8_t* dst = read_base(sp.base + g.tr[r], lead);
536            for (uint64_t k = 0; k * pb < span; ++k) {
537                IoQueue::Job j;
538                j.fd = pfds_[(size_t) g.file[r]];
539                j.dfd = dfds_[(size_t) g.file[r]];
540                j.off = a0 + k * pb;
541                j.len = std::min(off + g.bytes[r], a0 + (k + 1) * pb) - j.off;
542                j.dst = dst + k * pb;
543                j.left = &sp.left;
544                j.bad = &sp.bad;
545                j.cancel = demand ? nullptr : &sp.cancel;
546                j.mask = &sp.mask[r];
547                j.bit = 1ull << k;
548                per[r].push_back(j);
549            }
550        }
551        // gate and up piece by piece (a row's gate/up job needs both), then down
552        std::vector<IoQueue::Job> jobs;
553        for (size_t k = 0; k < std::max(per[0].size(), per[1].size()); ++k)
554            for (int r = 0; r < 2; ++r)
555                if (k < per[r].size()) jobs.push_back(per[r][k]);
556        jobs.insert(jobs.end(), per[2].begin(), per[2].end());
557        sp.left.store((int) jobs.size(), std::memory_order_release);
558        st_.bytes_read.fetch_add((int64_t) (g.bytes[0] + g.bytes[1] + g.bytes[2]), std::memory_order_relaxed);
559        io_->push(jobs.data(), (int) jobs.size(), !demand);
560        return s;
561    }
562    // loading -> ready once its reads are done and whole (lock-free; a failed one is cleaned up by finish / take_slot)
563    void try_ready(Slot& sp) const {
564        int want = kLoading;
565        if (sp.left.load(std::memory_order_acquire) == 0 && !sp.bad.load(std::memory_order_acquire))
566            sp.state.compare_exchange_strong(want, kReady, std::memory_order_acq_rel);
567    }
568    // mu_ held; reads done.  A failed (or dropped) read frees the slot - unless it is pinned and `last` is false: a window
569    // holding it may still be reading its pieces that did land (DS4_LANE_STREAM), so only its last holder (wait_slots) frees it
570    void finish(Slot& sp, bool last = false) {
571        if (sp.state.load() != kLoading) return;
572        if (sp.bad.load() && sp.pin > 0 && !last) return;
573        if (sp.bad.load()) {
574            where_[(size_t) sp.layer][(size_t) sp.expert] = -1;
575            sp.layer = sp.expert = -1;
576            sp.state.store(kFree, std::memory_order_release);
577            sp.prefetch = false;
578            if (sp.cancel.load()) st_.cancelled.fetch_add(1, std::memory_order_relaxed);
579            else st_.fails.fetch_add(1, std::memory_order_relaxed);
580            return;
581        }
582        sp.state.store(kReady, std::memory_order_release);
583    }
584    bool grow() {
585        if (nalloc_ >= nmax_) return false;
586        const size_t n = std::min(kChunk, nmax_ - nalloc_);
587        const size_t bytes = n * slot_bytes_;
588        const uint64_t avail = cfg_.ram_avail ? cfg_.ram_avail() : ~uint64_t{0};
589        if (avail != ~uint64_t{0} && avail < bytes + cfg_.floor_bytes) return false;
590        void* p = arena_ + nalloc_ * slot_bytes_;
591        if (!os::range_commit(p, bytes)) return false;
592        chunks_.push_back({p, bytes});
593        void* dev = cfg_.map_chunk ? cfg_.map_chunk(p, bytes) : nullptr;
594        chunk_dev_.push_back(dev);
595        for (size_t i = 0; i < n; ++i) slots_[nalloc_ + i].base = (uint8_t*) p + i * slot_bytes_ + kSlack;
596        nalloc_ += n;
597        return true;
598    }
599    // the slot to give up (or a free one): the policy's lowest among the unpinned, not visible, ready ones.  mu_ held.
600    int take_slot(bool demand) {
601        for (size_t i = free_hint_; i < nalloc_; ++i)
602            if (slots_[i].state.load(std::memory_order_acquire) == kFree) {
603                free_hint_ = i + 1;
604                return (int) i;
605            }
606        if (grow()) return take_slot(demand);
607        int best = -1;
608        double bv = 0;
609        for (size_t i = 0; i < nalloc_; ++i) {
610            Slot& sp = slots_[i];
611            if (sp.state.load(std::memory_order_acquire) == kLoading && sp.left.load(std::memory_order_acquire) == 0) {
612                try_ready(sp);
613                if (sp.state.load(std::memory_order_acquire) == kLoading) finish(sp);
614                if (sp.state.load(std::memory_order_acquire) == kFree) {
615                    free_hint_ = std::min(free_hint_, i);
616                    return (int) i;
617                }
618            }
619            if (sp.pin > 0 || sp.visible || sp.state.load(std::memory_order_acquire) != kReady) continue;
620            const double v = score(sp);
621            if (best < 0 || v < bv) {
622                best = (int) i;
623                bv = v;
624            }
625        }
626        if (best < 0) return -1;
627        free_hint_ = std::min<size_t>(free_hint_, (size_t) best);
628        return best;
629    }
630
631    Cfg cfg_;
632    std::vector<LayerGeo> geo_;
633    std::vector<os::fd_t> dfds_, pfds_;
634    size_t slot_bytes_ = 0, nmax_ = 0, nalloc_ = 0, free_hint_ = 0, arena_bytes_ = 0;
635    uint8_t* arena_ = nullptr;
636    size_t shrunk_ = 0;
637    std::unique_ptr<Slot[]> slots_;
638    std::vector<std::pair<void*, size_t>> chunks_;
639    std::vector<void*> chunk_dev_;
640    std::vector<std::vector<int>> where_;
641    std::vector<std::vector<float>> heat_;
642    std::vector<uint64_t> hits_in_layer_;
643    uint64_t clock_ = 0;
644    std::mutex mu_;
645    std::unique_ptr<IoQueue> io_;
646    Stats st_;
647};
648
649}  // namespace strata::ds4