"""FFN phase of the verify graph (doorbell to `add_hits` end) per layer kind, window rows T and layer class (ledger V2). Offline analysis of CUPTI windows (tools/cupti-trace traces, `lct.py`); host-side Python, stdlib only, uses no GPU. extract TRACE_DIR LEL|VANL OUT.json.gz|- read one trace (needs lct.py: --lct DIR, default /data/leleka-e2e/decode/tools, read only; run with `python3 -B`) and write the per-layer records of the 48-doorbell verify graphs (kernels doorbell .. combine, offsets in ns) classes FILE... class shares and mean phase per kind and T timeline [--kind gdn|qsa] [--t T] [--cls F|C|X] FILE... kernel sequence of the FFN phase per role: stream, p50 start/duration/gap loss VANL_FILE LEL_FILE... [--t 2,3,4] LEL minus VANL per graph: shift-share into the causes (a)-(e) of the loss arrival FILE... per T and class: p50 PCIe landing, M-wait end (CPU rows arrive), tail whatif LEL_FILE VANL_FILE slack-aware estimate of the device-side options of the design document Layer classes (the expert tier decides how long a layer waits for the host; classes keep sessions comparable): F no PCIe leg and no CPU wait: the phase is the device chain C CPU rows late (M wait above 4 us) and no PCIe leg: the phase is arrival of the CPU rows plus the tail X PCIe leg (LEL: B wait above 3.5 us; VANL: fetch_blobs kernel above 2 us), with or without a CPU wait Roles of the routed chain: DB doorbell, EQ expert-input quantize, WA wait A (+ PC plan copy in VANL), V_GU/V_DN VRAM-tier experts, WB wait B, FB fetch_blobs+rebase (VANL), P_GU/P_DN PCIe-tier pass, WM wait M, CR copy rows, AH add_hits, CB combine. SH is the shared-expert chain (parallel to the routed chain on the side-stream variants, in front of it in CL.2). """ import argparse import collections import gzip import json import statistics as st import sys CHAIN = ["DB", "EQ", "WA", "PC", "V_GU", "V_DN", "WB", "FB", "P_GU", "P_DN", "WM", "CR", "AH", "CB"] FIRST = {"chain_doorbell_publish": "DB", "doorbell_publish_res": "DB", "quantize_q8_1": "EQ", "chain_wait_copy_i32": "WA", "copy_i32_from_mapped": "PC", "native_gu_swiglu": "GU", "native_down_multi": "DN", "verify_wait_flag_ge": "WAIT", "wait_flag_ge": "WAIT", "fetch_blobs": "FB", "rebase_ptrs": "FB", "chain_copy_rows_from_mapped": "CR", "copy_rows_from_mapped": "CR", "add_hits": "AH", "mtp_full_combine": "CB", "combine_k10_vec4": "CB"} WAIT_FLOOR_US = 4.0 LEL_B_LONG_US = 3.5 VANL_FETCH_LONG_US = 2.0 def role_of(fam): if fam in FIRST: return FIRST[fam] if fam.startswith("sm120_moe_gu_swiglu"): return "GU" if fam.startswith("window_moe_down"): return "DN" return "SH" # ---------------------------------------------------------------- extract (needs lct.py) def graphs_of(trace): by = collections.defaultdict(list) for k in trace.kernels: by[k.corr].append(k) ids = sorted((c for c, v in by.items() if len(v) >= 900), key=lambda c: min(k.start for k in by[c])) return [sorted(by[c], key=lambda k: k.start) for c in ids[2:-2]] def layer_record(lct, trace, fams, ks, bells, li): name = lambda k: trace.names.get(k.name, "?") # noqa: E731 bell = ks[bells[li]] lo = ks[bells[li - 1]].start if li else ks[0].start nxt = ks[bells[li + 1]].start if li < len(bells) - 1 else bell.start + 600000 seg = [k for k in ks if lo <= k.start < nxt] qsa = any("topk_cluster" in name(k) for k in seg if k.start < bell.start) ffn = [k for k in seg if k.start >= bell.start] hits = [k for k in ffn if "add_hits" in name(k)] comb = [k for k in ffn if "combine" in name(k) and hits and k.start >= hits[0].start] if not hits or not comb: return None body, streams, rec = [k for k in ffn if k.start <= comb[0].start], {}, [] for k in body: fam = fams.setdefault(lct.family(name(k)), len(fams)) rec.append([fam, streams.setdefault(k.stream, len(streams)), k.start - bell.start, k.end - k.start, k.gx, k.gy]) rows = [k.gx // 10 for k in body if "copy_rows" in name(k)] return [0, li, int(qsa), rows[0] if rows else -1, rec, hits[0].end - bell.start, comb[0].end - bell.start] def extract(path, mode, out, lct_dir): sys.path.insert(0, lct_dir) sys.dont_write_bytecode = True import lct trace = lct.Trace(path) fams, layers = {}, [] for gi, ks in enumerate(graphs_of(trace)): bells = [i for i, k in enumerate(ks) if "doorbell_publish" in trace.names.get(k.name, "")] if len(bells) != 48: continue for li in range(48): rec = layer_record(lct, trace, fams, ks, bells, li) if rec: rec[0] = gi layers.append(rec) blob = json.dumps({"path": path, "mode": mode, "fams": sorted(fams, key=fams.get), "layers": layers}, separators=(",", ":")).encode() sink = sys.stdout.buffer if out == "-" else open(out, "wb") sink.write(gzip.compress(blob, 6)) sink.flush() # ---------------------------------------------------------------- loading and roles def view(fams, layer): """role -> list of (start, end, stream, gx, gy) in ns from the doorbell start.""" body = sorted(layer[4], key=lambda k: k[2]) waits = [k for k in body if role_of(fams[k[0]]) == "WAIT"] wnames = ("WA", "WB", "WM") if len(waits) == 3 else ("WB", "WM") roles, n_gu, n_dn, n_w = collections.defaultdict(list), 0, 0, 0 for fam, stream, start, dur, gx, gy in body: role = role_of(fams[fam]) if role == "GU": role, n_gu = ("V_GU", "P_GU")[min(n_gu, 1)], n_gu + 1 elif role == "DN": role, n_dn = ("V_DN", "P_DN")[min(n_dn, 1)], n_dn + 1 elif role == "WAIT": role, n_w = wnames[min(n_w, len(wnames) - 1)], n_w + 1 roles[role].append((start, start + dur, stream, gx, gy)) return roles def leg_class(roles, mode): wait_m = roles["WM"][0][1] - roles["WM"][0][0] if roles.get("WM") else 0 if mode == "VANL": pcie = bool(roles.get("FB")) and roles["FB"][0][1] - roles["FB"][0][0] > VANL_FETCH_LONG_US * 1e3 else: pcie = bool(roles.get("WB")) and roles["WB"][0][1] - roles["WB"][0][0] > LEL_B_LONG_US * 1e3 if pcie: return "X" return "C" if wait_m > WAIT_FLOOR_US * 1e3 else "F" def load(path): d = json.load(gzip.open(path)) cells = [] for lay in d["layers"]: roles = view(d["fams"], lay) cells.append({"g": lay[0], "li": lay[1], "qsa": lay[2], "T": lay[3], "phase": lay[5], "cb": lay[6], "R": roles, "cls": leg_class(roles, d["mode"])}) name = path.replace("\\", "/").rsplit("/", 1)[-1].replace(".json.gz", "") return {"name": name, "mode": d["mode"], "cells": cells} def pick(ds, **kw): out = ds["cells"] for key, val in kw.items(): if val is not None: out = [c for c in out if c[key] == val] return out def mean(v): return st.mean(v) if v else 0.0 def pct(v, p): v = sorted(v) return v[min(len(v) - 1, int(p * len(v)))] if v else 0.0 # ---------------------------------------------------------------- classes def cmd_classes(files): for f in files: ds = load(f) print("== %s: phase mean per layer (us), share of layers, by kind, T and class" % ds["name"]) for kind, kn in ((0, "gdn"), (1, "qsa")): for t in range(1, 7): sub = pick(ds, qsa=kind, T=t) if len(sub) < 100: continue cols = [] for cls in "FCX": s = [c["phase"] / 1e3 for c in sub if c["cls"] == cls] cols.append("%s %4.1f%% %6.1f (p50 %6.1f)" % (cls, 100 * len(s) / len(sub), mean(s), pct(s, .5))) print(" %s T%d n=%6d | %s" % (kn, t, len(sub), " | ".join(cols))) # ---------------------------------------------------------------- timeline def chain_of(roles): out, prev_end = [], 0 for r in CHAIN: if roles.get(r): s, e = min(x[0] for x in roles[r]), max(x[1] for x in roles[r]) out.append((r, s, e, s - prev_end, roles[r][0][2])) prev_end = e return out def shared_chain_stats(c, acc): sh, cb, ah = c["R"].get("SH"), c["R"].get("CB"), c["R"].get("AH") if sh and cb and ah: sh_end = max(x[1] for x in sh) acc["slack"].append((cb[0][0] - sh_end) / 1e3) acc["len"].append((sh_end - min(x[0] for x in sh)) / 1e3) acc["late"].append(sh_end > ah[0][1]) def timeline_table(ds, kind, t, cls): sub = [c for c in pick(ds, qsa=kind, T=t) if cls in (None, "all") or c["cls"] == cls] acc = collections.defaultdict(lambda: {"s": [], "d": [], "g": [], "st": collections.Counter()}) ends, sh = [], collections.defaultdict(list) for c in sub: for r, s, e, gap, stream in chain_of(c["R"]): a = acc[r] a["s"].append(s / 1e3) a["d"].append((e - s) / 1e3) a["g"].append(gap / 1e3) a["st"][stream] += 1 ends.append(c["phase"] / 1e3) shared_chain_stats(c, sh) return len(sub), acc, ends, sh def timeline_cell(a): if not a: return "-" stream = a["st"].most_common(1)[0][0] return "%.1f / %.1f / %.1f / s%d" % (pct(a["s"], .5), pct(a["d"], .5), pct(a["g"], .5), stream) def cmd_timeline(files, kind, t, cls): kinds = [(0, "gdn"), (1, "qsa")] if kind is None else [({"gdn": 0, "qsa": 1}[kind], kind)] sets = [load(f) for f in files] for kv, kn in kinds: for tt in ([t] if t else (2, 3, 4)): tabs = [timeline_table(d, kv, tt, cls) for d in sets] print("\n### %s T=%d class %s (p50 start / duration / gap before / stream, us; n = layers)" % ( kn, tt, cls or "all")) print("| role | " + " | ".join("%s (n=%d)" % (d["name"], tb[0]) for d, tb in zip(sets, tabs)) + " |") print("| --- |" + " --- |" * len(sets)) for r in CHAIN: print("| %s | " % r + " | ".join(timeline_cell(tb[1].get(r)) for tb in tabs) + " |") print("| phase end (add_hits end) | " + " | ".join("%.1f" % pct(tb[2], .5) for tb in tabs) + " |") print("| shared chain length / slack before combine / share ending after add_hits | " + " | ".join( "%.1f / %.1f / %.1f%%" % (pct(tb[3]["len"], .5), pct(tb[3]["slack"], .5), 100 * mean([1.0 if x else 0.0 for x in tb[3]["late"]])) if tb[3]["len"] else "-" for tb in tabs) + " |") # ---------------------------------------------------------------- loss (shift-share) def by_graph_totals(ds, t): """Graphs of T rows with all 48 layers: count, mean, standard error of the mean and median of the FFN phase (ms).""" tot, cnt, gt = collections.defaultdict(float), collections.Counter(), {} for c in ds["cells"]: tot[c["g"]] += c["phase"] / 1e3 cnt[c["g"]] += 1 gt[c["g"]] = c["T"] xs = [v / 1e3 for g, v in tot.items() if cnt[g] == 48 and gt[g] == t] se = (st.pstdev(xs) / len(xs) ** .5) if len(xs) > 1 else 0.0 return len(xs), mean(xs), se, pct(xs, .5) def cell_stats(ds, kind, t): sub = pick(ds, qsa=kind, T=t) out = {} for cls in "FCX": s = [c for c in sub if c["cls"] == cls] arr = [c["R"]["WM"][0][1] / 1e3 for c in s if c["R"].get("WM")] out[cls] = {"w": len(s) / len(sub) if sub else 0, "phase": mean([c["phase"] / 1e3 for c in s]), "arrival": mean(arr), "layers": s} return out def f_buckets(cells): """Mean per layer (us) of the F-class chain, split into the cause buckets (a) order/number, (b) streams, (c) gaps, (d) kernel durations.""" acc = collections.defaultdict(list) z = (0, 0, 0) for c in cells: ch = {r: (s, e, g) for r, s, e, g, _ in chain_of(c["R"])} d = lambda r: (ch.get(r, z)[1] - ch.get(r, z)[0]) / 1e3 # noqa: E731 g = lambda r: ch.get(r, z)[2] / 1e3 # noqa: E731 acc["b serial shared expert (doorbell end to expert quantize start)"].append(g("EQ")) acc["a plan wait + plan copy (WA, PC kernels and gaps)"].append(d("WA") + g("WA") + d("PC") + g("PC")) acc["a PCIe region (WB, FB, P_GU, P_DN kernels and gaps)"].append( sum(d(r) + g(r) for r in ("WB", "FB", "P_GU", "P_DN"))) later = ("V_GU", "V_DN", "WM", "CR", "AH") acc["c gaps before V_GU, V_DN, WM, CR, AH"].append(sum(g(r) for r in later)) for r in ("DB", "EQ", "V_GU", "V_DN", "WM", "CR", "AH"): acc["d kernel %s" % r].append(d(r)) return {k: mean(v) for k, v in acc.items()} def loss_terms(cl, cv, kind_mult, terms, shares, kind): for cls in "FCX": wl, wv = cl[cls]["w"], cv[cls]["w"] if wv and wl: terms["within_" + cls] += kind_mult * wv * (cl[cls]["phase"] - cv[cls]["phase"]) / 1e3 terms["arrival_" + cls] += kind_mult * wv * (cl[cls]["arrival"] - cv[cls]["arrival"]) / 1e3 terms["mix"] += kind_mult * (wl - wv) * cl[cls]["phase"] / 1e3 if kind == 0: shares[cls] = (wl, wv) if cl["F"]["layers"] and cv["F"]["layers"]: bl, bv = f_buckets(cl["F"]["layers"]), f_buckets(cv["F"]["layers"]) terms["_wF"] += kind_mult * cv["F"]["w"] for k in bl: terms["F:" + k] += kind_mult * cv["F"]["w"] * (bl[k] - bv[k]) / 1e3 def loss_row(lel, van, t): nl, _, sl, medl = by_graph_totals(lel, t) nv, _, sv, medv = by_graph_totals(van, t) if nl < 10 or nv < 10: return None terms, shares, tot = collections.defaultdict(float), {}, {"L": 0.0, "V": 0.0} for kind, mult in ((0, 36), (1, 12)): cl, cv = cell_stats(lel, kind, t), cell_stats(van, kind, t) loss_terms(cl, cv, mult, terms, shares, kind) for cls in "FCX": tot["L"] += mult * cl[cls]["w"] * cl[cls]["phase"] / 1e3 tot["V"] += mult * cv[cls]["w"] * cv[cls]["phase"] / 1e3 return {"nL": nl, "nV": nv, "L": (tot["L"], sl), "V": (tot["V"], sv), "med": (medl, medv), "terms": terms, "shares": shares} def print_loss_row(t, r): t_ = r["terms"] se = (r["L"][1] ** 2 + r["V"][1] ** 2) ** .5 share = lambda i: "/".join("%.0f" % (100 * r["shares"][c][i]) for c in "FCX") # noqa: E731 delta, med = r["L"][0] - r["V"][0], r["med"][0] - r["med"][1] print("T=%d graphs L %d V %d | L %.3f V %.3f delta %+.3f (1 se %.3f) | per-graph median delta %+.3f | " "layer shares F/C/X (gdn) L %s V %s" % (t, r["nL"], r["nV"], r["L"][0], r["V"][0], delta, se, med, share(0), share(1))) tail_c, tail_x = t_["within_C"] - t_["arrival_C"], t_["within_X"] - t_["arrival_X"] print(" within F %+.3f | within C %+.3f (arrival %+.3f, tail %+.3f) | within X %+.3f (arrival %+.3f, tail %+.3f)" " | mix %+.3f" % (t_["within_F"], t_["within_C"], t_["arrival_C"], tail_c, t_["within_X"], t_["arrival_X"], tail_x, t_["mix"])) print(" F-class buckets (the phase from the doorbell to add_hits end; both kinds, VANL F share), ms per graph," " LEL minus VANL:") per_layer = 1000.0 / t_["_wF"] if t_["_wF"] else 0.0 for k in sorted(k for k in t_ if k.startswith("F:")): print(" %-66s %+.3f ms (%+.1f us per F layer)" % (k[2:], t_[k], t_[k] * per_layer)) def own_mix_line(rows): """The rows' deltas weighted by the LEL variant's own graph count per T (VANL at the same T weights).""" w = {t: r["nL"] for t, r in rows.items()} n = sum(w.values()) avg = lambda f: sum(w[t] * f(rows[t]) for t in rows) / n # noqa: E731 term = lambda r, *keys: sum(r["terms"][k] for k in keys) # noqa: E731 mix = "/".join("T%d %.0f%%" % (t, 100 * w[t] / n) for t in sorted(w)) print("own T mix %s: L %.3f V %.3f delta %+.3f | within F %+.3f | arrival C+X %+.3f | tail C+X %+.3f | " "mix %+.3f" % ( mix, avg(lambda r: r["L"][0]), avg(lambda r: r["V"][0]), avg(lambda r: r["L"][0] - r["V"][0]), avg(lambda r: term(r, "within_F")), avg(lambda r: term(r, "arrival_C", "arrival_X")), avg(lambda r: term(r, "within_C", "within_X") - term(r, "arrival_C", "arrival_X")), avg(lambda r: term(r, "mix")))) def cmd_loss(vanl_file, lel_files, ts): van = load(vanl_file) for f in lel_files: lel = load(f) print("\n## %s minus %s, ms per graph (12 qsa + 36 gdn layers), by window rows T" % (lel["name"], van["name"])) rows = {} for t in ts: row = loss_row(lel, van, t) if row: rows[t] = row print_loss_row(t, row) if rows: own_mix_line(rows) # ---------------------------------------------------------------- arrival def landing_us(c): """When the PCIe leg has landed: end of wait B (LEL, DMA) or of the fetch kernels (VANL), after the doorbell.""" r = c["R"].get("FB") or c["R"].get("WB") return max(x[1] for x in r) / 1e3 if r else 0.0 def cmd_arrival(files): for f in files: ds = load(f) print("== %s (all layers of both kinds; us after the doorbell start, p50)" % ds["name"]) for t in (2, 3, 4): for cls in "FCX": sub = [c for c in pick(ds, T=t) if c["cls"] == cls and c["R"].get("WM")] if len(sub) < 50: continue m_end = [c["R"]["WM"][0][1] / 1e3 for c in sub] print(" T=%d %s n=%6d share %4.1f%% | landing %6.1f | M end %6.1f | tail after M end %5.1f | " "phase %6.1f" % ( t, cls, len(sub), 100 * len(sub) / len(pick(ds, T=t)), pct([landing_us(c) for c in sub], .5), pct(m_end, .5), pct([c["phase"] / 1e3 - m for c, m in zip(sub, m_end)], .5), pct([c["phase"] / 1e3 for c in sub], .5))) # ---------------------------------------------------------------- what-if def dur(c, role): x = c["R"].get(role) return (x[0][1] - x[0][0]) / 1e3 if x else 0.0 def floors(ds): return {k: pct([dur(c, k) for c in ds["cells"] if c["cls"] == "F" and c["R"].get(k)], .5) for k in ("WB", "WM")} def shared_slack_us(c): """Time the shared-expert side chain ends before the combine starts: no routed-chain saving can exceed it.""" sh, cb, ah = c["R"].get("SH"), c["R"].get("CB"), c["R"].get("AH") parallel = bool(sh) and bool(cb) and bool(ah) and sh[0][2] != ah[0][2] return (cb[0][0] - max(x[1] for x in sh)) / 1e3 if parallel else 1e9 def whatif_gain(c, fl, target_dn): """Uncapped gain per layer (us) of each option. A saving before a wait is absorbed by that wait's slack (time the device waited beyond its floor); a saving after the last wait is on the critical path.""" sb, sm = max(0.0, dur(c, "WB") - fl["WB"]), max(0.0, dur(c, "WM") - fl["WM"]) ab = lambda x, s: max(0.0, x - s) # noqa: E731 return { "A pcie-tier gate/up grid.y 4 (kernel strides already)": ab(dur(c, "P_GU") - 0.7, sm), "B sub16 down kernel, VRAM pass (target VANL F mean)": ab(dur(c, "V_DN") - target_dn, sb + sm), "B sub16 down kernel, PCIe pass (target 0.7 us)": ab(dur(c, "P_DN") - 0.7, sm), "C add_hits folded into the combine (upper bound: AH duration)": dur(c, "AH"), "D wait M folded into copy rows (F: WM duration; waiting layers: 0.5 us assumed)": dur(c, "WM") if c["cls"] == "F" else 0.5, } def cmd_whatif(lel_file, vanl_file): """No saving exceeds the slack of the shared-expert side chain: once the routed chain is shorter than it, the combine waits for the shared expert. The last line applies that cap to the sum of all options.""" lel, van = load(lel_file), load(vanl_file) fl = floors(lel) print("== %s, floors (F-class p50, us): wait B %.2f wait M %.2f" % (lel["name"], fl["WB"], fl["WM"])) for t in (2, 3, 4): tgt = mean([dur(c, "V_DN") for c in pick(van, T=t) if c["cls"] == "F"]) sub = pick(lel, T=t) graphs = len({c["g"] for c in sub}) if not graphs: continue acc, both = collections.defaultdict(float), 0.0 for c in sub: cap, gains = shared_slack_us(c), whatif_gain(c, fl, tgt) for k, v in gains.items(): acc[k] += min(cap, v) both += min(cap, sum(gains.values())) print("T=%d graphs %d (VANL F-class V_DN %.1f us): ms per graph (us per layer), each option capped alone" % ( t, graphs, tgt)) for k, v in acc.items(): print(" %-80s %.3f ms (%.1f us per layer)" % (k, v / graphs / 1e3, v / len(sub))) print(" %-80s %.3f ms (%.1f us per layer)" % ( "all options together, capped", both / graphs / 1e3, both / len(sub))) def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="cmd", required=True) e = sub.add_parser("extract") e.add_argument("trace") e.add_argument("mode", choices=("LEL", "VANL")) e.add_argument("out") e.add_argument("--lct", default="/data/leleka-e2e/decode/tools") for name in ("classes", "timeline", "loss", "arrival", "whatif"): p = sub.add_parser(name) p.add_argument("files", nargs="+") p.add_argument("--kind", choices=("gdn", "qsa")) p.add_argument("--t", default=None) p.add_argument("--cls", choices=("F", "C", "X", "all"), default="all") a = ap.parse_args() if a.cmd == "extract": extract(a.trace, a.mode, a.out, a.lct) elif a.cmd == "classes": cmd_classes(a.files) elif a.cmd == "timeline": cmd_timeline(a.files, a.kind, int(a.t) if a.t else None, a.cls) elif a.cmd == "arrival": cmd_arrival(a.files) elif a.cmd == "loss": cmd_loss(a.files[0], a.files[1:], [int(x) for x in (a.t or "2,3,4").split(",")]) else: cmd_whatif(a.files[0], a.files[1]) if __name__ == "__main__": main()