okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aad676f43
main
1// src/spec/draft_policy.cpp - see include/strata/spec/draft_policy.hpp. 2#include "strata/spec/draft_policy.hpp" 3 4#include <algorithm> 5#include <cmath> 6#include <cstdio> 7#include <cstdlib> 8#include <filesystem> 9#include <fstream> 10 11namespace strata::spec { 12namespace { 13 14// The shape of a round's cost by window size, relative to one token, used only for sizes not measured yet (the 15// measured round times replace it). Between the RTX 5070's measured curves: +10 ms per token with every missed expert 16// on the CPU (bench/results/2026-09-27-spec/window-cost), flatter with the default CPU/DMA split. 17// (sizes 9-16, above the measured curves: +0.4 a token) 18constexpr double kShape [DraftPolicy ::kMaxT + 1 ]= {0.0 ,1.0 ,1.35 ,1.7 ,2.05 ,2.45 ,2.85 ,3.25 ,3.6 , 194.0 ,4.4 ,4.8 ,5.2 ,5.6 ,6.0 ,6.4 ,6.8 }; 20constexpr double kCostAlpha = 0.1 ;// EMA weight of a new round time 21constexpr double kTokAlpha = 0.05 ;// EMA weight of a new MTP window outcome 22constexpr double kCalDecay = 0.995 ;// the MTP probability -> acceptance table fades slowly 23constexpr double kDecay = 0.97 ;// lookup counts: older windows fade 24// Before a bucket has data: the longer the match, the likelier its continuation (llama.cpp's lookup decoding gates 25// on the same thing); worth 4 observations, so a few real windows override it 26constexpr double kPriorQ [DraftPolicy ::kBuckets ]= {0.75 ,0.88 ,0.93 ,0.96 }; 27constexpr double kPriorN = 4.0 ; 28constexpr int kProbes = 3 ;// a lookup window size is tried this often before its guessed cost can veto it 29// A size not measured for this many rounds is tried again when a confident lookup could use it: its cost was set in 30// one stretch (a prompt's cache refill, say) and, priced high, it would never be measured again (#1252) 31constexpr double kStaleRounds = 300.0 ; 32 33// STRATA_SPEC_FIXED=1 and STRATA_SPEC_FIXED_TABLE="T1,T2,.." (round ms of windows of 1, 2, .. rows): an expert's fixed table for every 34// context bucket, read once per process (the measured table of --draft-costs is the normal source). 35struct FixedEnv { 36bool on = false; 37double ms [DraftPolicy ::kMaxT ]= {}; 38int n = 0 ; 39}; 40const FixedEnv & fixed_env () { 41static const FixedEnv cfg = [] { 42FixedEnv c ; 43const char * e = std::getenv ("STRATA_SPEC_FIXED" ); 44c .on = e != nullptr && e [0 ]== '1' ; 45if (const char * tab = std::getenv ("STRATA_SPEC_FIXED_TABLE" );c .on && tab != nullptr && tab [0 ]!= '\0' ) { 46for (const char * q = tab ;* q != '\0' && c .n < DraftPolicy ::kMaxT ;) { 47c .ms [c .n ++ ]= std::atof (q ); 48while (* q != '\0' && * q != ',' )++ q ; 49if (* q == ',' )++ q ; 50 } 51 } 52return c ; 53 }(); 54return cfg ; 55} 56 57double trimmed_mean (std::vector < float > v ) { 58 std::sort (v .begin (),v .end ()); 59const size_t k = (size_t ) ((double )v .size ()* CostLearner ::kTrim ); 60double s = 0.0 ; 61size_t n = 0 ; 62for (size_t i = k ;i + k < v .size ();++ i ,++ n )s += v [i ]; 63if (n == 0 ) { 64for (const float x :v )s += x ; 65n = v .size (); 66 } 67return n > 0 ?s / (double )n :0.0 ; 68} 69 70double median_of (std::vector < float > v ) { 71if (v .empty ())return 0.0 ; 72 std::nth_element (v .begin (),v .begin ()+ (std::ptrdiff_t ) (v .size () /2 ),v .end ()); 73return v [v .size () /2 ]; 74} 75 76}// namespace 77 78// ---------------------------------------------------------------------------------------------------- CostLearner 79 80static_assert(CostLearner ::kMaxT == DraftPolicy ::kMaxT && CostLearner ::kCtxBuckets == DraftPolicy ::kCtxBuckets ,"one table shape" ); 81 82void CostLearner ::add (int bucket ,int t ,double ms ,double busy_age_s ) { 83if (!(ms > 0.0 )|| !std::isfinite (ms ))return ; 84bucket = std::clamp (bucket ,0 ,kCtxBuckets - 1 ); 85t = std::clamp (t ,1 ,kMaxT ); 86const bool late = busy_age_s > kFreshS ;// a GPU that has been busy for long can run in another state than a request after a pause finds it 87++ (late ?late_ :rounds_ ); 88auto & v = (late ?late_s_ :s_ )[(size_t )bucket ][(size_t )t ]; 89if ((int )v .size ()< kKeep )v .push_back ((float )ms ); 90} 91 92void CostLearner ::reset () { 93for (auto & b :s_ ) 94for (auto & v :b )v .clear (); 95for (auto & b :late_s_ ) 96for (auto & v :b )v .clear (); 97rounds_ = 0 ; 98late_ = 0 ; 99} 100 101bool CostLearner ::state_effect (int bucket ,int min_n )const { 102if (bucket < 0 || bucket >=kCtxBuckets )return false; 103const int need = std::max (1 ,min_n ); 104for (int t = 1 ;t <=kMaxT ;++ t ) { 105const auto & f = s_ [(size_t )bucket ][(size_t )t ]; 106const auto & l = late_s_ [(size_t )bucket ][(size_t )t ]; 107if ((int )f .size ()< need || (int )l .size ()< need )continue ; 108const double tf = trimmed_mean (f ),tl = trimmed_mean (l ); 109if (tf > 0.0 && std::fabs (tl - tf ) /tf > kStateTol )return true; 110 } 111return false; 112} 113 114std::array < std::vector < float > ,CostLearner ::kMaxT + 1 > CostLearner ::sets (int bucket ,bool pooled )const { 115 std::array < std::vector < float > ,kMaxT + 1 > out ; 116for (int t = 1 ;t <=kMaxT ;++ t ) { 117out [(size_t )t ]= s_ [(size_t )bucket ][(size_t )t ]; 118if (pooled )out [(size_t )t ].insert (out [(size_t )t ].end (),late_s_ [(size_t )bucket ][(size_t )t ].begin (),late_s_ [(size_t )bucket ][(size_t )t ].end ()); 119 } 120return out ; 121} 122 123bool CostLearner ::state_known (int bucket ,int min_n )const { 124if (bucket < 0 || bucket >=kCtxBuckets )return false; 125const int need = std::max (1 ,min_n ); 126for (int t = 1 ;t <=kMaxT ;++ t ) 127if ((int )s_ [(size_t )bucket ][(size_t )t ].size () >=need && (int )late_s_ [(size_t )bucket ][(size_t )t ].size () >=need )return true; 128return false; 129} 130 131int CostLearner ::usable (int bucket ,int t ,int min_n )const { 132if (bucket < 0 || bucket >=kCtxBuckets || t < 1 || t > kMaxT )return 0 ; 133int n = (int )s_ [(size_t )bucket ][(size_t )t ].size (); 134if (!state_effect (bucket ,min_n ))n += (int )late_s_ [(size_t )bucket ][(size_t )t ].size (); 135return n ; 136} 137 138int CostLearner ::samples (int bucket ,int t )const { 139if (bucket < 0 || bucket >=kCtxBuckets || t < 1 || t > kMaxT )return 0 ; 140return (int )s_ [(size_t )bucket ][(size_t )t ].size (); 141} 142 143std::vector < double > CostLearner ::table (int bucket ,int min_n ,int upto )const { 144 std::vector < double > out ; 145if (bucket < 0 || bucket >=kCtxBuckets )return out ; 146const std::array < std::vector < float > ,kMaxT + 1 > b = sets (bucket , !state_effect (bucket ,min_n )); 147int top = 0 ; 148 std::array < double ,kMaxT + 1 > got {}; 149 std::vector < int > seen ;// the measured sizes (min_n samples), ascending; a rough one (kWeakN samples) joins when it is accepted below 150for (int t = 1 ;t <=kMaxT ;++ t ) { 151if (!b [(size_t )t ].empty ())top = t ; 152if ((int )b [(size_t )t ].size () >= std::max (1 ,min_n )) { 153got [(size_t )t ]= trimmed_mean (b [(size_t )t ]); 154seen .push_back (t ); 155 } 156 } 157if (top == 0 || seen .empty ())return out ; 158top = std::max (top , std::min (upto ,kMaxT )); 159// the cost of an unmeasured size from the measured ones: linear between two, the prior shape below them, above them the straight line with the 160// steeper of the last segment's slope and the slope over all measured sizes (never flatter than the measured trend) 161const auto fill = [& ](int t ) { 162int lo = 0 ,hi = 0 ; 163for (const int u :seen ) { 164if (u < t )lo = u ; 165if (u > t && hi == 0 )hi = u ; 166 } 167if (lo > 0 && hi > 0 )return got [(size_t )lo ]+ (got [(size_t )hi ]- got [(size_t )lo ])* (t - lo ) / (double ) (hi - lo ); 168if (hi > 0 )return got [(size_t )hi ]* kShape [t ] /kShape [hi ]; 169if (seen .size ()< 2 )return got [(size_t )lo ]* kShape [t ] /kShape [lo ]; 170const int u2 = seen .back (),u1 = seen [seen .size ()- 2 ],u0 = seen .front (); 171const double slope = std::max ({0.0 , (got [(size_t )u2 ]- got [(size_t )u1 ]) / (double ) (u2 - u1 ), (got [(size_t )u2 ]- got [(size_t )u0 ]) / (double ) (u2 - u0 )}); 172return got [(size_t )u2 ]+ slope * (t - u2 ); 173 }; 174for (int t = 1 ;t <=top ;++ t ) { 175if (got [(size_t )t ]> 0.0 ) { 176out .push_back (got [(size_t )t ]); 177continue ; 178 } 179double v = fill (t ); 180const int n = (int )b [(size_t )t ].size (); 181if (n >=kWeakN ) {// a few rounds: their median counts when it is not below the trend and not far above it (a stalled handful does not) 182 std::vector < float > s = b [(size_t )t ]; 183 std::sort (s .begin (),s .end ()); 184const double med = n %2 ? (double )s [(size_t )n /2 ] :0.5 * ((double )s [(size_t )n /2 - 1 ]+ (double )s [(size_t )n /2 ]); 185if (med >=v && med <=kWeakMax * v ) { 186v = med ; 187got [(size_t )t ]= med ; 188seen .insert (std::upper_bound (seen .begin (),seen .end (),t ),t ); 189 } 190 } 191out .push_back (v ); 192 } 193for (size_t i = 1 ;i < out .size ();++ i )out [i ]= std::max (out [i ],out [i - 1 ]);// more rows never cost less 194return out ; 195} 196 197CostLearner ::Verdict CostLearner ::check (int64_t min_rounds ,int min_n )const { 198Verdict v ; 199char b [160 ]; 200bool any = false,every_bucket_ok = true,effect = false; 201for (int k = 0 ;k < kCtxBuckets ;++ k ) { 202bool has = false,measured = false; 203double prev_ms = 0.0 ; 204int prev_t = 0 ; 205const bool eff = state_effect (k ,min_n ); 206effect = effect || eff ; 207const std::array < std::vector < float > ,kMaxT + 1 > use = sets (k , !eff ); 208for (int t = 1 ;t <=kMaxT ;++ t ) { 209const auto & s = use [(size_t )t ]; 210has = has || !s .empty (); 211if ((int )s .size ()< std::max (1 ,min_n ))continue ; 212measured = true; 213const double tm = trimmed_mean (s ); 214if (prev_t > 0 && tm < prev_ms * (1.0 - kOrderSlack )&& v .why .empty ()) { 215 std::snprintf (b ,sizeof b ,"bucket %d: T%d %.2f ms below T%d %.2f ms" ,k ,t ,tm ,prev_t ,prev_ms ); 216v .disturbed = true; 217v .why = b ; 218 } 219prev_ms = tm ; 220prev_t = t ; 221if ((int )s .size ()< 2 * std::max (1 ,min_n ))continue ; 222const size_t h = s .size () /2 ; 223const double a = trimmed_mean (std::vector < float > (s .begin (),s .begin ()+ (std::ptrdiff_t )h )); 224const double c = trimmed_mean (std::vector < float > (s .begin ()+ (std::ptrdiff_t )h ,s .end ())); 225if (a > 0.0 && std::fabs (c - a ) /a > kDriftMax && v .why .empty ()) { 226 std::snprintf (b ,sizeof b ,"bucket %d: T%d first half %.2f ms, second half %.2f ms" ,k ,t ,a ,c ); 227v .disturbed = true; 228v .why = b ; 229 } 230const double med = median_of (s ); 231size_t spikes = 0 ; 232for (const float x :s )spikes += x > 2.0 * med ?1 :0 ; 233if ((double )spikes > kSpikeMax * (double )s .size ()&& v .why .empty ()) { 234 std::snprintf (b ,sizeof b ,"bucket %d: T%d %zu of %zu rounds above twice the median %.2f ms" ,k ,t ,spikes ,s .size (),med ); 235v .disturbed = true; 236v .why = b ; 237 } 238 } 239any = any || measured ; 240if (has && !measured )every_bucket_ok = false; 241 } 242// no state effect: every round counts. With one: the fresh rounds, or, for a stretch that never paused (one long burst keeps only its first kFreshS 243// seconds), kFallbackFactor x the quota in rounds of any age when the fresh ones are at least 1 / kFallbackShare of the quota 244const bool enough = effect ? (rounds_ >=min_rounds || (rounds_ + late_ >=kFallbackFactor * min_rounds && rounds_ * kFallbackShare >=min_rounds )) 245 :rounds_ + late_ >=min_rounds ; 246v .ready = enough && any && every_bucket_ok ; 247return v ; 248} 249 250// ---------------------------------------------------------------------------------------------------- the table file 251 252namespace { 253constexpr const char * kCostFileHead = "strata-draft-costs 2" ;// 2: learned from the rounds of the first seconds of a busy run; a version 1 file is learned again 254// the path as UTF-8 (the server passes it so); on Windows a plain std::string would be read in the ANSI code page 255std::filesystem::path utf8_path (const std::string & s ) {return std::filesystem::path (std::u8string (s .begin (),s .end ())); } 256std::string one_line (std::string s ) { 257for (char & c :s ) 258if (c == '\n' || c == '\r' )c = ' ' ; 259return s ; 260} 261}// namespace 262 263bool read_cost_file (const std::string & path ,const std::string & key ,CostFile & out , std::string & why ) { 264out = CostFile {}; 265 std::ifstream f (utf8_path (path ), std::ios::binary ); 266if (!f ) {why = "no table file yet" ;return false; } 267 std::string line ; 268if (!std::getline (f ,line )|| line != kCostFileHead ) {why = "not a table file of this format" ;return false; } 269if (!std::getline (f ,line )|| line .rfind ("key " ,0 )!= 0 ) {why = "the file has no key" ;return false; } 270if (line .substr (4 )!= one_line (key )) {why = "learned on another machine or with other settings" ;return false; } 271bool ended = false,any = false; 272while (std::getline (f ,line )) { 273if (line == "end" ) {ended = true;break ; } 274if (line .rfind ("share " ,0 )== 0 ) { 275char * e = nullptr ; 276const double s = std::strtod (line .c_str ()+ 6 ,& e ); 277if (e == line .c_str ()+ 6 || * e != '\0' || !(s >=0.0 )|| !(s <=1.0 )) {why = "a malformed share" ;return false; } 278out .cpu_share = s ; 279continue ; 280 } 281if (line .rfind ("pcie " ,0 )== 0 ) { 282char * e = nullptr ; 283const double s = std::strtod (line .c_str ()+ 5 ,& e ); 284if (e == line .c_str ()+ 5 || * e != '\0' || !(s >=0.0 )|| !(s <=1.0 )) {why = "a malformed PCIe share" ;return false; } 285out .pcie_frac = s ; 286continue ; 287 } 288if (line .rfind ("state " ,0 )== 0 ) {// calibration lines (DraftPolicy::start_calibration); a file without them has no calibration done 289if (line != "state 0" && line != "state 1" ) {why = "a malformed state" ;return false; } 290out .state_effect = line == "state 1" ; 291continue ; 292 } 293if (line == "fresh 1" ) {out .fresh = true;continue ; } 294if (line .rfind ("reqs " ,0 )== 0 ) { 295int rq = -1 ; 296if (std::sscanf (line .c_str (),"reqs %d" ,& rq )!= 1 || rq < 0 || rq > 1000000 ) {why = "a malformed request count" ;return false; } 297out .reqs = rq ; 298continue ; 299 } 300if (line .rfind ("real " ,0 )== 0 ) { 301int rb = -1 ; 302unsigned m = 0 ; 303if (std::sscanf (line .c_str (),"real %d %u" ,& rb ,& m )!= 2 || rb < 0 || rb >=CostLearner ::kCtxBuckets ) {why = "a malformed real mark" ;return false; } 304out .real [(size_t )rb ]= m ; 305continue ; 306 } 307if (line .rfind ("cal " ,0 )== 0 ) { 308int cb = -1 ,ct = -1 ,cn = -1 ,used = 0 ; 309double cs = -1.0 ; 310if (std::sscanf (line .c_str (),"cal %d %d %d %lf%n" ,& cb ,& ct ,& cn ,& cs ,& used )!= 4 || cb < 0 || cb >=CostLearner ::kCtxBuckets || ct < 1 || ct > CostLearner ::kMaxT 311|| cn < 0 || cn > 100000 || !(cs >=0.0 )|| !(cs < 1e9 )) { 312why = "a malformed calibration line" ; 313return false; 314 } 315CalAcc ca ; 316ca .n = cn ; 317ca .sum = cs ; 318 {// the rounds themselves (a line from before them: none, the mean decides as it did) 319const char * p = line .c_str ()+ used ; 320int k = 0 ; 321bool ok = true; 322while (k < CalAcc ::kVals ) { 323char * e = nullptr ; 324const double v = std::strtod (p ,& e ); 325if (e == p )break ; 326if (!(v > 0.0 )|| !(v < 1e6 )) {ok = false;break ; } 327ca .vals [(size_t )k ++ ]= v ; 328p = e ; 329 } 330ca .nv = ok && k == cn && cn <=CalAcc ::kVals ?k :0 ; 331 } 332out .cal [(size_t )cb ][(size_t )ct ]= ca ; 333continue ; 334 } 335if (line .rfind ("rc " ,0 )== 0 ) { 336int rb = -1 ,rt = -1 ; 337double rv = -1.0 ; 338if (std::sscanf (line .c_str (),"rc %d %d %lf" ,& rb ,& rt ,& rv )!= 3 || rb < 0 || rb >=CostLearner ::kCtxBuckets || rt < 1 || rt > CostLearner ::kMaxT || !(rv > 0.0 )|| !(rv < 1e5 )) { 339why = "a malformed real cost" ; 340return false; 341 } 342out .real_cost [(size_t )rb ][(size_t )rt ]= rv ; 343continue ; 344 } 345int b = -1 ,used = 0 ; 346if (std::sscanf (line .c_str (),"bucket %d %n" ,& b ,& used )< 1 || used == 0 || b < 0 || b >=CostLearner ::kCtxBuckets ) { 347why = "a malformed line" ; 348return false; 349 } 350 std::vector < double > v ; 351const char * q = line .c_str ()+ used ; 352while (* q != '\0' ) { 353char * e = nullptr ; 354const double x = std::strtod (q ,& e ); 355if (e == q || !(x > 0.0 )|| !(x < 1e5 )) {why = "a malformed table" ;return false; } 356v .push_back (x ); 357q = e ; 358if (* q == ',' )++ q ; 359else if (* q != '\0' ) {why = "a malformed table" ;return false; } 360 } 361if (v .empty ()|| (int )v .size ()> CostLearner ::kMaxT ) {why = "a table of the wrong length" ;return false; } 362out .tables [(size_t )b ]= std::move (v ); 363any = true; 364 } 365if (!ended || (!any && !out .fresh )|| (any && out .fresh )) {why = "the file is cut short" ;return false; } 366out .key = key ; 367return true; 368} 369 370bool write_cost_file (const std::string & path ,const CostFile & c , std::string & why ) { 371namespace fs= std::filesystem; 372 std::error_code ec ; 373const fs::path p = utf8_path (path ); 374if (p .has_parent_path ()) fs::create_directories (p .parent_path (),ec ); 375if (ec ) {why = "could not make the folder (" + ec .message ()+ ")" ;return false; } 376 fs::path tmp = p ; 377tmp += ".tmp" ; 378 { 379 std::ofstream f (tmp , std::ios::binary | std::ios::trunc ); 380if (!f ) {why = "could not write the file" ;return false; } 381f <<kCostFileHead <<"\nkey " <<one_line (c .key ) <<"\n" ; 382char b [32 ]; 383for (int k = 0 ;k < CostLearner ::kCtxBuckets ;++ k ) { 384if (c .tables [(size_t )k ].empty ())continue ; 385f <<"bucket " <<k <<" " ; 386for (size_t i = 0 ;i < c .tables [(size_t )k ].size ();++ i ) { 387 std::snprintf (b ,sizeof b ,"%s%.3f" ,i ?"," :"" ,c .tables [(size_t )k ][i ]); 388f <<b ; 389 } 390f <<"\n" ; 391 } 392if (c .state_effect )f <<"state 1\n" ; 393if (c .reqs > 0 )f <<"reqs " <<c .reqs <<"\n" ; 394if (c .fresh )f <<"fresh 1\n" ; 395for (int k = 0 ;k < CostLearner ::kCtxBuckets ;++ k ) { 396if (c .real [(size_t )k ]!= 0u )f <<"real " <<k <<" " <<c .real [(size_t )k ] <<"\n" ; 397for (int t = 1 ;t <=CostLearner ::kMaxT ;++ t ) 398if ((c .real [(size_t )k ] >> (t - 1 )& 1u )&& c .real_cost [(size_t )k ][(size_t )t ]> 0.0 ) { 399 std::snprintf (b ,sizeof b ,"%.4f" ,c .real_cost [(size_t )k ][(size_t )t ]); 400f <<"rc " <<k <<" " <<t <<" " <<b <<"\n" ; 401 } 402for (int t = 1 ;t <=CostLearner ::kMaxT ;++ t ) { 403const CalAcc & a = c .cal [(size_t )k ][(size_t )t ]; 404if (a .n <=0 || (c .real [(size_t )k ] >> (t - 1 )& 1u ))continue ; 405 std::snprintf (b ,sizeof b ,"%.4f" ,a .sum ); 406f <<"cal " <<k <<" " <<t <<" " <<a .n <<" " <<b ; 407if (a .nv == a .n ) 408for (int i = 0 ;i < a .nv ;++ i ) { 409 std::snprintf (b ,sizeof b ,"%.4f" , (double )a .vals [(size_t )i ]); 410f <<" " <<b ; 411 } 412f <<"\n" ; 413 } 414 } 415if (c .cpu_share >=0.0 ) { 416 std::snprintf (b ,sizeof b ,"share %.3f\n" , std::min (c .cpu_share ,1.0 )); 417f <<b ; 418 } 419if (c .pcie_frac >=0.0 ) { 420 std::snprintf (b ,sizeof b ,"pcie %.3f\n" , std::min (c .pcie_frac ,1.0 )); 421f <<b ; 422 } 423f <<"end\n" ; 424f .flush (); 425if (!f ) {why = "could not write the file" ; fs::remove (tmp ,ec );return false; } 426 } 427 fs::rename (tmp ,p ,ec );// replaces an older file whole (MoveFileEx with REPLACE_EXISTING on Windows) 428if (ec ) {why = "could not replace the file (" + ec .message ()+ ")" ; fs::remove (tmp ,ec );return false; } 429return true; 430} 431 432void mark_learned_real (CostFile & cf ) { 433for (int k = 0 ;k < CostLearner ::kCtxBuckets ;++ k ) { 434 std::vector < double >& tab = cf .tables [(size_t )k ]; 435for (size_t i = 0 ;i < tab .size ();++ i ) { 436const double v = std::round (tab [i ]* 1000.0 ) /1000.0 ; 437if (!(v > 0.0 ))continue ;// never for a valid table; the size then stays not real (held, as before) 438tab [i ]= v ; 439cf .real [(size_t )k ] |=1u <<i ; 440cf .real_cost [(size_t )k ][i + 1 ]= v ; 441 } 442 } 443} 444 445// ---------------------------------------------------------------------------------------------------- DraftPolicy 446 447DraftPolicy ::DraftPolicy (int max_t ,double margin ) 448 :max_t_ (std::clamp (max_t ,1 ,kMaxT )),margin_ (margin ) { 449const FixedEnv & f = fixed_env (); 450if (f .on ) 451for (int k = 0 ;k < kCtxBuckets ;++ k )set_fixed_costs (f .n > 0 ?f .ms :nullptr ,f .n ,k ); 452} 453 454void DraftPolicy ::set_fixed_costs (const double * ms ,int n ,int bucket ) { 455if (!fixed_ && !live_saved_ ) {// the live costs at this point: start_calibration() may hand them back 456live_cost_ = cost_ ; 457live_n_ = cost_n_ ; 458live_saved_ = true; 459 } 460fixed_ = true; 461held_table_ = false; 462held_ .clear (); 463if (ms == nullptr || n <=0 )return ; 464bucket = std::clamp (bucket ,0 ,kCtxBuckets - 1 ); 465fixed_n_ [(size_t )bucket ]= std::min (n ,kMaxT ); 466for (int t = 1 ;t <=kMaxT ;++ t ) {// the table replaces what was measured; sizes past its end scale from it (cost_ms) 467const bool in = t <=n && ms [t - 1 ]> 0.0 ; 468cost_ [bucket ][t ]= in ?ms [t - 1 ] :0.0 ; 469cost_n_ [bucket ][t ]= in ?1e6 :0.0 ; 470learned_ [(size_t )bucket ][(size_t )t ]= cost_ [bucket ][t ]; 471 } 472} 473 474void DraftPolicy ::set_sizes (unsigned mask ) {sizes_ = mask |2u ; } 475 476void DraftPolicy ::disable (int t ) { 477if (t > 1 && t <=kMaxT )sizes_ &= ~(1u <<t ); 478} 479 480int DraftPolicy ::fit (int t )const { 481for (t = std::min (t ,max_t_ );t > 1 ;-- t ) 482if (allowed (t ))return t ; 483return 1 ; 484} 485 486int DraftPolicy ::bucket (int match ) { 487return match < 6 ?0 :match < 12 ?1 :match < 24 ?2 :3 ; 488} 489 490double DraftPolicy ::lookup_rate (int match )const { 491const int b = bucket (match ); 492return (ok_ [b ]+ kPriorN * kPriorQ [b ]) / (ok_ [b ]+ bad_ [b ]+ kPriorN ); 493} 494 495double DraftPolicy ::cost_ms (int t )const { 496t = std::clamp (t ,1 ,kMaxT ); 497if (cost_n_ [bk_ ][t ]> 0 )return cost_ [bk_ ][t ]; 498// scale from the measured sizes, weighting each by how often it was seen 499double num = 0.0 ,den = 0.0 ; 500for (int u = 1 ;u <=kMaxT ;++ u ) 501if (cost_n_ [bk_ ][u ]> 0 ) { 502const double w = std::min (cost_n_ [bk_ ][u ],20.0 ); 503num += w * cost_ [bk_ ][u ]* kShape [t ] /kShape [u ]; 504den += w ; 505 } 506return den > 0 ?num /den :kShape [t ]; 507} 508 509double DraftPolicy ::clamp_sample (int t ,double ms )const { 510if (!robust_ )return ms ; 511const double known = cost_ms (t );// the measured value, or the scaled guess from the other widths 512if (cost_n_ [bk_ ][t ]== 0 ) { 513// the first use of a width captures its graph: that round says nothing about its cost, the guess from the other widths stands in 514for (int u = 1 ;u <=kMaxT ;++ u ) 515if (cost_n_ [bk_ ][u ]> 0 )return known ; 516return ms ; 517 } 518return std::min (ms ,2.0 * known ); 519} 520 521void DraftPolicy ::seed_costs (const double * ms ,int n ,double weight ,int bucket ) { 522bucket = std::clamp (bucket ,0 ,kCtxBuckets - 1 ); 523for (int t = 1 ;t <= std::min (n ,kMaxT );++ t ) 524if (ms [t - 1 ]> 0.0 && cost_n_ [bucket ][t ]== 0 ) { 525cost_ [bucket ][t ]= ms [t - 1 ]; 526cost_n_ [bucket ][t ]= weight ; 527 } 528} 529 530void DraftPolicy ::set_context (long long pos ) { 531if (!robust_ )return ; 532const int nb = pos < 6000 ?0 :pos < 24000 ?1 :2 ; 533if (nb == bk_ )return ; 534bool has = false; 535for (int t = 1 ;t <=kMaxT ;++ t )has = has || cost_n_ [nb ][t ]> 0 ; 536if (!has ) {// nothing measured at this length yet: the nearest bucket that has data is the prior (one sample's worth) 537for (int d = 1 ;d < kCtxBuckets && !has ;++ d ) 538for (const int src : {nb - d ,nb + d }) { 539if (src < 0 || src >=kCtxBuckets || has )continue ; 540for (int t = 1 ;t <=kMaxT ;++ t ) 541if (cost_n_ [src ][t ]> 0 ) { 542cost_ [nb ][t ]= cost_ [src ][t ]; 543cost_n_ [nb ][t ]= 1.0 ; 544last_ [nb ][t ]= rounds_ ; 545has = true; 546 } 547 } 548 } 549bk_ = nb ; 550} 551 552std::string DraftPolicy ::cost_table_text ()const { 553 std::string out ; 554char b [64 ]; 555for (int k = 0 ;k < kCtxBuckets ;++ k ) { 556bool any = false; 557for (int t = 1 ;t <=kMaxT ;++ t )any = any || cost_n_ [k ][t ]> 0 ; 558if (!any )continue ; 559out += (out .empty () ?"" :" | " ); 560out += k == 0 ?"ctx<6K:" :k == 1 ?"ctx<24K:" :"ctx>=24K:" ; 561for (int t = 1 ;t <=kMaxT ;++ t ) 562if (cost_n_ [k ][t ]> 0 ) { 563 std::snprintf (b ,sizeof b ," T%d:%.2f(n=%.0f)" ,t ,cost_ [k ][t ],cost_n_ [k ][t ]); 564out += b ; 565 } 566 } 567return out ; 568} 569 570bool DraftPolicy ::stale (int t )const {return !fixed_ && cost_n_ [bk_ ][t ]> 0 && rounds_ - last_ [bk_ ][t ]> kStaleRounds ; } 571 572double DraftPolicy ::mtp_tokens (int t )const { 573if (mtp_n_ [t ]> 0 )return mtp_tok_ [t ]; 574return 1.0 + 0.7 * (t - 1 );// before any MTP window of this size: a typical acceptance 575} 576 577DraftPolicy ::Pick DraftPolicy ::choose (int t_mtp ,int lookup_k ,int match ,int pad_cap )const { 578Pick p ; 579p .t = std::clamp (t_mtp ,1 ,max_t_ ); 580if (lookup_k <=0 )return p ; 581if (learning_ && !fixed_ ) {// a learning stretch measures the sizes it has too few rounds of, when a proposal is long enough for one 582const int s = explore_size (lookup_k ,pad_cap ); 583if (s > 0 ) { 584p .lookup = true; 585p .t = s ; 586p .pad = std::max (0 ,s - 1 - lookup_k ); 587return p ; 588 } 589 } 590const double base = mtp_tokens (p .t ) /cost_ms (p .t ); 591const double q = lookup_rate (match ); 592double e = 1.0 ,qi = 1.0 ,best = 0.0 ; 593int best_t = 0 ; 594for (int k = 1 ;k <= std::min (lookup_k ,max_t_ - 1 );++ k ) { 595qi *=q ; 596e += qi ; 597if (!allowed (k + 1 ))continue ; 598const double r = e /cost_ms (k + 1 ); 599if (r > best ) {best = r ;best_t = k + 1 ; } 600 } 601const int t_full = fit (std::min (lookup_k ,max_t_ - 1 )+ 1 ); 602if (best_t > 0 && best > base * (1.0 + margin_ )) { 603p .lookup = true; 604p .t = best_t ; 605// a wider size whose cost has gone stale is re-measured, so one slow stretch cannot price it out for good 606if (best_t < t_full && q >=0.85 && stale (t_full ))p .t = t_full ; 607return p ; 608 } 609// a guessed cost can keep the policy from ever measuring a size: the first few times a confident lookup would 610// need a size not measured yet, it is tried (verification keeps the output; only the one round's speed is at stake) 611if (!fixed_ && t_full > p .t && t_full > 1 && (cost_n_ [bk_ ][t_full ]- delayed_n_ [bk_ ][t_full ]+ tried_ [bk_ ][t_full ]< kProbes || stale (t_full ))&& q >=0.85 ) { 612p .lookup = true; 613p .t = t_full ; 614 } 615return p ; 616} 617 618bool DraftPolicy ::explore_ok ()const { 619const double age = busy_age_ < 0.0 ?0.0 :busy_age_ ; 620if (age <=CostLearner ::kFreshS )return true;// a fresh round: it counts on every machine 621return learner_ .state_known (bk_ ,20 )&& !learner_ .state_effect (bk_ ,20 );// a late round counts only where the stretch has shown no state effect 622} 623 624int DraftPolicy ::explore_next (int reach ,int skip )const { 625if (learner_ .rounds ()+ learner_ .late_rounds ()< kExploreAfter || forced_total_ >=kExploreBudget || !explore_ok ())return 0 ; 626for (int s = 2 ;s <= std::min (reach ,max_t_ );++ s ) { 627if (s == skip || !allowed (s )|| forced_ [(size_t )s ] >=kExplorePerSize || learner_ .usable (bk_ ,s ,20 ) >=kExploreN )continue ; 628++ forced_ [(size_t )s ]; 629++ forced_total_ ; 630return s ; 631 } 632return 0 ; 633} 634 635int DraftPolicy ::explore_size (int lookup_k ,int pad_cap )const { 636return explore_next (std::max (lookup_k ,pad_cap )+ 1 ,0 ); 637} 638 639int DraftPolicy ::explore_lookup (int cap )const { 640if (!learning_ || fixed_ )return 0 ; 641return explore_next (cap ,0 ); 642} 643 644int DraftPolicy ::explore_window (int t ,int cap )const { 645if (!learning_ || fixed_ )return 0 ; 646return explore_next (cap ,t ); 647} 648 649void DraftPolicy ::observe_forced (int t ,double round_ms ) { 650t = std::clamp (t ,1 ,kMaxT ); 651if (learning_ && round_ms > 0 )learner_ .add (bk_ ,t ,round_ms ,busy_age_ ); 652if (round_ms > 0 && !fixed_ ) { 653round_ms = clamp_sample (t ,round_ms ); 654const double alpha = robust_ ? std::max (kCostAlpha ,1.0 / (cost_n_ [bk_ ][t ]+ 1.0 )) :kCostAlpha ; 655cost_ [bk_ ][t ]= cost_n_ [bk_ ][t ]> 0 ? (1.0 - alpha )* cost_ [bk_ ][t ]+ alpha * round_ms :round_ms ; 656cost_n_ [bk_ ][t ]+= 1.0 ; 657last_ [bk_ ][t ]= rounds_ ; 658 } 659rounds_ += 1.0 ; 660} 661 662void DraftPolicy ::reset_learning () { 663learner_ .reset (); 664forced_total_ = 0 ; 665forced_ .fill (0 ); 666} 667 668void DraftPolicy ::observe (bool lookup ,int t ,int accepted ,int match ,double round_ms ) { 669t = std::clamp (t ,1 ,kMaxT ); 670if (learning_ && round_ms > 0 )learner_ .add (bk_ ,t ,round_ms ,busy_age_ ); 671if (calib_on_ && round_ms > 0 )calib_add (bk_ ,t ,round_ms ,busy_age_ ); 672if (round_ms > 0 && !fixed_ ) { 673round_ms = clamp_sample (t ,round_ms ); 674const double alpha = robust_ ? std::max (kCostAlpha ,1.0 / (cost_n_ [bk_ ][t ]+ 1.0 )) :kCostAlpha ;// a running mean for the first samples 675cost_ [bk_ ][t ]= cost_n_ [bk_ ][t ]> 0 ? (1.0 - alpha )* cost_ [bk_ ][t ]+ alpha * round_ms :round_ms ; 676cost_n_ [bk_ ][t ]+= 1.0 ; 677last_ [bk_ ][t ]= rounds_ ; 678 } 679rounds_ += 1.0 ; 680if (lookup ) { 681const int b = bucket (match ); 682ok_ [b ]= kDecay * ok_ [b ]+ accepted ; 683bad_ [b ]= kDecay * bad_ [b ]+ (accepted < t - 1 ?1.0 :0.0 ); 684 }else { 685const double got = accepted + 1.0 ; 686mtp_tok_ [t ]= mtp_n_ [t ]> 0 ? (1.0 - kTokAlpha )* mtp_tok_ [t ]+ kTokAlpha * got :got ; 687mtp_n_ [t ]+= 1.0 ; 688 } 689} 690 691// ---- calibration of a fixed table against real requests (see the header) 692 693void DraftPolicy ::apply_table () { 694if (!fixed_ )return ;// a held table: cost_ is the live cost, not touched 695for (int k = 0 ;k < kCtxBuckets ;++ k ) { 696const int n = fixed_n_ [(size_t )k ]; 697if (n <=0 )continue ; 698// a size that is not real (real requests never reached it in kCalibReqs requests): its learned cost x the mean (real / learned) of the real sizes of 699// 2 or more rows, so it is not left at a price that the sizes next to it have left (size 1 stays); no real size of 2+ rows: its learned cost 700double sum = 0.0 ; 701int cnt = 0 ; 702for (int t = 2 ;t <=n ;++ t ) 703if ((real_ [(size_t )k ] >> (t - 1 )& 1u )&& learned_ [(size_t )k ][(size_t )t ]> 0.0 ) { 704sum += real_cost_ [(size_t )k ][(size_t )t ] /learned_ [(size_t )k ][(size_t )t ]; 705++ cnt ; 706 } 707const double r = cnt > 0 ?sum /cnt :1.0 ; 708for (int t = 1 ;t <=n ;++ t ) { 709if (real_ [(size_t )k ] >> (t - 1 )& 1u )cost_ [(size_t )k ][(size_t )t ]= real_cost_ [(size_t )k ][(size_t )t ]; 710else cost_ [(size_t )k ][(size_t )t ]= learned_ [(size_t )k ][(size_t )t ]* (t >=2 ?r :1.0 ); 711 } 712// more rows never cost less. An inversion is repaired from the trusted side: a size that is only guessed (not real), or that sits below another real size, is 713// LOWERED to the price of the next larger size first (a cold first-use round or a live value taken at take-over made it too high; raising every larger size to it, 714// as a forward pass alone does, made one 20 ms 2-row price of the srv118 table the price of every size from 2 to 7 rows and the policy took 12-row windows); 715// a real size above an unreached next size is left, and the forward pass then lifts that guess to it 716for (int t = n - 1 ;t >=1 ;-- t ) { 717const bool real_t = real_ [(size_t )k ] >> (t - 1 )& 1u ,real_next = real_ [(size_t )k ] >>t & 1u ; 718if (cost_ [(size_t )k ][(size_t )t ]> cost_ [(size_t )k ][(size_t )t + 1 ]&& (!real_t || real_next )) 719cost_ [(size_t )k ][(size_t )t ]= cost_ [(size_t )k ][(size_t )t + 1 ]; 720 } 721for (int t = 2 ;t <=n ;++ t ) 722if (cost_ [(size_t )k ][(size_t )t ]< cost_ [(size_t )k ][(size_t )t - 1 ])cost_ [(size_t )k ][(size_t )t ]= cost_ [(size_t )k ][(size_t )t - 1 ]; 723 } 724} 725 726void DraftPolicy ::start_calibration (bool state_effect ,const std::array < unsigned ,kCtxBuckets >& real , 727const std::array < std::array < CalAcc ,kMaxT + 1 > ,kCtxBuckets >& cal , 728const std::array < std::array < double ,kMaxT + 1 > ,kCtxBuckets >& real_cost ,int reqs ) { 729reqs_ = std::max (reqs ,0 ); 730calib_fresh_only_ = state_effect ; 731real_ = real ; 732cal_ = cal ; 733real_cost_ = real_cost ; 734for (int k = 0 ;k < kCtxBuckets ;++ k )// a mark without a cost (a damaged file) is no mark 735for (int t = 1 ;t <=kMaxT ;++ t ) 736if ((real_ [(size_t )k ] >> (t - 1 )& 1u )&& !(real_cost_ [(size_t )k ][(size_t )t ]> 0.0 ))real_ [(size_t )k ] &= ~(1u << (t - 1 )); 737apply_table (); 738calib_dirty_ = false; 739calib_on_ = false; 740for (int k = 0 ;k < kCtxBuckets ;++ k ) { 741const int n = fixed_n_ [(size_t )k ]; 742for (int t = 1 ;t <=n ;++ t ) 743if (!(real_ [(size_t )k ] >> (t - 1 )& 1u ))calib_on_ = true; 744 } 745// not calibrated: live costs decide, as without a table, until kCalibReqs requests have collected real rounds (a size real requests do not reach 746// would hold the table back for good) 747if (calib_on_ && reqs_ < kCalibReqs && fixed_ && live_saved_ )hold_table (); 748} 749 750void DraftPolicy ::start_passive (const CostFile & cf ,int n ) { 751passive_ = true; 752calib_fresh_only_ = true;// see the header: only the first seconds of a busy run count, no detection of a load-time effect 753real_ = {}; 754real_ [0 ]= cf .real [0 ]; 755cal_ = {}; 756cal_ [0 ]= cf .cal [0 ]; 757real_cost_ = {}; 758real_cost_ [0 ]= cf .real_cost [0 ]; 759learned_ = {}; 760fixed_n_ = {}; 761fixed_n_ [0 ]= std::clamp (n ,1 ,kMaxT ); 762for (int t = 1 ;t <=kMaxT ;++ t )// a mark without a cost (a damaged file) is no mark; a size past the table length is none 763if ((real_ [0 ] >> (t - 1 )& 1u )&& (!(real_cost_ [0 ][(size_t )t ]> 0.0 )|| t > fixed_n_ [0 ]))real_ [0 ] &= ~(1u << (t - 1 )); 764reqs_ = std::max (cf .reqs ,0 ); 765held_table_ = true; 766fixed_ = false; 767calib_on_ = true; 768calib_dirty_ = false; 769} 770 771void DraftPolicy ::take_over_passive () { 772const int bk_was = bk_ ; 773for (int k = 0 ;k < kCtxBuckets ;++ k ) { 774const int n = fixed_n_ [(size_t )k ]; 775for (int t = 1 ;t <=n ;++ t ) { 776double v ; 777if (real_ [(size_t )k ] >> (t - 1 )& 1u )v = real_cost_ [(size_t )k ][(size_t )t ];// a real size: its own cost 778else if (cost_n_ [k ][t ]> 0 && cost_ [k ][t ]> 0.0 )v = cost_ [k ][t ];// a size never reached 16 rounds: what the live estimator has now 779else { 780bk_ = k ; 781v = cost_ms (t );// never measured: the policy's own prior, as without a table 782bk_ = bk_was ; 783 } 784if (!(v > 0.0 ))v = t > 1 ?learned_ [(size_t )k ][(size_t )t - 1 ] :1.0 ; 785learned_ [(size_t )k ][(size_t )t ]= v ; 786 } 787 } 788passive_ = false; 789} 790 791void DraftPolicy ::hold_table () { 792for (int k = 0 ;k < kCtxBuckets ;++ k ) { 793if (fixed_n_ [(size_t )k ] <=0 )continue ; 794cost_ [(size_t )k ]= live_cost_ [(size_t )k ]; 795cost_n_ [(size_t )k ]= live_n_ [(size_t )k ]; 796 } 797fixed_ = false; 798held_table_ = true; 799held_ .clear (); 800} 801 802void DraftPolicy ::use_table () { 803fixed_ = true; 804apply_table ();// every size is real: its real cost 805for (int k = 0 ;k < kCtxBuckets ;++ k ) { 806const int n = fixed_n_ [(size_t )k ]; 807if (n <=0 )continue ; 808for (int t = 1 ;t <=kMaxT ;++ t ) { 809const bool in = t <=n && cost_ [(size_t )k ][(size_t )t ]> 0.0 ; 810if (!in )cost_ [(size_t )k ][(size_t )t ]= 0.0 ; 811cost_n_ [(size_t )k ][(size_t )t ]= in ?1e6 :0.0 ; 812 } 813 } 814fixed_ = true; 815held_table_ = false; 816held_ .clear (); 817} 818 819void DraftPolicy ::calib_add (int bucket ,int t ,double ms ,double age ) { 820 static_assert(kCalibN <=CalAcc ::kVals ,"a size's rounds are all kept for the median" ); 821if (bucket < 0 || bucket >=kCtxBuckets || t < 1 || t > fixed_n_ [(size_t )bucket ])return ; 822if (real_ [(size_t )bucket ] >> (t - 1 )& 1u )return ; 823if (calib_fresh_only_ && age > CostLearner ::kFreshS )return ;// the table is what rounds of the first seconds of a busy run cost 824double base = learned_ [(size_t )bucket ][(size_t )t ]; 825if (!(base > 0.0 )&& passive_ )base = cost_n_ [bucket ][t ]> 0 ?cost_ [bucket ][t ] :0.0 ;// no learned table: the live cost of the size is the reference 826if (!(base > 0.0 ))return ; 827CalAcc & a = cal_ [(size_t )bucket ][(size_t )t ]; 828if (a .n >=kCalibN )return ; 829const double r = std::clamp (ms ,kCalibLo * base ,kCalibHi * base );// one stalled round moves the mean by at most (kCalibHi - 1) / kCalibN 830a .sum += r ; 831if (a .nv == a .n && a .n < CalAcc ::kVals )a .vals [(size_t )a .nv ++ ]= r ;// the rounds are kept: the price is their median 832a .n += 1 ; 833calib_dirty_ = true; 834} 835 836bool DraftPolicy ::calibrate (CostFile & cf , std::string & report ) { 837report .clear (); 838if (!calib_on_ && !calib_dirty_ )return false; 839if (held_table_ )++ reqs_ ;// a request that ran while the table is held back 840char b [96 ]; 841bool changed = calib_dirty_ || held_table_ ,replaced = false;// a held table: the request count changed 842for (int k = 0 ;k < kCtxBuckets ;++ k ) { 843const int n = fixed_n_ [(size_t )k ]; 844for (int t = 1 ;t <=n ;++ t ) { 845if (real_ [(size_t )k ] >> (t - 1 )& 1u )continue ; 846CalAcc & a = cal_ [(size_t )k ][(size_t )t ]; 847if (a .n < kCalibN )continue ; 848double v = a .sum /a .n ;// a file from before the kept rounds: the mean 849if (a .nv == a .n && a .n > 0 ) {// the median of the rounds: a cold first use, a stall, another process move a mean, not a median 850 std::array < double ,CalAcc ::kVals > s = a .vals ; 851 std::sort (s .begin (),s .begin ()+ a .nv ); 852v = a .nv %2 == 1 ?s [(size_t )a .nv /2 ] :0.5 * (s [(size_t )a .nv /2 - 1 ]+ s [(size_t )a .nv /2 ]); 853 } 854const double base = learned_ [(size_t )k ][(size_t )t ]; 855if (!(base > 0.0 )|| (v >=kCalibOkLo * base && v <=kCalibOkHi * base )) {// no learned cost (passive): the clamped rounds are taken as they are 856if (base > 0.0 ) std::snprintf (b ,sizeof b ,"%s%d rows %.2f -> %.2f" ,report .empty () ?"" :", " ,t ,base ,v ); 857else std::snprintf (b ,sizeof b ,"%s%d rows real %.2f" ,report .empty () ?"" :", " ,t ,v ); 858report += b ; 859real_cost_ [(size_t )k ][(size_t )t ]= v ; 860real_ [(size_t )k ] |=1u << (t - 1 ); 861replaced = true; 862 } 863a = CalAcc {};// replaced, or disturbed (rounds dropped, collected again) 864 } 865 } 866if (replaced && fixed_ ) {// the table is in use with sizes that were not reached: their scaled costs follow the real sizes 867 std::array < std::array < double ,kMaxT + 1 > ,kCtxBuckets > before = cost_ ; 868apply_table (); 869for (int k = 0 ;k < kCtxBuckets ;++ k ) 870for (int t = 1 ;t <=fixed_n_ [(size_t )k ];++ t ) 871if (!(real_ [(size_t )k ] >> (t - 1 )& 1u )&& std::fabs (cost_ [(size_t )k ][(size_t )t ]- before [(size_t )k ][(size_t )t ])> 0.005 ) { 872 std::snprintf (b ,sizeof b ,"%s%d rows (not real yet) %.2f -> %.2f" ,report .empty () ?"" :", " ,t ,before [(size_t )k ][(size_t )t ],cost_ [(size_t )k ][(size_t )t ]); 873report += b ; 874 } 875 } 876for (int k = 0 ;k < kCtxBuckets ;++ k ) { 877const int n = fixed_n_ [(size_t )k ]; 878if (n <=0 )continue ; 879if (!(passive_ && !fixed_ ))cf .tables [(size_t )k ].assign (learned_ [(size_t )k ].begin ()+ 1 ,learned_ [(size_t )k ].begin ()+ 1 + n );// the file keeps the learned costs 880cf .real [(size_t )k ]= real_ [(size_t )k ]; 881for (int t = 0 ;t <=kMaxT ;++ t ) { 882cf .cal [(size_t )k ][(size_t )t ]= cal_ [(size_t )k ][(size_t )t ]; 883cf .real_cost [(size_t )k ][(size_t )t ]= real_cost_ [(size_t )k ][(size_t )t ]; 884 } 885 } 886cf .state_effect = calib_fresh_only_ ; 887cf .reqs = reqs_ ; 888cf .fresh = passive_ ; 889calib_dirty_ = false; 890calib_on_ = false; 891for (int k = 0 ;k < kCtxBuckets ;++ k ) 892for (int t = 1 ;t <=fixed_n_ [(size_t )k ];++ t ) 893if (!(real_ [(size_t )k ] >> (t - 1 )& 1u ))calib_on_ = true; 894// the last size is calibrated, or kCalibReqs requests have not reached the rest: the table decides from the next round on 895if (held_table_ && (!calib_on_ || reqs_ >=kCalibReqs )) { 896if (passive_ ) { 897take_over_passive (); 898for (int k = 0 ;k < kCtxBuckets ;++ k ) { 899const int n = fixed_n_ [(size_t )k ]; 900if (n > 0 )cf .tables [(size_t )k ].assign (learned_ [(size_t )k ].begin ()+ 1 ,learned_ [(size_t )k ].begin ()+ 1 + n ); 901 } 902cf .fresh = false; 903changed = true; 904 } 905use_table (); 906if (calib_on_ )report += std::string (report .empty () ?"" :", " )+ "table in use, sizes real requests did not reach keep a scaled learned cost" ; 907 } 908return changed || replaced ; 909} 910 911void DraftPolicy ::observe_committed (bool lookup ,int t ,int accepted ,int match ) { 912t = std::clamp (t ,1 ,kMaxT ); 913rounds_ += 1.0 ; 914if (lookup ) { 915tried_ [bk_ ][t ]+= 1.0 ; 916last_ [bk_ ][t ]= rounds_ ;// tried now: not stale within this generation 917const int b = bucket (match ); 918ok_ [b ]= kDecay * ok_ [b ]+ accepted ; 919bad_ [b ]= kDecay * bad_ [b ]+ (accepted < t - 1 ?1.0 :0.0 ); 920 }else { 921const double got = accepted + 1.0 ; 922mtp_tok_ [t ]= mtp_n_ [t ]> 0 ? (1.0 - kTokAlpha )* mtp_tok_ [t ]+ kTokAlpha * got :got ; 923mtp_n_ [t ]+= 1.0 ; 924 } 925} 926 927void DraftPolicy ::defer_cost (int64_t end ,int t ,double round_ms ) { 928if (round_ms > 0 && (learning_ || calib_on_ || !fixed_ ))held_ .push_back ({end ,bk_ , std::clamp (t ,1 ,kMaxT ),round_ms ,busy_age_ }); 929} 930 931void DraftPolicy ::apply_costs (int64_t committed ) { 932size_t n = 0 ; 933const int bucket_now = bk_ ; 934for (;n < held_ .size ()&& held_ [n ].end < committed ;++ n ) { 935const HeldCost & h = held_ [n ]; 936if (learning_ )learner_ .add (h .bucket ,h .t ,h .ms ,h .age ); 937if (calib_on_ )calib_add (h .bucket ,h .t ,h .ms ,h .age ); 938if (fixed_ )continue ; 939bk_ = h .bucket ;// observe()'s update, in the bucket the round ran in 940const double ms = clamp_sample (h .t ,h .ms ); 941const double alpha = robust_ ? std::max (kCostAlpha ,1.0 / (cost_n_ [bk_ ][h .t ]+ 1.0 )) :kCostAlpha ; 942cost_ [bk_ ][h .t ]= cost_n_ [bk_ ][h .t ]> 0 ? (1.0 - alpha )* cost_ [bk_ ][h .t ]+ alpha * ms :ms ; 943cost_n_ [bk_ ][h .t ]+= 1.0 ; 944delayed_n_ [bk_ ][h .t ]+= 1.0 ;// a round already counted by observe_committed 945last_ [bk_ ][h .t ]= rounds_ ; 946 } 947bk_ = bucket_now ; 948held_ .erase (held_ .begin (),held_ .begin ()+ (std::ptrdiff_t )n ); 949} 950 951namespace { 952int p_bucket (double p ) { 953const int b = (int ) (p * 8.0 ); 954return b < 0 ?0 :b > 7 ?7 :b ; 955} 956}// namespace 957 958// Until a bucket has data a draft is as likely to hold as the MTP says (worth kPriorN observations); measured 959// acceptance of the MTP chain is not the same as its own softmax (code and thinking text are over-confident). 960double DraftPolicy ::draft_rate (double p )const { 961const int b = p_bucket (p ); 962const double centre = std::clamp (p ,0.0 ,1.0 ); 963return (pa_ok_ [b ]+ kPriorN * centre ) / (pa_n_ [b ]+ kPriorN ); 964} 965 966void DraftPolicy ::observe_probs (const float * p ,int n ,int accepted ) { 967// draft j was reached when the drafts before it held; it held when j < accepted 968for (int j = 0 ;j < n && j <=accepted ;++ j ) { 969const int b = p_bucket (p [j ]); 970pa_ok_ [b ]= kCalDecay * pa_ok_ [b ]+ (j < accepted ?1.0 :0.0 ); 971pa_n_ [b ]= kCalDecay * pa_n_ [b ]+ 1.0 ; 972 } 973} 974 975bool DraftPolicy ::keep_draft (ChainState & st ,int idx ,float p ,int cap )const { 976cap = std::clamp (cap ,1 ,max_t_ ); 977if (idx == 0 ) { 978st = ChainState {}; 979st .best_v = 1.0 /cost_ms (1 ); 980 } 981const double a = draft_rate (p ); 982st .q *=a ; 983st .e += st .q ; 984const int rows = idx + 2 ; 985if (rows <=cap ) { 986const double v = st .e /cost_ms (rows ); 987if (v > st .best_v * (1.0 + margin_ /3.0 )) { 988st .best_v = v ; 989st .best_rows = rows ; 990 } 991// a width not measured yet is tried a few times when the chain is likely to hold that far 992if (!fixed_ && cost_n_ [bk_ ][rows ]< kProbes && st .q >=0.15 )st .best_rows = rows ; 993 } 994st .kept = st .best_rows - 1 ; 995if (rows + 1 > cap )return false;// no row left for another draft 996// one or two more drafts, each as likely to hold as this one did, could they beat the best width so far? 997const double v1 = (st .e + st .q * a ) /cost_ms (rows + 1 ); 998const double v2 = rows + 2 <=cap ? (st .e + st .q * a + st .q * a * a ) /cost_ms (rows + 2 ) :0.0 ; 999return std::max (v1 ,v2 )> st .best_v * (1.0 + margin_ /3.0 )|| (!fixed_ && cost_n_ [bk_ ][rows + 1 ]< kProbes && st .q * a >=0.15 ); 1000} 1001 1002double DraftPolicy ::chain_rate (int match )const { 1003// prior: a chained draft is a lookup continuing the MTP's drafts - weaker evidence than a plain match of that length 1004constexpr double kChainPrior [kBuckets ]= {0.45 ,0.65 ,0.8 ,0.9 }; 1005const int b = bucket (match ); 1006return (cok_ [b ]+ kPriorN * kChainPrior [b ]) / (cok_ [b ]+ cbad_ [b ]+ kPriorN ); 1007} 1008 1009int DraftPolicy ::chain (int t_mtp ,double p_mtp ,int k_avail ,int match )const { 1010t_mtp = std::clamp (t_mtp ,1 ,max_t_ ); 1011const int kmax = std::min (k_avail ,max_t_ - t_mtp ); 1012if (kmax <=0 )return 0 ; 1013const double e0 = mtp_tokens (t_mtp ),base = e0 /cost_ms (t_mtp ),c = chain_rate (match ); 1014p_mtp = std::clamp (p_mtp ,0.0 ,1.0 ); 1015double gain = 0.0 ,ci = 1.0 ,best = 0.0 ; 1016int best_k = 0 ; 1017for (int k = 1 ;k <=kmax ;++ k ) { 1018ci *=c ; 1019gain += ci ; 1020if (!allowed (t_mtp + k ))continue ; 1021const double r = (e0 + p_mtp * gain ) /cost_ms (t_mtp + k ); 1022if (r > best ) {best = r ;best_k = k ; } 1023 } 1024const int t_full = fit (t_mtp + kmax ),k_full = t_full - t_mtp ; 1025if (best_k > 0 && best > base * (1.0 + margin_ )) { 1026// As choose(): a profitable shorter chain must not keep a stale full size from being measured again. 1027if (best_k < k_full && p_mtp * c >=0.6 && stale (t_full ))return k_full ; 1028return best_k ; 1029 } 1030// as choose(): a size whose cost is only guessed is tried a few times when the continuation looks likely 1031if (!fixed_ && k_full > 0 && (cost_n_ [bk_ ][t_full ]< kProbes || stale (t_full ))&& p_mtp * c >=0.6 )return k_full ; 1032return 0 ; 1033} 1034 1035void DraftPolicy ::observe_chain (int t_mtp ,int k ,int accepted ,int match ,double round_ms ) { 1036const int t = std::clamp (t_mtp + k ,1 ,kMaxT ); 1037if (learning_ && round_ms > 0 )learner_ .add (bk_ ,t ,round_ms ,busy_age_ ); 1038if (round_ms > 0 && !fixed_ ) { 1039round_ms = clamp_sample (t ,round_ms ); 1040const double alpha = robust_ ? std::max (kCostAlpha ,1.0 / (cost_n_ [bk_ ][t ]+ 1.0 )) :kCostAlpha ;// a running mean for the first samples 1041cost_ [bk_ ][t ]= cost_n_ [bk_ ][t ]> 0 ? (1.0 - alpha )* cost_ [bk_ ][t ]+ alpha * round_ms :round_ms ; 1042cost_n_ [bk_ ][t ]+= 1.0 ; 1043last_ [bk_ ][t ]= rounds_ ; 1044 } 1045rounds_ += 1.0 ; 1046// the MTP part is an ordinary MTP window as far as its own drafts go 1047const int mtp_acc = std::min (accepted ,t_mtp - 1 ); 1048const double got = mtp_acc + 1.0 ; 1049mtp_tok_ [t_mtp ]= mtp_n_ [t_mtp ]> 0 ? (1.0 - kTokAlpha )* mtp_tok_ [t_mtp ]+ kTokAlpha * got :got ; 1050mtp_n_ [t_mtp ]+= 1.0 ; 1051if (accepted < t_mtp - 1 )return ;// the chain was never reached: it says nothing about the lookup 1052const int b = bucket (match ),ok = accepted - (t_mtp - 1 ); 1053cok_ [b ]= kDecay * cok_ [b ]+ ok ; 1054cbad_ [b ]= kDecay * cbad_ [b ]+ (ok < k ?1.0 :0.0 ); 1055} 1056 1057}// namespace strata::spec