183 lines
9.3 KiB
Python
183 lines
9.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Prefetch lead-time probe for the in-GPU preparation scheduler (candidate C of the single-copy study).
|
|
|
|
Input: the routing dump of a decode run (`LELEKA_ORIGINAL_SERVE_DUMP_ROUTING=FILE`, written by `single-copy-ab.sh PHASES=route`): records of
|
|
(layer i32, k i32, k expert ids i32, k weights f32), k = 10. A decode window is a batch of T rows (the verified draft tokens); the engine calls the
|
|
router layer by layer and writes T records per layer, so one window is: for layer 0..47: T records. A window starts when the layer number drops.
|
|
|
|
Question answered: at the START of a window (when the previous window's routing is known) and at the moment layer L-1 of the CURRENT window has been routed, how many of the
|
|
experts that layer L will use can be named in advance, with how many candidates, and how much wall time is left before layer L runs
|
|
(L x window_ms / 48 for the start-of-window predictions; ~0 for the router result of the layer itself)?
|
|
|
|
Predictors (all causal):
|
|
prev1 the experts of the last row of the previous window at the same layer (what the previous token used)
|
|
prev2 the union over the last two rows
|
|
prev4 the union over the last four rows
|
|
topN the N most frequent experts of that layer in the first half of the trace (the profile ranking idea), N = 8, 16, 32, 64
|
|
prev1+top16 union
|
|
lastlayer experts of layer L-1 in the current window -> experts that co-occurred with them at layer L in the first half (a co-occurrence table); known one layer ahead
|
|
Metrics per predictor: recall = |pred & actual| / |actual| (actual = union of the window's rows at layer L), mean candidates per layer, lead ms.
|
|
|
|
Second part (--profile expert-profile.bin): the share of expert uses that a STATIC tier of the top-N experts of the shipped ranking would serve from VRAM, for
|
|
N = today's slot counts and for the counts a compressed tier (level-2 KAR, 0.7506 of the IQ3_S bytes: 1.332x the slots) would hold. The adaptive tier and the lent
|
|
slots move this number; the static figure bounds the gain of "more slots" from below/above only roughly, and it is the same arithmetic for both sides.
|
|
|
|
usage: routing-lead.py ROUTING.bin [--window-ms 11.0] [--profile expert-profile.bin] [--selftest]
|
|
"""
|
|
import struct, sys, collections, random
|
|
|
|
K = 10 # TOP_K of the Original serve path
|
|
|
|
|
|
def records(path):
|
|
data = open(path, "rb").read()
|
|
off = 0
|
|
while off + 8 <= len(data):
|
|
layer, k = struct.unpack_from("<ii", data, off)
|
|
if k != K or off + 8 + 8 * k > len(data):
|
|
break
|
|
ids = struct.unpack_from("<%di" % k, data, off + 8)
|
|
yield layer, ids
|
|
off += 8 + 8 * k
|
|
|
|
|
|
def windows(path):
|
|
"""list of windows; a window is {layer: [ids, ...rows]}"""
|
|
out, cur, last = [], collections.OrderedDict(), -1
|
|
for layer, ids in records(path):
|
|
if layer < last and cur:
|
|
out.append(cur)
|
|
cur = collections.OrderedDict()
|
|
cur.setdefault(layer, []).append(ids)
|
|
last = layer
|
|
if cur:
|
|
out.append(cur)
|
|
return out
|
|
|
|
|
|
def analyse(wins, window_ms):
|
|
layers = sorted({l for w in wins for l in w})
|
|
half = len(wins) // 2
|
|
train, test = wins[:half], wins[half:]
|
|
freq = {l: collections.Counter() for l in layers}
|
|
cooc = {l: collections.defaultdict(collections.Counter) for l in layers}
|
|
for w in train:
|
|
for l in layers:
|
|
for ids in w.get(l, []):
|
|
freq[l].update(ids)
|
|
for l in layers[1:]:
|
|
prev = set(e for ids in w.get(l - 1, []) for e in ids)
|
|
for ids in w.get(l, []):
|
|
for a in prev:
|
|
cooc[l][a].update(ids)
|
|
tops = {n: {l: set(e for e, _ in freq[l].most_common(n)) for l in layers} for n in (8, 16, 32, 64)}
|
|
names = ["prev1", "prev2", "prev4", "top8", "top16", "top32", "top64", "prev1+top16", "lastlayer(16)"]
|
|
stat = {n: [0, 0, 0] for n in names} # hit, actual, candidates
|
|
per_layer = {n: collections.defaultdict(lambda: [0, 0]) for n in names}
|
|
rows_hist = collections.Counter()
|
|
history = [] # rows of previous windows, in order, as {layer: ids}
|
|
for wi, w in enumerate(wins):
|
|
rows_hist[len(w.get(layers[0], []))] += 1
|
|
if wi >= half and history:
|
|
last = history[-4:]
|
|
for l in layers:
|
|
actual = set(e for ids in w.get(l, []) for e in ids)
|
|
if not actual:
|
|
continue
|
|
prev_rows = [r[l] for r in last if l in r]
|
|
preds = {
|
|
"prev1": set(prev_rows[-1]) if prev_rows else set(),
|
|
"prev2": set(e for r in prev_rows[-2:] for e in r),
|
|
"prev4": set(e for r in prev_rows for e in r),
|
|
"top8": tops[8][l], "top16": tops[16][l], "top32": tops[32][l], "top64": tops[64][l],
|
|
}
|
|
preds["prev1+top16"] = preds["prev1"] | preds["top16"]
|
|
if l - 1 in w:
|
|
prev_layer = set(e for ids in w[l - 1] for e in ids)
|
|
score = collections.Counter()
|
|
for a in prev_layer:
|
|
score.update(cooc[l].get(a, {}))
|
|
preds["lastlayer(16)"] = set(e for e, _ in score.most_common(16))
|
|
else:
|
|
preds["lastlayer(16)"] = set()
|
|
for n in names:
|
|
s = stat[n]
|
|
s[0] += len(preds[n] & actual); s[1] += len(actual); s[2] += len(preds[n])
|
|
p = per_layer[n][l]; p[0] += len(preds[n] & actual); p[1] += len(actual)
|
|
# one row per window position is enough for "previous rows": keep the rows of this window
|
|
rows = max((len(v) for v in w.values()), default=0)
|
|
for r in range(rows):
|
|
history.append({l: w[l][r] for l in w if r < len(w[l])})
|
|
ntest = max(len(test) * len(layers), 1)
|
|
print("windows %d (train %d, test %d), layers %d, rows per window histogram %s" % (len(wins), half, len(test), len(layers), dict(sorted(rows_hist.items()))))
|
|
print("%-16s %8s %12s | recall by layer group (lead ms at the group's first layer, for start-of-window predictors)" % ("predictor", "recall", "candidates"))
|
|
t_layer = window_ms / 48.0
|
|
groups = [(0, 11), (12, 23), (24, 35), (36, 47)]
|
|
for n in names:
|
|
s = stat[n]
|
|
rec = s[0] / s[1] if s[1] else float("nan")
|
|
line = "%-16s %7.1f%% %12.1f |" % (n, 100 * rec, s[2] / ntest)
|
|
for a, b in groups:
|
|
h = sum(per_layer[n][l][0] for l in range(a, b + 1) if l in per_layer[n])
|
|
t = sum(per_layer[n][l][1] for l in range(a, b + 1) if l in per_layer[n])
|
|
lead = "~0.2" if n == "lastlayer(16)" else "%.1f" % (a * t_layer)
|
|
line += " L%d-%d %5.1f%% (%s ms)" % (a, b, 100 * h / t if t else float("nan"), lead)
|
|
print(line)
|
|
print("lead time of a start-of-window prediction at layer L = L x %.3f ms (window %.1f ms / 48); the layer's own router result gives ~0 lead (the same layer runs next)." % (t_layer, window_ms))
|
|
|
|
|
|
def tier_hit_rates(wins, profile_path):
|
|
d = open(profile_path, "rb").read()
|
|
magic, ver, layers, experts, n1, n2 = struct.unpack_from("<4sIIIII", d, 0)
|
|
assert magic == b"STRP" and n1 == layers * experts, (magic, n1)
|
|
flat = struct.unpack_from("<%dH" % (2 * n1), d, 24)
|
|
rank = {}
|
|
for i in range(n1):
|
|
rank[(flat[2 * i], flat[2 * i + 1])] = i
|
|
uses, uniq = [], []
|
|
for w in wins:
|
|
seen = set()
|
|
for l, rows in w.items():
|
|
for ids in rows:
|
|
for e in ids:
|
|
r = rank.get((l, e))
|
|
uses.append(r if r is not None else n1)
|
|
for e in set(e for ids in rows for e in ids):
|
|
seen.add((l, e))
|
|
uniq.extend(rank.get(k, n1) for k in seen)
|
|
print("static tier (top-N of the shipped ranking) over %d expert uses, %d window-unique (layer, expert) pairs:" % (len(uses), len(uniq)))
|
|
for n, label in ((8000, "replay shape"), (11280, "today, seed-off 245k slots"), (12192, "today, auto slots (product)"), (15028, "compressed, same VRAM as 11,280"),
|
|
(16243, "compressed, same VRAM as 12,192"), (20000, "")):
|
|
print(" N=%6d %-34s uses in tier %5.1f %% window-unique pairs in tier %5.1f %%" % (
|
|
n, label, 100 * sum(1 for r in uses if r < n) / len(uses), 100 * sum(1 for r in uniq if r < n) / len(uniq)))
|
|
|
|
|
|
def selftest():
|
|
import tempfile, os
|
|
rnd = random.Random(1)
|
|
path = os.path.join(tempfile.gettempdir(), "routing-selftest.bin")
|
|
with open(path, "wb") as f:
|
|
for _ in range(60):
|
|
t = rnd.choice((1, 4, 5))
|
|
for layer in range(48):
|
|
for _r in range(t):
|
|
ids = rnd.sample(range(512), K)
|
|
f.write(struct.pack("<ii", layer, K) + struct.pack("<10i", *ids) + struct.pack("<10f", *([0.1] * 10)))
|
|
w = windows(path)
|
|
assert len(w) == 60 and all(len(x) == 48 for x in w), (len(w), [len(x) for x in w[:3]])
|
|
analyse(w, 11.0)
|
|
print("selftest ok (random routing: recall should be ~ candidates/512)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if "--selftest" in sys.argv:
|
|
selftest()
|
|
else:
|
|
ms = 11.0
|
|
if "--window-ms" in sys.argv:
|
|
ms = float(sys.argv[sys.argv.index("--window-ms") + 1])
|
|
w = windows(sys.argv[1])
|
|
analyse(w, ms)
|
|
if "--profile" in sys.argv:
|
|
tier_hit_rates(w, sys.argv[sys.argv.index("--profile") + 1])
|