okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
22.5 KiB577 linesraw
1// sycl/src/ngram/ple_reader.cpp - SYCL port: upstream src/ngram/ple_reader.cpp plus a per-gather timing trace
2// (STRATA_PLE_TRACE=1: where a decode round's PLE wait goes). See include/strata/ngram/ple_reader.hpp.
3#include <cstdio>
4#include <cstdlib>
5#include "strata/ngram/ple_reader.hpp"
6
7#include <algorithm>
8#include <chrono>
9#include <condition_variable>
10#include <cstring>
11#include <deque>
12#include <exception>
13#include <mutex>
14#include <thread>
15#include <unordered_map>
16
17namespace strata::ngram {
18
19using platform::Completion;
20using platform::DirectFile;
21using platform::now_us;
22
23double ReaderStats::percentile(double q) const {
24    if (read_us.empty()) return 0.0;
25    std::vector<float> v(read_us);
26    const size_t k = std::min(v.size() - 1, (size_t) (q * (double) (v.size() - 1) + 0.5));
27    std::nth_element(v.begin(), v.begin() + (ptrdiff_t) k, v.end());
28    return v[k];
29}
30
31namespace {
32
33constexpr size_t LATENCY_RING = 65536;
34constexpr uint32_t WAYS = 8;
35constexpr uint32_t EMPTY = 0xFFFFFFFFu;
36
37/// Set-associative row cache: 8 ways per set, round-robin replacement inside a set. Bounded by construction.
38struct RowCache {
39    uint64_t sets = 0;
40    uint32_t rb = ROW_BYTES;        // bytes per row
41    std::vector<uint32_t> keys;     // sets * WAYS
42    std::vector<uint8_t> data;      // sets * WAYS * rb
43    std::vector<uint8_t> next;      // per-set replacement pointer
44    uint64_t used = 0;
45
46    void init(uint64_t rows, uint32_t row_bytes = ROW_BYTES) {
47        sets = rows / WAYS;
48        rb = row_bytes;
49        keys.assign(sets * WAYS, EMPTY);
50        data.assign(sets * WAYS * rb, 0);
51        next.assign(sets, 0);
52        used = 0;
53    }
54    static uint64_t mix(uint32_t r) {
55        uint64_t x = r * 0x9E3779B97F4A7C15ull;
56        return x ^ (x >> 29);
57    }
58    const uint8_t* find(uint32_t row) const {
59        if (sets == 0) return nullptr;
60        const uint64_t s = mix(row) % sets;
61        for (uint32_t w = 0; w < WAYS; ++w)
62            if (keys[s * WAYS + w] == row) return &data[(s * WAYS + w) * rb];
63        return nullptr;
64    }
65    void insert(uint32_t row, const uint8_t* bytes) {
66        if (sets == 0 || find(row) != nullptr) return;
67        const uint64_t s = mix(row) % sets;
68        uint32_t w = next[s];
69        next[s] = (uint8_t) ((w + 1) % WAYS);
70        if (keys[s * WAYS + w] == EMPTY) ++used;
71        keys[s * WAYS + w] = row;
72        std::memcpy(&data[(s * WAYS + w) * rb], bytes, rb);
73    }
74};
75
76struct Use {
77    uint32_t row;
78    uint32_t in_page;      // byte offset of the row inside the read buffer
79    uint8_t* dst;
80};
81
82struct Job {
83    uint64_t offset = 0;   // aligned file offset
84    uint32_t length = 0;   // PAGE or 2 * PAGE (a row that straddles a page boundary)
85    uint32_t ticket = 0;
86    std::vector<Use> uses;
87    double issued_us = 0;
88    bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`)
89};
90
91struct TicketState {
92    uint32_t pending = 0;  // jobs not yet completed
93    uint32_t jobs = 0;     // SYCL port trace: jobs issued, and when it was issued / first submitted / last completed
94    double t_issue = 0, t_first = 0, t_last = 0;
95};
96bool ple_trace() {
97    static const bool v = std::getenv("STRATA_PLE_TRACE") != nullptr;
98    return v;
99}
100
101}  // namespace
102
103// THREADING. With `io_thread` (the default) one worker thread owns every DirectFile call: it submits queued jobs
104// and reaps completions, so `issue` on the caller's thread only builds jobs and wakes it (~11 us per ReadFile
105// no longer lands on the host loop). `mu` guards everything below except `file`, which only the worker touches
106// (plus `wake`, which is thread-safe). Without `io_thread` the caller does all of it, as before.
107struct PleReader::Impl {
108    DirectFile file;
109    uint64_t table_offset = 0;
110    uint64_t n_rows = 0;
111    uint32_t row_bytes = ROW_BYTES;
112    uint32_t max_inflight = 0;
113    uint8_t* slab = nullptr;              // max_inflight slots of 2 pages
114    std::vector<uint32_t> free_slots;
115    std::vector<Job> inflight;            // indexed by slot
116    std::vector<Completion> delayed;      // completed but held back by fault injection
117    std::deque<Job> queue;                // not yet submitted
118    std::unordered_map<uint32_t, TicketState> tickets;
119    uint32_t next_ticket = 1;
120    RowCache cache;
121    ReaderStats stats;
122    size_t ring_pos = 0;
123    double delay_us = 0;
124    std::string error;
125    // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off
126    double keep_us = 0;
127    double keep_window_us = 0;
128    double last_issue_us = 0;             // the last `issue`
129    double last_read_us = 0;              // the last read that went out, rows or keep-alive
130    uint64_t rng = 0x9E3779B97F4A7C15ull;
131
132    bool threaded = false;
133    bool stop = false;
134    std::mutex mu;
135    std::condition_variable cv_work;      // worker: there is something to submit
136    std::condition_variable cv_done;      // collectors: a ticket may have completed
137    std::thread worker;
138
139    uint8_t* slot_buf(uint32_t s) { return slab + (size_t) s * 2 * PAGE; }
140    bool busy() const { return free_slots.size() < max_inflight || !delayed.empty(); }
141
142    void cancel_queued() {
143        for (const Job& job : queue) {
144            auto it = tickets.find(job.ticket);
145            if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
146        }
147        queue.clear();
148    }
149
150    void record_latency(double us) {
151        stats.read_us_sum += us;
152        if (stats.read_us.size() < LATENCY_RING) stats.read_us.push_back((float) us);
153        else stats.read_us[ring_pos++ % LATENCY_RING] = (float) us;
154    }
155
156    bool pump() {
157        while (!queue.empty() && !free_slots.empty()) {
158            const uint32_t s = free_slots.back();
159            free_slots.pop_back();
160            inflight[s] = std::move(queue.front());
161            queue.pop_front();
162            Job& j = inflight[s];
163            j.issued_us = now_us();
164            if (ple_trace()) {
165                auto tt = tickets.find(j.ticket);
166                if (tt != tickets.end() && tt->second.t_first == 0) tt->second.t_first = j.issued_us;
167            }
168            std::string kerr;             // a keep-alive read that cannot go out must not fail the reader
169            if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) {
170                if (j.keepalive) {                 // no more of them: the SSD may sleep as before
171                    keep_us = 0;
172                    j.keepalive = false;
173                    free_slots.push_back(s);
174                    continue;
175                }
176                j.uses.clear();
177                auto it = tickets.find(j.ticket);
178                if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
179                free_slots.push_back(s);
180                cancel_queued();
181                return false;
182            }
183            last_read_us = j.issued_us;
184            if (!j.keepalive) {                    // a keep-alive read counts when it completes (`finish`)
185                stats.submit_us += now_us() - j.issued_us;
186                ++stats.reads;
187            }
188        }
189        return true;
190    }
191
192    /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows
193    /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it).
194    double keepalive_due(double now) const {
195        if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1;
196        return last_read_us + keep_us;
197    }
198
199    /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer).
200    void queue_keepalive() {
201        rng ^= rng << 13;
202        rng ^= rng >> 7;
203        rng ^= rng << 17;
204        const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) row_bytes) / PAGE;
205        Job j;
206        j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE;
207        j.length = PAGE;
208        j.keepalive = true;
209        queue.push_back(std::move(j));
210    }
211
212    bool finish(const Completion& c) {
213        const uint32_t s = (uint32_t) c.tag;
214        if (s >= inflight.size()) {
215            error = "PleReader: invalid table-read completion";
216            cancel_queued();
217            return false;
218        }
219        Job& j = inflight[s];
220        if (j.keepalive) {                         // no rows: it counts once it is done, with how long it took;
221            if (c.ok) {                            // a failed one turns the keep-alive off, not the reader
222                ++stats.keepalive_reads;
223                stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us);
224            } else {
225                keep_us = 0;
226            }
227            j.keepalive = false;
228            free_slots.push_back(s);
229            return error.empty() ? pump() : true;
230        }
231        if (!c.ok) {
232            error = "PleReader: a table read failed";
233            cancel_queued();
234            j.uses.clear();
235            auto it = tickets.find(j.ticket);
236            if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
237            free_slots.push_back(s);
238            return false;
239        }
240        record_latency(now_us() - j.issued_us);
241        stats.bytes += c.bytes;
242        const uint8_t* buf = slot_buf(s);
243        for (const Use& u : j.uses) {
244            if (u.in_page + row_bytes > c.bytes) {
245                error = "PleReader: short read inside the table";
246                cancel_queued();
247                j.uses.clear();
248                auto it = tickets.find(j.ticket);
249                if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
250                free_slots.push_back(s);
251                return false;
252            }
253        }
254        for (const Use& u : j.uses) {
255            std::memcpy(u.dst, buf + u.in_page, row_bytes);
256            cache.insert(u.row, buf + u.in_page);
257        }
258        auto it = tickets.find(j.ticket);
259        if (it != tickets.end() && it->second.pending > 0) --it->second.pending;
260        if (ple_trace() && it != tickets.end()) it->second.t_last = now_us();
261        j.uses.clear();
262        free_slots.push_back(s);
263        return error.empty() ? pump() : true;
264    }
265
266    /// Completions (or wake packets) just returned by `file.wait`, applying fault injection.
267    bool process(const Completion* got, int n) {
268        bool ok = true;
269        for (int i = 0; i < n; ++i) {
270            if (got[i].tag == DirectFile::WAKE_TAG) continue;
271            if (got[i].tag >= inflight.size()) {
272                error = "PleReader: invalid table-read completion";
273                cancel_queued();
274                ok = false;
275                continue;
276            }
277            if (delay_us > 0 && now_us() - inflight[(uint32_t) got[i].tag].issued_us < delay_us) {
278                delayed.push_back(got[i]);
279                ++stats.late_injected;
280                continue;
281            }
282            if (!finish(got[i])) ok = false;   // drain the rest of this batch so no completed slot is stranded
283        }
284        return ok;
285    }
286
287    bool release_delayed() {
288        const double now = now_us();
289        for (size_t i = 0; i < delayed.size();) {
290            if (now - inflight[(uint32_t) delayed[i].tag].issued_us >= delay_us) {
291                const Completion c = delayed[i];
292                delayed.erase(delayed.begin() + (ptrdiff_t) i);
293                if (!finish(c)) return false;
294            } else {
295                ++i;
296            }
297        }
298        return true;
299    }
300
301    /// Caller-thread mode: process whatever has completed; blocks up to `timeout_ms` for the first completion.
302    bool drain(int timeout_ms) {
303        Completion got[64];
304        if (!delayed.empty()) {
305            if (!release_delayed()) return false;
306            timeout_ms = 0;                        // keep polling the held completions
307        }
308        const int n = file.wait(got, 64, timeout_ms);
309        return process(got, n);
310    }
311
312    void worker_loop() {
313        std::unique_lock<std::mutex> lk(mu);
314        for (;;) {
315            // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read.
316            while (!(stop || !queue.empty() || busy())) {
317                const double now = now_us();
318                const double due = keepalive_due(now);
319                if (due < 0) cv_work.wait(lk);
320                else if (now >= due) queue_keepalive();
321                else cv_work.wait_for(lk, std::chrono::microseconds(std::max<int64_t>(1000, (int64_t) (due - now))));
322            }
323            if (stop && !busy()) break;
324            if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed";
325            if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed";
326            if (!error.empty()) {
327                cv_done.notify_all();
328                if (!busy()) { cv_work.wait(lk, [&] { return stop; }); break; }
329            }
330            if (!busy()) { cv_done.notify_all(); continue; }
331            // Block in the port WITHOUT the lock, so `issue` can queue work; `issue` wakes us with a packet.
332            const int timeout = delayed.empty() ? -1 : 0;
333            lk.unlock();
334            Completion got[64];
335            const int n = file.wait(got, 64, timeout);
336            lk.lock();
337            if (!process(got, n) && error.empty()) error = "PleReader: read failed";
338            cv_done.notify_all();
339        }
340    }
341};
342
343PleReader::PleReader() : impl_(new Impl) {}
344PleReader::~PleReader() {
345    close();
346    delete impl_;
347}
348
349bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_rows, uint32_t max_inflight,
350                     uint64_t cache_rows, std::string& err, bool io_thread, uint32_t row_bytes) {
351    close();
352    if (max_inflight == 0 || max_inflight > 1024) { err = "PleReader: max_inflight must be 1..1024"; return false; }
353    if (row_bytes == 0 || row_bytes > PAGE) { err = "PleReader: row_bytes must be 1..4096"; return false; }
354    if (!impl_->file.open(path, err)) return false;
355    impl_->row_bytes = row_bytes;
356    if (table_offset + n_rows * (uint64_t) row_bytes > impl_->file.size()) {
357        err = "PleReader: the table extends past the end of " + path;
358        close();
359        return false;
360    }
361    impl_->table_offset = table_offset;
362    impl_->n_rows = n_rows;
363    impl_->max_inflight = max_inflight;
364    impl_->slab = (uint8_t*) DirectFile::alloc_aligned((size_t) max_inflight * 2 * PAGE);
365    if (impl_->slab == nullptr) { err = "PleReader: cannot allocate read buffers"; close(); return false; }
366    impl_->inflight.assign(max_inflight, Job{});
367    impl_->free_slots.clear();
368    for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s);
369    impl_->cache.init(cache_rows, row_bytes);
370    impl_->error.clear();
371    impl_->keep_us = 0;
372    impl_->last_issue_us = impl_->last_read_us = 0;
373    impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us();
374    if (impl_->rng == 0) impl_->rng = 1;
375    reset_stats();
376    impl_->stop = false;
377    impl_->threaded = io_thread;
378    if (io_thread) {
379        try {
380            impl_->worker = std::thread([this] { impl_->worker_loop(); });
381        } catch (const std::exception& e) {
382            err = std::string("PleReader: cannot create I/O worker: ") + e.what();
383            close();
384            return false;
385        } catch (...) {
386            err = "PleReader: cannot create I/O worker";
387            close();
388            return false;
389        }
390    }
391    return true;
392}
393
394void PleReader::close() {
395    Impl& m = *impl_;
396    if (m.worker.joinable()) {
397        {
398            std::lock_guard<std::mutex> lk(m.mu);
399            m.stop = true;
400            m.queue.clear();                       // unsubmitted work is dropped; in-flight reads still drain
401        }
402        m.cv_work.notify_all();
403        m.file.wake();
404        m.worker.join();
405    }
406    // Outstanding reads must finish before their buffers are released (caller-thread mode, or a worker that
407    // stopped on an error).
408    if (m.file.is_open()) {
409        while (m.free_slots.size() < m.max_inflight) {
410            Completion c[64];
411            const int n = m.file.wait(c, 64, -1);
412            if (n == 0) break;
413            for (int i = 0; i < n; ++i)
414                if (c[i].tag != DirectFile::WAKE_TAG) m.free_slots.push_back((uint32_t) c[i].tag);
415        }
416    }
417    m.file.close();
418    DirectFile::free_aligned(m.slab);
419    m.slab = nullptr;
420    m.queue.clear();
421    m.tickets.clear();
422    m.delayed.clear();
423    m.inflight.clear();
424    m.free_slots.clear();
425    m.cache.init(0);
426    m.threaded = false;
427    m.stop = false;
428    m.keep_us = 0;
429    m.last_issue_us = m.last_read_us = 0;
430}
431
432bool PleReader::is_open() const { return impl_->file.is_open(); }
433uint32_t PleReader::row_bytes() const { return impl_->row_bytes; }
434
435PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_raw) {
436    Impl& m = *impl_;
437    std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
438    if (m.threaded) lk.lock();
439    const uint32_t id = m.next_ticket++;
440    if (m.next_ticket == 0) m.next_ticket = 1;
441    const double now = now_us();
442    const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us);
443    m.last_issue_us = now;
444    TicketState& ts = m.tickets[id];
445    // After a failed read the reader stays failed (`collect` reports `error` until the next `open`) and its worker has
446    // parked (worker_loop). A ticket queued now would never be read and `collect` would wait for it for ever, so it
447    // is not queued: it has no jobs, and `collect` returns the error at once.
448    if (!m.error.empty()) {
449        ts.pending = 0;
450        return Ticket{id};
451    }
452    std::unordered_map<uint64_t, size_t> by_page;     // aligned offset -> index in `jobs`
453    std::vector<Job> jobs;
454    for (size_t i = 0; i < n; ++i) {
455        const uint32_t rb = m.row_bytes;
456        uint8_t* dst = out_raw + i * rb;
457        ++m.stats.requests;
458        if (rows[i] >= m.n_rows) {
459            std::memset(dst, 0, rb);
460            continue;
461        }
462        if (const uint8_t* hit = m.cache.find(rows[i])) {
463            std::memcpy(dst, hit, rb);
464            ++m.stats.cache_hits;
465            continue;
466        }
467        const uint64_t at = m.table_offset + (uint64_t) rows[i] * rb;
468        const uint64_t first = at / PAGE * PAGE;
469        const uint32_t length = (uint32_t) ((at + rb - 1) / PAGE * PAGE - first + PAGE);
470        auto f = by_page.find(first);
471        if (f != by_page.end()) {
472            Job& j = jobs[f->second];
473            j.length = std::max(j.length, length);
474            j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst});
475            ++m.stats.dedup_rows;
476            continue;
477        }
478        by_page.emplace(first, jobs.size());
479        Job j;
480        j.offset = first;
481        j.length = length;
482        j.ticket = id;
483        j.uses.push_back(Use{rows[i], (uint32_t) (at - first), dst});
484        jobs.push_back(std::move(j));
485    }
486    // Sorted by offset: prefill chunks then read the SSD in near-sequential order.
487    std::sort(jobs.begin(), jobs.end(), [](const Job& a, const Job& b) { return a.offset < b.offset; });
488    ts.pending = (uint32_t) jobs.size();
489    ts.jobs = ts.pending;
490    ts.t_issue = now_us();
491    const bool has_jobs = ts.pending > 0;
492    for (Job& j : jobs) m.queue.push_back(std::move(j));
493    if (m.threaded) {
494        lk.unlock();
495        if (has_jobs) {
496            m.cv_work.notify_one();
497            m.file.wake();                         // in case the worker is blocked in the port
498        } else if (rearm) {
499            m.cv_work.notify_one();                // the keep-alive had lapsed: start it again
500        }
501    } else if (!m.pump() && m.error.empty()) {
502        m.error = "PleReader: submit failed";
503    }
504    return Ticket{id};
505}
506
507bool PleReader::collect(Ticket t, std::string& err) {
508    Impl& m = *impl_;
509    const double start = now_us();
510    if (m.threaded) {
511        std::unique_lock<std::mutex> lk(m.mu);
512        auto it = m.tickets.find(t.id);
513        if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
514        m.cv_done.wait(lk, [&] {
515            const auto current = m.tickets.find(t.id);
516            return current == m.tickets.end() || current->second.pending == 0;
517        });
518        it = m.tickets.find(t.id);
519        if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
520        if (!m.error.empty()) { err = m.error; m.tickets.erase(it); return false; }
521        m.stats.wait_us += now_us() - start;
522        if (ple_trace() && it->second.jobs > 0 && it->second.jobs < 200) {
523            const TicketState& ts = it->second;
524            const double now = now_us();
525            std::fprintf(stderr, "ple trace: %3u jobs  issue->submit %8.1f  submit->last %8.1f  last->return %8.1f  "
526                         "collect wait %8.1f us\n", ts.jobs, ts.t_first - ts.t_issue, ts.t_last - ts.t_first,
527                         now - ts.t_last, now - start);
528        }
529        m.tickets.erase(it);
530        return true;
531    }
532    auto it = m.tickets.find(t.id);
533    if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
534    while (it->second.pending > 0) {
535        const bool drained = m.drain(-1);
536        if (!drained && m.error.empty()) m.error = "PleReader: read failed";
537        it = m.tickets.find(t.id);
538        if (it == m.tickets.end()) { err = "PleReader: unknown ticket"; return false; }
539    }
540    if (!m.error.empty()) { err = m.error; m.tickets.erase(it); return false; }
541    m.stats.wait_us += now_us() - start;
542    m.tickets.erase(it);
543    return true;
544}
545
546void PleReader::set_keepalive(double period_ms, double window_s) {
547    Impl& m = *impl_;
548    {
549        std::lock_guard<std::mutex> lk(m.mu);
550        m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0;
551        m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0;
552    }
553    m.cv_work.notify_all();
554}
555
556void PleReader::set_injected_delay_us(double delay_us) {
557    std::lock_guard<std::mutex> lk(impl_->mu);
558    impl_->delay_us = delay_us < 0 ? 0 : delay_us;
559}
560const ReaderStats& PleReader::stats() const { return impl_->stats; }
561ReaderStats PleReader::snapshot() const {
562    Impl& m = *impl_;
563    std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
564    if (m.threaded) lk.lock();
565    return m.stats;
566}
567void PleReader::reset_stats() {
568    Impl& m = *impl_;
569    std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);
570    if (m.threaded) lk.lock();                     // the worker may be counting a keep-alive read
571    m.stats = ReaderStats{};
572    m.ring_pos = 0;
573}
574uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; }
575uint64_t PleReader::cache_size() const { return impl_->cache.used; }
576
577}  // namespace strata::ngram