okami.mom/strata

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

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

main
17.3 KiB405 linesraw
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
10    python 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
16  fill-only   the engine's current admission: compulsory miss, never evict.  The baseline a policy has
17              to beat, and the answer for any run whose trace never exceeds the slot count.
18  lru         evict the least-recently-used resident.
19  lfu-decay   frequency counts halved every --decay-window lookups, so a hot-once expert fades and the
20              cache can follow a topic shift; evict the lowest count, the oldest on a tie.  (Halving the
21              table is O(slots) per window; this instead DOUBLES new increments at each window boundary,
22              which scales every past access by the same 1/2 and leaves the table untouched.  Comparisons
23              stay exact: counts are sums of powers of two, below 2^53 for any realistic trace.)
24  oracle      Belady's MIN: evict the resident whose next use is furthest in the future.  Not
25              implementable online - it reads the trace ahead - but it is the upper bound any policy can
26              reach 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."""
59    return (layer << 16) | expert
60
61
62def decode(code):
63    return 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
69    Same records as make_profile.read_trace - (layer, k, k expert ids, k weights) - but eviction policy
70    is a question about order, so the frequencies it returns are not enough.  Out-of-range pairs are
71    skipped the same way it skips them."""
72    blob = Path(path).read_bytes()
73    codes, off = array("I"), 0
74    while off + 8 <= len(blob):
75        layer, k = struct.unpack_from("<ii", blob, off)
76        off += 8
77        for e in struct.unpack_from("<%di" % k, blob, off):
78            if 0 <= layer < n_layers and 0 <= e < n_expert:
79                codes.append(encode(layer, e))
80        off += 8 * k  # the ids and the weights
81    return 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
86    admits/evicts by the policy; `hits` and `evictions` accumulate.  `prefill(pairs)` seats the profile's
87    ranked pairs first (rank 0 = most recently used), respecting each scope's capacity."""
88
89    name = "?"
90
91    def __init__(self, n_layers, n_expert, slots, per_layer, decay_window=65536):
92        self.n_layers, self.n_expert, self.slots, self.per_layer = n_layers, n_expert, slots, per_layer
93        self.hits = 0
94        self.evictions = 0
95
96    def scope(self, layer):
97        return layer if self.per_layer else 0
98
99    def capacity(self, layer):
100        """The slots a lookup on `layer` may use - ExpertCache::layer_slot_range's range, in size."""
101        if not self.per_layer:
102            return self.slots
103        q = self.slots // self.n_layers
104        hi = self.slots if layer == self.n_layers - 1 else (layer + 1) * q
105        return hi - layer * q
106
107    def prefill(self, pairs):
108        raise NotImplementedError
109
110    def lookup(self, code, i):
111        raise NotImplementedError
112
113
114class FillOnly(Sim):
115    """The engine's current admission: the first S distinct pairs stay resident forever."""
116
117    name = "fill-only"
118
119    def __init__(self, *args, **kw):
120        super().__init__(*args, **kw)
121        self.resident = set()
122        self.used = defaultdict(int)  # scope -> slots taken
123
124    def prefill(self, pairs):
125        for layer, e in pairs:
126            code, s = encode(layer, e), self.scope(layer)
127            if code not in self.resident and self.used[s] < self.capacity(layer):
128                self.resident.add(code)
129                self.used[s] += 1
130
131    def lookup(self, code, i):
132        layer, _ = decode(code)
133        if code in self.resident:
134            self.hits += 1
135            return True
136        s = self.scope(layer)
137        if self.used[s] < self.capacity(layer):
138            self.resident.add(code)
139            self.used[s] += 1
140        return False
141
142
143class Lru(Sim):
144    """Evict the least-recently-used resident of the scope.  OrderedDict: front = oldest."""
145
146    name = "lru"
147
148    def __init__(self, *args, **kw):
149        super().__init__(*args, **kw)
150        from collections import OrderedDict
151        self.od = defaultdict(OrderedDict)  # scope -> {code: None}
152
153    def 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.)
156        chosen, used = [], defaultdict(int)
157        for layer, e in pairs:
158            s = self.scope(layer)
159            if used[s] < self.capacity(layer):
160                chosen.append((encode(layer, e), s))
161                used[s] += 1
162        for code, s in reversed(chosen):
163            self.od[s][code] = None
164
165    def lookup(self, code, i):
166        layer, _ = decode(code)
167        od = self.od[self.scope(layer)]
168        if code in od:
169            od.move_to_end(code)
170            self.hits += 1
171            return True
172        if len(od) >= self.capacity(layer):
173            od.popitem(last=False)
174            self.evictions += 1
175        od[code] = None
176        return False
177
178
179class LfuDecay(Sim):
180    """Evict the lowest decayed-frequency resident of the scope, oldest on a tie.
181
182    Every 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
184    table (see the module docstring).  Victim selection is a lazy heap: entries go stale as counts
185    grow, and are popped when they surface."""
186
187    name = "lfu-decay"
188
189    def __init__(self, *args, decay_window=65536, **kw):
190        super().__init__(*args, **kw)
191        self.decay_window = decay_window
192        self.incr = 1.0
193        self.tick = 0
194        self.counts = {}                    # code -> scaled count
195        self.heaps = defaultdict(list)      # scope -> [(count, tick, code)]
196        self.used = defaultdict(int)        # scope -> slots taken
197
198    def prefill(self, pairs):
199        # Same two-step as Lru.prefill: top pairs per scope in ranked order, newest tick to rank 0.
200        chosen, used = [], defaultdict(int)
201        for layer, e in pairs:
202            s = self.scope(layer)
203            if used[s] < self.capacity(layer):
204                chosen.append((encode(layer, e), s))
205                used[s] += 1
206        for code, s in reversed(chosen):
207            if code not in self.counts:
208                self.counts[code] = self.incr
209                heapq.heappush(self.heaps[s], (self.incr, self.tick, code))
210                self.used[s] += 1
211                self.tick += 1
212
213    def lookup(self, code, i):
214        if self.tick > 0 and self.tick % self.decay_window == 0:
215            self.incr *= 2.0
216        tick, self.tick = self.tick, self.tick + 1
217        layer, _ = decode(code)
218        s = self.scope(layer)
219        if code in self.counts:             # resident (an evicted pair's count is deleted with it)
220            self.counts[code] += self.incr
221            heapq.heappush(self.heaps[s], (self.counts[code], tick, code))
222            self.hits += 1
223            return True
224        if self.used[s] >= self.capacity(layer):
225            h = self.heaps[s]
226            while h:                        # drop stale heap entries until the true minimum surfaces
227                c, _, cand = h[0]
228                if self.counts.get(cand) == c:
229                    break
230                heapq.heappop(h)
231            victim = heapq.heappop(h)[2]
232            del self.counts[victim]
233            self.used[s] -= 1
234            self.evictions += 1
235        self.counts[code] = self.incr
236        heapq.heappush(self.heaps[s], (self.incr, tick, code))
237        self.used[s] += 1
238        return False
239
240
241class Oracle(Sim):
242    """Belady's MIN: evict the resident whose next use is furthest away.  Needs the whole trace up
243    front (`prepare`), which is exactly why it is a bound and not a candidate."""
244
245    name = "oracle"
246
247    def __init__(self, *args, **kw):
248        super().__init__(*args, **kw)
249        self.cur = {}                       # code -> its next use at the current position (T: never)
250        self.heaps = defaultdict(list)      # scope -> [(-next_use, code)], lazy like LfuDecay's
251        self.used = defaultdict(int)
252
253    def prepare(self, codes):
254        T = len(codes)
255        nxt = array("I", [T]) * T
256        last = {}
257        for i in range(T - 1, -1, -1):
258            c = codes[i]
259            nxt[i] = last.get(c, T)
260            last[c] = i
261        self.nxt, self.first, self.T = nxt, last, T
262
263    def prefill(self, pairs):
264        for layer, e in pairs:
265            code, s = encode(layer, e), self.scope(layer)
266            if code not in self.cur and self.used[s] < self.capacity(layer):
267                self.cur[code] = self.first.get(code, self.T)
268                heapq.heappush(self.heaps[s], (-self.cur[code], code))
269                self.used[s] += 1
270
271    def lookup(self, code, i):
272        layer, _ = decode(code)
273        s = self.scope(layer)
274        if code in self.cur:
275            self.cur[code] = self.nxt[i]
276            heapq.heappush(self.heaps[s], (-self.nxt[i], code))
277            self.hits += 1
278            return True
279        if self.used[s] >= self.capacity(layer):
280            h = self.heaps[s]
281            while h:
282                neg, cand = h[0]
283                if cand in self.cur and self.cur[cand] == -neg:
284                    break
285                heapq.heappop(h)
286            victim = heapq.heappop(h)[1]
287            del self.cur[victim]
288            self.used[s] -= 1
289            self.evictions += 1
290        self.cur[code] = self.nxt[i]
291        heapq.heappush(self.heaps[s], (-self.nxt[i], code))
292        self.used[s] += 1
293        return 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,
300        decay_window=65536, prefill_pairs=None):
301    """One replay per (slots, policy).  Returns rows of dicts with the overall and per-window counts."""
302    T = len(codes)
303    rows = []
304    for slots in slots_list:
305        for name in policy_names:
306            sim = POLICIES[name](n_layers, n_expert, slots, per_layer, decay_window=decay_window)
307            if name == Oracle.name:
308                sim.prepare(codes)
309            if prefill_pairs:
310                sim.prefill(prefill_pairs)
311            w_hits, w_tot = [0] * windows, [0] * windows
312            for i, code in enumerate(codes):
313                w = i * windows // T if T else 0
314                w_tot[w] += 1
315                if sim.lookup(code, i):
316                    w_hits[w] += 1
317            rows.append({
318                "slots": slots, "policy": name, "hits": sim.hits, "lookups": T,
319                "evictions": sim.evictions, "w_hits": w_hits, "w_tot": w_tot,
320            })
321    return rows
322
323
324def fmt_rate(hits, lookups):
325    return f"{hits / lookups:.4f}" if lookups else "n/a"
326
327
328def report(rows, windows):
329    for slots in dict.fromkeys(r["slots"] for r in rows):
330        block = [r for r in rows if r["slots"] == slots]
331        print(f"\nslots = {slots}")
332        print(f"  {'policy':<10} {'hits':>10} {'lookups':>10} {'hit-rate':>9} {'evictions':>10}")
333        for r in block:
334            print(f"  {r['policy']:<10} {r['hits']:>10} {r['lookups']:>10} "
335                  f"{fmt_rate(r['hits'], r['lookups']):>9} {r['evictions']:>10}")
336        if windows > 1:
337            print(f"  per-window hit-rate ({windows} windows, in trace order):")
338            print(f"  {'policy':<10} " + " ".join(f"{'w' + str(i + 1):>8}" for i in range(windows)))
339            for r in block:
340                rates = " ".join(f"{fmt_rate(h, t):>8}" for h, t in zip(r["w_hits"], r["w_tot"]))
341                print(f"  {r['policy']:<10} {rates}")
342
343
344def write_csv(path, rows, scope):
345    with open(path, "w") as f:
346        f.write("slots,scope,policy,window,lookups,hits,hit_rate,evictions\n")
347        for r in rows:
348            f.write(f"{r['slots']},{scope},{r['policy']},all,{r['lookups']},{r['hits']},"
349                    f"{fmt_rate(r['hits'], r['lookups'])},{r['evictions']}\n")
350            for w, (h, t) in enumerate(zip(r["w_hits"], r["w_tot"])):
351                if len(r["w_tot"]) > 1:
352                    f.write(f"{r['slots']},{scope},{r['policy']},w{w + 1},{t},{h},{fmt_rate(h, t)},\n")
353
354
355def main(argv=None):
356    p = argparse.ArgumentParser(description=__doc__.splitlines()[0],
357                                formatter_class=argparse.RawDescriptionHelpFormatter)
358    p.add_argument("traces", nargs="+", help="--dump-routing files, replayed in the order given")
359    p.add_argument("--slots", default="4105",
360                       help="comma-separated slot counts (default: 4105, the R4 reference sizing)")
361    p.add_argument("--per-layer", action="store_true",
362                   help="R4.2g admission: each layer its own slot range, eviction stays in-layer")
363    p.add_argument("--windows", type=int, default=1,
364                   help="split the trace into this many equal windows and report hit-rate per window")
365    p.add_argument("--policies", default=",".join(POLICIES),
366                   help="comma-separated subset of: " + ",".join(POLICIES))
367    p.add_argument("--decay-window", type=int, default=65536,
368                   help="lfu-decay: lookups between table-wide halvings (default: 65536)")
369    p.add_argument("--prefill", help="profile.bin to start from (the engine's --expert-profile start)")
370    p.add_argument("--n-expert", type=int, default=N_EXPERT, help="experts per layer (default: 512)")
371    p.add_argument("--csv", help="also write the results to this CSV file")
372    a = p.parse_args(argv)
373
374    codes = array("I")
375    for t in a.traces:
376        codes.extend(read_trace(t, a.n_expert))
377    if not codes:
378        raise SystemExit("no usable lookups in the trace(s)")
379    slots_list = [int(s) for s in a.slots.split(",")]
380    policy_names = a.policies.split(",")
381    unknown = set(policy_names) - set(POLICIES)
382    if unknown:
383        raise SystemExit(f"unknown policies: {', '.join(sorted(unknown))} (have: {', '.join(POLICIES)})")
384    prefill = MP.read_profile(a.prefill, a.n_expert) if a.prefill else None
385
386    scope = "per-layer" if a.per_layer else "global"
387    distinct = len(set(codes))
388    print(f"trace: {', '.join(a.traces)}")
389    print(f"{len(codes):,} lookups, {distinct:,} distinct (layer, expert) pairs, "
390          f"scope: {scope}, prefill: {a.prefill or 'none (cold start)'}"
391          + (f", decay-window: {a.decay_window}" if "lfu-decay" in policy_names else ""))
392    if distinct <= min(slots_list):
393        print("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
396    rows = run(codes, N_LAYER, a.n_expert, slots_list, a.per_layer, policy_names,
397               a.windows, a.decay_window, prefill)
398    report(rows, a.windows)
399    if a.csv:
400        write_csv(a.csv, rows, scope)
401        print(f"\nwrote {a.csv}")
402
403
404if __name__ == "__main__":
405    main()