diff --git a/scripts/e2e/decode/routing-lead.py b/scripts/e2e/decode/routing-lead.py new file mode 100644 index 00000000..49019e0e --- /dev/null +++ b/scripts/e2e/decode/routing-lead.py @@ -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(" 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("&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() {