okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d5f319bff
main
1"""Offline replay of a --dump-routing trace through the expert cache policies. 2 3python replay_cache_policy.py TRACE.bin PROFILE.bin SLOTS [--every 4 --decay 0.7 --swaps 96 --margin 1.5 --mincand 2.0] 4 5Trace record = int32 layer, int32 k, k int32 ids, k float32 weights; the verify window writes one record per token and 6layer, so a layer group is the run of records with one layer and a window starts when the layer does not rise. 7The simulated adaptive tier is generate.cpp's adapt(): usage += 1 per routed entry, a round every `every` windows, per 8layer the best non-resident (usage >= mincand) against the worst resident (needs margin), the best `swaps` over all 9layers, usage *= decay. Reports the share of routed entries served by the cache (the engine's "hits / all routed"). 10""" 11import sys 12import numpy as np 13 14NL ,NE = 48 ,512 15 16 17def load_trace (path ): 18raw = np .fromfile (path ,dtype = np .int32 ) 19k = int (raw [1 ]) 20rec = 2 + 2 * k 21raw = raw [: (len (raw )// rec )* rec ].reshape (- 1 ,rec ) 22layer = raw [:,0 ] 23ids = raw [:,2 :2 + k ] 24# layer groups 25chg = np .flatnonzero (np .diff (layer )!= 0 )+ 1 26starts = np .concatenate ([[0 ],chg ]) 27ends = np .concatenate ([chg , [len (layer )]]) 28windows ,cur ,last = [],None ,- 1 29for s ,e in zip (starts ,ends ): 30l = int (layer [s ]) 31if cur is None or l <= last : 32if cur is not None : 33windows .append (cur ) 34cur = [] 35cur .append ((l ,ids [s :e ])) 36last = l 37if cur : 38windows .append (cur ) 39# keep complete windows only 40return [w for w in windows if len (w )== NL ],k 41 42 43def load_profile (path ,slots ): 44with open (path ,"rb" )as f : 45assert f .read (4 )== b"STRP" 46hdr = np .frombuffer (f .read (20 ),dtype = np .uint32 ) 47n_ranked = int (hdr [4 ]) 48pairs = np .frombuffer (f .read (4 * n_ranked ),dtype = np .uint16 ).reshape (- 1 ,2 ) 49return pairs [:slots ] 50 51 52class Policy : 53def __init__ (self ,every = 4 ,decay = 0.7 ,swaps = 96 ,margin = 1.5 ,mincand = 2.0 ,mode = 'entries' ,mingain = 0.0 ,posw = 1.0 ): 54self .every ,self .decay ,self .swaps ,self .margin ,self .mincand = every ,decay ,swaps ,margin ,mincand 55self .mode ,self .mingain ,self .posw = mode ,mingain ,posw 56 57 58def adapt_round (res ,usage ,pol ): 59sw = [] 60for l in range (NL ): 61u = usage [l ] 62r = res [l ] 63cand = np .flatnonzero (~ r & (u >= pol .mincand )) 64vict = np .flatnonzero (r ) 65if len (cand )== 0 or len (vict )== 0 : 66continue 67cand = cand [np .argsort (- u [cand ],kind = "stable" )] 68vict = vict [np .argsort (u [vict ],kind = "stable" )] 69n = min (len (cand ),len (vict )) 70gain = u [cand [:n ]]- u [vict [:n ]] 71ok = u [cand [:n ]]>= u [vict [:n ]]+ pol .margin 72# the engine stops at the first pair that does not clear the margin 73bad = np .flatnonzero (~ ok ) 74n2 = int (bad [0 ])if len (bad )else n 75for i in range (n2 ): 76sw .append ((gain [i ],l ,int (cand [i ]),int (vict [i ]))) 77sw .sort (key = lambda t :- t [0 ]) 78sw = [t for t in sw if t [0 ]>= pol .mingain ][:pol .swaps ] 79for g ,l ,i ,o in sw : 80res [l ,i ]= True 81res [l ,o ]= False 82return len (sw ) 83 84 85def simulate (windows ,init ,pol ,reset_every = 0 ): 86res = np .zeros ((NL ,NE ),bool ) 87res [init [:,0 ],init [:,1 ]]= True 88usage = np .zeros ((NL ,NE )) 89hits = ent = swaps = 0 90miss_ent = miss_dist = 0 91for wi ,w in enumerate (windows ): 92for l ,ids in w : 93r = res [l ,ids ] 94hits += int (r .sum ()) 95ent += r .size 96ms = ids [~ r ] 97miss_ent += len (ms ) 98miss_dist += len (np .unique (ms )) 99if pol .mode == 'distinct' : 100usage [l ,np .unique (ids )]+= 1.0 101elif pol .posw != 1.0 : 102wts = np .repeat (pol .posw ** np .arange (ids .shape [0 ]),ids .shape [1 ]) 103np .add .at (usage [l ],ids .ravel (),wts ) 104else : 105np .add .at (usage [l ],ids .ravel (),1.0 ) 106if (wi + 1 )% pol .every == 0 : 107swaps += adapt_round (res ,usage ,pol ) 108usage *= pol .decay 109return dict (share = hits / max (1 ,ent ),swaps = swaps ,windows = len (windows ),entries = ent ,miss_ent = miss_ent , 110miss_dist = miss_dist ) 111 112 113def static_oracle (windows ,slots ): 114cnt = np .zeros ((NL ,NE )) 115for w in windows : 116for l ,ids in w : 117np .add .at (cnt [l ],ids .ravel (),1.0 ) 118flat = np .argsort (- cnt .ravel (),kind = "stable" )[:slots ] 119hit = cnt .ravel ()[flat ].sum ()/ cnt .sum () 120return hit 121 122 123if __name__ == "__main__" : 124tr ,prof ,slots = sys .argv [1 ],sys .argv [2 ],int (sys .argv [3 ]) 125 126def opt (name ,default ,cast = float ): 127return cast (sys .argv [sys .argv .index (name )+ 1 ])if name in sys .argv else default 128 129pol = Policy (every = opt ("--every" ,4 ,int ),decay = opt ("--decay" ,0.7 ),swaps = opt ("--swaps" ,96 ,int ), 130margin = opt ("--margin" ,1.5 ),mincand = opt ("--mincand" ,2.0 )) 131windows ,k = load_trace (tr ) 132"windows" ,len (windows ),"k" ,k ,"tokens/window" ,np .mean ([len (w [0 ][1 ])for w in windows ])) 133init = load_profile (prof ,slots ) 134"static oracle (top-%d by this trace's own counts): %.4f" % (slots ,static_oracle (windows ,slots ))) 135base = simulate (windows ,init ,Policy (every = 10 ** 9 )) 136"profile only, no adaptation: %.4f" % base ["share" ]) 137cur = simulate (windows ,init ,pol ) 138"policy every %d, swaps %d, decay %.2f: share %.4f, swaps %d (%.2f/window); miss entries %d, distinct misses %d " 139"(%.1f%% fewer reads)" % (pol .every ,pol .swaps ,pol .decay ,cur ["share" ],cur ["swaps" ],cur ["swaps" ]/ cur ["windows" ], 140cur ["miss_ent" ],cur ["miss_dist" ], 141100 * (1 - cur ["miss_dist" ]/ max (1 ,cur ["miss_ent" ]))))