"""E7 nsys（rank0 = node0 GPU0，profile 第 20-21 步）→ 每步 GPU 时间分解与 exposed communication。
分类：
  EP 通信：dispatcher 的通信 kernel（NCCL SendRecv/AllGather 在 EP 所在 stream；DeepEP dispatch/combine/notify；
           HybridEP dispatch/combine/device_sync/rdma_sync）
  DP 等其他通信：DDP 梯度 ReduceScatter / 参数 AllGather（独立 stream）和 loss/grad-norm 的小 AllReduce
  计算：其余所有 kernel（含 permute/unpermute、GEMM、attention、优化器）
exposed_X = X 的时间并集中没有任何计算 kernel 同时在跑的部分；idle = 窗口内没有任何 kernel 的时间。"""
import csv
import sqlite3
import sys

ROOT = "/root/paddlejob/amfp-public/weiziyang/moe_dispatcher/bench/results"
EP_NAMES = {"dispatch", "combine", "cached_notify", "notify_dispatch", "dispatch_kernel", "combine_kernel",
            "device_sync_kernel", "rdma_sync_kernel", "ncclDevKernel_SendRecv"}
STEPS = 2


def union(iv):
    out = []
    for s, e in sorted(iv):
        if out and s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out


def length(u):
    return sum(e - s for s, e in u)


def intersect(a, b):
    i = j = 0; tot = 0
    while i < len(a) and j < len(b):
        s, e = max(a[i][0], b[j][0]), min(a[i][1], b[j][1])
        tot += max(0, e - s)
        if a[i][1] < b[j][1]:
            i += 1
        else:
            j += 1
    return tot


def analyze(backend):
    db = sqlite3.connect(f"{ROOT}/train/E7-B1-{backend}-nsys/nsys_node0.sqlite")
    ks = db.execute("""select k.start, k.end, k.streamId, s.value from CUPTI_ACTIVITY_KIND_KERNEL k
                       join StringIds s on k.shortName = s.id where k.deviceId = 0""").fetchall()
    dp_streams = {st for _, _, st, n in ks if n.startswith("ncclDevKernel_ReduceScatter")}
    ep, dp, comp = [], [], []
    for s, e, st, n in ks:
        if st in dp_streams and n.startswith("nccl"):
            dp.append((s, e))
        elif n in EP_NAMES or (n.startswith("ncclDevKernel_AllGather") and st not in dp_streams):
            ep.append((s, e))
        elif n.startswith("nccl"):
            dp.append((s, e))  # loss/grad-norm 的小 AllReduce 归到非 EP 通信
        else:
            comp.append((s, e))
    win = max(e for _, e, _, _ in ks) - min(s for s, _, _, _ in ks)
    U = {k: union(v) for k, v in [("ep", ep), ("dp", dp), ("comp", comp), ("all", ep + dp + comp)]}
    r = dict(backend=backend, window_ms=win / 1e6 / STEPS,
             ep_kernel_ms=sum(e - s for s, e in ep) / 1e6 / STEPS, ep_union_ms=length(U["ep"]) / 1e6 / STEPS,
             ep_exposed_ms=(length(U["ep"]) - intersect(U["ep"], U["comp"])) / 1e6 / STEPS,
             dp_exposed_ms=(length(U["dp"]) - intersect(U["dp"], union(comp + ep))) / 1e6 / STEPS,
             compute_union_ms=length(U["comp"]) / 1e6 / STEPS, idle_ms=(win - length(U["all"])) / 1e6 / STEPS)
    return {k: (round(v, 1) if isinstance(v, float) else v) for k, v in r.items()}


if __name__ == "__main__" and "--timeline" not in sys.argv:
    rows = [analyze(b) for b in (sys.argv[1:] or ["alltoall", "deepep", "hybridep"])]
    with open(f"{ROOT}/aggregate/train_nsys_breakdown.csv", "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
    for r in rows:
        print(r)


def timeline_fig(span_ms=12.0):
    """F9：三个 backend 各取第 20 步中段一个 MoE 层前向附近的 span_ms 窗口，按 stream 画 kernel 时间线。"""
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    colors = {"EP comm": "#C44E52", "DP/other comm": "#937860", "permute": "#DD8452", "GEMM": "#4C72B0", "attention": "#55A868", "other compute": "#8172B3"}

    def cat(n, st, dp_streams):
        if st in dp_streams and n.startswith("nccl"):
            return "DP/other comm"
        if n in EP_NAMES or n.startswith("ncclDevKernel_AllGather"):
            return "EP comm"
        if n.startswith("nccl"):
            return "DP/other comm"
        if "permute" in n:
            return "permute"
        if n.startswith(("nvjet", "sm90_xmma", "cutlass")) or "gemm" in n.lower():
            return "GEMM"
        if "sdpa" in n or "flash" in n:
            return "attention"
        return "other compute"

    fig, axes = plt.subplots(3, 1, figsize=(13, 7))
    for ax, b in zip(axes, ["alltoall", "deepep", "hybridep"]):
        db = sqlite3.connect(f"{ROOT}/train/E7-B1-{b}-nsys/nsys_node0.sqlite")
        ks = db.execute("""select k.start, k.end, k.streamId, s.value from CUPTI_ACTIVITY_KIND_KERNEL k
                           join StringIds s on k.shortName = s.id where k.deviceId = 0 order by k.start""").fetchall()
        dp_streams = {st for _, _, st, n in ks if n.startswith("ncclDevKernel_ReduceScatter")}
        # 前向 attention fprop 之后的第一个 EP 通信 kernel，取窗口中段那一层
        fprops = [s for s, _, _, n in ks if "fprop" in n]
        t_attn = fprops[len(fprops) // 4]
        t0 = t_attn - 1.0e6
        win = [(s, e, st, n) for s, e, st, n in ks if e > t0 and s < t0 + span_ms * 1e6]
        streams = sorted({st for _, _, st, _ in win})
        for s, e, st, n in win:
            c = cat(n, st, dp_streams)
            ax.barh(streams.index(st), (min(e, t0 + span_ms * 1e6) - max(s, t0)) / 1e6, left=(max(s, t0) - t0) / 1e6,
                    color=colors[c], height=0.7)
        ax.set_yticks(range(len(streams)), [f"stream {st}" for st in streams], fontsize=7)
        ax.set_xlim(0, span_ms)
        ax.set_title(f"{b}: GPU0 kernels, {span_ms:.0f} ms window around one MoE layer forward (step 20)", fontsize=9)
    axes[-1].set_xlabel("ms")
    handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in colors.values()]
    fig.legend(handles, list(colors), loc="lower center", fontsize=7, ncol=6)
    fig.suptitle("F9 (measured, Nsight Systems): EP comm sits on the critical path; no compute runs under it (EP overlap off)", fontsize=10)
    fig.tight_layout(rect=(0, 0.04, 1, 0.95))
    out = "/root/paddlejob/amfp-public/weiziyang/moe_dispatcher/bench/plots/figures/F9_timeline.png"
    fig.savefig(out, dpi=150)
    print("wrote", out)


if __name__ == "__main__" and "--timeline" in sys.argv:
    timeline_fig()
