#!/usr/bin/env python3
"""Decode-round ledger of one CUPTI window: graph launches (verify windows and MTP draft/commit steps), their GPU spans, idle between them,
the PCIe stage and the host calls around them.
python3 scripts/profile/lct_decode.py
[--t0 MS --t1 MS] [--big 1000]
Every decode round is a handful of CUDA graph launches: one big verify-window graph (>= --big kernels: 48 layers of GDN/QSA/GR/MoE kernels, the PCIe
stage as copy-kernel branch (Original: fetch_blobs) or as DMA with flag waits (port: verify_wait_flag_ge)) and small MTP graphs (draft chain steps,
commit). Kernels carry the correlation id of their graph launch, so the GPU span of each launch is exact. Output: per graph class the number of
launches, GPU span, kernel-sum, launch-call cost and launch->first-kernel latency; the idle time between consecutive graph executions (host: sampling,
planning, CPU-pool wait); H2D copies by stream; per-category kernel time of the big graphs.
"""
import argparse
import collections
import os
import re
import statistics
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import lct as L
CATS = [
(r"fetch_blobs|copy_rows_from_mapped|copy_from_mapped|copy_i32_from_mapped|copy_indexed|doorbell_publish", "PCIe stage / doorbell / copies"),
(r"wait_flag_ge", "flag waits (CPU/PCIe)"),
(r"gdn", "GDN"),
(r"qsa|attn_chunk|attn_merge|kv_append|block_topk|append|^gate$", "QSA"),
(r"gr_|^norm$|add_streams|weighted_rms|post|pre_final|pre_gated|down_silu", "GR / HC"),
(r"moe|gu_|down_grouped|group_resident|route|swiglu|combine|quantize_q8_0|native_(gu|down|swiglu)|window_moe", "MoE"),
(r"head|sampler|row_top_prob|native_q6_k|map_ids|mtp_select", "head / sampler"),
(r"mtp", "MTP chain"),
(r"mmvq|mmvf|quantize", "dense projections"),
]
def cat(fam):
for rx, name in CATS:
if re.search(rx, fam):
return name
return "other"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dir")
ap.add_argument("--t0", type=float, default=None)
ap.add_argument("--t1", type=float, default=None)
ap.add_argument("--big", type=int, default=1000)
a = ap.parse_args()
win = None if a.t0 is None and a.t1 is None else (a.t0 or 0, a.t1 if a.t1 is not None else 1e12)
t = L.Trace(a.dir, window_ms=win)
W = (t.t1 - t.t0) / 1e6
gl = {x.corr: x for x in t.apis if "GraphLaunch" in t.names.get(x.name, "")}
byc = collections.defaultdict(list)
for k in t.kernels:
byc[k.corr].append(k)
rows = []
for corr, x in gl.items():
ks = byc.get(corr)
if not ks:
continue
rows.append(dict(call_start=x.start, call=x.end - x.start, s=min(k.start for k in ks), e=max(k.end for k in ks), n=len(ks),
ksum=sum(k.end - k.start for k in ks), ks=ks))
rows.sort(key=lambda r: r["s"])
big = [r for r in rows if r["n"] >= a.big]
small = [r for r in rows if r["n"] < a.big]
print("== %s: %.0f ms window, %d graph launches with kernels (%d verify-window graphs, %d small)" % (a.dir, W, len(rows), len(big), len(small)))
def stat(name, rs):
if not rs:
return
span = [(r["e"] - r["s"]) / 1e6 for r in rs]
print(" %-28s x%-4d GPU span mean %7.3f ms (p10 %.3f p90 %.3f), kernel sum %7.3f ms, launch call %6.1f us, call->first kernel %7.1f us" % (
name, len(rs), statistics.mean(span), sorted(span)[len(span) // 10], sorted(span)[len(span) * 9 // 10],
statistics.mean(r["ksum"] for r in rs) / 1e6, statistics.mean(r["call"] for r in rs) / 1e3,
statistics.mean(r["s"] - r["call_start"] for r in rs) / 1e3))
stat("verify-window graphs", big)
groups = collections.defaultdict(list)
for r in small:
groups[r["n"]].append(r)
for n, rs in sorted(groups.items(), key=lambda kv: -sum(r["e"] - r["s"] for r in kv[1]))[:6]:
stat("small graph, %d kernels" % n, rs)
spans = sorted((r["s"], r["e"]) for r in rows)
gaps = []
cur = spans[0][1] if spans else 0
for s, e in spans[1:]:
if s > cur:
gaps.append(s - cur)
cur = max(cur, e)
busy = L.total(L.union(spans))
print(" graph execution busy %.1f ms of %.1f ms; idle between graph executions %.1f ms in %d gaps (mean %.0f us, p90 %.0f us)" % (
busy / 1e6, W, sum(gaps) / 1e6, len(gaps), (statistics.mean(gaps) / 1e3 if gaps else 0), (sorted(gaps)[len(gaps) * 9 // 10] / 1e3 if gaps else 0)))
if big:
wall = [(b["s"] - a_["e"]) for a_, b in zip(big, big[1:])]
per_round = (big[-1]["e"] - big[0]["s"]) / max(1, len(big) - 1)
print(" one verify window every %.2f ms on average (graph start to start, includes draft/commit and host work)" % (per_round / 1e6))
print(" between consecutive verify graphs: idle %.2f ms mean (draft + commit + host)" % (statistics.mean(wall) / 1e6))
print(" per-category kernel time of the verify-window graphs (ms per window):")
cs = collections.defaultdict(float)
for r in big:
for k in r["ks"]:
cs[cat(L.canon(L.family(t.kname(k))) if hasattr(L, "canon") else L.family(t.kname(k)))] += k.end - k.start
for c, v in sorted(cs.items(), key=lambda kv: -kv[1]):
print(" %-34s %8.2f" % (c, v / len(big) / 1e6))
cp = collections.defaultdict(lambda: [0, 0, 0])
for c in t.copies:
x = cp[(L.CKIND.get(c.ckind), L.MKIND.get(c.skind), c.stream)]
x[0] += 1
x[1] += c.bytes
x[2] += c.end - c.start
for k, v in sorted(cp.items(), key=lambda kv: -kv[1][1])[:5]:
print(" copies %-28s %7d, %9.1f MB, busy %8.1f ms, %5.1f GB/s" % (k, v[0], v[1] / 1e6, v[2] / 1e6, v[1] / max(1, v[2])))
api = collections.defaultdict(lambda: [0, 0])
for x in t.apis:
y = api[t.names.get(x.name)]
y[0] += 1
y[1] += x.end - x.start
print(" host calls (CPU ms): " + ", ".join("%s %d x %.1f" % (k.replace("_v3020", "").replace("_v10000", ""), v[0], v[1] / 1e6)
for k, v in sorted(api.items(), key=lambda kv: -kv[1][1])[:7]))
if __name__ == "__main__":
main()