okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
00c004617
main
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 : 37explicit Pool (int n ,const std::vector < int >& cpus = {}, int spin_us = 200 ) : spin_us_ ( spin_us ) { 38for (int i = 0 ; i < n ; ++ i ) { 39th_ . emplace_back ([ this ] { loop (); }); 40if (! cpus . empty ()) os:: pin_thread ( th_ . back (), cpus [(size_t) i % cpus . size ()]); 41} 42} 43~ Pool () { 44quit_ . store (true); 45{ 46std::lock_guard < std::mutex > lk (mu_); 47} 48cv_ . notify_all (); 49for (auto & t : th_ ) t . join (); 50} 51int size () const { return (int) th_ . size () + 1 ; } 52 53void run (int n , const std::function < void(int) >& fn ) { 54start ( n , fn ); 55help (); 56wait (); 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.) 60void start (int n , const std::function < void(int) >& fn ) { 61n_ = n ; 62if ( n <= 0 ) return ; 63const uint64_t g = ( gen_ . load (std:: memory_order_relaxed ) + 1 ) & 0xffffffffu ; 64ticket_ . store (( g << 32 ) | 0x7fffffffu , std:: memory_order_seq_cst ); 65fn_ = & fn ; 66total_ . store ( n , std:: memory_order_release ); 67done_ . store ( 0 , std:: memory_order_relaxed ); 68ticket_ . store ( g << 32 , std:: memory_order_release ); 69gen_ . store ( g , std:: memory_order_release ); 70if ( sleeping_ . load (std:: memory_order_acquire ) > 0 ) { 71std::lock_guard < std::mutex > lk (mu_); 72cv_ . notify_all (); 73} 74} 75void help () { 76if ( n_ > 0 ) work ( gen_ . load (std:: memory_order_acquire )); 77} 78void wait () { 79if ( n_ <= 0 ) return ; 80while ( done_ . load (std:: memory_order_acquire ) < n_ ) cpu_relax (); 81n_ = 0 ; 82} 83 84private : 85void work (uint64_t g ) { 86for (;;) { 87uint64_t t = ticket_ . load (std:: memory_order_acquire ); 88if (( t >> 32 ) != g ) return ; 89const int n = total_ . load (std:: memory_order_acquire ); 90if ((int) ( t & 0xffffffffu ) >= n ) return ; 91if (! ticket_ . compare_exchange_weak ( t , t + 1 , std:: memory_order_acq_rel )) continue ; 92( * fn_ )((int) ( t & 0xffffffffu )); 93done_ . fetch_add ( 1 , std:: memory_order_acq_rel ); 94} 95} 96void loop () { 97uint64_t seen = gen_ . load (); 98for (;;) { 99const auto t0 = std::chrono::steady_clock:: now (); 100uint64_t g ; 101for (;;) { 102g = gen_ . load (std:: memory_order_acquire ); 103if ( g != seen || quit_ . load (std:: memory_order_relaxed )) break ; 104cpu_relax (); 105if (std::chrono::steady_clock:: now () - t0 > std::chrono:: microseconds ( spin_us_ )) { 106std::unique_lock < std::mutex > lk (mu_); 107sleeping_ . fetch_add ( 1 ); 108cv_ . wait ( lk , [ & ] { return gen_ . load () != seen || quit_ . load (); }); 109sleeping_ . fetch_sub ( 1 ); 110} 111} 112if ( quit_ . load ()) return ; 113seen = g ; 114work ( g ); 115} 116} 117 118std::vector < std::thread > th_ ; 119int spin_us_ ; 120int n_ = 0 ; // the current batch's size (the caller's side) 121const std::function < void(int) >* fn_ = nullptr ; 122alignas( 64 ) std::atomic < uint64_t > ticket_ { 0 }; 123alignas( 64 ) std::atomic < uint64_t > gen_ { 0 }; 124alignas( 64 ) std::atomic < int > total_ { 0 }; 125alignas( 64 ) std::atomic < int > done_ { 0 }; 126std::atomic < int > sleeping_ { 0 }; 127std::atomic < bool > quit_ {false}; 128std::mutex mu_ ; 129std::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 : 139struct Job { 140os::fd_t fd = os:: kBadFd , dfd = os:: kBadFd ; 141uint64_t off = 0 , len = 0 ; 142uint8_t * dst = nullptr ; 143std::atomic < int >* left = nullptr ; 144std::atomic < bool >* bad = nullptr ; 145const uint8_t * mem = nullptr ; // non-null: a copy of len bytes from memory to dst instead of a read 146const void * map = nullptr ; // the range in the file's mapping: all in the page cache, it is read buffered 147uint8_t * keep = nullptr ; // non-null (a read): the len bytes read copied here as well 148std::atomic < bool >* cancel = nullptr ; // set before the job starts: it is dropped unread (bad is set, left counted down) 149std::atomic < uint64_t >* mask = nullptr ; // non-null: `bit` set here once the read landed whole (before left counts down) 150uint64_t bit = 0 ; 151}; 152explicit IoQueue (int n ) { 153for (int i = 0 ; i < n ; ++ i ) th_ . emplace_back ([ this ] { loop (); }); 154} 155~ IoQueue () { 156{ 157std::lock_guard < std::mutex > lk (mu_); 158quit_ = true; 159} 160cv_ . notify_all (); 161for (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 164void push ( const Job * jobs , int n , bool low = false) { 165{ 166std::lock_guard < std::mutex > lk (mu_); 167for (int i = 0 ; i < n ; ++ i ) ( low ? ql_ : q_ ). push_back ( jobs [ i ]); 168} 169if ( n == 1 ) cv_ . notify_one (); 170else cv_ . notify_all (); 171} 172// Recheck the request under done_mu_: it may have completed before this wait began. 173void wait_any (int us , const std::atomic < int >* left = nullptr ) { 174std::unique_lock < std::mutex > lk (done_mu_); 175const uint64_t seen = done_ ; 176done_cv_ . wait_for ( lk , std::chrono:: microseconds ( us ), [ & ] { 177return done_ != seen || ( left != nullptr && left -> load (std:: memory_order_acquire ) <= 0 ); 178}); 179} 180double 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) 182double any_ms () const { 183std::lock_guard < std::mutex > lk (run_mu_); 184double us = (double) any_us_ ; 185if ( running_ > 0 ) us += (double) std::chrono:: duration_cast < std::chrono::microseconds > (std::chrono::steady_clock:: now () - any_t0_ ). count (); 186return us / 1000.0 ; 187} 188uint64_t direct_bytes () const { return direct_ . load (std:: memory_order_relaxed ); } 189uint64_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 191uint64_t run_jobs () const { return run_jobs_ . load (std:: memory_order_relaxed ); } 192uint64_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 198static uint64_t run_cap () { 199static const uint64_t cap = [] { 200const char * v = std:: getenv ( "DS4_READ_RUN_MB" ); 201return v != nullptr ? (uint64_t) (std:: atof ( v ) * 1048576.0 ) : 0 ; 202}(); 203return cap ; 204} 205static bool joins ( const Job & j ) { 206return 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 209bool read_one ( const Job & j ) { 210const uint64_t lead = j . off % os:: kDirectAlign ; 211bool ok = false; 212if ( j . mem != nullptr ) { 213std:: memcpy ( j . dst , j . mem , (size_t) j . len ); 214ok = true; 215} else if ( j . dfd != os:: kBadFd && !( j . map != nullptr && os:: resident ( j . map , (size_t) j . len )) && 216os:: pread_direct ( j . dfd , j . dst , j . len , j . off )) { // (the page cache's ones: buffered, below) 217ok = true; 218direct_ . fetch_add ( j . len , std:: memory_order_relaxed ); 219} else if (os:: pread_par ( j . fd , j . dst + lead , j . len , j . off )) { 220ok = true; 221buffered_ . fetch_add ( j . len , std:: memory_order_relaxed ); 222} 223if ( 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) 224return 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) 229bool read_run ( const std::vector < Job >& r ) { 230const size_t n = r . size (); 231const uint64_t A = os:: kDirectAlign , a0 = r [ 0 ]. off & ~( A - 1 ); 232const uint64_t end = r [ n - 1 ]. off + r [ n - 1 ]. len , a1 = ( end + A - 1 ) & ~( A - 1 ); 233std::vector < uint8_t *> bufs (n); 234std::vector < uint64_t > lens (n); 235uint64_t pos = a0 ; 236for (size_t i = 0 ; i < n ; ++ i ) { 237if ( r [ i ]. map != nullptr && os:: resident ( r [ i ]. map , (size_t) r [ i ]. len )) return false; 238const uint64_t cut = i + 1 < n ? r [ i + 1 ]. off & ~(uint64_t) 511 : a1 ; 239bufs [ i ] = r [ i ]. dst + ( pos - ( r [ i ]. off & ~( A - 1 ))); 240lens [ i ] = cut - pos ; 241pos = cut ; 242} 243if (!os:: preadv_direct ( r [ 0 ]. dfd , bufs . data (), lens . data (), (int) n , a0 , end - a0 )) return false; 244for (size_t i = 0 ; i + 1 < n ; ++ i ) { 245const uint64_t cut = r [ i + 1 ]. off & ~(uint64_t) 511 ; 246if ( cut < r [ i + 1 ]. off ) 247std:: 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} 250for ( const Job & j : r ) { 251if ( j . keep != nullptr ) std:: memmove ( j . keep , j . dst + j . off % A , (size_t) j . len ); 252direct_ . fetch_add ( j . len , std:: memory_order_relaxed ); 253} 254return true; 255} 256static void finish ( const Job & j , bool ok ) { 257if (! ok && j . bad != nullptr ) j . bad -> store (true, std:: memory_order_release ); 258if ( ok && j . mask != nullptr ) j . mask -> fetch_or ( j . bit , std:: memory_order_acq_rel ); 259if ( j . left != nullptr ) j . left -> fetch_sub ( 1 , std:: memory_order_acq_rel ); 260} 261void loop () { 262std::vector < Job > run ; 263for (;;) { 264Job j ; 265run . clear (); 266{ 267std::unique_lock < std::mutex > lk (mu_); 268cv_ . wait ( lk , [ & ] { return quit_ || ! q_ . empty () || ! ql_ . empty (); }); 269if ( quit_ && q_ . empty () && ql_ . empty ()) return ; 270std::deque < Job >& = q_ . empty () ? ql_ : q_ ; 271j = . front (); 272. pop_front (); 273if ( run_cap () > 0 && joins ( j )) { // (the queued reads that continue it, in queue order) 274uint64_t at = j . off + j . len , bytes = j . len ; 275run . push_back ( j ); 276for (bool more = true; more && bytes < run_cap ();) { 277more = false; 278const size_t scan = std:: min < size_t > ( . size (), 64 ); 279for (size_t i = 0 ; i < scan ; ++ i ) { 280const Job & x = [ i ]; 281if ( x . off != at || x . dfd != j . dfd || ! joins ( x ) || bytes + x . len > run_cap ()) continue ; 282run . push_back ( x ); 283at += x . len ; 284bytes += x . len ; 285. erase ( . begin () + (std::ptrdiff_t) i ); 286more = true; 287break ; 288} 289} 290if ( run . size () == 1 ) run . clear (); 291} 292} 293if ( j . cancel != nullptr && j . cancel -> load (std:: memory_order_acquire )) { // (dropped unread) 294if ( j . bad != nullptr ) j . bad -> store (true, std:: memory_order_release ); 295if ( j . left != nullptr ) j . left -> fetch_sub ( 1 , std:: memory_order_acq_rel ); 296{ 297std::lock_guard < std::mutex > lk (done_mu_); 298++ done_ ; 299} 300done_cv_ . notify_all (); 301continue ; 302} 303const auto t0 = std::chrono::steady_clock:: now (); 304{ 305std::lock_guard < std::mutex > lk (run_mu_); 306if ( running_ ++ == 0 ) any_t0_ = t0 ; 307} 308std::vector < char > oks ; 309if (! run . empty ()) { 310if ( read_run ( run )) { 311oks . assign ( run . size (), 1 ); 312run_jobs_ . fetch_add ( run . size (), std:: memory_order_relaxed ); 313runs_ . fetch_add ( 1 , std:: memory_order_relaxed ); 314} 315else 316for ( const Job & x : run ) oks . push_back ( read_one ( x ) ? 1 : 0 ); 317} else 318oks . push_back ( read_one ( j ) ? 1 : 0 ); 319const auto t1 = std::chrono::steady_clock:: now (); 320busy_us_ . fetch_add ((uint64_t) std::chrono:: duration_cast < std::chrono::microseconds > ( t1 - t0 ). count (), 321std:: memory_order_relaxed ); 322{ 323std::lock_guard < std::mutex > lk (run_mu_); 324if ( -- running_ == 0 ) any_us_ += (uint64_t) std::chrono:: duration_cast < std::chrono::microseconds > ( t1 - any_t0_ ). count (); 325} 326if (! run . empty ()) 327for (size_t i = 0 ; i < run . size (); ++ i ) finish ( run [ i ], oks [ i ] != 0 ); 328else 329finish ( j , oks [ 0 ] != 0 ); 330{ 331std::lock_guard < std::mutex > lk (done_mu_); 332done_ += run . empty () ? 1 : run . size (); 333} 334done_cv_ . notify_all (); 335} 336} 337std::vector < std::thread > th_ ; 338std::mutex mu_ , done_mu_ ; 339std::condition_variable cv_ , done_cv_ ; 340std::deque < Job > q_ , ql_ ; 341uint64_t done_ = 0 ; 342bool quit_ = false; 343std::atomic < uint64_t > busy_us_ { 0 }, direct_ { 0 }, buffered_ { 0 }, run_jobs_ { 0 }, runs_ { 0 }; 344mutable std::mutex run_mu_ ; // (running_, any_us_, any_t0_) 345int running_ = 0 ; 346uint64_t any_us_ = 0 ; 347std::chrono::steady_clock::time_point any_t0_ ; 348}; 349 350} // namespace strata::ds4