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
4.4 KiB132 linesraw
1"""h100sim.py - replay the H100 routing corpus (1.78M tokens, code/agent/chat/multi/math/long, DS4_TRACE format, see
2phaseA-tests/h100/trace_tools.py) through an LRU expert cache at this PC's sizes, with and without a profile warm start.
3
4  h100sim.py <trace.bin[.zst]> <profile.bin> [--tokens N] [--skip S] [--caps 30,40,44] [--sizes sizes.json]
5
6Prints the demand hit rate by bytes after a warm-up of `--warm` tokens, for: empty start LRU; LRU started with the profile's
7hottest experts in (the engine's preload) and the same cold-start window's hit rate (first 2000 tokens), and a static top-N
8(profile only, no adaptation)."""
9import argparse
10import collections
11import io
12import json
13import struct
14import sys
15
16import numpy as np
17
18
19def decode(path, max_tokens, skip):
20    if path.endswith('.zst'):
21        import zstandard
22        raw = zstandard.ZstdDecompressor().stream_reader(open(path, 'rb')).read()
23    else:
24        raw = open(path, 'rb').read()
25    buf = np.frombuffer(raw, dtype=np.uint8)
26    pos, n = 0, len(buf)
27    per = {l: [] for l in range(40)}
28    got = [0] * 40
29    while pos < n:
30        b0 = int(buf[pos])
31        if b0 & 0x80:
32            l = b0 & 0x7F
33            T = int(buf[pos + 1]) | (int(buf[pos + 2]) << 8)
34            pos += 3
35        else:
36            l = b0
37            T = int(buf[pos + 1]) & 0x7F
38            pos += 2
39        sz = T * 12
40        if pos + sz > n:
41            break
42        per[l].append(buf[pos:pos + sz].view(np.int16).reshape(T, 6))
43        pos += sz
44        if min(got) >= skip + max_tokens:
45            break
46        got[l] += T
47    arr = []
48    for l in range(40):
49        a = np.concatenate(per[l])[skip:skip + max_tokens]
50        arr.append(a)
51    m = min(len(a) for a in arr)
52    return np.stack([a[:m] for a in arr], axis=1)   # [tokens][layer][6]
53
54
55def lru(acc_iter, size, cap, init=None, warm=0):
56    od = collections.OrderedDict()
57    used = 0
58    if init:
59        for k in init:
60            od[k] = size[k[0]]
61            used += size[k[0]]
62    hb = tb = 0.0
63    first_hb = first_tb = 0.0
64    for i, (t, k) in enumerate(acc_iter):
65        sz = size[k[0]]
66        cnt = t >= warm
67        early = t < 2000
68        if k in od:
69            od.move_to_end(k)
70            if cnt:
71                hb += sz
72            if early:
73                first_hb += sz
74        else:
75            od[k] = sz
76            used += sz
77            while used > cap:
78                _, s0 = od.popitem(last=False)
79                used -= s0
80        if cnt:
81            tb += sz
82        if early:
83            first_tb += sz
84    return 100 * hb / max(tb, 1), 100 * first_hb / max(first_tb, 1)
85
86
87def main():
88    ap = argparse.ArgumentParser()
89    ap.add_argument('trace')
90    ap.add_argument('profile')
91    ap.add_argument('--tokens', type=int, default=40000)
92    ap.add_argument('--skip', type=int, default=0)
93    ap.add_argument('--warm', type=int, default=4000)
94    ap.add_argument('--caps', default='30,40')
95    ap.add_argument('--sizes', default=r'C:\ds-ista-work\sizes.json')
96    a = ap.parse_args()
97    d = json.load(open(a.sizes))
98    size = {int(k): float(v) for k, v in d['exp_layer'].items()}
99    tr = decode(a.trace, a.tokens, a.skip)
100    prof = np.fromfile(a.profile, dtype=np.uint32).reshape(-1, 384)[:40]
101    print('trace', tr.shape, 'tokens', len(tr))
102
103    def acc():
104        for t in range(len(tr)):
105            for l in range(40):
106                for e in tr[t, l]:
107                    yield t, (l, int(e))
108    dens = sorted(((prof[l, e] / size[l], l, e) for l in range(40) for e in range(384)), reverse=True)
109    for cg in [float(x) for x in a.caps.split(',')]:
110        cap = cg * 1e9
111        r0, f0 = lru(acc(), size, cap, None, a.warm)
112        order, used = [], 0.0
113        for _, l, e in dens:
114            if used + size[l] > cap:
115                break
116            order.append((l, e))
117            used += size[l]
118        r1, f1 = lru(acc(), size, cap, list(reversed(order)), a.warm)   # hottest last = most recent
119        # static: top-N of the profile, no adaptation
120        sel = set(order)
121        hb = tb = 0.0
122        for t, k in acc():
123            if t >= a.warm:
124                tb += size[k[0]]
125                if k in sel:
126                    hb += size[k[0]]
127        print('cap %.0f GB: LRU from empty: steady hit %.1f%% (first 2000 tokens %.1f%%); LRU from the profile\'s hottest: steady %.1f%% (first 2000 tokens %.1f%%); static top-N alone %.1f%%' % (
128            cg, r0, f0, r1, f1, 100 * hb / tb))
129
130
131if __name__ == '__main__':
132    main()