"""Served-step records from an nsys sqlite export, one JSON line per stream count seen in the capture window (a step's
stream count = its GDN commit grid z / 48): step median, the GDN commit launch, the gate|up int8 launches by layer type,
and whole-layer spans (opener start to next opener start)."""
import sqlite3, sys, statistics as st, collections, json
f = sys.argv[1]; db = sqlite3.connect(f)
steps = db.execute("select n.start,n.end from NVTX_EVENTS n left join StringIds s on s.id=n.textId where coalesce(s.value,n.text)='decode_step' order by n.start").fetchall()
lo, hi = steps[0][0], steps[-1][1]
ks = db.execute("select s.value,k.start,k.end,k.gridX,k.gridY,k.gridZ,k.graphId from CUPTI_ACTIVITY_KIND_KERNEL k join StringIds s on s.id=k.demangledName where k.start>=? and k.end<=? order by k.start", (lo, hi)).fetchall()
vg = collections.Counter(k[6] for k in ks if k[6] is not None).most_common(1)[0][0]
med = lambda x: round(st.median(x), 2) if x else None
groups = collections.defaultdict(list); i = 0
for s, e in steps:
    while i < len(ks) and ks[i][1] < s: i += 1
    j = i; mine = []
    while j < len(ks) and ks[j][2] <= e: mine.append(ks[j]); j += 1
    i = j
    z = collections.Counter(k[5] for k in mine if "delta_rule" in k[0] and k[6] == vg)
    if not z: continue
    groups[z.most_common(1)[0][0] // 48].append(((e - s) / 1e6, [k for k in mine if k[6] == vg], mine))
for rows, items in sorted(groups.items()):
    durs = sorted(d for d, _, _ in items); n = len(items)
    commit = []; cls = collections.defaultdict(list); spans = collections.defaultdict(list); busy = []
    for _, v, allk in items:
        busy.append(sum(k[2] - k[1] for k in allk) / 1e6)
        last = None; pair = 0; t_open = None
        for k in v:
            nm = k[0]; opener = "gdn" if "delta_rule" in nm else ("attn" if "ni8_prefill_kernel" in nm else None)
            if opener:
                if last is not None: spans[last].append((k[1] - t_open) / 1e3)
                last, pair, t_open = opener, 0, k[1]
                if opener == "gdn": commit.append((k[2] - k[1]) / 1e3)
                continue
            if last and "i8_gemm_kernel" in nm and "_mb" not in nm and k[3] == 136:
                pair += 1; cls[(last, pair)].append((k[2] - k[1]) / 1e3)
    g = lambda key: med(cls[key])
    print(json.dumps(dict(file=f.split("/")[-1].replace(".sqlite", ""), streams=rows, steps=n, step_ms_median=round(st.median(durs), 3),
        step_ms_p25=round(durs[n // 4], 3), step_ms_p75=round(durs[3 * n // 4], 3), gpu_busy_ms=round(st.median(busy), 3),
        commit_us=med(commit), commit_ms_step=round(sum(commit) / 1e3 / n, 3),
        gdn_gateup1_us=g(("gdn", 1)), gdn_gateup2_us=g(("gdn", 2)), attn_gateup1_us=g(("attn", 1)), attn_gateup2_us=g(("attn", 2)),
        gdn_layer_span_us=med(spans["gdn"]), attn_layer_span_us=med(spans["attn"]),
        gdn_layers_ms_step=round(sum(spans["gdn"]) / 1e3 / n, 3), attn_layers_ms_step=round(sum(spans["attn"]) / 1e3 / n, 3))))
