okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b019a3037
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_main.cpp - maya-ds4: DeepSeek-V4.1-Flash on Maya. 4// 5// maya-ds4 --pack <model>/maya-ds4 --ids 0,128803,... --n 16 greedy tokens after the ids 6// maya-ds4 --pack ... --ids ... --dump-logits out.f32 every position's logits (the oracle's check) 7// maya-ds4 --pack ... --serve Maya's engine protocol on stdin / stdout 8// 9// --serve speaks what serve/server.py's StrataEngine expects: INFO lines, then `READY <context> stop`; per request 10// `GEN <max_new> [key=value ...] <id,id,...>` answered by `T <id>` lines and `DONE <generated> <prompt> <prompt ms> 11// <decode ms> <stop|length|cancel> 0 0 <reused> 0 0`; `STOP` ends a request early, `QUIT` the engine. A prompt that 12// continues the state (the conversation so far) reuses it; one that only shares the last prompt's start goes back to 13// that prompt's end; anything else starts over. `GENI <max_new> [keys] <file> <ids>` carries the prompt's pictures 14// (the file: see read_pics); the state is shared only where the same picture sits at the same place. With 15// STRATA_DS4_SLOT_KEEP=1 the conversations are kept when another one takes the model (a slot each: the state, the 16// compressed KV included), and across runs in STRATA_DS4_SLOT_DIR - so a request that does not continue the state but 17// does continue a kept conversation reads only its new tokens. 18// `pin=N` on a GEN marks the first N prompt tokens as a start other requests share (a system prompt and its tools): the 19// read stops there for a checkpoint, so a request behind the same start - another agent - goes back to it instead of 20// reading it again (also without slots). STRATA_DS4_REUSE=0 turns every reuse off (each request reads its whole prompt). 21#include "ds4_model.hpp" 22#include "ds4_scr_plan.hpp" 23#include "ds4_os.hpp" 24#include "ds4_packinfo.hpp" 25#include "ds4_slotmeta.hpp" 26#include "ds4_picspans.hpp" 27 28#include <algorithm> 29#include <cmath> 30#include <numeric> 31#include <atomic> 32#include <chrono> 33#include <climits> 34#include <condition_variable> 35#include <csignal> 36#include <filesystem> 37#include <memory> 38#include <cstdio> 39#include <fstream> 40#include <sstream> 41#include <cstdlib> 42#include <cstring> 43#include <deque> 44#include <iostream> 45#include <mutex> 46#include <string> 47#include <thread> 48#include <unordered_map> 49#include <vector> 50 51namespace { 52 53double now_ms () { 54return std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ().time_since_epoch ()).count (); 55} 56 57// the bytes this process had the storage read for it (Linux's /proc/self/io; -1 where there is none): the Monitor's 58// disk reads a token, the experts read in place from the model's files included 59long long io_read_bytes () { 60#ifdef __linux__ 61 std::FILE * f = std::fopen ("/proc/self/io" ,"r" ); 62if (f == nullptr )return -1 ; 63char line [128 ]; 64long long v = -1 ; 65while (std::fgets (line ,sizeof line ,f )!= nullptr ) 66if (std::sscanf (line ,"read_bytes: %lld" ,& v )== 1 )break ; 67 std::fclose (f ); 68return v ; 69#else 70return -1 ; 71#endif 72} 73 74std::vector < int > parse_ids (const std::string & s ) { 75 std::vector < int > v ; 76const char * p = s .c_str (); 77while (* p ) { 78char * e = nullptr ; 79const long x = std::strtol (p ,& e ,10 ); 80if (e == p )break ; 81v .push_back ((int )x ); 82p = e ; 83while (* p == ',' || * p == ' ' )++ p ; 84 } 85return v ; 86} 87 88void usage () { 89 std::fprintf (stderr , 90"maya-ds4 --pack <model>/maya-ds4 [--gpus 0,1,...] [--max-context N] [--reserve-mib N]\n" 91" [--vram-experts F] [--cpu-threads N] [--expert-profile FILE|none] [--ssd-cache GB] [--ssd-policy lru|lfu|lfulru] [--no-expert-cache] [--verbose]\n" 92" [--tp N] [--threads on|off] [--prefill-chunk N] [--dspark on|off|none|auto] [--dspark-block N] [--dspark-conf F] [--experts N|auto]\n" 93" [--vision on|off] [--mmap-experts on|off|auto]\n" 94" (--ids I,J,... [--images FILE] [--n N] [--dump-logits FILE] | --serve\n" 95" | --encode-image FILE.rgb --size WxH --dump-image OUT\n" 96" | --pack-info)\n" ); 97} 98 99// stdin lines on a thread, so a request can see STOP while it decodes 100struct Lines { 101 std::mutex mu ; 102 std::condition_variable cv ; 103 std::deque < std::string > q ; 104bool eof = false; 105 std::atomic < bool > stop {false}; 106void start () { 107 std::thread ([this ] { 108 std::string l ; 109while (std::getline (std::cin ,l )) { 110if (!l .empty ()&& l .back ()== '\r' )l .pop_back (); 111 std::lock_guard < std::mutex > lk (mu ); 112if (l == "STOP" || l .rfind ("STOP " ,0 )== 0 ) { 113stop .store (true); 114continue ; 115 } 116if (l == "QUIT" )stop .store (true); 117q .push_back (l ); 118cv .notify_all (); 119 } 120 std::lock_guard < std::mutex > lk (mu ); 121eof = true; 122stop .store (true); 123cv .notify_all (); 124 }).detach (); 125 } 126bool next (std::string & l ) { 127 std::unique_lock < std::mutex > lk (mu ); 128cv .wait (lk , [& ] {return !q .empty ()|| eof ; }); 129if (q .empty ())return false; 130l = q .front (); 131q .pop_front (); 132return true; 133 } 134}; 135 136// The drafts between two stats: each draft position (1st, 2nd, ..) - how often it was verified with every draft 137// before it kept, and how often it was kept then 138std::string per_position (const strata::ds4::Stats & s0 ,const strata::ds4::Stats & s1 ) { 139 std::string pp = "per position (kept / reached):" ; 140for (int i = 0 ;i < 8 ;++ i ) { 141const long long r = s1 .draft_reached [i ]- s0 .draft_reached [i ],k = s1 .draft_kept [i ]- s0 .draft_kept [i ]; 142if (r <=0 )break ; 143char b [64 ]; 144 std::snprintf (b ,sizeof b ," %d: %lld/%lld %.0f%%" ,i + 1 ,k ,r ,100.0 * (double )k / (double )r ); 145pp += b ; 146 } 147return pp ; 148} 149 150static std::FILE * g_round_log = nullptr ; 151static std::string g_round_tag ; 152static std::vector < float > g_round_conf ; 153static int g_round_nd = 0 ; 154 155// The drafts' cut on the product of their confidences (DeepInfer's cumulative rule): a draft is verified while the chance 156// that it and every draft before it are kept stays at least this - a long window whose later drafts are likely lost is 157// not verified whole. STRATA_DS4_DSPARK_CUM=F, a request's dspark_cum key; 0: off, only the floor on each draft's own 158// confidence (dspark_conf). Off by default (not measured faster on code: H100 / owner PC); Project Maya runs 0.5 (a Radeon 8065S: decode +6.5%, the same tokens) 159float dspark_cum_default () { 160static const float v = [] { 161const char * e = std::getenv ("STRATA_DS4_DSPARK_CUM" ); 162return e != nullptr ? (float ) std::atof (e ) :0.0f ; 163 }(); 164return v ; 165} 166 167// ---- suffix drafting (DS4_SUFFIX_DRAFT=K): drafts copied from the token history, no drafter model --------------------- 168// The context's last n (DS4_SUFFIX_MIN, 3) tokens looked up among their earlier occurrences; the one whose match runs 169// furthest back proposes the up to K tokens that followed it, verified by verify() like DSpark's drafts (greedy: the 170// trunk's argmax; sampled: q a point at each draft, the speculative-sampling rule - exact either way). A match shorter 171// than the floor drafts nothing; the floor rises while recent drafts are rejected, so text that does not repeat itself 172// runs plain steps. 173struct SuffixDrafter { 174int kmax = 0 ,nmin = 3 ; 175int floor_ = 3 ;// the shortest match that drafts now 176double ema = 0.5 ;// recent accepted share of the drafts offered 177 std::vector < int > h ;// the history indexed so far 178 std::unordered_map < uint64_t , std::vector < int32_t >> at ;// the n-gram ending at i -> every such i, ascending 179long long rounds = 0 ,offered = 0 ,accepted = 0 ,tried = 0 ; 180 181uint64_t key (size_t end )const {// the n-gram h[end - nmin + 1 .. end] 182uint64_t k = 1469598103934665603ull ; 183for (size_t i = end + 1 - (size_t )nmin ;i <=end ;++ i )k = (k ^ (uint64_t ) (uint32_t )h [i ])* 1099511628211ull ; 184return k ; 185 } 186// the history becomes toks + [tok]: appended to, or indexed again where it does not continue what was indexed 187void sync (const std::vector < int32_t >& toks ,int tok ) { 188const size_t n = toks .size ()+ 1 ; 189auto want = [& ](size_t i ) {return i < toks .size () ?toks [i ] :tok ; }; 190bool prefix = h .size () <=n ; 191for (size_t i = 0 ;prefix && i < h .size ();++ i )prefix = h [i ]== want (i ); 192if (!prefix ) { 193h .clear (); 194at .clear (); 195 } 196h .reserve (n ); 197for (size_t i = h .size ();i < n ;++ i ) { 198h .push_back (want (i )); 199if (i + 1 >= (size_t )nmin )at [key (i )].push_back ((int32_t )i ); 200 } 201 } 202// up to `room` drafts after the history's end; empty: no match long enough 203void propose (int room , std::vector < int >& d ) { 204d .clear (); 205const size_t n = h .size (); 206if (room <=0 || n < (size_t )nmin + 1 )return ; 207const auto it = at .find (key (n - 1 )); 208if (it == at .end ())return ; 209const std::vector < int32_t >& v = it -> second ; 210int best = -1 ,best_len = 0 ; 211int seen = 0 ; 212for (size_t j = v .size ();j -- > 0 && seen < 32 ;) {// the latest occurrences first 213const int p = v [j ]; 214if ((size_t )p >=n - 1 )continue ; 215++ seen ; 216int len = 0 ; 217while (len < 64 && (size_t )len <= (size_t )p && h [(size_t )p - len ]== h [n - 1 - len ])++ len ; 218if (len > best_len ) { 219best_len = len ; 220best = p ; 221 } 222 } 223if (best < 0 || best_len < floor_ )return ; 224// a short match proposes few: 3 tokens of prose that happened before rarely go on the same way, and a window's 225// cost grows with its rows; a copy's match is soon long 226const int k = std::min ({kmax ,room , std::max (2 ,best_len - 1 )}); 227for (size_t i = (size_t )best + 1 ;i < n && (int )d .size ()< k ;++ i )d .push_back (h [i ]); 228 } 229void record (int off ,int acc ) { 230++ rounds ; 231offered += off ; 232accepted += acc ; 233ema = 0.8 * ema + 0.2 * ((double )acc / (double ) std::max (1 ,off )); 234// a run of rejections asks longer matches of the next drafts; accepted ones bring the floor back 235floor_ = ema < 0.2 ? std::min (floor_ + 1 ,12 ) :ema > 0.5 ? std::max (nmin ,floor_ - 1 ) :floor_ ; 236 } 237}; 238// DS4_SUFFIX_DRAFT=K: on, at most K drafts a round; K=7 measured best (focalor, 5070 + CPU lane, Cache-Prior routing, 239// 128 tokens): a Python rewrite 12.8 -> 22.7 tok/s, a Go rename 12.6 -> 24.1, prose 13.1 -> 12.8 and 14.7 -> 14.7; the 240// greedy tokens the same as without on all four 241SuffixDrafter * g_suffix = nullptr ; 242 243// One round of decoding after `tok` (the token at pos(), not fed yet): with the drafter, its drafts while their 244// confidence holds (at most `room` - 1 of them), verified together; else a plain step. `out` gets the tokens that follow 245// tok (the accepted drafts, then the trunk's next), the last of them the next round's tok. 246bool round (strata::ds4::Model & m ,int tok ,int room ,bool spec ,float conf_min ,float temperature ,float top_p ,int top_k , 247float min_p ,unsigned long long seed ,unsigned long long & counter , std::vector < int >& out ,int & offered , 248int & accepted , std::string & err ,float cum_min = -1.0f ,bool suffix_ok = true) { 249out .clear (); 250offered = accepted = 0 ; 251if (spec && room > 1 && m .draft_block ()> 0 ) { 252 std::vector < int > drafts ; 253 std::vector < float > conf ; 254if (!m .draft (tok ,drafts ,conf ,err ,temperature ,top_p ,top_k ,min_p ,seed ,counter ))return false; 255g_round_conf = conf ; 256g_round_nd = (int )drafts .size (); 257int keep = 0 ; 258if (cum_min < 0 )cum_min = dspark_cum_default (); 259float cum = 1.0f ; 260while (keep < (int )drafts .size ()&& keep < room - 1 && conf [(size_t )keep ] >=conf_min && 261 (cum *=conf [(size_t )keep ]) >=cum_min ) 262++ keep ; 263if (keep > 0 ) { 264drafts .resize ((size_t )keep ); 265int acc = 0 ,next = -1 ; 266if (!m .verify (tok ,drafts ,temperature ,top_p ,top_k ,min_p ,seed ,counter ,acc ,next ,err ))return false; 267if (g_round_log != nullptr ) {// DS4_ROUND_LOG: tag, drafts offered, accepted, the confidences 268 std::fprintf (g_round_log ,"%s\t%d\t%d" ,g_round_tag .c_str (),keep ,acc ); 269for (int i = 0 ;i < keep ;++ i ) std::fprintf (g_round_log ,"\t%.4f" ,g_round_conf [(size_t )i ]); 270 std::fprintf (g_round_log ,"\n" ); 271 } 272counter += (unsigned long long )acc + 1 ; 273for (int i = 0 ;i < acc ;++ i )out .push_back (drafts [(size_t )i ]); 274out .push_back (next ); 275offered = keep ; 276accepted = acc ; 277return true; 278 } 279 } 280if (g_suffix != nullptr && suffix_ok && room > 1 && m .draft_block ()== 0 ) { 281 std::vector < int > drafts ; 282g_suffix -> sync (m .tokens (),tok ); 283g_suffix -> propose (std::min (room - 1 ,15 ),drafts ); 284if (!drafts .empty ()) { 285int acc = 0 ,next = -1 ; 286if (!m .verify (tok ,drafts ,temperature ,top_p ,top_k ,min_p ,seed ,counter ,acc ,next ,err ))return false; 287g_suffix -> record ((int )drafts .size (),acc ); 288if (g_round_log != nullptr ) 289 std::fprintf (g_round_log ,"%s\tsuffix\t%zu\t%d\n" ,g_round_tag .c_str (),drafts .size (),acc ); 290counter += (unsigned long long )acc + 1 ; 291for (int i = 0 ;i < acc ;++ i )out .push_back (drafts [(size_t )i ]); 292out .push_back (next ); 293offered = (int )drafts .size (); 294accepted = acc ; 295return true; 296 } 297++ g_suffix -> tried ; 298 } 299if (!m .step (tok , true,err ))return false; 300out .push_back (m .sample (temperature ,top_p ,top_k ,min_p ,seed ,counter ++ )); 301return true; 302} 303 304struct Req { 305long long max_new = 0 ; 306float temperature = 0.0f ,top_p = 1.0f ,min_p = 0.0f ; 307int top_k = 64 ; 308unsigned long long seed = 0 ; 309int spec = -1 ;// spec=0|1: this request drafts or not (-1: as the engine was started) 310float conf = -1.0f ;// dspark_conf=F: the drafts' confidence floor for this request (-1: the engine's) 311long long pin = 0 ;// pin=N: the first N prompt tokens are a start other requests share (a system prompt and its 312// tools): the state at N is kept as a checkpoint, so another agent behind the same start 313// goes back to it instead of reading it again 314float cum = -1.0f ;// dspark_cum=F: the cut on the product of the confidences (-1: the engine's, dspark_cum_default) 315 std::string file ;// GENI: the pictures 316 std::vector < int > ids ; 317int score = 0 ;// score=N (a test of reuse, e.g. SCR): the prompt's last N tokens read in windows of 8 with 318 std::string score_out ;// their next-token log-probabilities written to scoreout=PATH (quant_quality.py rows) 319}; 320 321namespace ps= strata::ds4::picspans; 322 323// A prompt's picture: where its span starts, its pixels (the server's resize: RGB rows, both sides multiples of the 324// patch size), a hash of them; once encoded, its span's rows 325struct Pic { 326int64_t start = 0 ; 327int width = 0 ,height = 0 ; 328uint64_t hash = 0 ; 329size_t len = 0 ;// the span (0: not known yet) 330 std::vector < uint8_t > rgb ; 331}; 332 333// GENI's file: int32 'DSI1', int32 count, then per picture int64 start, int32 width, int32 height and its 334// height x width x 3 RGB bytes, in prompt order 335bool read_pics (const std::string & path , std::vector < Pic >& v , std::string & err ) { 336 std::FILE * f = std::fopen (path .c_str (),"rb" ); 337if (f == nullptr ) { 338err = "cannot open the pictures' file " + path ; 339return false; 340 } 341char magic [4 ]= {}; 342int32_t n = 0 ; 343bool ok = std::fread (magic ,1 ,4 ,f )== 4 && std::memcmp (magic ,"DSI1" ,4 )== 0 && std::fread (& n ,4 ,1 ,f )== 1 && 344n >=0 && n <=4096 ; 345for (int i = 0 ;ok && i < n ;++ i ) { 346Pic p ; 347int32_t wh [2 ]= {}; 348ok = std::fread (& p .start ,8 ,1 ,f )== 1 && std::fread (wh ,4 ,2 ,f )== 2 && wh [0 ]> 0 && wh [1 ]> 0 && 349 (int64_t )wh [0 ]* wh [1 ] <= (64 <<20 ); 350if (!ok )break ; 351p .width = wh [0 ],p .height = wh [1 ]; 352p .rgb .resize ((size_t )p .width * p .height * 3 ); 353ok = std::fread (p .rgb .data (),1 ,p .rgb .size (),f )== p .rgb .size (); 354uint64_t h = 1469598103934665603ull ;// FNV-1a over the size and the pixels 355for (int32_t x :wh ) 356for (int b = 0 ;b < 4 ;++ b )h = (h ^ (uint8_t ) (x >> (8 * b )))* 1099511628211ull ; 357for (uint8_t b :p .rgb )h = (h ^b )* 1099511628211ull ; 358p .hash = h ; 359v .push_back (std::move (p )); 360 } 361 std::fclose (f ); 362if (!ok )err = path + ": not a pictures' file (DSI1)" ; 363return ok ; 364} 365 366// the encoded spans, the latest few (a conversation sends its pictures with every turn) 367struct SpanCache { 368 std::deque < std::pair < uint64_t , std::shared_ptr < const std::vector < uint16_t >>>> q ; 369 std::shared_ptr < const std::vector < uint16_t >> get (strata::ds4::Model & m ,const Pic & p , std::string & err ) { 370for (size_t i = 0 ;i < q .size ();++ i ) 371if (q [i ].first == p .hash ) { 372auto r = q [i ].second ; 373q .erase (q .begin ()+ (long )i ); 374q .emplace_front (p .hash ,r ); 375return r ; 376 } 377auto rows = std::make_shared < std::vector < uint16_t >> (); 378if (!m .encode_image (p .rgb .data (),p .width ,p .height ,* rows ,err ))return nullptr ; 379q .emplace_front (p .hash ,rows ); 380if (q .size ()> 8 )q .pop_back (); 381return rows ; 382 } 383}; 384 385bool parse_gen (const std::string & line ,Req & r ,bool geni ) { 386const char * p = line .c_str ()+ (geni ?5 :4 ); 387char * e = nullptr ; 388r .max_new = std::strtoll (p ,& e ,10 ); 389if (e == p )return false; 390p = e ; 391for (;;) { 392while (* p == ' ' )++ p ; 393const char * s = p ; 394while (* p && * p != ' ' )++ p ; 395if (p == s )break ; 396const std::string tok (s , (size_t ) (p - s )); 397const size_t eq = tok .find ('=' ); 398if (eq == std::string::npos && geni && r .file .empty ()) { 399r .file = tok ; 400continue ; 401 } 402if (eq == std::string::npos ) { 403r .ids = parse_ids (tok ); 404break ; 405 } 406const std::string k = tok .substr (0 ,eq ),v = tok .substr (eq + 1 ); 407if (k == "temperature" )r .temperature = std::strtof (v .c_str (),nullptr ); 408else if (k == "top_p" )r .top_p = std::strtof (v .c_str (),nullptr ); 409else if (k == "top_k" )r .top_k = std::atoi (v .c_str ()); 410else if (k == "min_p" )r .min_p = std::strtof (v .c_str (),nullptr ); 411else if (k == "seed" )r .seed = std::strtoull (v .c_str (),nullptr ,10 ); 412else if (k == "spec" )r .spec = std::atoi (v .c_str ())!= 0 ; 413else if (k == "dspark_conf" )r .conf = std::strtof (v .c_str (),nullptr ); 414else if (k == "pin" )r .pin = std::atoll (v .c_str ()); 415else if (k == "score" )r .score = std::max (0 , std::atoi (v .c_str ())); 416else if (k == "scoreout" )r .score_out = v ; 417else if (k == "dspark_cum" || k == "spec_cum" )r .cum = std::strtof (v .c_str (),nullptr ); 418 } 419return !r .ids .empty ()&& (!geni || !r .file .empty ()); 420} 421 422int serve (strata::ds4::Model & m ,const std::string & eos_list ,bool spec ,float conf_min ,const std::string & pack ) { 423 std::vector < int > eos = parse_ids (eos_list ); 424for (const std::string & l :m .info_lines ()) std::printf ("%s\n" ,l .c_str ()); 425 std::printf ("READY %lld stop\n" , (long long )m .max_context ()); 426 std::fflush (stdout ); 427 std::fprintf (stderr ,"maya ds4 serve: GEN <max_new> [keys] <ids>; GENI <max_new> [keys] <pictures> <ids>; STOP, QUIT\n" ); 428Lines in ; 429in .start (); 430 std::string line ; 431unsigned long long counter = 0 ; 432 std::vector < Pic > held ;// the pictures the state holds (start, hash, span) 433SpanCache spans ; 434const int img_tok = m .image_token (); 435// CONVERSATION SLOTS: a request that does not continue the conversation in the model first sets that one aside 436// (Model::slot_save: its window rings, the compressors' partial groups and every source's compressed KV and index 437// keys), then takes back the kept conversation this prompt does continue (slot_load) - chats, and an agent's side 438// requests, that interleave no longer re-read each other's prompts (70k and 185k tokens alternating: 75-200 s a 439// switch at ~930 tok/s). STRATA_DS4_SLOT_KEEP=1 turns them on and keeps them across runs, in STRATA_DS4_SLOT_DIR 440// (default <pack>/slots): a slot is a .bin (the state) and a .meta (this model's identity, the conversation's 441// tokens and its size), both written under a temporary name first; a slot whose .meta is missing, foreign or does 442// not match its file, or unused for STRATA_DS4_SLOT_DAYS (7) days, is removed at start. STRATA_DS4_SLOT_CAP (4) is 443// the conversations kept in RAM; past it the least recently used is written to the folder and read back from there 444// (RAM first, the folder past the cap), and the engine's end writes the ones in RAM to the folder, so the next run 445// reads on from them. STRATA_DS4_SLOT_GB (16) caps the folder's .bin files: at start, and after every write, the 446// folder's least recently used conversation is removed while they are over it (never the one just written, so a 447// conversation bigger than the cap stays). STRATA_DS4_SLOT_MIN (1024) is the shortest conversation set aside (a 448// shorter one is read again in about the time its slot would take). A conversation with pictures keeps them in a 449// .pics file (start, span, hash, size each): the matchers compare a picture's span by its hash (picspans::keyed), 450// so a prompt takes back a slot only where its tokens and its pictures agree. 451const auto env_num = [](const char * k ,double d ) {const char * v = std::getenv (k );return v ? std::atof (v ) :d ; }; 452const bool slot_keep = 453 std::getenv ("STRATA_DS4_SLOT_KEEP" )!= nullptr && std::atoi (std::getenv ("STRATA_DS4_SLOT_KEEP" ))!= 0 ; 454const bool reuse = std::getenv ("STRATA_DS4_REUSE" )== nullptr || std::atoi (std::getenv ("STRATA_DS4_REUSE" ))!= 0 ; 455const char * scr_env = std::getenv ("STRATA_DS4_SCR" ); 456const bool scr = scr_env != nullptr && std::string (scr_env )== "1" ; 457 std::vector < int64_t > scr_pads ; 458 std::vector < int64_t > state_pads ;// (the pads of the conversation in the model, as a request starts: a slot keeps them) 459// (with SCR on, a slot also holds the masters - the engine's - and the pad positions - a .pads file beside it) 460int slot_max = slot_keep ? std::max (0 , (int )env_num ("STRATA_DS4_SLOT_CAP" ,4 )) :0 ; 461const size_t slot_min = (size_t ) std::max (1.0 ,env_num ("STRATA_DS4_SLOT_MIN" ,1024 )); 462const double slot_days = env_num ("STRATA_DS4_SLOT_DAYS" ,7 ); 463const uint64_t slot_budget = (uint64_t ) (env_num ("STRATA_DS4_SLOT_GB" ,16 )* 1073741824.0 ); 464namespace fs= std::filesystem; 465 std::filesystem::path slot_dir ; 466struct Slot { 467 std::vector < int32_t > tokens ; 468 std::string path ;// empty: the state is in data (RAM) 469uint64_t bytes = 0 ,used = 0 ; 470 std::shared_ptr < std::vector < uint8_t >> data ;// the RAM slot's bytes (null: a file slot) 471 std::vector < int64_t > cks ;// the positions short of its end it can be taken back at 472 std::vector < int64_t > pads ;// SCR: the pad tokens' positions in `tokens` 473 std::vector < ps::Span > pics ;// its pictures, in `tokens`' positions 474 std::vector < int32_t > keys ;// `tokens` as the matchers see them (picspans::keyed) 475 }; 476const auto spans_of = [](const std::vector < Pic >& v ) { 477 std::vector < ps::Span > out ; 478for (const Pic & q :v )out .push_back ({q .start , (int64_t )q .len ,q .hash ,q .width ,q .height }); 479return out ; 480 }; 481const auto pics_of_spans = [](const std::vector < ps::Span >& v ,size_t below ) { 482 std::vector < Pic > out ; 483for (const ps::Span & s :v ) 484if ((size_t )s .start < below ) { 485Pic q ; 486q .start = s .start ,q .width = s .width ,q .height = s .height ,q .hash = s .hash ,q .len = (size_t )s .len ; 487out .push_back (std::move (q )); 488 } 489return out ; 490 }; 491const auto ranges_of = [](const std::vector < ps::Span >& v ) { 492 std::vector < std::pair < int64_t ,int64_t >> out ; 493for (const ps::Span & s :v )out .emplace_back (s .start ,s .len ); 494return out ; 495 }; 496 std::vector < Slot > slots ; 497uint64_t slot_clock = 0 ,slot_seq = 0 ; 498const std::string slot_identity = m .slot_identity (); 499const auto note = [& ](const std::string & msg ) { 500 std::fprintf (stderr ,"ds4 slots: %s\n" ,msg .c_str ()); 501 std::printf ("NOTE sessions: %s\n" ,msg .c_str ()); 502 std::fflush (stdout ); 503 }; 504const auto gb = [](uint64_t b ) { 505char s [32 ]; 506 std::snprintf (s ,sizeof s ,"%.2f GB" , (double )b /1e9 ); 507return std::string (s ); 508 }; 509const auto meta_of = [](const std::string & bin ) {return bin .substr (0 ,bin .size ()- 4 )+ ".meta" ; }; 510const auto pads_of = [](const std::string & bin ) {return bin .substr (0 ,bin .size ()- 4 )+ ".pads" ; }; 511const auto picf_of = [](const std::string & bin ) {return bin .substr (0 ,bin .size ()- 4 )+ ".pics" ; }; 512const auto pads_read = [& ](const std::string & bin ) { 513 std::vector < int64_t > v ; 514 std::ifstream f (pads_of (bin ), std::ios::binary ); 515int64_t x = 0 ; 516while (f .read ((char * )& x ,8 ))v .push_back (x ); 517return v ; 518 }; 519const auto meta_write = [& ](const std::string & path ,const std::vector < int32_t >& toks ,uint64_t bytes , 520const std::vector < int64_t >& cks )-> bool { 521return strata::ds4::slotmeta::write (path ,slot_identity ,toks ,bytes ,cks ); 522 }; 523// a .meta of this model -> its tokens and the slot's size (false: foreign, damaged or not this model's) 524const auto meta_read = [& ](const std::string & path , std::vector < int32_t >& toks ,uint64_t & bytes , 525 std::vector < int64_t >& cks )-> bool { 526return strata::ds4::slotmeta::read (path ,slot_identity ,m .max_context (),toks ,bytes ,cks ); 527 }; 528const auto slot_age_days = [](const std::string & p ) { 529 std::error_code ec ; 530const auto t = fs::last_write_time (p ,ec ); 531if (ec )return 1e9 ; 532return std::chrono::duration < double > (fs::file_time_type::clock::now ()- t ).count () /86400.0 ; 533 }; 534const auto slot_drop = [& ](size_t i ) { 535if (slots [i ].data )// a RAM slot: its buffer simply dies 536slots [i ].data .reset (); 537else { 538 std::error_code ec ; 539 std::filesystem::remove (slots [i ].path ,ec ); 540 std::filesystem::remove (meta_of (slots [i ].path ),ec ); 541 std::filesystem::remove (pads_of (slots [i ].path ),ec ); 542 std::filesystem::remove (picf_of (slots [i ].path ),ec ); 543 } 544slots .erase (slots .begin ()+ (long )i ); 545 }; 546const auto slot_count = [& ](int & ram ,int & disk ) { 547ram = disk = 0 ; 548for (const Slot & s :slots ) (s .data ?ram :disk )+= 1 ; 549 }; 550// the folder's conversations (their .bin; a .meta beside each is a few KB: identity and tokens) 551const auto slot_folder_bytes = [& ]() { 552uint64_t total = 0 ; 553 std::error_code ec ; 554for (const auto & de : std::filesystem::directory_iterator (slot_dir ,ec )) { 555const std::string fn = de .path ().filename ().string (); 556if (fn .rfind ("slot-" ,0 )== 0 && fn .size ()> 9 && fn .compare (fn .size ()- 4 ,4 ,".bin" )== 0 ) { 557const uint64_t bytes = (uint64_t ) std::filesystem::file_size (de .path (),ec ); 558if (!ec )total += bytes ; 559 } 560 } 561return total ; 562 }; 563// the folder over STRATA_DS4_SLOT_GB: its least recently used conversation goes first, and never `keep` (the one just 564// written), so a conversation bigger than the cap stays 565const auto slot_trim = [& ](const std::string & keep ) { 566const uint64_t before = slot_folder_bytes (); 567size_t dropped = 0 ; 568while (slot_folder_bytes ()> slot_budget ) { 569size_t lru = SIZE_MAX ; 570for (size_t i = 0 ;i < slots .size ();++ i ) 571if (!slots [i ].data && slots [i ].path != keep && (lru == SIZE_MAX || slots [i ].used < slots [lru ].used )) 572lru = i ; 573if (lru == SIZE_MAX )break ; 574slot_drop (lru ); 575++ dropped ; 576 } 577if (dropped > 0 ) { 578char msg [256 ]; 579 std::snprintf (msg ,sizeof msg ,"the folder held %s (over STRATA_DS4_SLOT_GB, %s): %zu least recently used " 580"conversation(s) removed, %s left" ,gb (before ).c_str (),gb (slot_budget ).c_str (),dropped , 581gb (slot_folder_bytes ()).c_str ()); 582note (msg ); 583 } 584 }; 585// a RAM slot into the folder (its bytes, then its .meta); false: not written (its bytes go, then) 586const auto slot_write_file = [& ](Slot & s )-> bool { 587 std::error_code ec ; 588const auto space = std::filesystem::space (slot_dir ,ec ); 589if (!ec && space .available < ((uint64_t )8 <<30 )) {// (8 GB free, the GLM engine's guard) 590 std::fprintf (stderr ,"ds4 slots: under 8 GB free in %s - the conversation is not written\n" , 591slot_dir .string ().c_str ()); 592return false; 593 } 594const auto stamp = std::chrono::duration_cast < std::chrono::milliseconds > ( 595 std::chrono::system_clock::now ().time_since_epoch ()).count (); 596const std::string path = 597 (slot_dir / ("slot-" + std::to_string (stamp )+ "-" + std::to_string (++ slot_seq )+ ".bin" )).string (); 598 { 599 std::ofstream f (path + ".tmp" , std::ios::binary | std::ios::trunc ); 600f .write ((const char * )s .data -> data (), (std::streamsize )s .data -> size ()); 601f .flush (); 602if (!f ) { 603 std::filesystem::remove (path + ".tmp" ,ec ); 604 std::fprintf (stderr ,"ds4 slots: writing %s.tmp failed (disk full?)\n" ,path .c_str ()); 605return false; 606 } 607 } 608if (!s .pads .empty ()) {// (before the .meta: a slot whose .meta is there has its pads) 609 std::ofstream pf (pads_of (path ), std::ios::binary | std::ios::trunc ); 610pf .write ((const char * )s .pads .data (), (std::streamsize ) (s .pads .size ()* 8 )); 611 } 612const bool pics_ok = s .pics .empty ()|| ps::write (picf_of (path ),s .pics );// (also before the .meta) 613 fs::rename (path + ".tmp" ,path ,ec ); 614if (ec || !pics_ok || !meta_write (meta_of (path ),s .tokens ,s .data -> size (),s .cks )) { 615 std::filesystem::remove (pads_of (path ),ec ); 616 std::filesystem::remove (picf_of (path ),ec ); 617 std::filesystem::remove (path + ".tmp" ,ec ); 618 std::filesystem::remove (path ,ec ); 619 std::fprintf (stderr ,"ds4 slots: writing %s failed\n" ,path .c_str ()); 620return false; 621 } 622s .path = path ; 623s .bytes = s .data -> size (); 624s .data .reset (); 625slot_trim (path );// (the folder over its cap: the least recently used conversation goes, not this one) 626return true; 627 }; 628// the conversation in the model into a slot (the state is lost otherwise: another one takes the model) 629const auto slot_put = [& ](const char * why ) { 630if (slot_max <=0 )return ; 631const std::vector < int32_t >& t = m .tokens (); 632if (t .size ()< slot_min )return ;// (a fresh engine's 0-token state is no conversation: nothing to set aside) 633const auto t0 = std::chrono::steady_clock::now (); 634auto buf = std::make_shared < std::vector < uint8_t >> (); 635 std::string e ; 636const uint64_t bytes = m .slot_save (* buf ,e );// (a state unchanged since it was taken refuses here: nothing 637if (bytes == 0 ) {// changes, its slot stays) 638if (e != "it is already set aside" ) 639 std::fprintf (stderr ,"ds4 slots: setting the conversation aside failed (%s) - it is read from token 0 " 640"when it comes back\n" ,e .c_str ()); 641return ; 642 } 643 std::vector < ps::Span > pics = spans_of (held ); 644 std::vector < int32_t > keys = ps::keyed (t ,pics ); 645for (size_t i = slots .size ();i -- > 0 ;)// an earlier state of this conversation is superseded 646if (slots [i ].keys .size () <=keys .size ()&& std::equal (slots [i ].keys .begin (),slots [i ].keys .end (),keys .begin ())) 647slot_drop (i ); 648slots .push_back ({t ,"" ,bytes ,++ slot_clock ,nullptr ,m .check_positions (),scr ?state_pads : std::vector < int64_t > {}, 649 std::move (pics ), std::move (keys )}); 650slots .back ().data = buf ; 651while (true) {// past the cap: the least recently used conversation in RAM to the folder, or gone 652int ram = 0 ,disk = 0 ; 653slot_count (ram ,disk ); 654if (ram <=slot_max )break ; 655size_t lru = SIZE_MAX ; 656for (size_t i = 0 ;i < slots .size ();++ i ) 657if (slots [i ].data && (lru == SIZE_MAX || slots [i ].used < slots [lru ].used ))lru = i ; 658if (lru == SIZE_MAX )break ; 659if (!slot_write_file (slots [lru ]))slot_drop (lru ); 660 } 661int ram = 0 ,disk = 0 ; 662slot_count (ram ,disk ); 663char msg [256 ]; 664 std::snprintf (msg ,sizeof msg ,"saved a %zu-token conversation%s%s (%s in RAM in %.1f s); %d in RAM, %d in %s" , 665t .size (),held .empty () ?"" : (" with " + std::to_string (held .size ())+ " picture(s)" ).c_str (),why ,gb (bytes ).c_str (), 666 std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (),ram ,disk , 667slot_dir .string ().c_str ()); 668note (msg ); 669 }; 670// kept conversation i back in the model, whole (false: e says why; the model is reset if the load broke off) 671const auto slot_bring = [& ](size_t i , std::string & e )-> bool { 672const int64_t n = (int64_t )slots [i ].tokens .size (); 673const auto marked = [& ](bool ok ) {// (the state's pictures: no Engram n-grams over them) 674if (ok && !slots [i ].pics .empty ())m .mark_images (ranges_of (slots [i ].pics )); 675return ok ; 676 }; 677if (slots [i ].data )return marked (m .slot_load (slots [i ].data -> data (),slots [i ].data -> size (),n ,e )); 678 std::ifstream f (slots [i ].path , std::ios::binary ); 679if (!f ) { 680e = "cannot read " + slots [i ].path ; 681return false; 682 } 683f .seekg (0 , std::ios::end ); 684const std::streamoff sz = f .tellg (); 685f .seekg (0 , std::ios::beg ); 686if (sz <=0 ) { 687e = slots [i ].path + " is empty" ; 688return false; 689 } 690 std::vector < uint8_t > file ((size_t )sz ); 691if (!f .read ((char * )file .data (),sz )) { 692e = "reading " + slots [i ].path + " failed" ; 693return false; 694 } 695return marked (m .slot_load (file .data (),file .size (),n ,e )); 696 }; 697// the kept conversation this prompt shares the most of - past `floor` tokens, what the model itself can go back 698// to - back in the model: the tokens it covers (0: none). A conversation the prompt continues whole comes back 699// whole (`whole`); one it leaves part way - a retried prompt, a history the client renders again without the 700// earlier reasoning - comes back at its latest checkpoint the prompt still agrees with (the end of a prompt, the 701// position before it, the anchor where its run of continued prompts began). 702const auto slot_take = [& ](const std::vector < int >& prompt ,size_t floor ,bool & whole )-> size_t { 703whole = false; 704if (slot_max <=0 || prompt .size ()< 2 )return 0 ; 705 std::vector < strata::ds4::slotmeta::Cand > cands ; 706for (const Slot & sl :slots )cands .push_back ({& sl .keys ,& sl .cks }); 707size_t len = 0 ; 708const size_t best = strata::ds4::slotmeta::pick (cands ,prompt ,floor ,& len ); 709if (best == SIZE_MAX )return 0 ; 710const size_t whole_len = slots [best ].tokens .size (); 711const auto t0 = std::chrono::steady_clock::now (); 712const bool ram = slots [best ].data != nullptr ; 713 std::string e ; 714if (!slot_bring (best ,e )) { 715note ("taking a conversation back failed (" + (e .empty () ? std::string ("it did not load" ) :e )+ 716") - reading its prompt again" ); 717slot_drop (best ); 718return 0 ; 719 } 720if (len < whole_len && !(m .restore ((int64_t )len )&& (size_t )m .pos ()== len )) { 721note ("going back to token " + std::to_string (len )+ " of a kept conversation failed - reading its prompt again" ); 722m .reset (); 723return 0 ; 724 } 725whole = len == whole_len ; 726held = pics_of_spans (slots [best ].pics ,len ); 727slots [best ].used = ++ slot_clock ; 728if (!ram ) {// its age counts from its last use (a file slot's only) 729 std::error_code ec ; 730 fs::last_write_time (meta_of (slots [best ].path ), fs::file_time_type::clock::now (),ec ); 731 } 732char msg [256 ]; 733 std::string part ; 734if (!whole )part = " at token " + std::to_string (len )+ " of " + std::to_string (whole_len ); 735 std::snprintf (msg ,sizeof msg ,"took back a %zu-token conversation%s from %s (%.1f s); %zu new tokens to read" , 736len ,part .c_str (),ram ?"RAM" :"the folder" , 737 std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (), 738prompt .size ()- len ); 739note (msg ); 740return len ; 741 }; 742if (slot_max > 0 ) { 743slot_dir = std::getenv ("STRATA_DS4_SLOT_DIR" ) ? std::filesystem::path (std::getenv ("STRATA_DS4_SLOT_DIR" )) 744 : std::filesystem::path (pack ) /"slots" ; 745 std::error_code ec ; 746 std::filesystem::create_directories (slot_dir ,ec ); 747if (!std::filesystem::is_directory (slot_dir ,ec )) { 748 std::fprintf (stderr ,"ds4 slots: %s is not writable - conversations are not set aside\n" , 749slot_dir .string ().c_str ()); 750slot_max = 0 ; 751 }else { 752struct Found { 753 std::string bin ; 754 std::vector < int32_t > toks ; 755uint64_t bytes ; 756 std::vector < int64_t > cks ; 757 fs::file_time_type t ; 758 std::vector < ps::Span > pics ; 759 }; 760 std::vector < Found > found ; 761size_t refused = 0 ; 762for (const auto & de : std::filesystem::directory_iterator (slot_dir ,ec )) {// a previous run's slots 763const std::string fn = de .path ().filename ().string (),p = de .path ().string (); 764if (fn .rfind ("slot-" ,0 )!= 0 )continue ; 765const bool is_bin = fn .size ()> 9 && fn .compare (fn .size ()- 4 ,4 ,".bin" )== 0 ; 766const bool is_meta = fn .size ()> 10 && fn .compare (fn .size ()- 5 ,5 ,".meta" )== 0 ; 767const bool is_pads = fn .size ()> 10 && fn .compare (fn .size ()- 5 ,5 ,".pads" )== 0 ; 768if (is_pads || (fn .size ()> 10 && fn .compare (fn .size ()- 5 ,5 ,".pics" )== 0 )) {// (kept with its .bin; one without goes) 769if (!fs::exists (p .substr (0 ,p .size ()- 5 )+ ".bin" ,ec )) std::filesystem::remove (de .path (),ec ); 770continue ; 771 } 772if (!is_bin && !is_meta ) {// a .tmp an interrupted write left 773 std::filesystem::remove (de .path (),ec ); 774continue ; 775 } 776if (!is_meta )continue ;// a .bin is judged by its .meta 777const std::string bin = p .substr (0 ,p .size ()- 5 )+ ".bin" ; 778Found fd {bin , {},0 , {}, fs::last_write_time (de .path (),ec ), {}}; 779const uint64_t have = fs::exists (bin ,ec ) ? (uint64_t ) fs::file_size (bin ,ec ) :0 ; 780if (meta_read (p ,fd .toks ,fd .bytes ,fd .cks )&& have == fd .bytes && fd .bytes > 0 && slot_age_days (p ) <=slot_days && 781 ps::read (picf_of (bin ), (int64_t )fd .toks .size (),fd .pics )) 782found .push_back (std::move (fd )); 783else { 784++ refused ; 785 std::filesystem::remove (p ,ec ); 786 std::filesystem::remove (bin ,ec ); 787 std::filesystem::remove (picf_of (bin ),ec ); 788 } 789 } 790for (const auto & de : std::filesystem::directory_iterator (slot_dir ,ec )) {// a .bin without its .meta 791const std::string p = de .path ().string (),fn = de .path ().filename ().string (); 792if (fn .rfind ("slot-" ,0 )== 0 && fn .size ()> 9 && fn .compare (fn .size ()- 4 ,4 ,".bin" )== 0 && 793 !fs::exists (meta_of (p ),ec )) 794 std::filesystem::remove (de .path (),ec ); 795 } 796 std::sort (found .begin (),found .end (), [](const Found & a ,const Found & b ) {return a .t < b .t ; }); 797uint64_t total = 0 ; 798for (auto & fd :found ) { 799total += fd .bytes ; 800 std::vector < int32_t > keys = ps::keyed (fd .toks ,fd .pics ); 801slots .push_back ({std::move (fd .toks ),fd .bin ,fd .bytes ,++ slot_clock ,nullptr , std::move (fd .cks ),pads_read (fd .bin ), 802 std::move (fd .pics ), std::move (keys )}); 803 } 804 std::string msg = "folder " + slot_dir .string ()+ ": " + std::to_string (slots .size ())+ 805" conversation(s) kept from earlier runs (" + gb (total )+ ")" ; 806if (refused )msg += ", " + std::to_string (refused )+ " not this model's or incomplete - removed" ; 807note (msg ); 808slot_trim ("" );// (the folder over STRATA_DS4_SLOT_GB: the least recently used conversation goes first) 809 } 810 } 811if (slot_max > 0 ) { 812#if !defined(_WIN32 ) 813// (the server ends the engine with QUIT and waits for it; a SIGTERM to the whole process group - systemd 814// stopping a service, a supervisor killing the server's group - must not end it mid-write, and a server that 815// is already gone must not end it with SIGPIPE when it writes its last lines) 816 std::signal (SIGTERM ,SIG_IGN ); 817 std::signal (SIGINT ,SIG_IGN ); 818 std::signal (SIGPIPE ,SIG_IGN ); 819#endif 820 } 821while (in .next (line )) { 822if (line == "QUIT" )break ; 823const bool geni = line .rfind ("GENI " ,0 )== 0 ; 824if (!geni && line .rfind ("GEN " ,0 )!= 0 ) { 825 std::printf ("ERR unsupported command '%s' (GEN, GENI, STOP and QUIT)\n" ,line .substr (0 ,line .find (' ' )).c_str ()); 826 std::fflush (stdout ); 827continue ; 828 } 829in .stop .store (false); 830Req r ; 831if (!parse_gen (line ,r ,geni )) { 832 std::printf ("ERR expected: GEN <max_new> [keys] <id,id,...> or GENI <max_new> [keys] <file> <id,id,...>\n" ); 833 std::fflush (stdout ); 834continue ; 835 } 836const double t0 = now_ms (); 837 std::vector < Pic > pics ; 838 { 839 std::string e ; 840if (geni && img_tok < 0 )e = "this engine has no vision tower, so it cannot read pictures" ; 841else if (geni && read_pics (r .file ,pics ,e )) 842for (const Pic & q :pics ) 843if (q .start < 0 || (size_t )q .start >=r .ids .size ()|| r .ids [(size_t )q .start ]!= img_tok ) 844e = "a picture's span does not start at an image token of the prompt" ; 845if (!e .empty ()) { 846 std::printf ("ERR %s\n" ,e .c_str ()); 847 std::printf ("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n" ,r .ids .size ()); 848 std::fflush (stdout ); 849continue ; 850 } 851 } 852 {// each picture's span (the run of image tokens at its start): the matchers key it by the picture's hash 853 std::vector < ps::Span > sp = spans_of (pics ); 854 ps::measure (r .ids ,img_tok ,sp ); 855for (size_t k = 0 ;k < pics .size ();++ k )pics [k ].len = (size_t )sp [k ].len ; 856 } 857if (!reuse ) {// (STRATA_DS4_REUSE=0, for A/Bs and tests: every request is a fresh read of its whole prompt) 858m .reset (); 859held .clear (); 860 } 861state_pads = scr_pads ; 862// SCR with kept conversations (Bonsai's way): the cached prompt this one reuses most - the model's, or a kept 863// one's - is the one it is planned against; a kept one that reuses more (by more than a junction's worth) is 864// brought back whole first, and the conversation in the model set aside 865// (pictures: the prompt and every conversation as the matchers see them, a span keyed by its picture's hash) 866 std::vector < int > pkey ; 867 { 868const std::vector < int32_t > k = ps::keyed (r .ids ,spans_of (pics )); 869pkey .assign (k .begin (),k .end ()); 870 } 871if (scr && reuse && slot_max > 0 && r .ids .size ()> 2 ) { 872const auto reuse_of = [& ](const std::vector < int32_t >& t ,const std::vector < int64_t >& pads )-> int64_t { 873 std::vector < int > phys ; 874 (void ) strata::core::scr_carry (pkey ,t ,pads ,201 ,phys ); 875size_t c0 = 0 ; 876while (c0 < t .size ()&& c0 < phys .size ()&& t [c0 ]== phys [c0 ])++ c0 ; 877int64_t n = (int64_t )c0 ; 878for (const auto & run : strata::ds4::scr_plan (t ,phys ).runs ) 879if (run .at >= (int64_t )c0 )n += run .n ; 880return n ; 881 }; 882const int64_t live = m .tokens ().empty () ?0 :reuse_of (ps::keyed (m .tokens (),spans_of (held )),scr_pads ); 883// (the prompt keeps under half of the model's conversation: another conversation - that one is set aside 884// before SCR moves a little of it; an edit of the same one keeps most of it and is not) 885const bool other = 2 * live < (int64_t )m .tokens ().size (); 886if (other )slot_put (" (SCR: another conversation)" ); 887size_t best = SIZE_MAX ; 888int64_t best_n = live + 512 ; 889for (size_t i = 0 ;i < slots .size ();++ i ) { 890const int64_t n = reuse_of (slots [i ].keys ,slots [i ].pads ); 891if (n > best_n )best = i ,best_n = n ; 892 } 893if (best != SIZE_MAX ) { 894const double tb = now_ms (); 895const std::vector < int32_t > want = slots [best ].keys ; 896if (!other && !m .tokens ().empty ())slot_put (" (SCR: a kept conversation reuses more of the prompt)" ); 897size_t k = SIZE_MAX ;// (slot_put may have dropped or moved slots) 898for (size_t i = 0 ;i < slots .size ()&& k == SIZE_MAX ;++ i ) 899if (slots [i ].keys == want )k = i ; 900 std::string e ; 901if (k != SIZE_MAX && slot_bring (k ,e )) { 902scr_pads = slots [k ].pads ; 903state_pads = scr_pads ; 904held = pics_of_spans (slots [k ].pics ,SIZE_MAX ); 905slots [k ].used = ++ slot_clock ; 906char msg [256 ]; 907 std::snprintf (msg ,sizeof msg ,"SCR: took back a %zu-token conversation (%.1f s): it reuses %lld of the " 908"prompt, the model's %lld" ,want .size (), (now_ms ()- tb ) /1000.0 , (long long )best_n , 909 (long long )live ); 910note (msg ); 911 }else { 912if (k != SIZE_MAX ) { 913note ("SCR: taking a conversation back failed (" + e + ") - reading its prompt again" ); 914slot_drop (k ); 915 } 916m .reset (); 917held .clear (); 918scr_pads .clear (); 919state_pads .clear (); 920 } 921 } 922 } 923// the state's tokens as the matchers see them: the same tokens with another picture (or none) do not share the 924// state from that picture's span on 925 std::vector < int32_t > skey = ps::keyed (m .tokens (),spans_of (held )); 926if (scr ) {// (the pads an earlier splice read, put back: the prompt's pictures move with them) 927 std::vector < int > physical ; 928scr_pads = strata::core::scr_carry (pkey ,skey ,scr_pads ,201 ,physical ); 929if (!scr_pads .empty ()) { 930const std::vector < int64_t > map = ps::insert_map (r .ids .size (),scr_pads ); 931for (Pic & q :pics )q .start = map [(size_t )q .start ]; 932pkey .swap (physical ); 933r .ids .assign (pkey .begin (),pkey .end ()); 934for (int & id :r .ids )if (id < 0 )id = img_tok ; 935 } 936 } 937const auto & st = m .tokens (); 938const size_t n_state = st .size (); 939size_t c = 0 ; 940while (c < n_state && c < r .ids .size ()&& skey [c ]== pkey [c ])++ c ; 941size_t from = 0 ; 942bool took = false,continued = false;// (continued: the conversation goes on - its anchor stays) 943// the conversation continues, reused in place - a conversation has to be in the model first: a fresh engine 944// (the start of a run, so every restart) holds 0 tokens, and every prompt "continues" that to token 0; taken 945// as a continuation, the take below would never run for the folder's conversations, the case they are for 946bool spliced = false; 947int64_t scr_cached = 0 ,scr_moved = 0 ;// (an SCR request's prompt: kept exactly, moved; the rest is read) 948if (scr && reuse && c < n_state && r .ids .size ()> 2 ) { 949// (score=N: the scored tokens are read fresh after the plan's prompt, never moved) 950const size_t sn = std::min < size_t > ((size_t )r .score ,r .ids .size ()- 2 ); 951const std::vector < int > head (pkey .begin (),pkey .end ()- (long )sn ); 952auto plan = strata::ds4::scr_plan (skey ,head ); 953static const int64_t band = std::max < int64_t > (2 ,env_num ("DS4_SCR_BAND" ,128 )) /2 * 2 ; 954static const int64_t exact_max = (int64_t )env_num ("DS4_SCR_EXACT_MAX" ,8192 ); 955// (no moved run, but a long shared start the model holds no checkpoint near - another agent behind the same 956// system prompt: the start is kept and joined like a run's end, with a junction band) 957const bool start_only = plan .empty ()&& plan .n_prefix >= std::max < int64_t > (256 ,band + 2 )&& 958plan .n_prefix - std::max < int64_t > (0 ,m .restorable (plan .n_prefix ))> exact_max ; 959if (start_only )plan .restore = plan .n_prefix /2 * 2 ; 960// (pictures: a run moves a picture's span whole or leaves it to be read, never half of it) 961if (!pics .empty ()) ps::whole_spans (plan ,spans_of (pics ),band , std::max < int64_t > (256 ,band + 2 )); 962if (!plan .empty ()|| start_only ) { 963auto pkeys = strata::core::scr_padded (head ,plan ,201 );// (as the matchers see it) 964pkeys .insert (pkeys .end (),pkey .end ()- (long )sn ,pkey .end ()); 965 std::vector < int > physical = pkeys ; 966for (int & id :physical )if (id < 0 )id = img_tok ; 967bool fits = (int64_t )physical .size ()+ std::max (0LL ,r .max_new ) <=m .max_context ()&& 968 std::all_of (physical .begin (),physical .end (), [& ](int id ) {return id >=0 && id < m .vocab (); }); 969 std::vector < strata::ds4::Model ::ScrMove > moves ; 970for (const auto & run :plan .runs ) { 971fits = fits && run .n >= std::max < int64_t > (256 ,band + 2 )&& run .old_start >=0 && run .at >=plan .restore && 972run .old_start + run .n <= (int64_t )st .size ()&& 973run .at + run .n + 2 <= (int64_t )physical .size ()&& 974 ((run .at |run .old_start |run .n )& 1 )== 0 && 975 std::equal (skey .begin ()+ run .old_start ,skey .begin ()+ run .old_start + run .n , 976pkeys .begin ()+ run .at ); 977moves .push_back ({run .old_start ,run .at ,run .n }); 978 } 979// the pictures where the padded prompt has them; the ones this splice reads (not in the exact prefix 980// it goes back to, nor in a run's kept part) are encoded and in place before anything moves 981 std::vector < Pic > pphys = pics ; 982 { 983const std::vector < int64_t > map = ps::insert_map (r .ids .size (), strata::core::scr_pad_positions (plan )); 984for (Pic & q :pphys )q .start = map [(size_t )q .start ]; 985 } 986const std::vector < std::pair < int64_t ,int64_t >> pranges = ranges_of (spans_of (pphys )); 987if (fits && !pphys .empty ()) { 988const int64_t p0 = plan .restore ,rs = m .restorable (p0 ); 989const int64_t lo = rs >=0 && p0 - rs <=exact_max ?rs : std::max < int64_t > (0 ,p0 - band ); 990 std::vector < strata::ds4::Image > imgs ; 991 std::string ie ; 992for (const Pic & q :pphys ) { 993const int64_t s = q .start ,e = q .start + (int64_t )q .len ; 994bool kept = e <=lo ; 995for (const auto & run :plan .runs )kept = kept || (s >=run .at && e <=run .at + run .n - band ); 996if (kept )continue ; 997 std::shared_ptr < const std::vector < uint16_t >> rows = spans .get (m ,q ,ie ); 998if (!rows || rows -> size () / (size_t )m .dim ()!= q .len ) { 999fits = false;// (the read below meets it again, and says why) 1000break ; 1001 } 1002imgs .push_back ({q .start ,rows }); 1003 } 1004if (fits )m .set_images (std::move (imgs )); 1005 } 1006 std::string se ; 1007const double tr0 = now_ms (); 1008int moved = !fits ?0 :moves .empty () ?1 :m .scr_relocate (moves ,se ); 1009 std::string seg_ms = "relocate " + std::to_string ((int ) (now_ms ()- tr0 ))+ " ms" ; 1010if (moved == 0 )m .set_images ({}); 1011// (an SCR jump takes the tokens back without their rows: the pictures among them are marked again) 1012const auto jump = [& ](int64_t at ) { 1013const bool ok = m .scr_jump (physical ,at ,se ,plan .n_prefix ); 1014if (ok && !pranges .empty ())m .mark_images (pranges ); 1015return ok ; 1016 }; 1017if (moved != 0 ) { 1018bool good = moved > 0 ; 1019// the exact prefix: back to a checkpoint at or before its end when one is near enough (read on 1020// exactly from there), else a junction band at its end 1021const int64_t p0 = plan .restore ,rs = m .restorable (p0 ); 1022int64_t cur = 0 ; 1023if (good && rs >=0 && p0 - rs <=exact_max && m .restore (p0 ))cur = m .pos (); 1024else if (good ) { 1025cur = p0 >=band ?p0 - band :0 ; 1026good = jump (cur ); 1027 } 1028scr_cached = cur ; 1029seg_ms += ", prefix " + std::to_string ((int ) (now_ms ()- tr0 ))+ " ms" ; 1030auto read_to = [& ](int64_t to ) {// (in the engine's feed units) 1031const double ts = now_ms (); 1032const int64_t c0 = cur ; 1033while (good && cur < to ) { 1034int64_t n = std::min < int64_t > (m .feed_unit (),to - cur ); 1035if (r .pin > cur && r .pin < cur + n )n = r .pin - cur ;// (pin=N: its checkpoint on the way) 1036good = m .feed (physical .data ()+ cur , (int )n ,0 ,se ); 1037cur += n ; 1038if (good && cur == r .pin )m .checkpoint (3 ); 1039 } 1040if (to > c0 )seg_ms += ", read " + std::to_string (to - c0 )+ " in " + std::to_string ((int ) (now_ms ()- ts ))+ " ms" ; 1041 }; 1042for (const auto & run :plan .runs ) { 1043read_to (run .at ); 1044const int64_t at = run .at + run .n - band ; 1045if (good )good = jump (at ); 1046cur = at ; 1047scr_moved += run .n - band ; 1048 } 1049if (!good ) { 1050m .reset (); 1051m .set_images ({}); 1052held .clear (); 1053scr_pads .clear (); 1054 std::printf ("ERR SCR splice failed: %s\n" ,se .c_str ()); 1055 std::printf ("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n" ,r .ids .size ()); 1056 std::fflush (stdout ); 1057continue ; 1058 } 1059auto inserted = strata::core::scr_pad_positions (plan ); 1060// Existing pad positions shift when new pads are inserted before them. 1061for (auto & at :scr_pads ) { 1062const int64_t original = at ; 1063for (const auto & run :plan .runs )if (run .new_start <=original )at += run .pad ; 1064 } 1065scr_pads .insert (scr_pads .end (),inserted .begin (),inserted .end ()); 1066 std::sort (scr_pads .begin (),scr_pads .end ()); 1067r .ids .swap (physical ); 1068pkey .swap (pkeys ); 1069for (size_t k = 0 ;k < pics .size ();++ k )pics [k ].start = pphys [k ].start ; 1070from = (size_t )m .pos (); 1071spliced = true; 1072 std::fprintf (stderr ,"ds4 SCR: %s; prompt %zu = cached %lld + scr %lld + prefilled %lld; %zu junctions (band %lld); %s\n" , 1073plan .str ().c_str (),r .ids .size (), (long long )scr_cached , (long long )scr_moved , 1074 (long long )r .ids .size ()- scr_cached - scr_moved ,plan .runs .size (), (long long )band ,seg_ms .c_str ()); 1075 } 1076 } 1077 } 1078if (spliced ) { 1079continued = false; 1080 }else if ((n_state > 0 || slot_max <=0 )&& c == n_state && n_state < r .ids .size ()) {// (slots off: as before) 1081from = n_state ; 1082continued = true; 1083 } 1084else { 1085// CONVERSATION SLOTS: this prompt does not continue the conversation in the model - that one is set aside 1086// first (another one takes the model, and its state is lost otherwise), then the kept conversation this 1087// prompt does continue is taken back - if it goes further back than the checkpoints the state itself holds 1088slot_put ("" ); 1089const int64_t limit = (int64_t ) std::min (c ,r .ids .size ()- 1 ); 1090const int64_t rs = m .restorable (limit ); 1091bool whole = false; 1092// (SCR: the kept conversations were weighed above, by what SCR reuses) 1093const size_t back = !scr ?slot_take (pkey ,rs > 0 ? (size_t )rs :0 ,whole ) :0 ; 1094if (back > 0 ) { 1095from = back ; 1096took = true; 1097continued = whole ; 1098 }else if (rs >=0 && m .restore (limit )) 1099from = (size_t )m .pos (); 1100else m .reset (); 1101 } 1102if (!took && from == 0 )held .clear ();// (a slot taken back brings its pictures: slot_take) 1103if ((int64_t )r .ids .size ()+ std::max (0LL ,r .max_new )> m .max_context ()) { 1104 std::printf ("ERR the prompt (%zu tokens) and max_new %lld are more than the context %lld\n" ,r .ids .size (), 1105r .max_new , (long long )m .max_context ()); 1106 std::fflush (stdout ); 1107continue ; 1108 } 1109 std::string err ; 1110bool ok = true; 1111// the pictures whose spans the prompt reads (the rest the state holds): encoded (or the cache's), checked 1112if (!pics .empty ()) { 1113 std::vector < strata::ds4::Image > imgs ; 1114const double te = now_ms (); 1115int encoded = 0 ; 1116for (Pic & q :pics ) { 1117for (const Pic & x :held ) 1118if (x .start == q .start && x .hash == q .hash )q .len = x .len ; 1119if (q .len > 0 && (size_t )q .start + q .len <=from )continue ; 1120 std::shared_ptr < const std::vector < uint16_t >> rows = spans .get (m ,q ,err ); 1121if (!rows ) { 1122ok = false; 1123break ; 1124 } 1125++ encoded ; 1126q .len = rows -> size () / (size_t )m .dim (); 1127bool fits = (size_t )q .start + q .len <=r .ids .size ()- 1 ; 1128for (size_t i = 0 ;fits && i < q .len ;++ i )fits = r .ids [(size_t )q .start + i ]== img_tok ; 1129if (!fits ) { 1130err = "a picture's span (" + std::to_string (q .len )+ " tokens at " + std::to_string (q .start )+ 1131") is not a run of image tokens in the prompt" ; 1132ok = false; 1133break ; 1134 } 1135imgs .push_back ({q .start ,rows }); 1136 } 1137if (ok ) { 1138m .set_images (std::move (imgs )); 1139 std::fprintf (stderr ,"maya ds4 serve: %zu pictures, %d read (%.0f ms)\n" ,pics .size (),encoded , 1140now_ms ()- te ); 1141 } 1142for (Pic & q :pics )q .rgb = {};// (only the start, hash and span stay) 1143 } 1144// the prompt in windows (PP <read> <total> <ms> <tok/s> <reuse> every 64 tokens), a checkpoint before its last 1145// token and one after it: the next turn re-renders this one, and shares its start up to one of them 1146const size_t n_score = std::min < size_t > ((size_t )r .score ,r .ids .size ()> from + 2 ?r .ids .size ()- from - 2 :0 ); 1147const size_t total = r .ids .size ()- n_score ;// (score=N: the last N read after, in windows of 8) 1148size_t done = from ,next_pp = from + 64 ; 1149m .set_progress ([& ](int64_t d ) {// (a run of chunks: each one through every layer) 1150const double ms = now_ms ()- t0 ; 1151 std::printf ("PP %zu %zu %.1f %.1f %zu\n" ,done + (size_t )d ,r .ids .size (),ms , 1152ms > 0 ?1000.0 * (double ) (done + (size_t )d - from ) /ms :0.0 ,from ); 1153 std::fflush (stdout ); 1154 }); 1155// (DS4_LAST_WINDOW=1: the last token in a window of its own after the checkpoint, as before - for A/B runs) 1156static const bool last_window = std::getenv ("DS4_LAST_WINDOW" )!= nullptr ; 1157// (pin=N: the read stops at N for a checkpoint of the shared start; only when this read crosses N, and N leaves 1158// the prompt's last token to the usual end) 1159const size_t pin_at = (r .pin >=256 && (size_t )r .pin + 1 < total ) ? (size_t )r .pin :0 ; 1160// a STOP while the prompt is read ends it there (the engine's run of chunks at a layer or chunk, windows between 1161// feeds) and goes back to the state before this prompt - kept here first, in checkpoint 1, which the prompt's 1162// own end overwrites as before - so the next request still shares the conversation up to it 1163if (from > 0 && from < total )m .checkpoint (1 ); 1164m .set_cancel ([& in ] {return in .stop .load (); }); 1165bool stopped = false; 1166while (ok && done < total ) { 1167if (in .stop .load ()) { 1168stopped = true; 1169break ; 1170 } 1171size_t n = std::min < size_t > ((size_t )m .feed_unit (),total - done ); 1172if (pin_at > done && pin_at < done + n )n = pin_at - done ; 1173// (the prompt's end: the last token in the same run, the checkpoint before it kept on the way) 1174const bool fin = done + n == total ; 1175if (fin && last_window ) { 1176ok = (n < 2 || m .feed (r .ids .data ()+ done , (int )n - 1 ,0 ,err )); 1177if (ok )m .checkpoint (1 ); 1178ok = ok && m .feed (r .ids .data ()+ done + n - 1 ,1 ,1 ,err ); 1179 }else 1180ok = fin ?m .feed_mark (r .ids .data ()+ done , (int )n ,1 ,1 ,err ) 1181 :m .feed (r .ids .data ()+ done , (int )n ,0 ,err ); 1182done += n ; 1183if (ok && pin_at != 0 && done == pin_at )m .checkpoint (3 ); 1184if (ok && (done >=next_pp || done == total )) { 1185const double ms = now_ms ()- t0 ; 1186 std::printf ("PP %zu %zu %.1f %.1f %zu\n" ,done ,r .ids .size (),ms , 1187ms > 0 ?1000.0 * (double ) (done - from ) /ms :0.0 ,from ); 1188 std::fflush (stdout ); 1189next_pp = done + 64 ; 1190 } 1191 } 1192m .set_cancel (nullptr ); 1193m .set_images ({}); 1194if (stopped || (!ok && m .cancelled ())) { 1195const bool back = from > 0 && m .restore ((int64_t )from )&& (size_t )m .pos ()== from ; 1196if (!back ) { 1197m .reset (); 1198held .clear (); 1199 } 1200 std::fprintf (stderr ,"ds4 serve: stopped while reading the prompt of %zu tokens, after %.0f ms%s\n" , 1201total ,now_ms ()- t0 ,back ?"; the conversation before it is kept" :"" ); 1202 std::printf ("DONE 0 %zu %.1f 0.0 cancel 0 0 %zu 0 0\n" ,r .ids .size (),now_ms ()- t0 ,back ?from : (size_t )0 ); 1203 std::fflush (stdout ); 1204continue ; 1205 } 1206if (!ok ) { 1207 std::fprintf (stderr ,"ds4: %s\n" ,err .c_str ()); 1208 std::printf ("ERR %s\n" ,err .c_str ()); 1209 std::printf ("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n" ,r .ids .size ()); 1210 std::fflush (stdout ); 1211m .reset (); 1212held .clear (); 1213continue ; 1214 } 1215if (n_score > 0 ) {// score=N: teacher-forced rows for the prompt's last N tokens (quant_quality.py's format) 1216 std::FILE * so = r .score_out .empty () ?nullptr : std::fopen (r .score_out .c_str (),"wb" ); 1217const int V = m .vocab (),eos_id = eos .empty () ?-1 :eos [0 ]; 1218 std::vector < float > lg ; 1219 std::vector < int > order ((size_t )V ); 1220for (size_t a = total ;ok && a + 1 < r .ids .size ();) { 1221const int T = (int ) std::min < size_t > (8 ,r .ids .size ()- 1 - a ); 1222ok = m .feed (r .ids .data ()+ a ,T ,T ,err )&& m .logits (lg )&& lg .size () >= (size_t )T * (size_t )V ; 1223for (int t = 0 ;ok && so != nullptr && t < T ;++ t ) { 1224const float * row = lg .data ()+ (size_t )t * (size_t )V ; 1225float mx = row [0 ]; 1226for (int v = 1 ;v < V ;++ v )mx = std::max (mx ,row [v ]); 1227double z = 0.0 ; 1228for (int v = 0 ;v < V ;++ v )z += std::exp ((double ) (row [v ]- mx )); 1229const double lz = std::log (z )+ (double )mx ; 1230 std::iota (order .begin (),order .end (),0 ); 1231 std::partial_sort (order .begin (),order .begin ()+ 64 ,order .end (), 1232 [& ](int x ,int y ) {return row [x ]> row [y ]|| (row [x ]== row [y ]&& x < y ); }); 1233const int tgt = r .ids [a + (size_t )t + 1 ]; 1234const double lt = (double )row [tgt ]- lz ,la = (double )row [order [0 ]]- lz ; 1235const double le = eos_id >=0 && eos_id < V ? (double )row [eos_id ]- lz :-1e30 ; 1236const double lt_ne = tgt == eos_id ?lt : std::log (std::max (1e-300 , std::exp (lt ) / std::max (1e-300 ,1.0 - std::exp (le )))); 1237 std::fprintf (so ,"%zu\t%d\t%.6f\t%d\t%.6f\t%d\t%.6f\t%.6f" ,a + (size_t )t ,tgt ,lt ,order [0 ],la , 1238order [0 ]== tgt ?1 :0 ,le ,lt_ne ); 1239for (int q = 0 ;q < 64 ;++ q ) std::fprintf (so ,"\t%d:%.6f" ,order [(size_t )q ], (double )row [order [(size_t )q ]]- lz ); 1240 std::fprintf (so ,"\n" ); 1241 } 1242a += (size_t )T ; 1243 } 1244if (so != nullptr ) std::fclose (so ); 1245ok = ok && m .feed (r .ids .data ()+ r .ids .size ()- 1 ,1 ,1 ,err ); 1246if (!ok ) { 1247 std::printf ("ERR %s\n" ,err .c_str ()); 1248 std::printf ("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n" ,r .ids .size ()); 1249 std::fflush (stdout ); 1250m .reset (); 1251held .clear (); 1252continue ; 1253 } 1254 } 1255if (const char * path = std::getenv ("STRATA_DUMP_FIRST_LOGITS" );path != nullptr && * path != '\0' ) { 1256static unsigned long long dump_counter = 0 ; 1257 std::vector < float > logits ; 1258const std::string name = std::string (path )+ "." + std::to_string (dump_counter ++ ); 1259 std::FILE * f = std::fopen (name .c_str (),"wb" ); 1260if (f != nullptr ) { 1261if (m .logits (logits )) std::fwrite (logits .data (),sizeof (float ),logits .size (),f ); 1262 std::fclose (f ); 1263 } 1264 } 1265held = std::move (pics ); 1266m .checkpoint (0 ); 1267if (!continued && slot_max > 0 )m .pin ();// (a new run of prompts: where it may be rendered again from) 1268const double t1 = now_ms (); 1269long long produced = 0 ; 1270const char * finish = "length" ; 1271const long long limit = r .max_new > 0 ?r .max_new :m .max_context ()- (long long )r .ids .size (); 1272long long d_off = 0 ,d_acc = 0 ; 1273bool cool = false; 1274int tok = m .sample (r .temperature ,r .top_p ,r .top_k ,r .min_p ,r .seed ,counter ++ ); 1275 std::vector < int > got ; 1276// STAT for the Monitor every 8 tokens and at the end, over this answer so far: the GLM engine's keys (speed, the 1277// VRAM hit, promotions a token) and DeepSeek's own - experts a token on the CPU lane, MB a token the storage 1278// read (Linux), the n-gram memory's (Engram) read time a token, the drafts' acceptance 1279const strata::ds4::Stats s_dec = m .stats (); 1280const long long io_dec = io_read_bytes (); 1281auto stat_line = [& ]() { 1282const strata::ds4::Stats & s = m .stats (); 1283const double ms = now_ms ()- t1 ; 1284const double fed = (double ) std::max < int64_t > (1 ,s .tokens - s_dec .tokens ); 1285const double ex = (double ) (s .experts - s_dec .experts ),cx = (double ) (s .cpu_experts - s_dec .cpu_experts ); 1286 std::string out = "STAT" ; 1287char b [160 ]; 1288 std::snprintf (b ,sizeof b ," tok_s=%.2f ms_tok=%.2f vram_hit=%.4f cpu=%.3f ram=%.3f promo=%.3f engram_ms=%.3f" , 1289ms > 0 ?1000.0 * (double )produced /ms :0.0 ,produced > 0 ?ms / (double )produced :0.0 , 1290ex > 0 ?1.0 - cx /ex :1.0 ,cx /fed , (double ) (s .ram_experts - s_dec .ram_experts ) /fed , 1291 (double ) (s .swaps - s_dec .swaps ) /fed , (s .engram_ms - s_dec .engram_ms ) /fed ); 1292out += b ; 1293const long long io = io_read_bytes (); 1294if (io >=0 && io_dec >=0 ) { 1295 std::snprintf (b ,sizeof b ," disk_mb=%.3f" , (double ) (io - io_dec ) /1e6 /fed ); 1296out += b ; 1297 } 1298if (d_off > 0 ) { 1299 std::snprintf (b ,sizeof b ," drafts=%.3f" , (double )d_acc / (double )d_off ); 1300out += b ; 1301 } 1302if (s .skipped > s_dec .skipped ) {// (STRATA_DS4_DISK_SKIP_W: experts left out a token) 1303 std::snprintf (b ,sizeof b ," skipped=%.3f" , (double ) (s .skipped - s_dec .skipped ) /fed ); 1304out += b ; 1305 } 1306 std::printf ("%s\n" ,out .c_str ()); 1307 }; 1308for (;;) { 1309if (in .stop .load ()) { 1310finish = "cancel" ; 1311break ; 1312 } 1313 std::printf ("T %d\n" ,tok ); 1314++ produced ; 1315if (produced %8 == 0 )stat_line (); 1316 std::fflush (stdout ); 1317bool end = false; 1318for (int e :eos )end = end || tok == e ; 1319if (end ) { 1320finish = "stop" ; 1321break ; 1322 } 1323if (produced >=limit || m .pos () >=m .max_context ())break ; 1324if (got .empty ()) {// the next round: the drafts (if any) and the token after them 1325const int room = (int ) std::min < long long > (limit - produced ,m .max_context ()- m .pos ()); 1326int off = 0 ,acc = 0 ; 1327// a round whose drafts were all below the confidence floor: the next one does without the drafter 1328// (a request's spec / dspark_conf keys over the engine's: the speed calibration measures both ways) 1329const bool try_spec = (r .spec < 0 ?spec :r .spec != 0 )&& !cool ; 1330if (!round (m ,tok ,room ,try_spec ,r .conf >=0 ?r .conf :conf_min ,r .temperature ,r .top_p ,r .top_k , 1331r .min_p ,r .seed ,counter ,got , 1332off ,acc ,err ,r .cum ,r .spec != 0 )) { 1333 std::fprintf (stderr ,"ds4: %s\n" ,err .c_str ()); 1334finish = "cancel" ; 1335break ; 1336 } 1337d_off += off ; 1338d_acc += acc ; 1339cool = try_spec && off == 0 ; 1340 std::reverse (got .begin (),got .end ()); 1341 } 1342tok = got .back (); 1343got .pop_back (); 1344 } 1345// (a stop within accepted drafts leaves the state past it: the next prompt shares less with it, and goes back to 1346// the checkpoint at this prompt's end) 1347stat_line (); 1348const double t2 = now_ms (); 1349// (reused: the tokens not read again - an SCR request's exact prefix and moved runs, not its resume point; with 1350// SCR on, the fields up to the prompt tokens read, then cached / scr / prefilled) 1351const size_t reused = spliced ? (size_t ) (scr_cached + scr_moved ) :from ; 1352if (scr ) 1353 std::printf ("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0 %zu 0 cached=%zu scr=%lld prefilled=%zu\n" ,produced , 1354r .ids .size (),t1 - t0 ,t2 - t1 ,finish ,d_acc ,d_off ,reused ,r .ids .size ()- reused , 1355spliced ? (size_t )scr_cached :from , (long long )scr_moved ,r .ids .size ()- reused ); 1356else 1357 std::printf ("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0\n" ,produced ,r .ids .size (),t1 - t0 ,t2 - t1 ,finish , 1358d_acc ,d_off ,from ); 1359 std::fflush (stdout ); 1360const auto & s = m .stats (); 1361 std::fprintf (stderr , 1362"maya ds4 serve: prompt %zu tokens = %zu reused + %zu read in %.0f ms (%.1f tok/s), %lld generated " 1363"in %.0f ms (%.2f tok/s); CPU lane %.1f%% of the experts\n" , 1364r .ids .size (),reused ,r .ids .size ()- reused ,t1 - t0 , 1365t1 > t0 ?1000.0 * (double ) (r .ids .size ()- reused ) / (t1 - t0 ) :0.0 ,produced ,t2 - t1 , 1366t2 > t1 ?1000.0 * (double )produced / (t2 - t1 ) :0.0 , 1367s .experts ?100.0 * (double )s .cpu_experts / (double )s .experts :0.0 ); 1368if (scr )// (the server's request line, and /metrics: Bonsai's cached / scr / prefilled split) 1369 std::fprintf (stderr ,"maya ds4 serve: SCR cached %zu scr %lld prefilled %zu of %zu\n" ,spliced ? (size_t )scr_cached :from , 1370 (long long )scr_moved ,r .ids .size ()- reused ,r .ids .size ()); 1371if (d_off > 0 ) std::fprintf (stderr ,"maya ds4 serve: drafts %lld of %lld kept; %s\n" ,d_acc ,d_off , 1372per_position (s_dec ,s ).c_str ()); 1373m .save_profile (); 1374 } 1375// the engine ends (QUIT or the end of its input): the conversation in the model is set aside, and every one in 1376// RAM is written to the folder, so the next run reads on from them 1377if (slot_max > 0 ) { 1378state_pads = scr_pads ; 1379slot_put (" as the engine ended" ); 1380size_t written = 0 ; 1381while (true) {// (a write can take the folder's least recently used conversation away: the list is asked again) 1382size_t i = SIZE_MAX ; 1383for (size_t k = 0 ;k < slots .size ();++ k ) 1384if (slots [k ].data ) { 1385i = k ; 1386break ; 1387 } 1388if (i == SIZE_MAX )break ; 1389if (slot_write_file (slots [i ]))++ written ; 1390else slot_drop (i );// (its state could not be written: there is nothing more to do at the engine's end) 1391 } 1392if (written > 0 ) { 1393int ram = 0 ,disk = 0 ; 1394slot_count (ram ,disk ); 1395char msg [256 ]; 1396 std::snprintf (msg ,sizeof msg ,"wrote %zu conversation(s) to %s; %d there in all" ,written , 1397slot_dir .string ().c_str (),disk ); 1398note (msg ); 1399 } 1400 } 1401m .save_profile (); 1402return 0 ; 1403} 1404 1405 1406// ---- Strata addition: teacher-forced scoring (the quality gate) ------------------------------------------------- 1407// --score IDS.json --score-out RUN.tsv: every segment of a tools/quant_quality.py ids file (name + ids) is read through 1408// the model from a fresh state; per position the log-probability of the text's next token and the 64 most likely 1409// tokens go out in the STRATA_LOGPOS row format that `quant_quality.py compare` reads (natural logs, full-vocabulary 1410// log-softmax in double). RUN.tsv.seg.json lists each segment's first line and size. 1411struct ScoreSeg { 1412 std::string name ; 1413 std::vector < int > ids ; 1414}; 1415 1416bool read_score_ids (const std::string & path , std::vector < ScoreSeg >& segs , std::string & err ) { 1417 std::FILE * f = std::fopen (path .c_str (),"rb" ); 1418if (f == nullptr ) { 1419err = path + ": cannot open" ; 1420return false; 1421 } 1422 std::string s ; 1423char buf [1 <<16 ]; 1424size_t k ; 1425while ((k = std::fread (buf ,1 ,sizeof buf ,f ))> 0 )s .append (buf ,k ); 1426 std::fclose (f ); 1427size_t p = 0 ; 1428for (;;) { 1429const size_t n0 = s .find ("\"name\"" ,p ); 1430if (n0 == std::string::npos )break ; 1431const size_t q0 = s .find ('"' ,s .find (':' ,n0 )+ 1 ); 1432const size_t q1 = s .find ('"' ,q0 + 1 ); 1433const size_t i0 = s .find ("\"ids\"" ,q1 ); 1434if (q0 == std::string::npos || q1 == std::string::npos || i0 == std::string::npos )break ; 1435const size_t b0 = s .find ('[' ,i0 ),b1 = s .find (']' ,b0 ); 1436if (b0 == std::string::npos || b1 == std::string::npos )break ; 1437ScoreSeg g ; 1438g .name = s .substr (q0 + 1 ,q1 - q0 - 1 ); 1439g .ids = parse_ids (s .substr (b0 + 1 ,b1 - b0 - 1 )); 1440segs .push_back (std::move (g )); 1441p = b1 ; 1442 } 1443if (segs .empty ()) { 1444err = path + ": no segments (expected quant_quality.py's ids file)" ; 1445return false; 1446 } 1447return true; 1448} 1449 1450int score (strata::ds4::Model & m ,const std::string & ids_path ,const std::string & out_path ,int window ,int eos ) { 1451 std::vector < ScoreSeg > segs ; 1452 std::string err ; 1453if (!read_score_ids (ids_path ,segs ,err )) { 1454 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1455return 1 ; 1456 } 1457// DS4_SCORE_PREFIX=N (a test of the long-prompt layer skip): the segments are joined into one stream, its first N 1458// tokens are read as one prompt (logits of the last row only: the path a long prompt takes, where the skip applies) 1459// and only the positions after them are scored, in windows 1460const long long prefix_n = std::getenv ("DS4_SCORE_PREFIX" ) ? std::atoll (std::getenv ("DS4_SCORE_PREFIX" )) :0 ; 1461// (DS4_SCORE_PREFIX_EACH=1: each segment its own prompt of N tokens, then its own scored positions) 1462const bool prefix_each = std::getenv ("DS4_SCORE_PREFIX_EACH" )!= nullptr && std::atoi (std::getenv ("DS4_SCORE_PREFIX_EACH" ))!= 0 ; 1463if (prefix_n > 0 && segs .size ()> 1 && !prefix_each ) { 1464ScoreSeg all ; 1465all .name = "concat" ; 1466for (const ScoreSeg & sg :segs )all .ids .insert (all .ids .end (),sg .ids .begin (),sg .ids .end ()); 1467segs .assign (1 ,all ); 1468 } 1469 std::FILE * out = std::fopen (out_path .c_str (),"wb" ); 1470 std::FILE * sj = std::fopen ((out_path + ".seg.json" ).c_str (),"wb" ); 1471if (out == nullptr || sj == nullptr ) { 1472 std::fprintf (stderr ,"strata-dsv41: cannot write %s\n" ,out_path .c_str ()); 1473return 1 ; 1474 } 1475 std::fprintf (sj ,"{\"segments\": [" ); 1476const int V = m .vocab (); 1477long long line = 0 ; 1478 std::vector < float > lg ; 1479 std::vector < int > order ; 1480const double t0 = now_ms (); 1481for (size_t si = 0 ;si < segs .size ();++ si ) { 1482const std::vector < int >& ids = segs [si ].ids ; 1483m .reset (); 1484const long long first = line ; 1485double sum_nll = 0.0 ; 1486long long top1 = 0 ,cnt = 0 ; 1487size_t a0 = 0 ; 1488if (prefix_n > 0 && (size_t )prefix_n + 1 < ids .size ()) { 1489a0 = (size_t )prefix_n ; 1490if (!m .feed (ids .data (), (int )a0 ,1 ,err )) { 1491 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1492return 1 ; 1493 } 1494 } 1495for (size_t a = a0 ;a + 1 < ids .size ();) { 1496const int T = (int ) std::min < size_t > ((size_t )window ,ids .size ()- 1 - a );// (positions a .. a+T-1 are scored) 1497if (!m .feed (ids .data ()+ a ,T ,T ,err )|| !m .logits (lg )|| lg .size ()< (size_t )T * (size_t )V ) { 1498 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .empty () ?"no logits" :err .c_str ()); 1499return 1 ; 1500 } 1501for (int t = 0 ;t < T ;++ t ) { 1502const float * r = lg .data ()+ (size_t )t * (size_t )V ; 1503float mx = r [0 ]; 1504for (int v = 1 ;v < V ;++ v )mx = std::max (mx ,r [v ]); 1505double z = 0.0 ; 1506for (int v = 0 ;v < V ;++ v )z += std::exp ((double ) (r [v ]- mx )); 1507const double lz = std::log (z )+ (double )mx ; 1508order .resize ((size_t )V ); 1509 std::iota (order .begin (),order .end (),0 ); 1510 std::partial_sort (order .begin (),order .begin ()+ 64 ,order .end (), [& ](int x ,int y ) { 1511return r [x ]> r [y ]|| (r [x ]== r [y ]&& x < y ); 1512 }); 1513const int tgt = ids [a + (size_t )t + 1 ]; 1514const double lt = (double )r [tgt ]- lz ; 1515const double la = (double )r [order [0 ]]- lz ; 1516const double le = eos >=0 && eos < V ? (double )r [eos ]- lz :-1e30 ; 1517// logp(target) with the end token left out of the distribution, as the engine's row has it 1518const double lt_ne = tgt == eos ?lt : std::log (std::max (1e-300 , std::exp (lt ) / std::max (1e-300 ,1.0 - std::exp (le )))); 1519 std::fprintf (out ,"%zu\t%d\t%.6f\t%d\t%.6f\t%d\t%.6f\t%.6f" ,a + (size_t )t ,tgt ,lt ,order [0 ],la , 1520order [0 ]== tgt ?1 :0 ,le ,lt_ne ); 1521for (int j = 0 ;j < 64 ;++ j ) std::fprintf (out ,"\t%d:%.6f" ,order [(size_t )j ], (double )r [order [(size_t )j ]]- lz ); 1522 std::fprintf (out ,"\n" ); 1523++ line ; 1524++ cnt ; 1525top1 += order [0 ]== tgt ; 1526sum_nll -= lt ; 1527 } 1528a += (size_t )T ; 1529 } 1530 std::fprintf (sj ,"%s{\"name\": \"%s\", \"first_line\": %lld, \"end_line\": %lld, \"n\": %lld, \"ppl\": %.6f, \"top1\": %.6f}" ,si ?", " :"" , 1531segs [si ].name .c_str (),first ,first + cnt ,cnt , std::exp (sum_nll / (double ) std::max (1LL ,cnt )), 1532 (double )top1 / (double ) std::max (1LL ,cnt )); 1533 std::fprintf (stderr ,"score %s: %lld positions, ppl %.4f, top-1 %.4f (%.0f s)\n" ,segs [si ].name .c_str (),cnt , 1534 std::exp (sum_nll / (double ) std::max (1LL ,cnt )), (double )top1 / (double ) std::max (1LL ,cnt ), 1535 (now_ms ()- t0 ) /1000.0 ); 1536 std::fflush (out ); 1537 } 1538 std::fprintf (sj ,"]}\n" ); 1539 std::fclose (sj ); 1540 std::fclose (out ); 1541return 0 ; 1542} 1543// ---- Strata H100 addition: profile run ------------------------------------------------------------------------- 1544// --profile-run IDS.json: every segment is fed through the model from a fresh state (no logits); the engine's expert 1545// profile (--expert-profile FILE, counts a layer and expert) and DS4_TRACE collect the routing. The profile is saved 1546// every 10 segments. --window sets the chunk (a chunked prompt path above 16). 1547int profile_run (strata::ds4::Model & m ,const std::string & ids_path ,int window ) { 1548 std::vector < ScoreSeg > segs ; 1549 std::string err ; 1550if (!read_score_ids (ids_path ,segs ,err )) { 1551 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1552return 1 ; 1553 } 1554const double t0 = now_ms (); 1555long long tot = 0 ; 1556for (size_t si = 0 ;si < segs .size ();++ si ) { 1557const std::vector < int >& ids = segs [si ].ids ; 1558m .reset (); 1559for (size_t a = 0 ;a < ids .size ();) { 1560const int T = (int ) std::min < size_t > ((size_t )window ,ids .size ()- a ); 1561if (!m .feed (ids .data ()+ a ,T ,0 ,err )) { 1562 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1563return 1 ; 1564 } 1565a += (size_t )T ; 1566 } 1567tot += (long long )ids .size (); 1568 std::fprintf (stderr ,"profile-run %zu/%zu %s: %zu tokens, %lld in all, %.0f s, %.1f tok/s\n" ,si + 1 ,segs .size (), 1569segs [si ].name .c_str (),ids .size (),tot , (now_ms ()- t0 ) /1000.0 ,1000.0 * (double )tot / (now_ms ()- t0 )); 1570if ((si + 1 ) %10 == 0 )m .save_profile (); 1571 } 1572m .save_profile (); 1573return 0 ; 1574} 1575// ---- Strata H100 addition: DSpark acceptance log --------------------------------------------------------------- 1576// --spec-eval IDS.json --n N: each segment is a prompt: fed from reset, then N greedy tokens decoded with the drafter, every 1577// draft verified (--dspark-conf 0); DS4_ROUND_LOG=file gets a line a round (segment name, drafts, accepted, confidences). 1578int spec_eval (strata::ds4::Model & m ,const std::string & ids_path ,int n ,int window ,float conf_min ,bool spec ) { 1579 std::vector < ScoreSeg > segs ; 1580 std::string err ; 1581if (!read_score_ids (ids_path ,segs ,err )) { 1582 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1583return 1 ; 1584 } 1585if (const char * f = std::getenv ("DS4_ROUND_LOG" ))g_round_log = std::fopen (f ,"wb" ); 1586const double t0 = now_ms (); 1587for (size_t si = 0 ;si < segs .size ();++ si ) { 1588const std::vector < int >& ids = segs [si ].ids ; 1589g_round_tag = segs [si ].name ; 1590m .reset (); 1591for (size_t a = 0 ;a < ids .size ();) { 1592const int T = (int ) std::min < size_t > ((size_t )window ,ids .size ()- a ); 1593const bool last = a + (size_t )T == ids .size (); 1594if (!m .feed (ids .data ()+ a ,T ,last ?1 :0 ,err )) { 1595 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1596return 1 ; 1597 } 1598a += (size_t )T ; 1599 } 1600unsigned long long counter = 0 ; 1601int tok = m .sample (0.0f ,1.0f ,1 ,0.0f ,1 ,counter ++ ); 1602 std::vector < int > got ; 1603int emitted = 1 ; 1604long long rounds = 0 ,acc_all = 0 ; 1605bool stop = false; 1606while (emitted < n && !stop ) { 1607int off = 0 ,acc = 0 ; 1608if (!round (m ,tok ,n - emitted ,spec ,conf_min ,0.0f ,1.0f ,1 ,0.0f ,1 ,counter ,got ,off ,acc ,err )) { 1609 std::fprintf (stderr ,"strata-dsv41: %s\n" ,err .c_str ()); 1610return 1 ; 1611 } 1612++ rounds ; 1613acc_all += acc ; 1614for (int t :got ) { 1615++ emitted ; 1616if (t == 1 )stop = true; 1617 } 1618tok = got .back (); 1619 } 1620 std::fprintf (stderr ,"spec-eval %zu/%zu %s: prompt %zu, %d tokens, %lld rounds, %.2f tokens a round, accepted %lld (%.0f s)\n" ,si + 1 , 1621segs .size (),segs [si ].name .c_str (),ids .size (),emitted ,rounds , (double ) (emitted - 1 ) / (double ) std::max (1LL ,rounds ), 1622acc_all , (now_ms ()- t0 ) /1000.0 ); 1623if (g_round_log != nullptr ) std::fflush (g_round_log ); 1624 } 1625return 0 ; 1626} 1627}// namespace 1628 1629#ifndef DS4_BUILD_ID 1630#define DS4_BUILD_ID "unknown" 1631#endif 1632 1633int main (int argc ,char ** argv ) { 1634 strata::ds4::os::fine_timer (); 1635 strata::ds4::Options o ; 1636 std::string ids_s ,dump ,eos = "1" ; 1637int n = 0 ,window = 0 ;// (0: the model's feed unit - a whole prompt on the chunked path; 16 for the scoring runs) 1638bool spec = true; 1639float temp = 0.0f ;// the CLI's sampling (0: greedy) 1640unsigned long long cli_seed = 1 ; 1641bool serve_mode = false; 1642bool pack_info_mode = false; 1643 std::string images ,enc_rgb ,enc_out ; 1644 std::string score_ids ,score_out ,prof_ids ,spec_ids ; 1645int enc_w = 0 ,enc_h = 0 ; 1646for (int i = 1 ;i < argc ;++ i ) { 1647const std::string a = argv [i ]; 1648auto val = [& ](const char * what )-> std::string { 1649if (i + 1 >=argc ) { 1650 std::fprintf (stderr ,"%s needs a value\n" ,what ); 1651 std::exit (2 ); 1652 } 1653return argv [++ i ]; 1654 }; 1655if (a == "--pack" )o .pack = val ("--pack" ); 1656else if (a == "--gpus" ) { 1657for (int g :parse_ids (val ("--gpus" )))o .gpus .push_back (g ); 1658 }else if (a == "--max-context" )o .max_context = std::atoll (val ("--max-context" ).c_str ()); 1659else if (a == "--reserve-mib" )o .reserve_mib = std::atoll (val ("--reserve-mib" ).c_str ()); 1660else if (a == "--vram-experts" )o .vram_experts = std::atof (val ("--vram-experts" ).c_str ()); 1661else if (a == "--cpu-threads" )o .cpu_threads = std::atoi (val ("--cpu-threads" ).c_str ()); 1662else if (a == "--expert-profile" )o .profile = val ("--expert-profile" ); 1663else if (a == "--ssd-cache" )o .ssd_cache_gb = std::atof (val ("--ssd-cache" ).c_str ()); 1664else if (a == "--ssd-policy" ) { 1665const std::string v = val ("--ssd-policy" ); 1666o .ssd_policy = v == "lfu" ?1 :v == "lfulru" ?2 :0 ; 1667 } 1668else if (a == "--eos" )eos = val ("--eos" ); 1669else if (a == "--no-expert-cache" )o .expert_cache = false; 1670else if (a == "--dspark" ) { 1671const std::string v = val ("--dspark" ); 1672spec = v != "off" ; 1673o .dspark = v != "none" ;// none: not even loaded 1674o .dspark_auto = v == "auto" ; 1675 }else if (a == "--dspark-conf" )o .dspark_conf = (float ) std::atof (val ("--dspark-conf" ).c_str ()); 1676else if (a == "--experts" ) { 1677const std::string v = val ("--experts" ); 1678o .experts = v == "auto" ?-1 : std::max (1 , std::atoi (v .c_str ())); 1679 } 1680else if (a == "--dspark-block" )o .dspark_block = std::max (0 , std::atoi (val ("--dspark-block" ).c_str ())); 1681else if (a == "--tp" )o .tp = std::max (1 , std::atoi (val ("--tp" ).c_str ())); 1682else if (a == "--prefill-chunk" )o .prefill_chunk = std::max (0 , std::atoi (val ("--prefill-chunk" ).c_str ())); 1683else if (a == "--threads" )o .threads = val ("--threads" )!= "off" ; 1684else if (a == "--vision" )o .vision = val ("--vision" )!= "off" ; 1685else if (a == "--mmap-experts" ) { 1686const std::string v = val ("--mmap-experts" ); 1687o .mmap_experts = v == "on" ?1 :v == "off" ?0 :-1 ; 1688 }else if (a == "--images" )images = val ("--images" ); 1689else if (a == "--encode-image" )enc_rgb = val ("--encode-image" ); 1690else if (a == "--dump-image" )enc_out = val ("--dump-image" ); 1691else if (a == "--size" ) { 1692const std::string v = val ("--size" ); 1693enc_w = std::atoi (v .c_str ()); 1694enc_h = v .find ('x' )!= std::string::npos ? std::atoi (v .c_str ()+ v .find ('x' )+ 1 ) :0 ; 1695 } 1696else if (a == "--temperature" )temp = (float ) std::atof (val ("--temperature" ).c_str ()); 1697else if (a == "--seed" )cli_seed = std::strtoull (val ("--seed" ).c_str (),nullptr ,10 ); 1698else if (a == "--verbose" || a == "-v" ) { 1699o .verbose = true; 1700 std::fprintf (stderr ,"ds4: build %s (%s)\n" ,DS4_BUILD_ID ,STRATA_VERSION ); 1701 }else if (a == "--version" ) { 1702 std::printf ("strata-dsv41 %s build %s\n" ,STRATA_VERSION ,DS4_BUILD_ID ); 1703return 0 ; 1704 } 1705else if (a == "--ids" )ids_s = val ("--ids" ); 1706else if (a == "--n" )n = std::atoi (val ("--n" ).c_str ()); 1707else if (a == "--window" )window = std::max (1 , std::atoi (val ("--window" ).c_str ()));// (> 16: the chunked prompt path) 1708else if (a == "--dump-logits" )dump = val ("--dump-logits" ); 1709else if (a == "--score" )score_ids = val ("--score" ); 1710else if (a == "--score-out" )score_out = val ("--score-out" ); 1711else if (a == "--profile-run" )prof_ids = val ("--profile-run" ); 1712else if (a == "--spec-eval" )spec_ids = val ("--spec-eval" ); 1713else if (a == "--serve" )serve_mode = true; 1714else if (a == "--pack-info" )pack_info_mode = true; 1715else if (a == "--layer-split" ) (void )val ("--layer-split" );// the server's (this engine balances its own split) 1716else if (a == "--help" || a == "-h" ) { 1717usage (); 1718return 0 ; 1719 }else { 1720 std::fprintf (stderr ,"unknown option %s\n" ,a .c_str ()); 1721usage (); 1722return 2 ; 1723 } 1724 } 1725if (pack_info_mode ) {// the pack's description only: no device, no weights, no lock 1726if (o .pack .empty ()) { 1727usage (); 1728return 2 ; 1729 } 1730return strata::ds4::pack_info (o .pack ,stdout ); 1731 } 1732if (o .pack .empty ()|| (!serve_mode && ids_s .empty ()&& enc_rgb .empty ()&& score_ids .empty ()&& prof_ids .empty ()&& spec_ids .empty ())) { 1733usage (); 1734return 2 ; 1735 } 1736if (o .profile .empty ())o .profile = o .pack + "/expert-profile.bin" ;// "none": no profile 1737if (o .profile == "none" )o .profile .clear (); 1738o .vision_only = !enc_rgb .empty (); 1739SuffixDrafter suffix ; 1740if (const char * e = std::getenv ("DS4_SUFFIX_DRAFT" );e != nullptr && std::atoi (e )> 0 ) { 1741// a window of more than DS4_ASYNC_T (8) rows takes the host-routed path: no Cache-Prior, no lookahead - 9 rows cost 8 tokens' 1742// time here, and their routing is not decode's 1743const char * at = std::getenv ("DS4_ASYNC_T" ); 1744suffix .kmax = std::max (1 , std::min (std::atoi (e ), (at != nullptr ? std::atoi (at ) :8 )- 1 )); 1745if (const char * f = std::getenv ("DS4_SUFFIX_MIN" ))suffix .nmin = suffix .floor_ = std::max (2 , std::atoi (f )); 1746g_suffix = & suffix ; 1747o .spec_buffers = true; 1748 } 1749 strata::ds4::Model m ; 1750 std::string err ; 1751if (!m .load (o ,err )) { 1752 std::fprintf (stderr ,"maya-ds4: %s\n" ,err .c_str ()); 1753return 1 ; 1754 } 1755if (!o .vision_only ) std::fprintf (stderr ,"%s" ,m .describe ().c_str ()); 1756if (const char * idle = std::getenv ("DS4_TEST_IDLE_MS" )) std::this_thread::sleep_for (std::chrono::milliseconds (std::atoi (idle )));// (tests: a person typing) 1757if (serve_mode ) { 1758// QUIT: everything that outlives the engine is written by now (the profile after every request, the kept 1759// conversations as serve ends), so it exits at once. A normal exit flushed every stdio stream, stdin too, 1760// whose lock the stdin reader thread holds while it waits for a line: the engine hung after QUIT until its 1761// input closed. 1762const int rc = serve (m ,eos ,spec ,o .dspark_conf ,o .pack ); 1763 std::fflush (stdout ); 1764 std::fflush (stderr ); 1765 std::_Exit (rc ); 1766 } 1767const int window_given = window ; 1768if (window == 0 )window = 16 ;// (the scoring / profiling runs; the plain run below takes the model's feed unit) 1769if (!prof_ids .empty ())return profile_run (m ,prof_ids ,window ); 1770if (!spec_ids .empty ())return spec_eval (m ,spec_ids ,n ,window ,o .dspark_conf ,spec ); 1771if (!score_ids .empty ())return score (m ,score_ids ,score_out .empty () ?score_ids + ".tsv" :score_out ,window , std::atoi (eos .c_str ())); 1772 1773if (!enc_rgb .empty ()) {// the vision tower alone: a picture's span rows (BF16 [rows][dim]) into --dump-image 1774 std::vector < uint8_t > px ((size_t ) std::max (0 ,enc_w )* std::max (0 ,enc_h )* 3 ); 1775 std::FILE * f = std::fopen (enc_rgb .c_str (),"rb" ); 1776const bool got = f != nullptr && !px .empty ()&& std::fread (px .data (),1 ,px .size (),f )== px .size (); 1777if (f != nullptr ) std::fclose (f ); 1778if (!got ) { 1779 std::fprintf (stderr ,"maya-ds4: %s: expected %d x %d RGB bytes (--size WxH)\n" ,enc_rgb .c_str (),enc_w ,enc_h ); 1780return 1 ; 1781 } 1782 std::vector < uint16_t > span ; 1783for (int k = 0 ;k < 2 ;++ k ) {// (the second: warm) 1784const double te = now_ms (); 1785if (!m .encode_image (px .data (),enc_w ,enc_h ,span ,err )) { 1786 std::fprintf (stderr ,"maya-ds4: %s\n" ,err .c_str ()); 1787return 1 ; 1788 } 1789 std::fprintf (stderr ,"vision: %d x %d pixels -> a span of %zu rows in %.0f ms\n" ,enc_w ,enc_h , 1790span .size () / (size_t )m .dim (),now_ms ()- te ); 1791 } 1792 std::FILE * o2 = enc_out .empty () ?nullptr : std::fopen (enc_out .c_str (),"wb" ); 1793if (o2 != nullptr ) { 1794 std::fwrite (span .data (),2 ,span .size (),o2 ); 1795 std::fclose (o2 ); 1796 } 1797return 0 ; 1798 } 1799if (!ids_s .empty ()&& ids_s [0 ]== '@' ) {// --ids @file: the ids in a file (a command line is 32 KB on Windows) 1800 std::ifstream idf (ids_s .substr (1 )); 1801 std::stringstream ss ; 1802ss <<idf .rdbuf (); 1803ids_s = ss .str (); 1804 } 1805const std::vector < int > ids = parse_ids (ids_s ); 1806if (!images .empty ()) {// --images: a GENI file's pictures, for the prompt's spans 1807 std::vector < Pic > pics ; 1808if (!read_pics (images ,pics ,err )) { 1809 std::fprintf (stderr ,"maya-ds4: %s\n" ,err .c_str ()); 1810return 1 ; 1811 } 1812 std::vector < strata::ds4::Image > imgs ; 1813for (const Pic & q :pics ) { 1814auto rows = std::make_shared < std::vector < uint16_t >> (); 1815const double te = now_ms (); 1816if (!m .encode_image (q .rgb .data (),q .width ,q .height ,* rows ,err )) { 1817 std::fprintf (stderr ,"maya-ds4: %s\n" ,err .c_str ()); 1818return 1 ; 1819 } 1820 std::fprintf (stderr ,"picture at %lld: %d x %d pixels, %zu tokens, %.0f ms\n" , (long long )q .start ,q .width , 1821q .height ,rows -> size () / (size_t )m .dim (),now_ms ()- te ); 1822imgs .push_back ({q .start ,rows }); 1823 } 1824m .set_images (std::move (imgs )); 1825 } 1826 std::FILE * df = dump .empty () ?nullptr : std::fopen (dump .c_str (),"wb" ); 1827 std::vector < float > lg ; 1828if (window_given == 0 )window = df != nullptr ?16 : std::max (16 , std::min (m .feed_unit (),1 <<30 )); 1829const double t0 = now_ms (); 1830for (size_t a = 0 ;a < ids .size ();) { 1831const int T = (int ) std::min < size_t > ((size_t )window ,ids .size ()- a ); 1832const bool last = a + (size_t )T == ids .size (); 1833const double tf0 = now_ms (); 1834if (!m .feed (ids .data ()+ a ,T ,df != nullptr ?T : (last ?1 :0 ),err )) { 1835 std::fprintf (stderr ,"maya-ds4: %s\n" ,err .c_str ()); 1836return 1 ; 1837 } 1838if (std::getenv ("DS4_FEEDLOG" )!= nullptr )// each feed's time: the incremental turn (--window W: a long prefix, then a short one) 1839 std::fprintf (stderr ,"feed at %zu: %d tokens in %.0f ms (%.1f tok/s)\n" ,a ,T ,now_ms ()- tf0 ,1000.0 * T / (now_ms ()- tf0 )); 1840if (df != nullptr && m .logits (lg )) std::fwrite (lg .data (),4 ,lg .size (),df ); 1841a += (size_t )T ; 1842 } 1843m .set_images ({}); 1844const double t1 = now_ms (); 1845 std::fprintf (stderr ,"prompt: %zu tokens in %.0f ms (%.2f tok/s, windows of %d)\n" ,ids .size (),t1 - t0 , 18461000.0 * (double )ids .size () / (t1 - t0 ),window ); 1847const strata::ds4::Stats s0 = m .stats (); 1848const char * tier_path = std::getenv ("DS4_TIERDUMP" ); 1849if (tier_path != nullptr )m .tier_dump (std::string (tier_path )+ ".pre" ); 1850if (s0 .eg_rows > 0 ) 1851 std::fprintf (stderr ,"prompt's Engram rows: %lld, %.1f%% without a read (repeats and the row cache), %lld read\n" , 1852 (long long )s0 .eg_rows ,100.0 * (double )s0 .eg_hits / (double )s0 .eg_rows , (long long )s0 .eg_reads ); 1853const long long io0 = io_read_bytes (); 1854 std::vector < int > out ; 1855 std::vector < double > tok_ms ;// (DS4_TOKLOG: each token's time since the one before - the latency ledger) 1856double t_prev = t1 ; 1857unsigned long long counter = 0 ; 1858long long d_off = 0 ,d_acc = 0 ,rounds = 0 ; 1859bool cool = false; 1860if (n > 0 ) { 1861int tok = m .sample (temp ,1.0f ,temp > 0 ?64 :1 ,0.0f ,cli_seed ,counter ++ ); 1862 std::vector < int > got ; 1863for (;;) { 1864out .push_back (tok ); 1865 { 1866const double tn = now_ms (); 1867tok_ms .push_back (tn - t_prev ); 1868t_prev = tn ; 1869 } 1870 std::printf ("%d," ,tok ); 1871 std::fflush (stdout ); 1872if ((tok == 1 && std::getenv ("DS4_NO_EOS" )== nullptr )|| (int )out .size () >=n )break ;// (DS4_NO_EOS: decode n tokens whatever) 1873if (got .empty ()) { 1874int off = 0 ,acc = 0 ; 1875const bool try_spec = spec && !cool ; 1876if (!round (m ,tok ,n - (int )out .size (),try_spec ,o .dspark_conf ,temp ,1.0f ,temp > 0 ?64 :1 ,0.0f , 1877cli_seed ,counter ,got ,off ,acc ,err )) { 1878 std::fprintf (stderr ,"maya-ds4: %s\n" ,err .c_str ()); 1879return 1 ; 1880 } 1881d_off += off ; 1882d_acc += acc ; 1883++ rounds ; 1884cool = try_spec && off == 0 ; 1885 std::reverse (got .begin (),got .end ()); 1886 } 1887tok = got .back (); 1888got .pop_back (); 1889 } 1890 std::printf ("\n" ); 1891if (df != nullptr && m .logits (lg )) std::fwrite (lg .data (),4 ,lg .size (),df ); 1892 } 1893if (spec && rounds > 0 ) { 1894const auto & s1 = m .stats (); 1895const double nv = (double ) std::max < int64_t > (1 ,s1 .drafts_rounds - s0 .drafts_rounds ); 1896 std::fprintf (stderr ,"dspark: %lld rounds, %lld drafts offered, %lld accepted (%.2f tokens a round); drafting " 1897"%.2f ms a round, verifying %.1f ms in all (%lld windows)\n" , 1898rounds ,d_off ,d_acc , (double )out .size () / (double )rounds , (s1 .draft_ms - s0 .draft_ms ) /nv , 1899s1 .verify_ms - s0 .verify_ms , (long long ) (s1 .drafts_offered > 0 ?0 :0 )); 1900 std::fprintf (stderr ,"dspark %s\n" ,per_position (s0 ,s1 ).c_str ()); 1901 } 1902if (g_suffix != nullptr && rounds > 0 ) 1903 std::fprintf (stderr ,"suffix: %lld rounds, %lld verified %lld drafts, %lld accepted (%.0f%%), %lld looked up without " 1904"a match; %.2f tokens a round\n" , 1905rounds ,g_suffix -> rounds ,g_suffix -> offered ,g_suffix -> accepted , 1906100.0 * (double )g_suffix -> accepted / (double ) std::max (1LL ,g_suffix -> offered ),g_suffix -> tried , 1907 (double )out .size () / (double )rounds ); 1908if (std::getenv ("DS4_TOKLOG" )!= nullptr && tok_ms .size ()> 8 ) {// the decode's tokens after the first (which carries the prompt's tail) 1909 std::vector < double > v (tok_ms .begin ()+ 1 ,tok_ms .end ()); 1910 std::sort (v .begin (),v .end ()); 1911 std::fprintf (stderr ,"token latency ms: p50 %.0f p95 %.0f p99 %.0f max %.0f mean %.0f (%zu tokens)\n" ,v [v .size () /2 ], 1912v [(size_t ) ((double )v .size ()* 0.95 )],v [(size_t ) ((double )v .size ()* 0.99 )],v .back (), 1913 std::accumulate (v .begin (),v .end (),0.0 ) / (double )v .size (),v .size ()); 1914const size_t n20 = std::min < size_t > (21 ,tok_ms .size ());// (tokens 2..21: what a long read leaves behind) 1915if (tok_ms .size ()> 30 ) 1916 std::fprintf (stderr ,"token latency ms: first20 mean %.0f, after mean %.0f\n" , 1917 std::accumulate (tok_ms .begin ()+ 1 ,tok_ms .begin ()+ (long )n20 ,0.0 ) / (double ) (n20 - 1 ), 1918 std::accumulate (tok_ms .begin ()+ (long )n20 ,tok_ms .end (),0.0 ) / (double ) (tok_ms .size ()- n20 )); 1919 } 1920const double t2 = now_ms (); 1921const auto & s = m .stats (); 1922const double nt = std::max < double > (1.0 , (double ) (s .tokens - s0 .tokens )); 1923if (s .aux_experts > s0 .aux_experts ) 1924 std::fprintf (stderr ,"decode: the expert GPU computed %.1f experts a token; %lld moved onto it\n" , 1925 (double ) (s .aux_experts - s0 .aux_experts ) /nt , (long long ) (s .aux_swaps - s0 .aux_swaps )); 1926 std::fprintf (stderr ,"decode: %zu tokens in %.0f ms (%.2f tok/s); CPU lane: %lld of %lld experts; the cache moved %lld " 1927"(%lld in all)\n" ,out .size (),t2 - t1 , 1928out .size ()> 1 ?1000.0 * (double ) (out .size ()- 1 ) / (t2 - t1 ) :0.0 , 1929 (long long ) (s .cpu_experts - s0 .cpu_experts ), (long long ) (s .experts - s0 .experts ), 1930 (long long ) (s .swaps - s0 .swaps ), (long long )s .swaps ); 1931 std::fprintf (stderr ,"decode per token: layers %.2f ms (of it: routing waits %.2f, CPU lane %.2f, the rest host launches), " 1932"head wait %.2f, Engram reads %.2f\n" , 1933 (s .layer_ms - s0 .layer_ms ) /nt , (s .gpu_wait_ms - s0 .gpu_wait_ms ) /nt , (s .cpu_ms - s0 .cpu_ms ) /nt , 1934 (s .head_ms - s0 .head_ms ) /nt , (s .engram_ms - s0 .engram_ms ) /nt ); 1935if (s .eg_rows > s0 .eg_rows ) {// the Engram rows: how many the row cache served, the reads' time behind the layers 1936const double rows = (double ) (s .eg_rows - s0 .eg_rows ); 1937 std::fprintf (stderr ,"Engram per token: %.0f rows, %.1f%% without a read (the row cache holds %lld of %lld), " 1938"%.1f read, the reads %.2f ms from asking to the last one (left to wait: %.2f)\n" , 1939rows /nt ,100.0 * (double ) (s .eg_hits - s0 .eg_hits ) /rows , (long long )s .eg_cached , 1940 (long long )s .eg_cache_cap , (double ) (s .eg_reads - s0 .eg_reads ) /nt , (s .eg_io_ms - s0 .eg_io_ms ) /nt , 1941 (s .engram_ms - s0 .engram_ms ) /nt ); 1942 } 1943const long long io1 = io_read_bytes (); 1944if (io0 >=0 && io1 >=0 ) 1945 std::fprintf (stderr ,"decode reads from the disk: %.1f MB a token\n" , (double ) (io1 - io0 ) /1e6 /nt ); 1946if (s .skipped > s0 .skipped )// STRATA_DS4_DISK_SKIP_W 1947 std::fprintf (stderr ,"decode left out %.1f experts a token not in RAM (%.1f%% of the routed)\n" , 1948 (double ) (s .skipped - s0 .skipped ) /nt , 1949100.0 * (double ) (s .skipped - s0 .skipped ) / std::max < double > (1.0 , (double ) (s .experts - s0 .experts ))); 1950if (s .store_slots_max > 0 ) {// --ssd-cache 1951const double h = (double ) (s .store_hits - s0 .store_hits ),m = (double ) (s .store_misses - s0 .store_misses ); 1952 std::fprintf (stderr , 1953"store: %.1f%% of the CPU lane's experts were in RAM (%.1f hits, %.1f misses a token); read %.1f MB a token " 1954"(demand and guesses), the CPU lane waited %.1f ms a token for them; %lld prefetched, %lld used, %lld given up " 1955"unused; slots %lld of %lld, %lld evictions, %lld failed reads; the GPU computed %.1f experts a token from the store " 1956"(%lld slots visible)\n" , 1957100.0 * h / std::max (1.0 ,h + m ),h /nt ,m /nt , (double ) (s .store_bytes - s0 .store_bytes ) /1e6 /nt , 1958 (s .store_wait_ms - s0 .store_wait_ms ) /nt , (long long ) (s .store_prefetched - s0 .store_prefetched ), 1959 (long long ) (s .store_pf_used - s0 .store_pf_used ), (long long ) (s .store_pf_wasted - s0 .store_pf_wasted ), 1960 (long long )s .store_slots , (long long )s .store_slots_max , (long long ) (s .store_evictions - s0 .store_evictions ), 1961 (long long ) (s .store_fails - s0 .store_fails ), (double ) (s .store_zc - s0 .store_zc ) /nt , 1962 (long long )s .store_zc_visible ); 1963 } 1964if (s .ahead_picks > s0 .ahead_picks ) {// lookahead 1965const double p = (double ) (s .ahead_picks - s0 .ahead_picks ),c = (double ) (s .ahead_cold - s0 .ahead_cold ); 1966 std::fprintf (stderr ,"lookahead: the guesses a layer before held %.1f%% of the picks (their top k %.1f%%, two layers " 1967"before %.1f%%); file-read picks asked for early %.1f%% (%lld of %lld); %.1f experts asked " 1968"for early a token\n" , 1969100.0 * (double ) (s .ahead_hit - s0 .ahead_hit ) /p ,100.0 * (double ) (s .ahead_hit_k - s0 .ahead_hit_k ) /p , 1970100.0 * (double ) (s .ahead_hit2 - s0 .ahead_hit2 ) /p , 1971c > 0 ?100.0 * (double ) (s .ahead_cold_hit - s0 .ahead_cold_hit ) /c :0.0 , 1972 (long long ) (s .ahead_cold_hit - s0 .ahead_cold_hit ), (long long ) (s .ahead_cold - s0 .ahead_cold ), 1973 (double ) (s .ahead_pf - s0 .ahead_pf ) /nt ); 1974 std::string rk = "lookahead: picked by the guess's rank (1 ..):" ; 1975for (int i = 0 ;i < 16 ;++ i ) { 1976const long long n = (long long ) (s .ahead_rank_n [i ]- s0 .ahead_rank_n [i ]); 1977if (n <=0 )break ; 1978char b [24 ]; 1979 std::snprintf (b ,sizeof b ," %.0f%%" ,100.0 * (double ) (s .ahead_rank_hit [i ]- s0 .ahead_rank_hit [i ]) / (double )n ); 1980rk += b ; 1981 } 1982 std::fprintf (stderr ,"%s\n" ,rk .c_str ()); 1983 } 1984 { 1985double tt [6 ],all = 0 ; 1986for (int i = 0 ;i < 6 ;++ i )all += tt [i ]= (double ) (s .tier [i ]- s0 .tier [i ]); 1987if (all > 0 ) 1988 std::fprintf (stderr ,"decode picks a token by tier: VRAM %.1f, expert GPU %.1f, store GPU-visible %.1f, store ready %.1f, " 1989"store in flight %.1f, no slot %.1f (%.1f in all)\n" , 1990tt [0 ] /nt ,tt [1 ] /nt ,tt [2 ] /nt ,tt [3 ] /nt ,tt [4 ] /nt ,tt [5 ] /nt ,all /nt ); 1991 } 1992if (tier_path != nullptr )m .tier_dump (std::string (tier_path )+ ".post" ); 1993if (s .prof_tokens > s0 .prof_tokens ) {// DS4_PROF 1994const double pt = (double ) (s .prof_tokens - s0 .prof_tokens ); 1995double sum = 0 ; 1996for (int i = 0 ;i < 6 ;++ i )sum += (s .prof_ms [i ]- s0 .prof_ms [i ]) /pt ; 1997 std::fprintf (stderr ,"GPU per token (DS4_PROF): %.2f ms - between layers %.2f, attention %.2f, routing + shared " 1998"expert %.2f, experts gate/up %.2f, waiting for the CPU lane %.2f, down + post %.2f\n" ,sum , 1999 (s .prof_ms [0 ]- s0 .prof_ms [0 ]) /pt , (s .prof_ms [1 ]- s0 .prof_ms [1 ]) /pt , 2000 (s .prof_ms [2 ]- s0 .prof_ms [2 ]) /pt , (s .prof_ms [3 ]- s0 .prof_ms [3 ]) /pt , 2001 (s .prof_ms [4 ]- s0 .prof_ms [4 ]) /pt , (s .prof_ms [5 ]- s0 .prof_ms [5 ]) /pt ); 2002 } 2003if (df != nullptr ) std::fclose (df ); 2004m .save_profile (); 2005return 0 ; 2006}