File size: 3,856 Bytes
5d12def
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""Shared backward-only timing and changed-cotangent CUDA Graph validation."""
import importlib.util
import sys
import statistics

import torch
import torch.distributed as dist


def load(path):
    directory = str(path.resolve().parent)
    if directory not in sys.path:
        sys.path.append(directory)
    spec = importlib.util.spec_from_file_location(path.stem, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def check(outputs, expected, tolerances, names=None):
    if len(outputs) != len(expected) or len(expected) != len(tolerances):
        raise ValueError(f"wrong gradient count: expected {len(tolerances)}, received {len(outputs)}")
    for i, (out, ref, (atol, rtol)) in enumerate(zip(outputs, expected, tolerances)):
        label = f"gradient {i}" if names is None else f"gradient {i} ({names[i]})"
        if out.shape != ref.shape or out.dtype != ref.dtype or out.device != ref.device:
            raise ValueError(f"{label}: received {tuple(out.shape)} {out.dtype} {out.device}, "
                             f"expected {tuple(ref.shape)} {ref.dtype} {ref.device}")
        # Chunk large parameter gradients to keep validation memory bounded.
        for x, y in zip(out.reshape(-1).split(2**20), ref.reshape(-1).split(2**20)):
            torch.testing.assert_close(x, y, atol=atol, rtol=rtol, msg=lambda m: f"{label}: {m}")


def qualify(calls, refresh, oracle, tolerances, repeats, names=None):
    """calls share fixed FWD state; refresh overwrites all dY tensors in place."""
    graphs, live_outputs = [], []
    refresh(137)
    expected = oracle()
    for call in calls:
        outputs = call()
        check(outputs, expected, tolerances, names)
        del outputs
    del expected
    for call in calls:
        graph = torch.cuda.CUDAGraph()
        with torch.cuda.graph(graph):
            outputs = call()
        graphs.append(graph)
        live_outputs.append(outputs)
    for seed in (153, 211):
        refresh(seed)
        expected = oracle()
        for graph, outputs in zip(graphs, live_outputs):
            for out in outputs:
                out.fill_(torch.nan)
            graph.replay()
            check(outputs, expected, tolerances, names)
        del expected
    samples = [[] for _ in calls]
    for rnd in range(9):
        order = range(len(calls)) if rnd % 2 == 0 else reversed(range(len(calls)))
        for i in order:
            if dist.is_initialized():
                dist.barrier()
            torch.cuda.synchronize()
            start, end = (torch.cuda.Event(enable_timing=True) for _ in range(2))
            start.record()
            for _ in range(repeats):
                graphs[i].replay()
            end.record()
            end.synchronize()
            us = start.elapsed_time(end) * 1000 / repeats
            if dist.is_initialized():
                maximum = torch.tensor(us, device="cuda", dtype=torch.float64)
                dist.all_reduce(maximum, op=dist.ReduceOp.MAX)
                us = maximum.item()
            samples[i].append(us)
    # Release captured collectives and flush CUDA callbacks before communicator teardown.
    for graph in graphs:
        graph.reset()
    live_outputs.clear()
    torch.cuda.synchronize()
    if dist.is_initialized():
        dist.barrier()
    result = dict(candidate_us=samples[0], candidate_median_us=statistics.median(samples[0]),
                  eager_checks_per_impl=1, fresh_graph_checks_per_impl=2, repeats=repeats,
                  device=torch.cuda.get_device_name(), torch=torch.__version__, cuda=torch.version.cuda)
    if len(calls) == 2:
        result.update(baseline_us=samples[1], baseline_median_us=statistics.median(samples[1]),
                      paired_speedup=statistics.median(b/c for c,b in zip(*samples)))
    return result