okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7dbd8c09f
main
1"""tools/bench_eviction.py - replay a `--dump-routing` trace against candidate ExpertCache eviction policies. 2 3`ExpertCache::admit` never evicts: eviction policy is the measured question (R4.1's LFU-decay vs LRU sweep, 4`include/strata/core/expert_cache.hpp`), and a placeholder policy would set the hit rate that everything 5downstream is sized against. This tool is the harness for that measurement, without a GPU: a policy's hit 6rate depends only on the ORDER the run routed (layer, expert) pairs, and `--dump-routing` records exactly 7that order. Replay the trace through a simulated slot pool per policy and the rates are comparable with 8the engine's own `h`, at any slot count, on any machine. 9 10python tools/bench_eviction.py TRACE... [--slots 4105,8000] [--per-layer] [--windows 4] 11[--policies fill-only,lru,lfu-decay,oracle] [--decay-window 65536] 12[--prefill data/expert-profile.bin] [--n-expert 512] [--csv out.csv] 13 14Policies (`--policies`, default all four): 15 16fill-only the engine's current admission: compulsory miss, never evict. The baseline a policy has 17to beat, and the answer for any run whose trace never exceeds the slot count. 18lru evict the least-recently-used resident. 19lfu-decay frequency counts halved every --decay-window lookups, so a hot-once expert fades and the 20cache can follow a topic shift; evict the lowest count, the oldest on a tie. (Halving the 21table is O(slots) per window; this instead DOUBLES new increments at each window boundary, 22which scales every past access by the same 1/2 and leaves the table untouched. Comparisons 23stay exact: counts are sums of powers of two, below 2^53 for any realistic trace.) 24oracle Belady's MIN: evict the resident whose next use is furthest in the future. Not 25implementable online - it reads the trace ahead - but it is the upper bound any policy can 26reach on this trace, so it says how much headroom a real policy is leaving. 27 28Scope mirrors `ExpertCache`: global (one shared pool, the engine's default) or `--per-layer` (R4.2g: 29layer `l` owns slots `[l*q, (l+1)*q)`, `q = slots // n_layers`, the last layer taking the remainder, and 30eviction stays inside the layer's own range - `layer_slot_range` in `src/core/expert_cache.cpp`). 31 32`--prefill` starts the run with the profile's top pairs resident (rank 0 counts as most-recently-used), 33which is how the engine actually starts with `--expert-profile`; without it the run starts cold. 34 35AGENTS.md: a number needs what it was measured on. The tool prints the trace files and the lookup and 36distinct-pair counts it ran over; quote those with any rate you take from it. The trace itself comes 37from a one-shot engine run (`--dump-routing FILE` on a prompt typical of the workload) - the model, 38quant and prompt are the environment, and they belong in any report of these rates. 39""" 40from __future__import annotations 41 42import argparse 43import heapq 44import struct 45import sys 46from array import array 47from collections import defaultdict 48from pathlib import Path 49 50sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 51import make_profile as MP # noqa: E402 (the profile reader; the trace format doc lives there too) 52 53N_LAYER = MP .N_LAYER # 48, fixed like make_profile's 54N_EXPERT = MP .N_EXPERT # 512; --n-expert for a pruned model 55 56 57def encode (layer ,expert ): 58"""One (layer, expert) pair as a uint32, so a trace is 4 bytes per lookup instead of two objects.""" 59return (layer << 16 )| expert 60 61 62def decode (code ): 63return code >> 16 ,code & 0xFFFF 64 65 66def read_trace (path ,n_expert = N_EXPERT ,n_layers = N_LAYER ): 67"""The routed (layer, expert) pairs of one `--dump-routing` file, IN ORDER, as encode()d codes. 68 69Same records as make_profile.read_trace - (layer, k, k expert ids, k weights) - but eviction policy 70is a question about order, so the frequencies it returns are not enough. Out-of-range pairs are 71skipped the same way it skips them.""" 72blob = Path (path ).read_bytes () 73codes ,off = array ("I" ),0 74while off + 8 <= len (blob ): 75layer ,k = struct .unpack_from ("<ii" ,blob ,off ) 76off += 8 77for e in struct .unpack_from ("<%di" % k ,blob ,off ): 78if 0 <= layer < n_layers and 0 <= e < n_expert : 79codes .append (encode (layer ,e )) 80off += 8 * k # the ids and the weights 81return codes 82 83 84class Sim : 85"""One policy's slot pool. `lookup(code, i)` answers hit/miss for the i-th lookup of the trace and 86admits/evicts by the policy; `hits` and `evictions` accumulate. `prefill(pairs)` seats the profile's 87ranked pairs first (rank 0 = most recently used), respecting each scope's capacity.""" 88 89name = "?" 90 91def __init__ (self ,n_layers ,n_expert ,slots ,per_layer ,decay_window = 65536 ): 92self .n_layers ,self .n_expert ,self .slots ,self .per_layer = n_layers ,n_expert ,slots ,per_layer 93self .hits = 0 94self .evictions = 0 95 96def scope (self ,layer ): 97return layer if self .per_layer else 0 98 99def capacity (self ,layer ): 100"""The slots a lookup on `layer` may use - ExpertCache::layer_slot_range's range, in size.""" 101if not self .per_layer : 102return self .slots 103q = self .slots // self .n_layers 104hi = self .slots if layer == self .n_layers - 1 else (layer + 1 )* q 105return hi - layer * q 106 107def prefill (self ,pairs ): 108raise NotImplementedError 109 110def lookup (self ,code ,i ): 111raise NotImplementedError 112 113 114class FillOnly (Sim ): 115"""The engine's current admission: the first S distinct pairs stay resident forever.""" 116 117name = "fill-only" 118 119def __init__ (self ,* args ,** kw ): 120super ().__init__ (* args ,** kw ) 121self .resident = set () 122self .used = defaultdict (int )# scope -> slots taken 123 124def prefill (self ,pairs ): 125for layer ,e in pairs : 126code ,s = encode (layer ,e ),self .scope (layer ) 127if code not in self .resident and self .used [s ]< self .capacity (layer ): 128self .resident .add (code ) 129self .used [s ]+= 1 130 131def lookup (self ,code ,i ): 132layer ,_ = decode (code ) 133if code in self .resident : 134self .hits += 1 135return True 136s = self .scope (layer ) 137if self .used [s ]< self .capacity (layer ): 138self .resident .add (code ) 139self .used [s ]+= 1 140return False 141 142 143class Lru (Sim ): 144"""Evict the least-recently-used resident of the scope. OrderedDict: front = oldest.""" 145 146name = "lru" 147 148def __init__ (self ,* args ,** kw ): 149super ().__init__ (* args ,** kw ) 150from collections import OrderedDict 151self .od = defaultdict (OrderedDict )# scope -> {code: None} 152 153def prefill (self ,pairs ): 154# Take each scope's top pairs in RANKED order, then insert them reversed so rank 0 lands 155# at the MRU end. (Iterating the profile reversed would seat its COLD end instead.) 156chosen ,used = [],defaultdict (int ) 157for layer ,e in pairs : 158s = self .scope (layer ) 159if used [s ]< self .capacity (layer ): 160chosen .append ((encode (layer ,e ),s )) 161used [s ]+= 1 162for code ,s in reversed (chosen ): 163self .od [s ][code ]= None 164 165def lookup (self ,code ,i ): 166layer ,_ = decode (code ) 167od = self .od [self .scope (layer )] 168if code in od : 169od .move_to_end (code ) 170self .hits += 1 171return True 172if len (od )>= self .capacity (layer ): 173od .popitem (last = False ) 174self .evictions += 1 175od [code ]= None 176return False 177 178 179class LfuDecay (Sim ): 180"""Evict the lowest decayed-frequency resident of the scope, oldest on a tie. 181 182Every lookup adds the current increment to the pair's count; the increment doubles every 183`decay_window` lookups, which is the table-wide halving of classic LFU-decay without touching the 184table (see the module docstring). Victim selection is a lazy heap: entries go stale as counts 185grow, and are popped when they surface.""" 186 187name = "lfu-decay" 188 189def __init__ (self ,* args ,decay_window = 65536 ,** kw ): 190super ().__init__ (* args ,** kw ) 191self .decay_window = decay_window 192self .incr = 1.0 193self .tick = 0 194self .counts = {}# code -> scaled count 195self .heaps = defaultdict (list )# scope -> [(count, tick, code)] 196self .used = defaultdict (int )# scope -> slots taken 197 198def prefill (self ,pairs ): 199# Same two-step as Lru.prefill: top pairs per scope in ranked order, newest tick to rank 0. 200chosen ,used = [],defaultdict (int ) 201for layer ,e in pairs : 202s = self .scope (layer ) 203if used [s ]< self .capacity (layer ): 204chosen .append ((encode (layer ,e ),s )) 205used [s ]+= 1 206for code ,s in reversed (chosen ): 207if code not in self .counts : 208self .counts [code ]= self .incr 209heapq .heappush (self .heaps [s ], (self .incr ,self .tick ,code )) 210self .used [s ]+= 1 211self .tick += 1 212 213def lookup (self ,code ,i ): 214if self .tick > 0 and self .tick % self .decay_window == 0 : 215self .incr *= 2.0 216tick ,self .tick = self .tick ,self .tick + 1 217layer ,_ = decode (code ) 218s = self .scope (layer ) 219if code in self .counts :# resident (an evicted pair's count is deleted with it) 220self .counts [code ]+= self .incr 221heapq .heappush (self .heaps [s ], (self .counts [code ],tick ,code )) 222self .hits += 1 223return True 224if self .used [s ]>= self .capacity (layer ): 225h = self .heaps [s ] 226while h :# drop stale heap entries until the true minimum surfaces 227c ,_ ,cand = h [0 ] 228if self .counts .get (cand )== c : 229break 230heapq .heappop (h ) 231victim = heapq .heappop (h )[2 ] 232del self .counts [victim ] 233self .used [s ]-= 1 234self .evictions += 1 235self .counts [code ]= self .incr 236heapq .heappush (self .heaps [s ], (self .incr ,tick ,code )) 237self .used [s ]+= 1 238return False 239 240 241class Oracle (Sim ): 242"""Belady's MIN: evict the resident whose next use is furthest away. Needs the whole trace up 243front (`prepare`), which is exactly why it is a bound and not a candidate.""" 244 245name = "oracle" 246 247def __init__ (self ,* args ,** kw ): 248super ().__init__ (* args ,** kw ) 249self .cur = {}# code -> its next use at the current position (T: never) 250self .heaps = defaultdict (list )# scope -> [(-next_use, code)], lazy like LfuDecay's 251self .used = defaultdict (int ) 252 253def prepare (self ,codes ): 254T = len (codes ) 255nxt = array ("I" , [T ])* T 256last = {} 257for i in range (T - 1 ,- 1 ,- 1 ): 258c = codes [i ] 259nxt [i ]= last .get (c ,T ) 260last [c ]= i 261self .nxt ,self .first ,self .T = nxt ,last ,T 262 263def prefill (self ,pairs ): 264for layer ,e in pairs : 265code ,s = encode (layer ,e ),self .scope (layer ) 266if code not in self .cur and self .used [s ]< self .capacity (layer ): 267self .cur [code ]= self .first .get (code ,self .T ) 268heapq .heappush (self .heaps [s ], (- self .cur [code ],code )) 269self .used [s ]+= 1 270 271def lookup (self ,code ,i ): 272layer ,_ = decode (code ) 273s = self .scope (layer ) 274if code in self .cur : 275self .cur [code ]= self .nxt [i ] 276heapq .heappush (self .heaps [s ], (- self .nxt [i ],code )) 277self .hits += 1 278return True 279if self .used [s ]>= self .capacity (layer ): 280h = self .heaps [s ] 281while h : 282neg ,cand = h [0 ] 283if cand in self .cur and self .cur [cand ]== - neg : 284break 285heapq .heappop (h ) 286victim = heapq .heappop (h )[1 ] 287del self .cur [victim ] 288self .used [s ]-= 1 289self .evictions += 1 290self .cur [code ]= self .nxt [i ] 291heapq .heappush (self .heaps [s ], (- self .nxt [i ],code )) 292self .used [s ]+= 1 293return False 294 295 296POLICIES = {p .name :p for p in (FillOnly ,Lru ,LfuDecay ,Oracle )} 297 298 299def run (codes ,n_layers ,n_expert ,slots_list ,per_layer ,policy_names ,windows = 1 , 300decay_window = 65536 ,prefill_pairs = None ): 301"""One replay per (slots, policy). Returns rows of dicts with the overall and per-window counts.""" 302T = len (codes ) 303rows = [] 304for slots in slots_list : 305for name in policy_names : 306sim = POLICIES [name ](n_layers ,n_expert ,slots ,per_layer ,decay_window = decay_window ) 307if name == Oracle .name : 308sim .prepare (codes ) 309if prefill_pairs : 310sim .prefill (prefill_pairs ) 311w_hits ,w_tot = [0 ]* windows , [0 ]* windows 312for i ,code in enumerate (codes ): 313w = i * windows // T if T else 0 314w_tot [w ]+= 1 315if sim .lookup (code ,i ): 316w_hits [w ]+= 1 317rows .append ({ 318"slots" :slots ,"policy" :name ,"hits" :sim .hits ,"lookups" :T , 319"evictions" :sim .evictions ,"w_hits" :w_hits ,"w_tot" :w_tot , 320 }) 321return rows 322 323 324def fmt_rate (hits ,lookups ): 325return f" { hits / lookups :.4f } " if lookups else "n/a" 326 327 328def report (rows ,windows ): 329for slots in dict .fromkeys (r ["slots" ]for r in rows ): 330block = [r for r in rows if r ["slots" ]== slots ] 331f"\nslots = { slots } " ) 332f" { 'policy' :<10 } { 'hits' :>10 } { 'lookups' :>10 } { 'hit-rate' :>9 } { 'evictions' :>10 } " ) 333for r in block : 334f" { r [ 'policy' ]:<10 } { r [ 'hits' ]:>10 } { r [ 'lookups' ]:>10 } " 335f" { fmt_rate ( r [ 'hits' ], r [ 'lookups' ]):>9 } { r [ 'evictions' ]:>10 } " ) 336if windows > 1 : 337f" per-window hit-rate ( { windows } windows, in trace order):" ) 338f" { 'policy' :<10 } " + " " .join (f" { 'w' + str ( i + 1 ):>8 } " for i in range (windows ))) 339for r in block : 340rates = " " .join (f" { fmt_rate ( h , t ):>8 } " for h ,t in zip (r ["w_hits" ],r ["w_tot" ])) 341f" { r [ 'policy' ]:<10 } { rates } " ) 342 343 344def write_csv (path ,rows ,scope ): 345with open (path ,"w" )as f : 346f .write ("slots,scope,policy,window,lookups,hits,hit_rate,evictions\n" ) 347for r in rows : 348f .write (f" { r [ 'slots' ] } , { scope } , { r [ 'policy' ] } ,all, { r [ 'lookups' ] } , { r [ 'hits' ] } ," 349f" { fmt_rate ( r [ 'hits' ], r [ 'lookups' ]) } , { r [ 'evictions' ] } \n" ) 350for w , (h ,t )in enumerate (zip (r ["w_hits" ],r ["w_tot" ])): 351if len (r ["w_tot" ])> 1 : 352f .write (f" { r [ 'slots' ] } , { scope } , { r [ 'policy' ] } ,w { w + 1 } , { t } , { h } , { fmt_rate ( h , t ) } ,\n" ) 353 354 355def main (argv = None ): 356p = argparse .ArgumentParser (description = __doc__ .splitlines ()[0 ], 357formatter_class = argparse .RawDescriptionHelpFormatter ) 358p .add_argument ("traces" ,nargs = "+" ,help = "--dump-routing files, replayed in the order given" ) 359p .add_argument ("--slots" ,default = "4105" , 360help = "comma-separated slot counts (default: 4105, the R4 reference sizing)" ) 361p .add_argument ("--per-layer" ,action = "store_true" , 362help = "R4.2g admission: each layer its own slot range, eviction stays in-layer" ) 363p .add_argument ("--windows" ,type = int ,default = 1 , 364help = "split the trace into this many equal windows and report hit-rate per window" ) 365p .add_argument ("--policies" ,default = "," .join (POLICIES ), 366help = "comma-separated subset of: " + "," .join (POLICIES )) 367p .add_argument ("--decay-window" ,type = int ,default = 65536 , 368help = "lfu-decay: lookups between table-wide halvings (default: 65536)" ) 369p .add_argument ("--prefill" ,help = "profile.bin to start from (the engine's --expert-profile start)" ) 370p .add_argument ("--n-expert" ,type = int ,default = N_EXPERT ,help = "experts per layer (default: 512)" ) 371p .add_argument ("--csv" ,help = "also write the results to this CSV file" ) 372a = p .parse_args (argv ) 373 374codes = array ("I" ) 375for t in a .traces : 376codes .extend (read_trace (t ,a .n_expert )) 377if not codes : 378raise SystemExit ("no usable lookups in the trace(s)" ) 379slots_list = [int (s )for s in a .slots .split ("," )] 380policy_names = a .policies .split ("," ) 381unknown = set (policy_names )- set (POLICIES ) 382if unknown : 383raise SystemExit (f"unknown policies: { ', ' . join ( sorted ( unknown )) } (have: { ', ' . join ( POLICIES ) } )" ) 384prefill = MP .read_profile (a .prefill ,a .n_expert )if a .prefill else None 385 386scope = "per-layer" if a .per_layer else "global" 387distinct = len (set (codes )) 388f"trace: { ', ' . join ( a . traces ) } " ) 389f" { len ( codes ):, } lookups, { distinct :, } distinct (layer, expert) pairs, " 390f"scope: { scope } , prefill: { a . prefill or 'none (cold start)' } " 391+ (f", decay-window: { a . decay_window } " if "lfu-decay" in policy_names else "" )) 392if distinct <= min (slots_list ): 393"note: the distinct pairs fit in every slot count given - fill-only cannot be beaten " 394"on this trace; use a longer trace or fewer slots to see policy differences" ) 395 396rows = run (codes ,N_LAYER ,a .n_expert ,slots_list ,a .per_layer ,policy_names , 397a .windows ,a .decay_window ,prefill ) 398report (rows ,a .windows ) 399if a .csv : 400write_csv (a .csv ,rows ,scope ) 401f"\nwrote { a . csv } " ) 402 403 404if __name__ == "__main__" : 405main ()