"""Compare eager dispatch and CUDA Graph replay on one CUDA device."""
import statistics
import time

import torch


def transform(x, out):
    torch.add(x, 1.0, out=out)
    out.relu_()
    out.mul_(2.0)


def measure(run, inputs, steps):
    torch.cuda.synchronize()
    start = time.perf_counter()
    for i in range(steps):
        run(inputs[i % len(inputs)])
    torch.cuda.synchronize()
    return (time.perf_counter() - start) * 1e6 / steps


@torch.inference_mode()
def main():
    if not torch.cuda.is_available() or torch.version.cuda is None:
        raise SystemExit("This example requires a CUDA-enabled PyTorch build and an NVIDIA GPU.")
    print(f"GPU: {torch.cuda.get_device_name()} | PyTorch: {torch.__version__} | CUDA build: {torch.version.cuda}")
    inputs = [torch.full((4096,), x, device="cuda", dtype=torch.float32)
              for x in (-3.0, 2.0)]
    static_x = torch.zeros_like(inputs[0])
    result = torch.empty_like(static_x)

    side = torch.cuda.Stream()
    side.wait_stream(torch.cuda.current_stream())
    with torch.cuda.stream(side):
        for _ in range(5):
            transform(static_x, result)
    torch.cuda.current_stream().wait_stream(side)

    graph = torch.cuda.CUDAGraph()
    with torch.cuda.graph(graph):
        transform(static_x, result)

    def replay(x):
        static_x.copy_(x)
        graph.replay()

    def eager_staged(x):
        static_x.copy_(x)
        transform(static_x, result)

    def eager_direct(x):
        transform(x, result)

    cases = [("eager direct", eager_direct), ("eager + copy", eager_staged),
             ("graph + copy", replay)]
    for _, run in cases:
        for x in inputs:
            run(x)
            torch.testing.assert_close(result, 2 * (x + 1).relu())
        measure(run, inputs, 100)

    samples = {name: [] for name, _ in cases}
    for r in range(9):
        order = r % len(cases)
        for name, run in cases[order:] + cases[:order]:
            samples[name].append(measure(run, inputs, 2000))
    print("4096 x FP32 | median wall time (microseconds/step), 9 rounds x 2000 steps")
    for name, values in samples.items():
        print(f"{name:15} {statistics.median(values):.2f}")


if __name__ == "__main__":
    main()
