"""Bit identity of the fused residual-add + RMSNorm launch against the eager chain.

Every row count 1..64 at each width and dtype pair, AOT artifacts only (a missing
artifact is an error, never a JIT on the card). One JSON record per line.
"""

import json
import os
import sys
from pathlib import Path

import torch

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

DT = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32}
PAIRS = [("bf16", "bf16"), ("fp16", "fp16"), ("bf16", "fp32"), ("fp16", "fp32"), ("fp32", "fp32")]
WIDTHS = [128, 640, 1024, 1536, 2048, 2688, 4096, 5120, 6144, 8192, 10240, 17408]
SEEDS = (11, 12, 13)


def operands(rows, n, xd, rd, seed, layout):
    g = torch.Generator(device="cuda").manual_seed(seed * 100003 + rows * 131 + n)
    scale = torch.exp(torch.randn(rows, 1, generator=g, device="cuda") * 2.0)
    x = (torch.randn(rows, n, generator=g, device="cuda") * scale).to(DT[xd])
    r = (torch.randn(rows, n, generator=g, device="cuda") * scale * 8).to(DT[rd])
    w = 1.0 + 0.3 * torch.randn(n, generator=g, device="cuda")
    if layout == "strided":
        # Rows of a wider buffer: a row stride that is not the width.
        xb = torch.zeros(rows, n + 64, dtype=x.dtype, device="cuda")
        rb = torch.zeros(rows, n + 192, dtype=r.dtype, device="cuda")
        xb[:, :n], rb[:, :n] = x, r
        x, r = xb[:, :n], rb[:, :n]
    elif layout == "lead2" and rows % 2 == 0:
        x, r = x.view(2, rows // 2, n), r.view(2, rows // 2, n)
    return x, r, w


def main():
    # The artifacts baked on a builder (scripts/aot_compile_triton.py --out-dir).
    _aot._AOT_DIR = Path(os.environ["NORM_AOT_DIR"])
    assert _aot.target_str() is not None
    total = {"calls": 0, "rows": 0, "mismatched_calls": 0}
    for xd, rd in PAIRS:
        for n in WIDTHS:
            rec = {"x": xd, "residual": rd, "width": n, "calls": 0, "rows": 0, "bad": []}
            plans = set()
            for rows in range(1, 65):
                plan = fused.reduce_plan(rows, n)
                assert plan is not None, (rows, n)
                assert fused._try_load_aot(xd, rd, *plan) is not None, (xd, rd, plan)
                plans.add(plan)
                for seed in SEEDS:
                    for layout in ("plain", "strided", "lead2"):
                        x, r, w = operands(rows, n, xd, rd, seed, layout)
                        r_ref = r.clone()
                        want = fused._eager(x, r_ref, w, 1e-6)
                        assert fused._operands(x, r, w) is not None
                        got = fused.add_rmsnorm_f16(x, r, w, 1e-6)
                        ok = (
                            got.dtype == torch.float16
                            and got.shape == want.shape
                            and torch.equal(got.view(torch.int16), want.view(torch.int16))
                            and torch.equal(r.contiguous().view(-1), r_ref.contiguous().view(-1))
                        )
                        rec["calls"] += 1
                        rec["rows"] += rows
                        if not ok:
                            diff = (got.view(torch.int16) != want.view(torch.int16)).sum().item()
                            rec["bad"].append([rows, seed, layout, diff])
            rec["plans"] = sorted(plans)
            rec["bad_calls"] = len(rec["bad"])
            rec["bad"] = rec["bad"][:6]
            total["calls"] += rec["calls"]
            total["rows"] += rec["rows"]
            total["mismatched_calls"] += rec["bad_calls"]
            print(json.dumps(rec), flush=True)
    total["card"] = torch.cuda.get_device_name(0)
    total["torch"] = torch.__version__
    print(json.dumps({"total": total}), flush=True)
    return 1 if total["mismatched_calls"] else 0


if __name__ == "__main__":
    sys.exit(main())
