okami.mom/strata

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

Niko1221Merge f-142-cuda-p1r into f-142 (inert lookahead stats, cache-policy replay tool, docs)d5f319bff

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