forked from pytorch/torchdynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautotune.py
executable file
·201 lines (177 loc) · 6.58 KB
/
autotune.py
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python
import argparse
import json
import logging
import os
import re
import subprocess
import sys
import time
import warnings
from collections import OrderedDict
import numpy as np
import torch
from tabulate import tabulate
import torchdynamo.optimizations.backends
from torchdynamo import config
from torchdynamo.optimizations.backends import BACKENDS
from torchdynamo.optimizations.subgraph import SubGraph
from torchdynamo.testing import same
from torchdynamo.utils import clone_inputs
from torchdynamo.utils import timed
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--repeat", "-n", type=int, default=20, help="number of timing runs"
)
parser.add_argument("--threads", "-t", type=int, help="number of threads to use")
parser.add_argument("--name")
parser.add_argument("--new", action="store_true")
parser.add_argument("--silent", "-q", action="store_true")
parser.add_argument("--max-age", type=int, default=48)
parser.add_argument("--stats", action="store_true")
parser.add_argument("--skip", action="append", help="dont use a backend")
parser.add_argument(
"--nvfuser",
action="store_true",
)
parser.add_argument(
"--limit",
"-l",
type=int,
)
args = parser.parse_args()
if args.silent:
torchdynamo.optimizations.backends.log.setLevel(logging.FATAL)
if args.threads:
torch.set_num_threads(args.threads)
if args.nvfuser:
torch._C._jit_override_can_fuse_on_cpu(False)
torch._C._jit_override_can_fuse_on_gpu(False)
torch._C._jit_set_texpr_fuser_enabled(False)
torch._C._jit_set_nvfuser_enabled(True)
else:
torch._C._jit_override_can_fuse_on_cpu(True)
torch._C._jit_override_can_fuse_on_gpu(True)
torch._C._jit_set_texpr_fuser_enabled(True)
if torch.cuda.is_available():
torch._C._jit_set_nvfuser_enabled(False)
if args.name:
name = re.sub(r"^[./]*subgraphs[./]*", "", args.name)
return run(args, name)
elif args.stats:
rows = []
for name in list_subgraphs(args):
with open(
os.path.join(config.base_dir, "subgraphs", name, "stats.json")
) as f:
keys, values = json.load(f)
rows.append(OrderedDict(zip(keys, values)))
headers = OrderedDict()
for row in rows:
headers.update(row)
headers = list(headers.keys())
rows = [[row.get(k, "") for k in headers] for row in rows]
print(tabulate(rows, headers=headers))
else:
for i, name in enumerate(list_subgraphs(args)):
path = os.path.join(config.base_dir, "subgraphs", name)
has_perf = os.path.exists(os.path.join(path, "perf.json"))
try:
age = time.time() - float(open(os.path.join(path, "timestamp")).read())
except OSError:
age = float("inf")
if has_perf and (args.new or age > args.max_age * 3600):
continue
print()
print("BEGIN", name, i)
cmd = [sys.executable] + list(sys.argv) + ["--name", name]
try:
subprocess.check_call(cmd)
except Exception:
try:
skip = open(os.path.join(path, "running")).read().strip()
print("ERROR skipping", skip)
cmd += ["--skip", skip]
subprocess.check_call(cmd)
except Exception:
logging.exception("failure from %s", name)
def list_subgraphs(args):
limit = args.limit or float("inf")
for name in sorted(os.listdir(os.path.join(config.base_dir, "subgraphs"))):
if name.startswith("g"):
yield name
limit -= 1
if limit <= 0:
return
def run(args, graph_name):
subgraph = SubGraph.load(graph_name)
# these next lines control which backends to try
# for a list see torchdynamo/optimizations/backends.py
if subgraph.is_cuda:
backend_names = [
"eager",
"cudagraphs",
"ts",
"cudagraphs_ts",
"ofi",
"cudagraphs_ts_ofi",
"tensorrt",
"nnc" if args.nvfuser else "nvfuser",
]
else:
backend_names = ["eager", "ts", "ofi", "onnxrt_cpu", "onnx2tf"]
skip = set(args.skip or [])
backend_names = [x for x in backend_names if x not in skip]
example_inputs = torch.load(
os.path.join(config.base_dir, "subgraphs", graph_name, "example_inputs.pt")
)
example_outputs = torch.load(
os.path.join(config.base_dir, "subgraphs", graph_name, "example_outputs.pt")
)
models = []
for name in backend_names:
with open(subgraph.filename("running"), "w") as fd:
fd.write(name)
try:
compiled_model = BACKENDS[name](subgraph)
if compiled_model is None:
continue
subgraph.restore()
result = compiled_model(*clone_inputs(example_inputs))
assert same(result, example_outputs)
models.append((name, compiled_model))
except AssertionError:
logging.exception(f"incorrect while running {name}")
except Exception:
logging.exception(f"error while running {name}")
os.unlink(subgraph.filename("running"))
del example_outputs
timings = np.zeros((args.repeat, len(models)), np.float64)
for rep in range(args.repeat):
# interleave the runs to handle frequency scaling and load changes
for i, (n, m) in enumerate(models):
result, timings[rep, i] = timed(m, example_inputs)
median = np.median(timings, axis=0)
names = [k for k, v in models]
sec = float(np.mean(timings[:, 0]))
headers = ["name", "sec"]
row = [graph_name, f"{sec:.4f}"]
if models[0][0] == "eager" and len(models) > 1:
speedups = [median[0] / median[i] for i in range(1, len(models))]
row.extend(f"{x:.2}x" for x in speedups)
headers.extend(names[1:])
else:
row.extend(f"{x:.2} sec" for x in median)
headers.extend(names)
print(tabulate([row], headers=headers))
perf = {k: float(v) for k, v in zip(names, median)}
with open(subgraph.filename("perf.json"), "w") as fd:
json.dump(perf, fd)
with open(subgraph.filename("stats.json"), "w") as fd:
json.dump([headers, row], fd)
if __name__ == "__main__":
logging.basicConfig(level=logging.WARNING)
warnings.filterwarnings("ignore")
with torch.no_grad():
main()