routing-lead.py prefetch probe; probe phase
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
#!/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 = 8. 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.
|
||||
|
||||
usage: routing-lead.py ROUTING.bin [--window-ms 11.0] [--selftest]
|
||||
"""
|
||||
import struct, sys, collections, random
|
||||
|
||||
K = 8
|
||||
|
||||
|
||||
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 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("<8i", *ids) + struct.pack("<8f", *([0.125] * 8)))
|
||||
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])
|
||||
analyse(windows(sys.argv[1]), ms)
|
||||
@@ -34,7 +34,7 @@ BIN_BASE=$D/bin-scbase; BIN_NEW=$D/bin-singlecopy; RT_BASE=$D/rt-scbase; RT_NEW=
|
||||
CAP=/data/leleka-e2e/sm120/capture/night5-long-256k
|
||||
INV=$SC/tools/ram-inventory.sh
|
||||
STAMPS=$SC/stamps
|
||||
PHASES=${PHASES:-"cold id e2e"}
|
||||
PHASES=${PHASES:-"probe cold id e2e"}
|
||||
BLOCKS=${BLOCKS:-6}
|
||||
ARMS_SET=${ARMS_SET:-"base sparse file"}
|
||||
RUN_TAG=${RUN_TAG:-}
|
||||
@@ -119,6 +119,16 @@ if [[ " $PHASES " == *" cold "* ]]; then
|
||||
done
|
||||
fi
|
||||
|
||||
# ---- phase probe: cost of the existing KAR level-2 decode on the GPU (candidate B/C evidence; no model, a few seconds) -------------------------
|
||||
if [[ " $PHASES " == *" probe "* ]]; then
|
||||
mkdir -p "$OUTR"
|
||||
if take_gpu probe; then
|
||||
{ echo "== KAR decode cost probe $(date -u +%FT%TZ) $(sha256sum $SC/tools/kar-probe-test | cut -c1-16)"; nvidia-smi --query-gpu=name,clocks.sm,clocks.mem --format=csv,noheader
|
||||
"$SC/tools/kar-probe-test" --ignored --nocapture kar_levels_expert_cost_probe 2>&1 | grep -a -E "KAR_PROBE|test result|panicked|error" ; } | tee -a "$OUTR/kar-probe.txt"
|
||||
drop_gpu
|
||||
fi
|
||||
fi
|
||||
|
||||
# ---- phase id: teacher-forced replay (bitwise identity) ----------------------------------------------------------------------------
|
||||
OI=$OUTR/id$RUN_TAG
|
||||
id_env() {
|
||||
|
||||
Reference in New Issue
Block a user