okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8ac8ce32e
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_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 () { 34return 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 : 42void init (size_t cap ,size_t bytes ) { 43cap_ = cap ; 44bytes_ = bytes ; 45map_ .reserve (std::min < size_t > (cap ,1u <<20 )); 46 } 47size_t capacity ()const {return cap_ ; } 48size_t size ()const {return keys_ .size (); } 49/// The row's payload, or nullptr (a hit marks it recently used). 50const uint8_t * find (uint64_t key ) { 51const auto it = map_ .find (key ); 52if (it == map_ .end ())return nullptr ; 53ref_ [it -> second ]= 1 ; 54return 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. 57uint8_t * put (uint64_t key ) { 58if (cap_ == 0 || bytes_ == 0 )return nullptr ; 59const auto it = map_ .find (key ); 60if (it != map_ .end ())return at (it -> second ); 61uint32_t s ; 62if (keys_ .size ()< cap_ ) { 63s = (uint32_t )keys_ .size (); 64if (s %kBlock == 0 )blocks_ .emplace_back (new uint8_t [(size_t )kBlock * bytes_ ]); 65keys_ .push_back (key ); 66ref_ .push_back (0 ); 67 }else { 68while (ref_ [hand_ ]) {// (a second chance for rows used since the hand last passed) 69ref_ [hand_ ]= 0 ; 70hand_ = (hand_ + 1 ) % (uint32_t )cap_ ; 71 } 72s = hand_ ; 73hand_ = (hand_ + 1 ) % (uint32_t )cap_ ; 74map_ .erase (keys_ [s ]); 75keys_ [s ]= key ; 76ref_ [s ]= 0 ; 77 } 78map_ .emplace (key ,s ); 79return at (s ); 80 } 81 82private : 83static constexpr uint32_t kBlock = 4096 ; 84uint8_t * at (uint32_t s ) {return blocks_ [s /kBlock ].get ()+ (size_t ) (s %kBlock )* bytes_ ; } 85size_t cap_ = 0 ,bytes_ = 0 ; 86uint32_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 { 97int file = -1 ; 98uint64_t off = 0 ; 99uint32_t n = 0 ; 100uint8_t * dst = nullptr ; 101uint8_t * scales = nullptr ; 102bool mx8 = false; 103int file2 = -1 ; 104uint64_t off2 = 0 ; 105uint32_t n2 = 0 ; 106uint64_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 116int64_t t0 = 0 ;// submitted (now_ns()) 117 std::atomic < int64_t > t1 {0 };// the last read done 118bool live = false;// submitted and not yet finished 119void clear () { 120reads .clear (); 121dups .clear (); 122ok .clear (); 123left .store (0 ); 124post .store (0 ); 125live = 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 134void start (const std::vector < std::string >& paths ,int threads , std::vector < char > direct = {}) { 135paths_ = paths ; 136direct_ = std:: move ( direct ); 137for (int i = 0 ; i < threads ; ++ i ) th_ . emplace_back ([ this ] { loop (); }); 138} 139void stop () { 140{ 141std::lock_guard < std::mutex > lk (mu_); 142quit_ = true; 143} 144cv_ . notify_all (); 145for (auto & t : th_ ) t . join (); 146th_ . clear (); 147if ( check_n_ . load () > 0 ) 148std:: 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} 151int threads () const { return (int) th_ . size (); } 152void submit (EgBatch & b ) { 153b . ok . assign ( b . reads . size (), 0 ); 154b . post . store ( 0 ); 155b . t0 = now_ns (); 156b . t1 . store ( b . t0 ); 157b . live = true; 158b . left . store ((int) b . reads . size (), std:: memory_order_release ); 159const int n = (int) b . reads . size (); 160if ( n == 0 ) return ; 161// a token's rows one job each; a prompt chunk's in runs (fewer trips through the queue's lock) 162const int step = std:: max ( 1 , std:: min ( 32 , n / (int) ( th_ . size () * 4 ))); 163int jobs = 0 ; 164{ 165std::lock_guard < std::mutex > lk (mu_); 166for (int i = 0 ; i < n ; i += step , ++ jobs ) q_ . push_back ({ & b , i , std:: min ( n , i + step )}); 167} 168if ( jobs >= (int) th_ . size ()) cv_ . notify_all (); 169else 170for (int i = 0 ; i < jobs ; ++ i ) cv_ . notify_one (); 171} 172/// Until every read of b is done. 173void wait (EgBatch & b ) { 174if ( b . left . load (std:: memory_order_acquire ) == 0 ) return ; 175std::unique_lock < std::mutex > lk (done_mu_); 176done_cv_ . wait ( lk , [ & ] { return b . left . load (std:: memory_order_acquire ) == 0 ; }); 177} 178 179private : 180void loop () { 181std::vector < os::fd_t > fds ( paths_ . size (), os:: kBadFd ); // this thread's own handles, opened on first use 182std::vector < os::fd_t > ufds ( paths_ . size (), os:: kBadFd ); // (and its unbuffered ones) 183std::vector < uint8_t > buf , abuf ( 3 * os:: kDirectAlign ); 184uint8_t * al = abuf . data () + (os:: kDirectAlign - (uintptr_t) abuf . data () % os:: kDirectAlign ) % os:: kDirectAlign ; 185for (;;) { 186Job job ; 187{ 188std::unique_lock < std::mutex > lk (mu_); 189cv_ . wait ( lk , [ & ] { return quit_ || ! q_ . empty (); }); 190if ( quit_ && q_ . empty ()) break ; 191job = q_ . front (); 192q_ . pop_front (); 193} 194EgBatch & b = * job . b ; 195for (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 ; 196const int64_t t = now_ns (); 197for (int64_t prev = b . t1 . load (); t > prev && ! b . t1 . compare_exchange_weak ( prev , t );) { 198} 199if ( b . left . fetch_sub ( job . i1 - job . i0 , std:: memory_order_acq_rel ) == job . i1 - job . i0 ) { // (b is the waiter's again) 200std::lock_guard < std::mutex > lk (done_mu_); 201done_cv_ . notify_all (); 202} 203} 204for (os::fd_t f : fds ) os:: close_fd ( f ); 205for (os::fd_t f : ufds ) os:: close_fd ( f ); 206} 207bool read (std::vector < os::fd_t >& fds , std::vector < os::fd_t >& ufds , uint8_t * al , const EgRead & r , 208std::vector < uint8_t >& buf ) { 209if (( r . mx8 || r . n2 == 0 ) && r . file >= 0 && (size_t) r . file < direct_ . size () && direct_ [(size_t) r . file ] && 210os:: direct_span ( r . off , r . n ) <= 2 * os:: kDirectAlign ) { 211os::fd_t & u = ufds [(size_t) r . file ]; 212if ( u == os:: kBadFd ) u = os:: open_unbuffered ( paths_ [(size_t) r . file ]); 213if ( u != os:: kBadFd && os:: pread_unbuffered ( u , al , r . n , r . off )) { 214const uint8_t * src = al + r . off % os:: kDirectAlign ; 215static const bool check = std:: getenv ( "DS4_EG_CHECK" ) != nullptr ; // (each row read buffered too) 216if ( check ) { 217std::vector < uint8_t > ref ( r . n ); 218os::fd_t & f2 = fds [(size_t) r . file ]; 219if ( f2 == os:: kBadFd ) f2 = os:: open_ro ( paths_ [(size_t) r . file ]); 220const bool ok = f2 != os:: kBadFd && os:: pread_full ( f2 , ref . data (), r . n , r . off ); 221if (! ok || std:: memcmp ( ref . data (), src , r . n ) != 0 ) ++ check_bad_ ; 222++ check_n_ ; 223} 224if (! r . mx8 ) { // (a GGUF's Q6_K / IQ4_NL row: its bytes as they are, the scales inside) 225std:: memcpy ( r . dst , src , r . n ); 226return true; 227} 228for (uint32_t k = 0 ; k < r . n / 33 ; ++ k ) { // [scale, 32 codes] -> codes | scales 229r . scales [ k ] = src [(size_t) k * 33 ]; 230std:: memcpy ( r . dst + (size_t) k * 32 , src + (size_t) k * 33 + 1 , 32 ); 231} 232return true; 233} // (else buffered, below) 234} 235auto fd = [ & ](int file ) { 236if ( file < 0 || file >= (int) fds . size ()) return os:: kBadFd ; 237if ( fds [(size_t) file ] == os:: kBadFd ) fds [(size_t) file ] = os:: open_ro ( paths_ [(size_t) file ]); 238return fds [(size_t) file ]; 239}; 240const os::fd_t f = fd ( r . file ); 241if ( f == os:: kBadFd ) return false; 242if (! r . mx8 ) { 243if (!os:: pread_full ( f , r . dst , r . n , r . off )) return false; 244if ( r . n2 == 0 ) return true; 245const os::fd_t f2 = fd ( r . file2 ); 246return f2 != os:: kBadFd && os:: pread_full ( f2 , r . scales , r . n2 , r . off2 ); 247} 248buf . resize ( r . n ); 249if (!os:: pread_full ( f , buf . data (), r . n , r . off )) return false; 250for (uint32_t k = 0 ; k < r . n / 33 ; ++ k ) { // [scale, 32 codes] -> codes | scales 251r . scales [ k ] = buf [(size_t) k * 33 ]; 252std:: memcpy ( r . dst + (size_t) k * 32 , buf . data () + (size_t) k * 33 + 1 , 32 ); 253} 254return true; 255} 256 257std::vector < std::string > paths_ ; 258std::vector < char > direct_ ; 259 260public : 261std::atomic < int64_t > check_n_ { 0 }, check_bad_ { 0 }; // (DS4_EG_CHECK: rows compared, rows that differed) 262std::vector < std::thread > th_ ; 263std::mutex mu_ ; 264std::condition_variable cv_ ; 265struct Job { 266EgBatch * b = nullptr ; 267int i0 = 0 , i1 = 0 ; // reads [i0, i1) 268}; 269std::deque < Job > q_ ; 270bool quit_ = false; 271std::mutex done_mu_ ; 272std::condition_variable done_cv_ ; 273}; 274 275} // namespace strata::ds4