File size: 2,727 Bytes
1ab6c33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Honest GPU timing. Import `bench` rather than hand-rolling a timer.

The failure this exists to prevent: an eager reference in this repo measured 185 ms wall against
2.06 ms of GPU-busy time. Wall-clock around a python call measures dispatch, not the kernel.

Rules enforced here: CUDA events (not time.time), warmup excluded, FRESH inputs per rep so a warm L2
does not masquerade as bandwidth, min-of-N (not mean, which drifts with clocks), and an optional
GPU-busy cross-check so host-bound code is caught rather than reported as kernel time.
"""
import statistics
import torch


def bench(fn, make_args=None, args=None, reps=10, warmup=5, return_all=False):
    """Time `fn`. Pass make_args(i)->tuple for fresh inputs per rep, or a fixed `args` tuple."""
    if make_args is None and args is None:
        raise ValueError("pass make_args or args")
    get = make_args if make_args is not None else (lambda i: args)

    for i in range(warmup):
        fn(*get(-1 - i))
    torch.cuda.synchronize()

    times = []
    for i in range(reps):
        a = get(i)
        torch.cuda.synchronize()
        s = torch.cuda.Event(enable_timing=True)
        e = torch.cuda.Event(enable_timing=True)
        s.record()
        out = fn(*a)
        e.record()
        torch.cuda.synchronize()
        times.append(s.elapsed_time(e) / 1e3)
        del a, out
    return (min(times), times) if return_all else min(times)


def gpu_busy(fn, args, reps=3):
    """Sum of kernel time from the profiler. If this is far below `bench`, you are HOST-bound and the
    kernel is not your problem yet -- go look at nsys, not ncu."""
    from torch.profiler import profile, ProfilerActivity
    for _ in range(3):
        fn(*args)
    torch.cuda.synchronize()
    with profile(activities=[ProfilerActivity.CUDA]) as p:
        for _ in range(reps):
            fn(*args)
        torch.cuda.synchronize()
    ks = [k for k in p.key_averages() if k.self_device_time_total > 0]
    return sum(k.self_device_time_total for k in ks) / reps / 1e6, sum(k.count for k in ks) / reps


def report(fn, make_args=None, args=None, work=None, unit="TFLOP/s", **kw):
    """Time, cross-check against GPU-busy, and convert to an achieved metric."""
    wall = bench(fn, make_args=make_args, args=args, **kw)
    a = (make_args(0) if make_args else args)
    busy, nk = gpu_busy(fn, a)
    print(f"wall {wall*1e6:9.1f} us   gpu-busy {busy*1e6:9.1f} us   kernels/call {nk:.0f}")
    if busy > 0 and wall / busy > 1.5:
        print(f"  !! wall is {wall/busy:.1f}x gpu-busy -- HOST-BOUND. Profile with nsys, not ncu.")
    if work:
        scale = 1e12 if unit == "TFLOP/s" else 2 ** 30
        print(f"  achieved {work/wall/scale:.4g} {unit}")
    return wall