okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
12.2 KiB358 linesraw
1"""cachesim.py - offline expert-cache policies on routing traces (DS4_TRACE files of strata-dsv41).
2
3A trace is a run of records: u8 layer, u8 T (bit 7: guesses follow), T x k int16 expert ids [, u8 na1, u8 na2, T x (na1 + na2)
4int16 guesses for the next layer and the one after].  One decode step (or verify window) is the records of layers 0..nl-1 in order.
5
6Sizes are in bytes (an expert's real size in its layer: sizes.json), capacities in GB.  Policies:
7  lru        one global LRU over (layer, expert)
8  lfu        frequency with exponential decay (LRFU / CRF), evicts the lowest score
9  static     the N hottest by training-trace frequency (a shipped per-set profile), no adaptation
10  static+lru half the capacity pinned from the profile, half LRU
11  belady     the offline optimum (farthest next use): the ceiling for any predictor of reuse
12  lru+ahead  LRU plus a prefetch of the guesses for the next layer (top m): counts the wasted bytes
13Reports: hit rate (by accesses and by bytes), SSD bytes per token (misses + wasted prefetch), the share of misses a guess covered.
14"""
15import argparse
16import collections
17import heapq
18import json
19import math
20import os
21import struct
22import sys
23
24
25WARM = 0   # accesses before this index warm the cache but are not counted
26
27
28def read_trace(path, k=6):
29    """-> list of steps; a step = list of (layer, [rows of expert ids], guesses or None)."""
30    data = open(path, 'rb').read()
31    pos, n = 0, len(data)
32    steps, cur, last_layer = [], [], -1
33    while pos + 2 <= n:
34        layer, t = data[pos], data[pos + 1]
35        pos += 2
36        has_ahead = bool(t & 0x80)
37        t &= 0x7f
38        rows = []
39        for _ in range(t):
40            rows.append(list(struct.unpack_from('<%dh' % k, data, pos)))
41            pos += 2 * k
42        guesses = None
43        if has_ahead:
44            na1, na2 = data[pos], data[pos + 1]
45            pos += 2
46            guesses = []
47            for _ in range(t):
48                g1 = list(struct.unpack_from('<%dh' % na1, data, pos)) if na1 else []
49                pos += 2 * na1
50                g2 = list(struct.unpack_from('<%dh' % na2, data, pos)) if na2 else []
51                pos += 2 * na2
52                guesses.append((g1, g2))
53        if layer <= last_layer and cur:
54            steps.append(cur)
55            cur = []
56        last_layer = layer
57        cur.append((layer, rows, guesses))
58    if cur:
59        steps.append(cur)
60    return steps
61
62
63def accesses(steps):
64    """the flat access stream: (step, layer, expert) with the union over a window's rows, in layer order"""
65    out = []
66    for si, st in enumerate(steps):
67        for layer, rows, _ in st:
68            seen = []
69            for r in rows:
70                for e in r:
71                    if e not in seen:
72                        seen.append(e)
73            for e in seen:
74                out.append((si, layer, e))
75    return out
76
77
78class Sizes:
79    def __init__(self, path):
80        d = json.load(open(path))
81        el = d['exp_layer']
82        self.s = {int(k): float(v) for k, v in el.items()}
83
84    def __call__(self, layer):
85        return self.s.get(layer, 8.6e6)
86
87
88def sim_lru(acc, size, cap):
89    od = collections.OrderedDict()
90    used = hits = hitb = tot = totb = 0
91    for i, (_, l, e) in enumerate(acc):
92        k = (l, e)
93        sz = size(l)
94        cnt = i >= WARM
95        tot += cnt
96        totb += sz * cnt
97        if k in od:
98            od.move_to_end(k)
99            hits += cnt
100            hitb += sz * cnt
101            continue
102        od[k] = sz
103        used += sz
104        while used > cap:
105            _, s0 = od.popitem(last=False)
106            used -= s0
107    return hits, hitb, tot, totb
108
109
110def sim_lfu(acc, size, cap, half_life_acc=20000):
111    lam = math.log(2) / half_life_acc
112    score, last, res = {}, {}, {}
113    heap = []
114    used = hits = hitb = tot = totb = 0
115    for t, (_, l, e) in enumerate(acc):
116        k = (l, e)
117        sz = size(l)
118        cnt = t >= WARM
119        tot += cnt
120        totb += sz * cnt
121        # CRF: decayed count, kept in log space: v = log(count) + lam * t
122        if k in res:
123            hits += cnt
124            hitb += sz * cnt
125        old = score.get(k)
126        v = lam * t
127        score[k] = v if old is None else v + math.log1p(math.exp(old - v)) if old - v < 50 else old
128        if k not in res:
129            res[k] = sz
130            used += sz
131        heapq.heappush(heap, (score[k], k))
132        while used > cap and heap:
133            sc, kk = heapq.heappop(heap)
134            if kk not in res or score[kk] != sc:
135                continue
136            if kk == k and len(res) == 1:
137                break
138            used -= res.pop(kk)
139    return hits, hitb, tot, totb
140
141
142def freq_table(acc):
143    c = collections.Counter((l, e) for _, l, e in acc)
144    return c
145
146
147def pick_static(freq, size, cap):
148    keys = sorted(freq, key=lambda k: -freq[k] / size(k[0]))
149    chosen, used = set(), 0
150    for k in keys:
151        s = size(k[0])
152        if used + s > cap:
153            continue
154        chosen.add(k)
155        used += s
156    return chosen
157
158
159def sim_static(acc, size, chosen):
160    hits = hitb = tot = totb = 0
161    for i, (_, l, e) in enumerate(acc):
162        sz = size(l)
163        cnt = i >= WARM
164        tot += cnt
165        totb += sz * cnt
166        if (l, e) in chosen:
167            hits += cnt
168            hitb += sz * cnt
169    return hits, hitb, tot, totb
170
171
172def sim_static_lru(acc, size, cap, chosen, pinned_bytes):
173    od = collections.OrderedDict()
174    used = hits = hitb = tot = totb = 0
175    room = cap - pinned_bytes
176    for i, (_, l, e) in enumerate(acc):
177        k = (l, e)
178        sz = size(l)
179        cnt = i >= WARM
180        tot += cnt
181        totb += sz * cnt
182        if k in chosen:
183            hits += cnt
184            hitb += sz * cnt
185            continue
186        if k in od:
187            od.move_to_end(k)
188            hits += cnt
189            hitb += sz * cnt
190            continue
191        od[k] = sz
192        used += sz
193        while used > room:
194            _, s0 = od.popitem(last=False)
195            used -= s0
196    return hits, hitb, tot, totb
197
198
199def sim_belady(acc, size, cap):
200    n = len(acc)
201    nxt = [0] * n
202    last = {}
203    for i in range(n - 1, -1, -1):
204        k = (acc[i][1], acc[i][2])
205        nxt[i] = last.get(k, n + 1)
206        last[k] = i
207    res = {}   # k -> next use
208    heap = []  # (-next use, k)
209    used = hits = hitb = tot = totb = 0
210    for i, (_, l, e) in enumerate(acc):
211        k = (l, e)
212        sz = size(l)
213        cnt = i >= WARM
214        tot += cnt
215        totb += sz * cnt
216        if k in res:
217            hits += cnt
218            hitb += sz * cnt
219            res[k] = nxt[i]
220            heapq.heappush(heap, (-nxt[i], k))
221            continue
222        if nxt[i] > n:      # never used again: do not keep
223            continue
224        res[k] = nxt[i]
225        used += sz
226        heapq.heappush(heap, (-nxt[i], k))
227        while used > cap and heap:
228            nu, kk = heapq.heappop(heap)
229            if kk not in res or res[kk] != -nu:
230                continue
231            used -= size(kk[0])
232            del res[kk]
233    return hits, hitb, tot, totb
234
235
236def sim_lru_ahead(steps, size, cap, m=6, depth=1):
237    """LRU + prefetch of the top-m guesses (from the record of layer L-1 for layer L): a miss that a guess covered is a 'hidden'
238    miss (its read started a layer early), a guess nobody used is wasted bytes."""
239    od = collections.OrderedDict()
240    used = 0
241    hits = tot = miss = hidden = 0
242    ssd = 0.0
243    wasted = 0.0
244    pend = {}   # (layer, expert) -> bytes prefetched, not yet used this step
245    nsteps = len(steps)
246
247    def put(k, sz):
248        nonlocal used
249        if k in od:
250            od.move_to_end(k)
251            return
252        od[k] = sz
253        used += sz
254        while used > cap:
255            _, s0 = od.popitem(last=False)
256            used -= s0
257
258    for st in steps:
259        pend.clear()
260        for layer, rows, guesses in st:
261            sz = size(layer)
262            seen = []
263            for r in rows:
264                for e in r:
265                    if e not in seen:
266                        seen.append(e)
267            for e in seen:
268                k = (layer, e)
269                tot += 1
270                if k in pend:
271                    hidden += 1
272                    del pend[k]
273                    miss += 1
274                    put(k, sz)
275                elif k in od:
276                    hits += 1
277                    od.move_to_end(k)
278                else:
279                    miss += 1
280                    ssd += sz
281                    put(k, sz)
282            for k, b in list(pend.items()):
283                if k[0] <= layer:
284                    wasted += b
285                    del pend[k]
286            if guesses:
287                nl = layer + 1
288                gs = []
289                for g1, g2 in guesses:
290                    for e in g1[:m]:
291                        if e not in gs:
292                            gs.append(e)
293                for e in gs:
294                    k = (nl, e)
295                    if k in od or k in pend:
296                        continue
297                    pend[k] = size(nl)
298                    ssd += size(nl)
299    for b in pend.values():
300        wasted += b
301    return dict(hit=hits / max(1, tot), hidden=hidden / max(1, tot), ssd_per_step_MB=ssd / max(1, nsteps) / 1e6,
302                wasted_per_step_MB=wasted / max(1, nsteps) / 1e6)
303
304
305def main():
306    ap = argparse.ArgumentParser()
307    ap.add_argument('traces', nargs='+', help='trace files: all are test sets; --train-on names the profile source')
308    ap.add_argument('--sizes', default='C:/ds-ista-work/sizes.json')
309    ap.add_argument('--caps', default='20,30,40,44', help='cache sizes in GB (VRAM hot set + pinned RAM)')
310    ap.add_argument('--train', nargs='*', default=[], help='traces the static profile is built from (others than the test)')
311    ap.add_argument('--warm-steps', type=int, default=0, help='steps at the start that fill the cache but are not counted')
312    ap.add_argument('--skip', default='', help='policies to skip (comma): lru,lfu,static,static+lru,belady,ahead')
313    a = ap.parse_args()
314    size = Sizes(a.sizes)
315    global WARM
316    skip = set(a.skip.split(','))
317    train_acc = []
318    for t in a.train:
319        train_acc += accesses(read_trace(t))
320    for path in a.traces:
321        steps = read_trace(path)
322        acc = accesses(steps)
323        nsteps = len(steps)
324        WARM = 0
325        if a.warm_steps:
326            WARM = next((i for i, x in enumerate(acc) if x[0] >= a.warm_steps), len(acc))
327            nsteps -= a.warm_steps
328        uniq = len({(l, e) for _, l, e in acc})
329        print('   unique experts touched: %d of 15360 (%.1f%%), %.1f GB' % (uniq, 100 * uniq / 15360, sum(size(l) for l, e in {(l, e) for _, l, e in acc}) / 1e9))
330        print('== %s: %d steps, %d expert accesses (%.1f a step)' % (os.path.basename(path), nsteps, len(acc), len(acc) / max(1, nsteps)))
331        tb = sum(size(l) for _, l, _ in acc) / nsteps
332        print('   bytes a step (union per layer): %.2f GB' % (tb / 1e9))
333        print('   %-14s %6s %9s %9s %12s' % ('policy', 'capGB', 'hit(acc)', 'hit(bytes)', 'SSD MB/step'))
334        for cg in [float(x) for x in a.caps.split(',')]:
335            cap = cg * 1e9
336            rows = []
337            if 'lru' not in skip:
338                rows.append(('lru', sim_lru(acc, size, cap)))
339            if 'lfu' not in skip:
340                rows.append(('lfu(decay)', sim_lfu(acc, size, cap)))
341            if train_acc and 'static' not in skip:
342                ch = pick_static(freq_table(train_acc), size, cap)
343                rows.append(('static', sim_static(acc, size, ch)))
344                ch2 = pick_static(freq_table(train_acc), size, cap / 2)
345                rows.append(('static+lru', sim_static_lru(acc, size, cap, ch2, cap / 2)))
346            if 'belady' not in skip:
347                rows.append(('belady', sim_belady(acc, size, cap)))
348            for name, (h, hb, t, tb_) in rows:
349                print('   %-14s %6.0f %8.1f%% %8.1f%% %12.1f' % (name, cg, 100 * h / t, 100 * hb / tb_, (tb_ - hb) / nsteps / 1e6))
350            if 'ahead' not in skip and any(g for st in steps for _, _, g in st):
351                for m in (6, 8, 12):
352                    r = sim_lru_ahead(steps, size, cap, m=m)
353                    print('   lru+ahead(top%-2d) %4.0f   hit %.1f%% (+%.1f%% hidden)  SSD %.0f MB/step (wasted %.0f)' % (
354                        m, cg, 100 * r['hit'], 100 * r['hidden'], r['ssd_per_step_MB'], r['wasted_per_step_MB']))
355
356
357if __name__ == '__main__':
358    main()