okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-1402-d1' into f-14027dbd8c09f

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