okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1"""cachesim.py - offline expert-cache policies on routing traces (DS4_TRACE files of strata-dsv41). 2 3A trace is a run of records: u8 layer, u8 T (bit 7: guesses follow), T x k int16 expert ids [, u8 na1, u8 na2, T x (na1 + na2) 4int16 guesses for the next layer and the one after]. One decode step (or verify window) is the records of layers 0..nl-1 in order. 5 6Sizes are in bytes (an expert's real size in its layer: sizes.json), capacities in GB. Policies: 7lru one global LRU over (layer, expert) 8lfu frequency with exponential decay (LRFU / CRF), evicts the lowest score 9static the N hottest by training-trace frequency (a shipped per-set profile), no adaptation 10static+lru half the capacity pinned from the profile, half LRU 11belady the offline optimum (farthest next use): the ceiling for any predictor of reuse 12lru+ahead LRU plus a prefetch of the guesses for the next layer (top m): counts the wasted bytes 13Reports: hit rate (by accesses and by bytes), SSD bytes per token (misses + wasted prefetch), the share of misses a guess covered. 14""" 15import argparse 16import collections 17import heapq 18import json 19import math 20import os 21import struct 22import sys 23 24 25WARM = 0 # accesses before this index warm the cache but are not counted 26 27 28def read_trace (path ,k = 6 ): 29"""-> list of steps; a step = list of (layer, [rows of expert ids], guesses or None).""" 30data = open (path ,'rb' ).read () 31pos ,n = 0 ,len (data ) 32steps ,cur ,last_layer = [], [],- 1 33while pos + 2 <= n : 34layer ,t = data [pos ],data [pos + 1 ] 35pos += 2 36has_ahead = bool (t & 0x80 ) 37t &= 0x7f 38rows = [] 39for _ in range (t ): 40rows .append (list (struct .unpack_from ('<%dh' % k ,data ,pos ))) 41pos += 2 * k 42guesses = None 43if has_ahead : 44na1 ,na2 = data [pos ],data [pos + 1 ] 45pos += 2 46guesses = [] 47for _ in range (t ): 48g1 = list (struct .unpack_from ('<%dh' % na1 ,data ,pos ))if na1 else [] 49pos += 2 * na1 50g2 = list (struct .unpack_from ('<%dh' % na2 ,data ,pos ))if na2 else [] 51pos += 2 * na2 52guesses .append ((g1 ,g2 )) 53if layer <= last_layer and cur : 54steps .append (cur ) 55cur = [] 56last_layer = layer 57cur .append ((layer ,rows ,guesses )) 58if cur : 59steps .append (cur ) 60return steps 61 62 63def accesses (steps ): 64"""the flat access stream: (step, layer, expert) with the union over a window's rows, in layer order""" 65out = [] 66for si ,st in enumerate (steps ): 67for layer ,rows ,_ in st : 68seen = [] 69for r in rows : 70for e in r : 71if e not in seen : 72seen .append (e ) 73for e in seen : 74out .append ((si ,layer ,e )) 75return out 76 77 78class Sizes : 79def __init__ (self ,path ): 80d = json .load (open (path )) 81el = d ['exp_layer' ] 82self .s = {int (k ):float (v )for k ,v in el .items ()} 83 84def __call__ (self ,layer ): 85return self .s .get (layer ,8.6e6 ) 86 87 88def sim_lru (acc ,size ,cap ): 89od = collections .OrderedDict () 90used = hits = hitb = tot = totb = 0 91for i , (_ ,l ,e )in enumerate (acc ): 92k = (l ,e ) 93sz = size (l ) 94cnt = i >= WARM 95tot += cnt 96totb += sz * cnt 97if k in od : 98od .move_to_end (k ) 99hits += cnt 100hitb += sz * cnt 101continue 102od [k ]= sz 103used += sz 104while used > cap : 105_ ,s0 = od .popitem (last = False ) 106used -= s0 107return hits ,hitb ,tot ,totb 108 109 110def sim_lfu (acc ,size ,cap ,half_life_acc = 20000 ): 111lam = math .log (2 )/ half_life_acc 112score ,last ,res = {}, {}, {} 113heap = [] 114used = hits = hitb = tot = totb = 0 115for t , (_ ,l ,e )in enumerate (acc ): 116k = (l ,e ) 117sz = size (l ) 118cnt = t >= WARM 119tot += cnt 120totb += sz * cnt 121# CRF: decayed count, kept in log space: v = log(count) + lam * t 122if k in res : 123hits += cnt 124hitb += sz * cnt 125old = score .get (k ) 126v = lam * t 127score [k ]= v if old is None else v + math .log1p (math .exp (old - v ))if old - v < 50 else old 128if k not in res : 129res [k ]= sz 130used += sz 131heapq .heappush (heap , (score [k ],k )) 132while used > cap and heap : 133sc ,kk = heapq .heappop (heap ) 134if kk not in res or score [kk ]!= sc : 135continue 136if kk == k and len (res )== 1 : 137break 138used -= res .pop (kk ) 139return hits ,hitb ,tot ,totb 140 141 142def freq_table (acc ): 143c = collections .Counter ((l ,e )for _ ,l ,e in acc ) 144return c 145 146 147def pick_static (freq ,size ,cap ): 148keys = sorted (freq ,key = lambda k :- freq [k ]/ size (k [0 ])) 149chosen ,used = set (),0 150for k in keys : 151s = size (k [0 ]) 152if used + s > cap : 153continue 154chosen .add (k ) 155used += s 156return chosen 157 158 159def sim_static (acc ,size ,chosen ): 160hits = hitb = tot = totb = 0 161for i , (_ ,l ,e )in enumerate (acc ): 162sz = size (l ) 163cnt = i >= WARM 164tot += cnt 165totb += sz * cnt 166if (l ,e )in chosen : 167hits += cnt 168hitb += sz * cnt 169return hits ,hitb ,tot ,totb 170 171 172def sim_static_lru (acc ,size ,cap ,chosen ,pinned_bytes ): 173od = collections .OrderedDict () 174used = hits = hitb = tot = totb = 0 175room = cap - pinned_bytes 176for i , (_ ,l ,e )in enumerate (acc ): 177k = (l ,e ) 178sz = size (l ) 179cnt = i >= WARM 180tot += cnt 181totb += sz * cnt 182if k in chosen : 183hits += cnt 184hitb += sz * cnt 185continue 186if k in od : 187od .move_to_end (k ) 188hits += cnt 189hitb += sz * cnt 190continue 191od [k ]= sz 192used += sz 193while used > room : 194_ ,s0 = od .popitem (last = False ) 195used -= s0 196return hits ,hitb ,tot ,totb 197 198 199def sim_belady (acc ,size ,cap ): 200n = len (acc ) 201nxt = [0 ]* n 202last = {} 203for i in range (n - 1 ,- 1 ,- 1 ): 204k = (acc [i ][1 ],acc [i ][2 ]) 205nxt [i ]= last .get (k ,n + 1 ) 206last [k ]= i 207res = {}# k -> next use 208heap = []# (-next use, k) 209used = hits = hitb = tot = totb = 0 210for i , (_ ,l ,e )in enumerate (acc ): 211k = (l ,e ) 212sz = size (l ) 213cnt = i >= WARM 214tot += cnt 215totb += sz * cnt 216if k in res : 217hits += cnt 218hitb += sz * cnt 219res [k ]= nxt [i ] 220heapq .heappush (heap , (- nxt [i ],k )) 221continue 222if nxt [i ]> n :# never used again: do not keep 223continue 224res [k ]= nxt [i ] 225used += sz 226heapq .heappush (heap , (- nxt [i ],k )) 227while used > cap and heap : 228nu ,kk = heapq .heappop (heap ) 229if kk not in res or res [kk ]!= - nu : 230continue 231used -= size (kk [0 ]) 232del res [kk ] 233return hits ,hitb ,tot ,totb 234 235 236def sim_lru_ahead (steps ,size ,cap ,m = 6 ,depth = 1 ): 237"""LRU + prefetch of the top-m guesses (from the record of layer L-1 for layer L): a miss that a guess covered is a 'hidden' 238miss (its read started a layer early), a guess nobody used is wasted bytes.""" 239od = collections .OrderedDict () 240used = 0 241hits = tot = miss = hidden = 0 242ssd = 0.0 243wasted = 0.0 244pend = {}# (layer, expert) -> bytes prefetched, not yet used this step 245nsteps = len (steps ) 246 247def put (k ,sz ): 248nonlocal used 249if k in od : 250od .move_to_end (k ) 251return 252od [k ]= sz 253used += sz 254while used > cap : 255_ ,s0 = od .popitem (last = False ) 256used -= s0 257 258for st in steps : 259pend .clear () 260for layer ,rows ,guesses in st : 261sz = size (layer ) 262seen = [] 263for r in rows : 264for e in r : 265if e not in seen : 266seen .append (e ) 267for e in seen : 268k = (layer ,e ) 269tot += 1 270if k in pend : 271hidden += 1 272del pend [k ] 273miss += 1 274put (k ,sz ) 275elif k in od : 276hits += 1 277od .move_to_end (k ) 278else : 279miss += 1 280ssd += sz 281put (k ,sz ) 282for k ,b in list (pend .items ()): 283if k [0 ]<= layer : 284wasted += b 285del pend [k ] 286if guesses : 287nl = layer + 1 288gs = [] 289for g1 ,g2 in guesses : 290for e in g1 [:m ]: 291if e not in gs : 292gs .append (e ) 293for e in gs : 294k = (nl ,e ) 295if k in od or k in pend : 296continue 297pend [k ]= size (nl ) 298ssd += size (nl ) 299for b in pend .values (): 300wasted += b 301return dict (hit = hits / max (1 ,tot ),hidden = hidden / max (1 ,tot ),ssd_per_step_MB = ssd / max (1 ,nsteps )/ 1e6 , 302wasted_per_step_MB = wasted / max (1 ,nsteps )/ 1e6 ) 303 304 305def main (): 306ap = argparse .ArgumentParser () 307ap .add_argument ('traces' ,nargs = '+' ,help = 'trace files: all are test sets; --train-on names the profile source' ) 308ap .add_argument ('--sizes' ,default = 'C:/ds-ista-work/sizes.json' ) 309ap .add_argument ('--caps' ,default = '20,30,40,44' ,help = 'cache sizes in GB (VRAM hot set + pinned RAM)' ) 310ap .add_argument ('--train' ,nargs = '*' ,default = [],help = 'traces the static profile is built from (others than the test)' ) 311ap .add_argument ('--warm-steps' ,type = int ,default = 0 ,help = 'steps at the start that fill the cache but are not counted' ) 312ap .add_argument ('--skip' ,default = '' ,help = 'policies to skip (comma): lru,lfu,static,static+lru,belady,ahead' ) 313a = ap .parse_args () 314size = Sizes (a .sizes ) 315global WARM 316skip = set (a .skip .split (',' )) 317train_acc = [] 318for t in a .train : 319train_acc += accesses (read_trace (t )) 320for path in a .traces : 321steps = read_trace (path ) 322acc = accesses (steps ) 323nsteps = len (steps ) 324WARM = 0 325if a .warm_steps : 326WARM = next ((i for i ,x in enumerate (acc )if x [0 ]>= a .warm_steps ),len (acc )) 327nsteps -= a .warm_steps 328uniq = len ({(l ,e )for _ ,l ,e in acc }) 329' unique experts touched: %d of 15360 (%.1f%%), %.1f GB' % (uniq ,100 * uniq / 15360 ,sum (size (l )for l ,e in {(l ,e )for _ ,l ,e in acc })/ 1e9 )) 330'== %s: %d steps, %d expert accesses (%.1f a step)' % (os .path .basename (path ),nsteps ,len (acc ),len (acc )/ max (1 ,nsteps ))) 331tb = sum (size (l )for _ ,l ,_ in acc )/ nsteps 332' bytes a step (union per layer): %.2f GB' % (tb / 1e9 )) 333' %-14s %6s %9s %9s %12s' % ('policy' ,'capGB' ,'hit(acc)' ,'hit(bytes)' ,'SSD MB/step' )) 334for cg in [float (x )for x in a .caps .split (',' )]: 335cap = cg * 1e9 336rows = [] 337if 'lru' not in skip : 338rows .append (('lru' ,sim_lru (acc ,size ,cap ))) 339if 'lfu' not in skip : 340rows .append (('lfu(decay)' ,sim_lfu (acc ,size ,cap ))) 341if train_acc and 'static' not in skip : 342ch = pick_static (freq_table (train_acc ),size ,cap ) 343rows .append (('static' ,sim_static (acc ,size ,ch ))) 344ch2 = pick_static (freq_table (train_acc ),size ,cap / 2 ) 345rows .append (('static+lru' ,sim_static_lru (acc ,size ,cap ,ch2 ,cap / 2 ))) 346if 'belady' not in skip : 347rows .append (('belady' ,sim_belady (acc ,size ,cap ))) 348for name , (h ,hb ,t ,tb_ )in rows : 349' %-14s %6.0f %8.1f%% %8.1f%% %12.1f' % (name ,cg ,100 * h / t ,100 * hb / tb_ , (tb_ - hb )/ nsteps / 1e6 )) 350if 'ahead' not in skip and any (g for st in steps for _ ,_ ,g in st ): 351for m in (6 ,8 ,12 ): 352r = sim_lru_ahead (steps ,size ,cap ,m = m ) 353' lru+ahead(top%-2d) %4.0f hit %.1f%% (+%.1f%% hidden) SSD %.0f MB/step (wasted %.0f)' % ( 354m ,cg ,100 * r ['hit' ],100 * r ['hidden' ],r ['ssd_per_step_MB' ],r ['wasted_per_step_MB' ])) 355 356 357if __name__ == '__main__' : 358main ()