okami.mom/strata

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

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
11.7 KiB275 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_engram_io.hpp - DeepSeek's Engram (n-gram memory) rows read off the decode's critical path.
4//
5// A token's Engram rows depend only on the token ids, so they are asked for as soon as the window's tokens are known
6// and collected only right before the layer that adds them (layer 1's hide behind the embedding and layer 0, layer
7// 14's behind layers 0-13).  The reads run on the reader's own threads, each with its own handles to the model's files
8// (on Windows the ReadFile calls on one synchronous handle run one at a time), FIFO: the first Engram layer's rows
9// first.  A bounded row cache (clock eviction) keeps rows already fetched: a row that recurs (the same n-gram again,
10// in the prompt or later) is a copy, not a read.  The rows are the file's bytes either way, so the output is the same.
11#pragma once
12
13#include "ds4_os.hpp"
14
15#include <algorithm>
16#include <atomic>
17#include <chrono>
18#include <condition_variable>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <deque>
23#include <memory>
24#include <mutex>
25#include <string>
26#include <thread>
27#include <unordered_map>
28#include <utility>
29#include <vector>
30
31namespace strata::ds4 {
32
33inline int64_t now_ns() {
34    return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch())
35        .count();
36}
37
38/// Rows already fetched: key -> `bytes` of payload, at most `cap` rows (grown on demand in blocks), clock eviction.
39/// Not thread-safe (the caller locks).
40class EgRowCache {
41public:
42    void init(size_t cap, size_t bytes) {
43        cap_ = cap;
44        bytes_ = bytes;
45        map_.reserve(std::min<size_t>(cap, 1u << 20));
46    }
47    size_t capacity() const { return cap_; }
48    size_t size() const { return keys_.size(); }
49    /// The row's payload, or nullptr (a hit marks it recently used).
50    const uint8_t* find(uint64_t key) {
51        const auto it = map_.find(key);
52        if (it == map_.end()) return nullptr;
53        ref_[it->second] = 1;
54        return at(it->second);
55    }
56    /// Room for key's payload (the caller fills it): a new slot while below capacity, else the clock's victim.
57    uint8_t* put(uint64_t key) {
58        if (cap_ == 0 || bytes_ == 0) return nullptr;
59        const auto it = map_.find(key);
60        if (it != map_.end()) return at(it->second);
61        uint32_t s;
62        if (keys_.size() < cap_) {
63            s = (uint32_t) keys_.size();
64            if (s % kBlock == 0) blocks_.emplace_back(new uint8_t[(size_t) kBlock * bytes_]);
65            keys_.push_back(key);
66            ref_.push_back(0);
67        } else {
68            while (ref_[hand_]) {   // (a second chance for rows used since the hand last passed)
69                ref_[hand_] = 0;
70                hand_ = (hand_ + 1) % (uint32_t) cap_;
71            }
72            s = hand_;
73            hand_ = (hand_ + 1) % (uint32_t) cap_;
74            map_.erase(keys_[s]);
75            keys_[s] = key;
76            ref_[s] = 0;
77        }
78        map_.emplace(key, s);
79        return at(s);
80    }
81
82private:
83    static constexpr uint32_t kBlock = 4096;
84    uint8_t* at(uint32_t s) { return blocks_[s / kBlock].get() + (size_t) (s % kBlock) * bytes_; }
85    size_t cap_ = 0, bytes_ = 0;
86    uint32_t hand_ = 0;
87    std::unordered_map<uint64_t, uint32_t> map_;
88    std::vector<uint64_t> keys_;
89    std::vector<uint8_t> ref_;
90    std::vector<std::unique_ptr<uint8_t[]>> blocks_;
91};
92
93/// One row to fetch: its bytes to dst, its scales to scales.  mx8: n bytes at off of a file, [scale, 32 codes] blocks
94/// (a GGUF's MXFP8 row); else n row bytes at off and n2 scale bytes at off2 of file2 (two reads; n2 0: none - a GGUF's
95/// Q6_K or IQ4_NL row, their scales inside their n bytes: 210 a 256 values, 18 a 32).
96struct EgRead {
97    int file = -1;
98    uint64_t off = 0;
99    uint32_t n = 0;
100    uint8_t* dst = nullptr;
101    uint8_t* scales = nullptr;
102    bool mx8 = false;
103    int file2 = -1;
104    uint64_t off2 = 0;
105    uint32_t n2 = 0;
106    uint64_t key = 0;
107};
108
109/// A batch of rows (one Engram layer of a window): reads, the other places a row read once goes, and its state.
110struct EgBatch {
111    std::vector<EgRead> reads;
112    std::vector<std::pair<int, std::pair<uint8_t*, uint8_t*>>> dups;   // read i -> another (codes, scales)
113    std::vector<uint8_t> ok;                                            // per read: 1 read whole
114    std::atomic<int> left{0};                                           // reads not yet done
115    std::atomic<int> post{0};                                           // 0 pending, 1 finishing, 2 finished
116    int64_t t0 = 0;                                                     // submitted (now_ns())
117    std::atomic<int64_t> t1{0};                                         // the last read done
118    bool live = false;                                                  // submitted and not yet finished
119    void clear() {
120        reads.clear();
121        dups.clear();
122        ok.clear();
123        left.store(0);
124        post.store(0);
125        live = false;
126    }
127};
128
129/// The reader's threads: each read on whichever is free, in submission order, with that thread's own file handles.
130class EgReader {
131public:
132    ~EgReader() { stop(); }
133    /// direct[i]: file i read unbuffered (Windows, a file nothing maps: os::open_unbuffered), else buffered
134    void start(const std::vector<std::string>& paths, int threads, std::vector<char> direct = {}) {
135        paths_ = paths;
136        direct_ = std::move(direct);
137        for (int i = 0; i < threads; ++i) th_.emplace_back([this] { loop(); });
138    }
139    void stop() {
140        {
141            std::lock_guard<std::mutex> lk(mu_);
142            quit_ = true;
143        }
144        cv_.notify_all();
145        for (auto& t : th_) t.join();
146        th_.clear();
147        if (check_n_.load() > 0)
148            std::fprintf(stderr, "ds4 Engram check (DS4_EG_CHECK): %lld rows read unbuffered, %lld differed from a buffered read\n",
149                         (long long) check_n_.load(), (long long) check_bad_.load());
150    }
151    int threads() const { return (int) th_.size(); }
152    void submit(EgBatch& b) {
153        b.ok.assign(b.reads.size(), 0);
154        b.post.store(0);
155        b.t0 = now_ns();
156        b.t1.store(b.t0);
157        b.live = true;
158        b.left.store((int) b.reads.size(), std::memory_order_release);
159        const int n = (int) b.reads.size();
160        if (n == 0) return;
161        // a token's rows one job each; a prompt chunk's in runs (fewer trips through the queue's lock)
162        const int step = std::max(1, std::min(32, n / (int) (th_.size() * 4)));
163        int jobs = 0;
164        {
165            std::lock_guard<std::mutex> lk(mu_);
166            for (int i = 0; i < n; i += step, ++jobs) q_.push_back({&b, i, std::min(n, i + step)});
167        }
168        if (jobs >= (int) th_.size()) cv_.notify_all();
169        else
170            for (int i = 0; i < jobs; ++i) cv_.notify_one();
171    }
172    /// Until every read of b is done.
173    void wait(EgBatch& b) {
174        if (b.left.load(std::memory_order_acquire) == 0) return;
175        std::unique_lock<std::mutex> lk(done_mu_);
176        done_cv_.wait(lk, [&] { return b.left.load(std::memory_order_acquire) == 0; });
177    }
178
179private:
180    void loop() {
181        std::vector<os::fd_t> fds(paths_.size(), os::kBadFd);   // this thread's own handles, opened on first use
182        std::vector<os::fd_t> ufds(paths_.size(), os::kBadFd);  // (and its unbuffered ones)
183        std::vector<uint8_t> buf, abuf(3 * os::kDirectAlign);
184        uint8_t* al = abuf.data() + (os::kDirectAlign - (uintptr_t) abuf.data() % os::kDirectAlign) % os::kDirectAlign;
185        for (;;) {
186            Job job;
187            {
188                std::unique_lock<std::mutex> lk(mu_);
189                cv_.wait(lk, [&] { return quit_ || !q_.empty(); });
190                if (quit_ && q_.empty()) break;
191                job = q_.front();
192                q_.pop_front();
193            }
194            EgBatch& b = *job.b;
195            for (int i = job.i0; i < job.i1; ++i) b.ok[(size_t) i] = read(fds, ufds, al, b.reads[(size_t) i], buf) ? 1 : 0;
196            const int64_t t = now_ns();
197            for (int64_t prev = b.t1.load(); t > prev && !b.t1.compare_exchange_weak(prev, t);) {
198            }
199            if (b.left.fetch_sub(job.i1 - job.i0, std::memory_order_acq_rel) == job.i1 - job.i0) {   // (b is the waiter's again)
200                std::lock_guard<std::mutex> lk(done_mu_);
201                done_cv_.notify_all();
202            }
203        }
204        for (os::fd_t f : fds) os::close_fd(f);
205        for (os::fd_t f : ufds) os::close_fd(f);
206    }
207    bool read(std::vector<os::fd_t>& fds, std::vector<os::fd_t>& ufds, uint8_t* al, const EgRead& r,
208              std::vector<uint8_t>& buf) {
209        if ((r.mx8 || r.n2 == 0) && r.file >= 0 && (size_t) r.file < direct_.size() && direct_[(size_t) r.file] &&
210            os::direct_span(r.off, r.n) <= 2 * os::kDirectAlign) {
211            os::fd_t& u = ufds[(size_t) r.file];
212            if (u == os::kBadFd) u = os::open_unbuffered(paths_[(size_t) r.file]);
213            if (u != os::kBadFd && os::pread_unbuffered(u, al, r.n, r.off)) {
214                const uint8_t* src = al + r.off % os::kDirectAlign;
215                static const bool check = std::getenv("DS4_EG_CHECK") != nullptr;   // (each row read buffered too)
216                if (check) {
217                    std::vector<uint8_t> ref(r.n);
218                    os::fd_t& f2 = fds[(size_t) r.file];
219                    if (f2 == os::kBadFd) f2 = os::open_ro(paths_[(size_t) r.file]);
220                    const bool ok = f2 != os::kBadFd && os::pread_full(f2, ref.data(), r.n, r.off);
221                    if (!ok || std::memcmp(ref.data(), src, r.n) != 0) ++check_bad_;
222                    ++check_n_;
223                }
224                if (!r.mx8) {   // (a GGUF's Q6_K / IQ4_NL row: its bytes as they are, the scales inside)
225                    std::memcpy(r.dst, src, r.n);
226                    return true;
227                }
228                for (uint32_t k = 0; k < r.n / 33; ++k) {   // [scale, 32 codes] -> codes | scales
229                    r.scales[k] = src[(size_t) k * 33];
230                    std::memcpy(r.dst + (size_t) k * 32, src + (size_t) k * 33 + 1, 32);
231                }
232                return true;
233            }   // (else buffered, below)
234        }
235        auto fd = [&](int file) {
236            if (file < 0 || file >= (int) fds.size()) return os::kBadFd;
237            if (fds[(size_t) file] == os::kBadFd) fds[(size_t) file] = os::open_ro(paths_[(size_t) file]);
238            return fds[(size_t) file];
239        };
240        const os::fd_t f = fd(r.file);
241        if (f == os::kBadFd) return false;
242        if (!r.mx8) {
243            if (!os::pread_full(f, r.dst, r.n, r.off)) return false;
244            if (r.n2 == 0) return true;
245            const os::fd_t f2 = fd(r.file2);
246            return f2 != os::kBadFd && os::pread_full(f2, r.scales, r.n2, r.off2);
247        }
248        buf.resize(r.n);
249        if (!os::pread_full(f, buf.data(), r.n, r.off)) return false;
250        for (uint32_t k = 0; k < r.n / 33; ++k) {   // [scale, 32 codes] -> codes | scales
251            r.scales[k] = buf[(size_t) k * 33];
252            std::memcpy(r.dst + (size_t) k * 32, buf.data() + (size_t) k * 33 + 1, 32);
253        }
254        return true;
255    }
256
257    std::vector<std::string> paths_;
258    std::vector<char> direct_;
259
260public:
261    std::atomic<int64_t> check_n_{0}, check_bad_{0};   // (DS4_EG_CHECK: rows compared, rows that differed)
262    std::vector<std::thread> th_;
263    std::mutex mu_;
264    std::condition_variable cv_;
265    struct Job {
266        EgBatch* b = nullptr;
267        int i0 = 0, i1 = 0;   // reads [i0, i1)
268    };
269    std::deque<Job> q_;
270    bool quit_ = false;
271    std::mutex done_mu_;
272    std::condition_variable done_cv_;
273};
274
275}  // namespace strata::ds4