okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7dbd8c09f
main
1"""Tests for tools/bench_eviction.py, without a model: synthetic traces and tiny slot pools. 2 3python -m unittest tools.test_bench_eviction 4""" 5from __future__import annotations 6 7import random 8import struct 9import sys 10import tempfile 11import unittest 12from pathlib import Path 13 14ROOT = Path (__file__ ).resolve ().parents [1 ] 15sys .path .insert (0 ,str (ROOT / "tools" )) 16import bench_eviction as BE # noqa: E402 17 18NL ,NE = 3 ,8 # tiny layer/expert counts; the sims take them as parameters 19 20 21def codes_of (pairs ): 22return BE .array ("I" , (BE .encode (layer ,e )for layer ,e in pairs )) 23 24 25def run_trace (sim ,pairs ): 26codes = codes_of (pairs ) 27for i ,c in enumerate (codes ): 28sim .lookup (c ,i ) 29return sim 30 31 32def write_trace (path ,records ): 33"""One record per (layer, [expert ids]); the reader skips k weights after the k ids.""" 34with open (path ,"wb" )as f : 35for layer ,experts in records : 36f .write (struct .pack ("<ii" ,layer ,len (experts ))) 37f .write (struct .pack ("<%di" % len (experts ),* experts )) 38f .write (struct .pack ("<%df" % len (experts ),* ([1.0 ]* len (experts )))) 39 40 41class ReadTrace (unittest .TestCase ): 42def test_reads_pairs_in_order_and_skips_weights_and_out_of_range (self ): 43with tempfile .TemporaryDirectory ()as d : 44p = Path (d )/ "t.bin" 45write_trace (p , [(0 , [3 ,1 ]), (2 , [0 ]), (99 , [1 ]), (1 , [77 ])]) 46got = BE .read_trace (p ,n_expert = NE ,n_layers = NL ) 47self .assertEqual (list (got ), [BE .encode (0 ,3 ),BE .encode (0 ,1 ),BE .encode (2 ,0 )]) 48# (99, ..) is a bad layer, (1, 77) a bad expert: skipped like make_profile.read_trace 49 50def test_n_expert_gates_the_pairs (self ): 51with tempfile .TemporaryDirectory ()as d : 52p = Path (d )/ "t.bin" 53write_trace (p , [(0 , [3 ,5 ])]) 54got = BE .read_trace (p ,n_expert = 4 ,n_layers = NL ) 55self .assertEqual (list (got ), [BE .encode (0 ,3 )]) 56 57 58class FillOnly (unittest .TestCase ): 59def test_never_evicts_and_refuses_when_full (self ): 60sim = run_trace (BE .FillOnly (NL ,NE ,2 ,False ), [(0 ,0 ), (0 ,1 ), (0 ,2 ), (0 ,0 )]) 61self .assertEqual (sim .hits ,1 )# only the repeat of (0,0) 62self .assertEqual (sim .evictions ,0 ) 63self .assertEqual (sim .resident , {BE .encode (0 ,0 ),BE .encode (0 ,1 )})# (0,2) was refused 64 65 66class Lru (unittest .TestCase ): 67def test_evicts_the_least_recently_used (self ): 68pairs = [(0 ,0 ), (0 ,1 ), (0 ,0 ), (0 ,2 ), (0 ,1 ), (0 ,0 )] 69sim = run_trace (BE .Lru (NL ,NE ,2 ,False ),pairs ) 70self .assertEqual (sim .hits ,1 )# the repeat of (0,0) at index 2 71self .assertEqual (sim .evictions ,3 ) 72resident = set ().union (* [set (od )for od in sim .od .values ()]) 73self .assertEqual (resident , {BE .encode (0 ,1 ),BE .encode (0 ,0 )}) 74 75 76class LfuDecay (unittest .TestCase ): 77PAIRS = [(0 ,0 )]* 4 + [(0 ,1 )]* 2 + [(0 ,2 )]# A hot early, B lukewarm late, then C arrives 78 79def test_decay_lets_a_stale_hot_expert_be_evicted (self ): 80sim = run_trace (BE .LfuDecay (NL ,NE ,2 ,False ,decay_window = 2 ),self .PAIRS ) 81# A's count was built on the small early increments and decays behind B's: C evicts A 82self .assertEqual (set (sim .counts ), {BE .encode (0 ,1 ),BE .encode (0 ,2 )}) 83self .assertEqual (sim .evictions ,1 ) 84 85def test_without_decay_frequency_wins_forever (self ): 86sim = run_trace (BE .LfuDecay (NL ,NE ,2 ,False ,decay_window = 10 ** 9 ),self .PAIRS ) 87# plain LFU: A(4) > B(2) forever, so C evicts B - the behaviour decay exists to change 88self .assertEqual (set (sim .counts ), {BE .encode (0 ,0 ),BE .encode (0 ,2 )}) 89 90 91class PerLayer (unittest .TestCase ): 92def test_a_layers_quota_is_its_own_range (self ): 93# layer_slot_range's arithmetic, in capacity() form: q = 7 // 3 = 2, the last layer takes the rest 94sim = BE .FillOnly (NL ,NE ,7 ,True ) 95self .assertEqual ([sim .capacity (l )for l in range (NL )], [2 ,2 ,3 ]) 96 97def test_a_full_layer_cannot_borrow_another_layers_slots (self ): 98sim = run_trace (BE .FillOnly (NL ,NE ,4 ,True ), 99 [(0 ,0 ), (0 ,1 ), (0 ,2 ), (1 ,0 ), (1 ,0 )]) 100self .assertNotIn (BE .encode (0 ,2 ),sim .resident )# layer 0's quota is 2: refused 101self .assertIn (BE .encode (1 ,0 ),sim .resident )# layer 1's quota is its own 102self .assertEqual (sim .hits ,1 ) 103 104 105class Oracle (unittest .TestCase ): 106def test_sees_past_lrus_blind_spot (self ): 107pairs = [(0 ,0 ), (0 ,1 ), (0 ,0 ), (0 ,2 ), (0 ,1 ), (0 ,2 )] 108codes = codes_of (pairs ) 109oracle = BE .Oracle (NL ,NE ,2 ,False ) 110oracle .prepare (codes ) 111for i ,c in enumerate (codes ): 112oracle .lookup (c ,i ) 113lru = run_trace (BE .Lru (NL ,NE ,2 ,False ),pairs ) 114# at index 3, oracle evicts (0,0) (never used again) where lru evicted (0,1) (used at index 4) 115self .assertEqual (oracle .hits ,3 ) 116self .assertEqual (lru .hits ,2 ) 117 118def test_is_an_upper_bound_on_a_random_trace (self ): 119rng = random .Random (20261005 ) 120pairs = [(rng .randrange (NL ),rng .randrange (NE ))for _ in range (4000 )] 121codes = codes_of (pairs ) 122rows = {r ["policy" ]:r for r in BE .run (codes ,NL ,NE , [4 ],False , 123 ["lru" ,"lfu-decay" ,"oracle" ],decay_window = 256 )} 124self .assertGreaterEqual (rows ["oracle" ]["hits" ],rows ["lru" ]["hits" ]) 125self .assertGreaterEqual (rows ["oracle" ]["hits" ],rows ["lfu-decay" ]["hits" ]) 126 127def test_policies_beat_fill_only_when_the_workload_shifts (self ): 128rng = random .Random (7 ) 129 130def phase (experts ,n ):# zipf-ish routing inside one expert set, like a conversation topic 131weights = [1.0 / (i + 1 )for i in range (len (experts ))] 132return [(rng .randrange (NL ),rng .choices (experts ,weights )[0 ])for _ in range (n )] 133 134pairs = phase ([0 ,1 ,2 ,3 ,4 ,5 ],2000 )+ phase ([6 ,7 ],2000 ) 135rows = {r ["policy" ]:r for r in BE .run (codes_of (pairs ),NL ,NE , [4 ],False , 136 ["fill-only" ,"lru" ,"lfu-decay" ],decay_window = 256 )} 137self .assertGreater (rows ["lru" ]["hits" ],rows ["fill-only" ]["hits" ]) 138self .assertGreater (rows ["lfu-decay" ]["hits" ],rows ["fill-only" ]["hits" ]) 139 140 141class WindowsAndPrefill (unittest .TestCase ): 142def test_windows_split_the_trace_in_order (self ): 143codes = codes_of ([(0 ,0 ), (0 ,1 )]* 4 ) 144 (row ,)= BE .run (codes ,NL ,NE , [2 ],False , ["lru" ],windows = 2 ) 145self .assertEqual (row ["w_tot" ], [4 ,4 ]) 146self .assertEqual (row ["w_hits" ], [2 ,4 ])# window 1 pays the two cold misses, window 2 all hits 147self .assertEqual (row ["hits" ],6 ) 148 149def test_prefill_seats_the_profile_with_rank0_as_mru (self ): 150sim = BE .Lru (NL ,NE ,2 ,False ) 151sim .prefill ([(0 ,0 ), (0 ,1 ), (0 ,2 )])# the third pair does not fit 152run_trace (sim , [(0 ,2 )])# evicts the prefill's colder end: (0,1) 153self .assertEqual (sim .evictions ,1 ) 154after = run_trace (sim , [(0 ,0 ), (0 ,1 )]) 155self .assertEqual (after .hits ,1 )# (0,0) still resident, (0,1) gone 156 157def test_prefill_respects_each_layers_quota (self ): 158sim = BE .FillOnly (NL ,NE ,6 ,True )# q = 6 // 3 = 2 slots per layer 159sim .prefill ([(0 ,0 ), (0 ,1 ), (0 ,2 ), (1 ,0 )]) 160self .assertNotIn (BE .encode (0 ,2 ),sim .resident )# layer 0's quota was already spent 161self .assertEqual (len (sim .resident ),3 ) 162 163 164if __name__ == "__main__" : 165unittest .main ()