"""Eager add + RMSNorm chain against the fused launch, as a captured graph replays them.

Each graph holds SITES instances over their own buffers (a step's norm sites in sequence), is
replayed REPS times, and the median replay is divided by SITES. AOT artifacts only.
One JSON record per line.
"""

import json
import os
import statistics
from pathlib import Path

import torch

from arbi_serve.kernels import _aot
from arbi_serve.kernels import add_rmsnorm_f16 as fused

SITES, REPS, N = 128, 200, 5120


def graph_us(fn, rows):
    g = torch.Generator(device="cuda").manual_seed(rows)
    xs = [(torch.randn(rows, N, generator=g, device="cuda") * 3).bfloat16() for _ in range(SITES)]
    rs = [torch.zeros(rows, N, device="cuda", dtype=torch.bfloat16) for _ in range(SITES)]
    w = 1 + 0.1 * torch.randn(N, generator=g, device="cuda")

    def run():
        return [fn(x, r, w, 1e-6) for x, r in zip(xs, rs, strict=True)]

    stream = torch.cuda.Stream()
    with torch.cuda.stream(stream):
        for _ in range(3):
            run()
        graph = torch.cuda.CUDAGraph()
        with torch.cuda.graph(graph, stream=stream):
            keep = run()
        times = []
        for _ in range(REPS):
            for r in rs:
                r.zero_()
            torch.cuda.synchronize()
            a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
            a.record()
            graph.replay()
            b.record()
            b.synchronize()
            times.append(a.elapsed_time(b) * 1e3 / SITES)
    del keep
    return statistics.median(times), min(times)


def main():
    _aot._AOT_DIR = Path(os.environ["NORM_AOT_DIR"])
    card = torch.cuda.get_device_name(0)
    for rows in (1, 2, 4, 8, 16, 32, 64):
        assert fused._try_load_aot("bf16", "bf16", *fused.reduce_plan(rows, N)) is not None
        rec = {"card": card, "rows": rows, "width": N, "sites_per_graph": SITES, "replays": REPS}
        for order in (1, 2):
            for name, fn in (("eager", fused._eager), ("fused", fused.add_rmsnorm_f16)):
                med, lo = graph_us(fn, rows)
                rec[f"{name}_us_per_site_run{order}"] = round(med, 3)
                rec[f"{name}_us_per_site_min_run{order}"] = round(lo, 3)
        print(json.dumps(rec), flush=True)


if __name__ == "__main__":
    main()
